"use client";

import {
  useLayoutEffect,
  useRef,
  useState,
  type FocusEvent,
  type FormEvent,
  type KeyboardEvent,
} from "react";
import type { LandingConfig } from "@/lib/landing-default";
import { formatHeadline, normalizeHeadlineValue, normalizeHighlightMarkers } from "@/lib/headline-format";

type Props = {
  value: string;
  editing?: boolean;
  className?: string;
  onPatch?: (patch: Partial<LandingConfig>) => void;
};

export default function HeadlineEditable({ value, editing, className, onPatch }: Props) {
  const [focused, setFocused] = useState(false);
  const [draft, setDraft] = useState("");
  const ref = useRef<HTMLHeadingElement>(null);

  const saved = normalizeHeadlineValue(value);

  useLayoutEffect(() => {
    if (!focused || !ref.current) return;
    const el = ref.current;
    el.textContent = draft;
    el.focus();
    const range = document.createRange();
    const sel = window.getSelection();
    range.selectNodeContents(el);
    range.collapse(false);
    sel?.removeAllRanges();
    sel?.addRange(range);
  }, [focused]); // eslint-disable-line react-hooks/exhaustive-deps -- init ao abrir edição

  const startEdit = () => {
    setDraft(saved);
    setFocused(true);
  };

  const commit = (raw: string) => {
    const next = normalizeHeadlineValue(raw);
    setFocused(false);
    onPatch?.({ headline: next });
  };

  if (!editing) {
    return <h1 className={className}>{formatHeadline(value)}</h1>;
  }

  if (!focused) {
    return (
      <h1
        className={className}
        onClick={startEdit}
        onKeyDown={(e: KeyboardEvent<HTMLHeadingElement>) => {
          if (e.key === "Enter" || e.key === " ") {
            e.preventDefault();
            startEdit();
          }
        }}
        role="button"
        tabIndex={0}
        style={{ cursor: "text" }}
        title="Clique para editar. Use *asteriscos* para destacar trechos."
      >
        {formatHeadline(value)}
      </h1>
    );
  }

  return (
    <h1
      key="headline-editing"
      ref={ref}
      className={className}
      contentEditable
      suppressContentEditableWarning
      onInput={(e: FormEvent<HTMLHeadingElement>) => {
        setDraft(normalizeHighlightMarkers(e.currentTarget.innerText).replace(/\s+/g, " "));
      }}
      onBlur={(e: FocusEvent<HTMLHeadingElement>) => commit(e.currentTarget.innerText)}
      onKeyDown={(e: KeyboardEvent<HTMLHeadingElement>) => {
        if (e.key === "Enter") {
          e.preventDefault();
          commit(e.currentTarget.innerText);
        }
      }}
    />
  );
}
