"use client";

/*
  A etiqueta do valor mínimo do item no tema Vendor, no desenho dele (cantos
  do tema, cor primária cheia, caixa clara com filete na cor da loja). O tema
  padrão tem a sua, em components/ValorMinimoDoItem.
  - computador: abre ao passar o mouse e no clique (o clique prende até
    clicar fora, Esc ou o X);
  - celular: abre no toque, fecha no toque fora ou no X;
  - a caixa vai para o <body> (portal) e leva as cores do tema lidas na hora,
    porque as variáveis --vd-* moram no contêiner do tema.
  Nunca mostra quanto o item "daria".
*/
import { useCallback, useEffect, useId, useLayoutEffect, useRef, useState } from "react";
import { createPortal } from "react-dom";
import { Info, X } from "lucide-react";
import { explicacaoDoMinimo, ROTULO_DO_MINIMO, textoDoMinimoDoItem } from "@/lib/adicionais";

const LARGURA = 290;
const MARGEM = 12;

type Cores = { primaria: string; texto: string; superficie: string; borda: string; raio: string };

export function VendorValorMinimo({
  minimo,
  modo = "produto",
  className = "",
}: {
  minimo: number;
  modo?: "produto" | "linha";
  className?: string;
}) {
  const [aberto, setAberto] = useState(false);
  const [preso, setPreso] = useState(false);
  const [posicao, setPosicao] = useState<{ top: number; left: number } | null>(null);
  const [cores, setCores] = useState<Cores | null>(null);
  const botao = useRef<HTMLButtonElement | null>(null);
  const caixa = useRef<HTMLDivElement | null>(null);
  const id = useId();

  const posicionar = useCallback(() => {
    const ancora = botao.current?.getBoundingClientRect();
    if (!ancora) return;
    const largura = Math.min(LARGURA, window.innerWidth - MARGEM * 2);
    const left = Math.min(Math.max(MARGEM, ancora.left + ancora.width / 2 - largura / 2), window.innerWidth - largura - MARGEM);
    const altura = caixa.current?.offsetHeight ?? 150;
    const acima = ancora.bottom + 8 + altura > window.innerHeight - MARGEM && ancora.top - 8 - altura > MARGEM;
    setPosicao({ top: acima ? ancora.top - 8 - altura : ancora.bottom + 8, left });
  }, []);

  const abrir = useCallback(() => {
    if (botao.current) {
      const estilo = getComputedStyle(botao.current);
      const ler = (nome: string, padrao: string) => estilo.getPropertyValue(nome).trim() || padrao;
      setCores({
        primaria: ler("--vd-primary", "#111827"),
        texto: ler("--vd-foreground", "#111827"),
        superficie: ler("--vd-surface", "#ffffff"),
        borda: ler("--vd-border", "#e5e7eb"),
        raio: ler("--vd-radius-lg", "12px"),
      });
    }
    setAberto(true);
  }, []);

  const fechar = useCallback((devolverFoco = false) => {
    setAberto(false);
    setPreso(false);
    if (devolverFoco) botao.current?.focus();
  }, []);

  useLayoutEffect(() => {
    if (aberto) posicionar();
  }, [aberto, posicionar]);

  useEffect(() => {
    if (!aberto) return;
    const foraDaqui = (evento: PointerEvent) => {
      const alvo = evento.target as Node;
      if (botao.current?.contains(alvo) || caixa.current?.contains(alvo)) return;
      fechar();
    };
    const tecla = (evento: KeyboardEvent) => {
      if (evento.key === "Escape") fechar(true);
    };
    window.addEventListener("pointerdown", foraDaqui);
    window.addEventListener("keydown", tecla);
    window.addEventListener("scroll", posicionar, true);
    window.addEventListener("resize", posicionar);
    return () => {
      window.removeEventListener("pointerdown", foraDaqui);
      window.removeEventListener("keydown", tecla);
      window.removeEventListener("scroll", posicionar, true);
      window.removeEventListener("resize", posicionar);
    };
  }, [aberto, fechar, posicionar]);

  return (
    <span
      className={`inline-flex max-w-full items-center gap-1.5 py-1 pl-2.5 pr-1 text-[12px] font-bold leading-tight ${className}`}
      style={{ backgroundColor: "var(--vd-primary)", color: "var(--vd-primary-fg)", borderRadius: "var(--vd-radius-md)" }}
    >
      <span className="min-w-0">{modo === "produto" ? textoDoMinimoDoItem(minimo) : ROTULO_DO_MINIMO}</span>
      <button
        ref={botao}
        type="button"
        aria-label="Como funciona o valor mínimo"
        aria-expanded={aberto}
        aria-controls={aberto ? id : undefined}
        onPointerEnter={(evento) => {
          if (evento.pointerType === "mouse") abrir();
        }}
        onPointerLeave={(evento) => {
          if (evento.pointerType === "mouse" && !preso) setAberto(false);
        }}
        onClick={() => {
          if (preso) fechar();
          else {
            abrir();
            setPreso(true);
          }
        }}
        className="inline-flex h-6 w-6 shrink-0 items-center justify-center transition-opacity hover:opacity-80 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-1"
        style={{ borderRadius: "var(--vd-radius-sm, 6px)", backgroundColor: "rgba(255,255,255,0.2)", color: "var(--vd-primary-fg)" }}
      >
        <Info size={14} strokeWidth={2.5} />
      </button>
      {aberto && typeof document !== "undefined"
        ? createPortal(
            <div
              ref={caixa}
              id={id}
              role="dialog"
              aria-label="Valor mínimo do item"
              onPointerEnter={() => setAberto(true)}
              onPointerLeave={(evento) => {
                if (evento.pointerType === "mouse" && !preso) setAberto(false);
              }}
              className="fixed z-[2147483000] border p-4 pr-9 text-left text-[13px] font-medium leading-relaxed shadow-2xl"
              style={{
                top: posicao?.top ?? -9999,
                left: posicao?.left ?? -9999,
                width: `min(${LARGURA}px, calc(100vw - ${MARGEM * 2}px))`,
                backgroundColor: cores?.superficie ?? "#ffffff",
                color: cores?.texto ?? "#111827",
                borderColor: cores?.borda ?? "#e5e7eb",
                borderLeft: `5px solid ${cores?.primaria ?? "#111827"}`,
                borderRadius: cores?.raio ?? "12px",
              }}
            >
              <p className="mb-1 text-[13px] font-bold" style={{ color: cores?.primaria }}>
                {textoDoMinimoDoItem(minimo)}
              </p>
              {explicacaoDoMinimo(minimo)}
              <button
                type="button"
                aria-label="Fechar"
                onClick={() => fechar(true)}
                className="absolute right-2 top-2 inline-flex h-7 w-7 items-center justify-center rounded-full opacity-70 hover:opacity-100"
              >
                <X size={15} />
              </button>
            </div>,
            document.body
          )
        : null}
    </span>
  );
}
