"use client";

import { useEffect, useRef, useState, type CSSProperties, type ReactNode } from "react";
import Link from "next/link";
import { usePathname } from "next/navigation";
import { ChevronDown, ChevronRight } from "lucide-react";
import type { Destino, ItemPronto } from "@/lib/navegacao-da-loja";

/*
  O menu próprio da loja nos temas Padrão e Vitrine (StoreContent).

  Só aparece quando a loja publicou itens no editor: sem isso o StoreContent
  desenha a lista de categorias de sempre. Os itens seguem o desenho da faixa
  de categorias de cada tema (mesmo tamanho de letra, mesmo sublinhado na
  rota atual); o item em destaque vira pílula na cor da loja, e o grupo abre
  uma lista ao passar o mouse (ou no toque).
*/

export function LinkDoMenu({
  destino,
  className,
  style,
  onClick,
  children,
}: {
  destino: Destino;
  className?: string;
  style?: CSSProperties;
  onClick?: () => void;
  children: ReactNode;
}) {
  const alvo = destino.novaAba ? "_blank" : undefined;
  const rel = destino.novaAba || destino.externo ? "noopener noreferrer" : undefined;
  if (destino.externo) {
    return (
      <a href={destino.href} target={alvo} rel={rel} className={className} style={style} onClick={onClick}>
        {children}
      </a>
    );
  }
  return (
    <Link href={destino.href} target={alvo} rel={rel} className={className} style={style} onClick={onClick}>
      {children}
    </Link>
  );
}

function naRota(caminho: string | null, item: ItemPronto) {
  if (!caminho) return false;
  const limpo = caminho.replace(/\/+$/, "");
  if (item.destino && !item.destino.externo) {
    const alvo = item.destino.href.replace(/\/+$/, "");
    /* "Início" só acende na própria home. */
    return limpo === alvo;
  }
  return item.filhos.some((filho) => !filho.destino.externo && limpo === filho.destino.href.replace(/\/+$/, ""));
}

function useGrupoAberto() {
  const [aberto, setAberto] = useState<string | null>(null);
  const relogio = useRef<number | null>(null);
  const caixa = useRef<HTMLDivElement | null>(null);
  const abrir = (id: string) => {
    if (relogio.current) window.clearTimeout(relogio.current);
    setAberto(id);
  };
  const fecharDepois = () => {
    if (relogio.current) window.clearTimeout(relogio.current);
    relogio.current = window.setTimeout(() => setAberto(null), 160);
  };
  useEffect(() => {
    if (!aberto) return;
    const fora = (evento: MouseEvent) => {
      if (!caixa.current?.contains(evento.target as Node)) setAberto(null);
    };
    const esc = (evento: KeyboardEvent) => {
      if (evento.key === "Escape") setAberto(null);
    };
    document.addEventListener("mousedown", fora);
    document.addEventListener("keydown", esc);
    return () => {
      document.removeEventListener("mousedown", fora);
      document.removeEventListener("keydown", esc);
    };
  }, [aberto]);
  useEffect(
    () => () => {
      if (relogio.current) window.clearTimeout(relogio.current);
    },
    []
  );
  return { aberto, setAberto, abrir, fecharDepois, caixa };
}

/** A faixa do computador. `variante` segue o desenho do tema. */
export function ItensDoMenuNaFaixa({
  itens,
  variante,
  corDaMarca,
  corDoTextoNaMarca,
  corDoTexto,
  fundoDaLista,
}: {
  itens: ItemPronto[];
  variante: "padrao" | "vitrine";
  corDaMarca: string;
  corDoTextoNaMarca: string;
  corDoTexto: string;
  fundoDaLista: string;
}) {
  const caminho = usePathname();
  const grupo = useGrupoAberto();

  return (
    <div ref={grupo.caixa} className="flex min-w-0 items-center gap-3 xl:gap-4 h-full">
      {itens.map((item) => {
        const ativo = naRota(caminho, item);
        const temFilhos = item.filhos.length > 0;
        const aberto = grupo.aberto === item.id;

        const classeBase =
          variante === "padrao"
            ? "relative text-[14px] font-semibold transition-colors whitespace-nowrap h-full flex items-center gap-1"
            : "relative shrink-0 text-sm transition-opacity py-1 flex items-center gap-1 whitespace-nowrap";

        const conteudo = (
          <>
            <span className={item.destaque ? "" : "group-hover:opacity-80 transition-opacity"}>{item.rotulo}</span>
            {temFilhos ? <ChevronDown size={14} className={`transition-transform ${aberto ? "rotate-180" : "opacity-60"}`} /> : null}
          </>
        );

        /* A pílula do destaque, nas duas variantes. */
        const estiloDoDestaque: CSSProperties = {
          backgroundColor: corDaMarca,
          color: corDoTextoNaMarca,
          borderRadius: 999,
          padding: "6px 14px",
          height: "auto",
          fontWeight: 700,
        };

        const estilo: CSSProperties = item.destaque
          ? estiloDoDestaque
          : variante === "padrao"
            ? { color: ativo || aberto ? corDaMarca : corDoTexto }
            : {
                color: corDoTexto,
                fontWeight: ativo ? 700 : 500,
                opacity: ativo || aberto ? 1 : 0.75,
                borderBottom: ativo ? `2px solid ${corDoTexto}` : "2px solid transparent",
              };

        const sublinhado =
          variante === "padrao" && !item.destaque ? (
            <span
              className={`absolute bottom-0 left-0 w-full h-0.5 rounded-t-full transition-transform origin-left ${ativo ? "scale-x-100" : "scale-x-0 group-hover:scale-x-100"}`}
              style={{ backgroundColor: corDaMarca, opacity: ativo ? 1 : 0.5 }}
            />
          ) : null;

        return (
          <div
            key={item.id}
            className="group relative h-full flex items-center shrink-0"
            onMouseEnter={temFilhos ? () => grupo.abrir(item.id) : undefined}
            onMouseLeave={temFilhos ? grupo.fecharDepois : undefined}
          >
            {item.destino ? (
              <LinkDoMenu destino={item.destino} className={classeBase} style={estilo}>
                {conteudo}
                {sublinhado}
              </LinkDoMenu>
            ) : (
              <button
                type="button"
                className={classeBase}
                style={estilo}
                aria-expanded={aberto}
                onClick={() => grupo.setAberto(aberto ? null : item.id)}
              >
                {conteudo}
                {sublinhado}
              </button>
            )}

            {temFilhos && aberto ? (
              <div
                className="absolute top-full left-0 z-[60] min-w-[14rem] rounded-xl border py-2 shadow-[0_10px_30px_rgba(15,23,42,0.12)]"
                style={{ backgroundColor: fundoDaLista, borderColor: "rgba(15,23,42,0.08)" }}
                onMouseEnter={() => grupo.abrir(item.id)}
                onMouseLeave={grupo.fecharDepois}
              >
                {item.filhos.map((filho) => (
                  <LinkDoMenu
                    key={filho.id}
                    destino={filho.destino}
                    onClick={() => grupo.setAberto(null)}
                    className="block px-5 py-2.5 text-[14px] font-medium transition-colors hover:bg-black/[0.04]"
                    style={{ color: variante === "padrao" ? "#475569" : corDoTexto }}
                  >
                    <span className="block truncate">{filho.rotulo}</span>
                  </LinkDoMenu>
                ))}
              </div>
            ) : null}
          </div>
        );
      })}
    </div>
  );
}

/** A lista do menu do celular (a gaveta lateral dos dois temas). */
export function ItensDoMenuNoCelular({
  itens,
  corDaMarca,
  fundoAtivo,
  corAtiva,
  aoEscolher,
}: {
  itens: ItemPronto[];
  corDaMarca: string;
  fundoAtivo: string;
  corAtiva: string;
  aoEscolher: () => void;
}) {
  const caminho = usePathname();
  const [abertos, setAbertos] = useState<Set<string>>(() => new Set());

  return (
    <div className="space-y-0.5">
      {itens.map((item) => {
        const ativo = naRota(caminho, item);
        const aberto = abertos.has(item.id);
        const estiloAtivo = ativo ? { backgroundColor: fundoAtivo, color: corAtiva } : undefined;

        if (!item.filhos.length && item.destino) {
          return (
            <LinkDoMenu
              key={item.id}
              destino={item.destino}
              onClick={aoEscolher}
              className="flex items-center gap-2.5 rounded-xl px-3 py-2.5 transition active:bg-slate-100"
              style={estiloAtivo}
            >
              <span className={`min-w-0 flex-1 truncate text-[14px] ${ativo ? "font-semibold" : "font-medium text-slate-700"}`}>
                {item.rotulo}
              </span>
              {item.destaque ? (
                <span className="shrink-0 rounded-full px-2 py-0.5 text-[10px] font-bold uppercase tracking-wide text-white" style={{ backgroundColor: corDaMarca }}>
                  Destaque
                </span>
              ) : (
                <ChevronRight size={16} className="shrink-0 text-slate-300" />
              )}
            </LinkDoMenu>
          );
        }

        return (
          <div key={item.id}>
            <button
              type="button"
              aria-expanded={aberto}
              onClick={() =>
                setAbertos((atual) => {
                  const novo = new Set(atual);
                  if (novo.has(item.id)) novo.delete(item.id);
                  else novo.add(item.id);
                  return novo;
                })
              }
              className="flex w-full items-center gap-2.5 rounded-xl px-3 py-2.5 text-left transition active:bg-slate-100"
              style={estiloAtivo}
            >
              <span className={`min-w-0 flex-1 truncate text-[14px] ${ativo ? "font-semibold" : "font-medium text-slate-700"}`}>
                {item.rotulo}
              </span>
              <ChevronDown size={16} className={`shrink-0 transition-transform ${aberto ? "rotate-180" : ""}`} style={{ color: ativo ? corDaMarca : "#94a3b8" }} />
            </button>
            {aberto ? (
              <div className="ml-[18px] space-y-0.5 border-l border-slate-200 py-1 pl-2.5">
                {item.filhos.map((filho) => (
                  <LinkDoMenu
                    key={filho.id}
                    destino={filho.destino}
                    onClick={aoEscolher}
                    className="block truncate rounded-lg px-3 py-2 text-[13px] text-slate-500 transition active:bg-slate-100"
                  >
                    {filho.rotulo}
                  </LinkDoMenu>
                ))}
              </div>
            ) : null}
          </div>
        );
      })}
    </div>
  );
}
