"use client";

import { useState, type ReactNode } from "react";
import Link from "next/link";
import {
  BadgeCheck,
  Barcode,
  Clock,
  CreditCard,
  Facebook,
  Headphones,
  Instagram,
  Linkedin,
  MapPin,
  Package,
  Plus,
  ShieldCheck,
  Truck,
  Twitter,
  Youtube,
  type LucideIcon,
} from "lucide-react";
import type { Destino, PaginaDaLoja } from "@/lib/navegacao-da-loja";
import type { BoutiqueCategoria, BoutiqueContato, BoutiqueRedes } from "./BoutiqueShell";

/*
  O rodapé da Boutique — o de sempre e o que a loja montou no editor
  (catalog_navegacao) usam o mesmo desenho, o da referência:

    1. faixa de garantias (branca): ícone fino, título e texto, em quatro
       colunas — sai da tarja de vantagens que a loja já cadastra;
    2. miolo cinza-claro (#F6F7F8) com até quatro colunas de títulos em caixa
       alta; no celular, cada coluna vira uma aba de acordeão (#CCD1D7);
    3. base: formas de pagamento, a logo com nome, CNPJ e endereço, e a
       compra segura.

  Com rodapé publicado no editor, as colunas, o "Sobre" e os blocos ligados
  ou desligados (contato, redes, pagamento, categorias) são os dele. Sem
  nada publicado, a Boutique mostra contato, categorias, a parte
  institucional e as redes.
*/

export type BoutiqueColunaPronta = { id: string; titulo: string; links: Array<{ id: string; rotulo: string; destino: Destino }> };

export type BoutiqueRodapePublicado = {
  sobre: string;
  colunas: BoutiqueColunaPronta[];
  mostrarContato: boolean;
  mostrarRedes: boolean;
  mostrarPagamento: boolean;
  mostrarCategorias: boolean;
};

export type BoutiqueGarantia = { icon?: string | null; title?: string | null; subtitle?: string | null };

const ICONES_DA_GARANTIA: Record<string, LucideIcon> = {
  truck: Truck,
  creditCard: CreditCard,
  shieldCheck: ShieldCheck,
  package: Package,
  clock: Clock,
  badgeCheck: BadgeCheck,
  mapPin: MapPin,
  headphones: Headphones,
};

/** O losango de quatro pétalas do Pix, em traço (o lucide não tem). */
export function IconeDoPix({ className, strokeWidth = 1.35 }: { className?: string; strokeWidth?: number }) {
  return (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={strokeWidth} strokeLinejoin="round" className={className} aria-hidden="true">
      <path d="M12 3.2 15 6.2 12 9.2 9 6.2Z" />
      <path d="M6.2 9 9.2 12 6.2 15 3.2 12Z" />
      <path d="M17.8 9 20.8 12 17.8 15 14.8 12Z" />
      <path d="M12 14.8 15 17.8 12 20.8 9 17.8Z" />
    </svg>
  );
}

/* O que o lojista digita no cadastro pode ser o endereço inteiro, o
   endereço sem https:// ou só o @ da conta. */
function linkDaRede(rede: keyof BoutiqueRedes, valor: string | null | undefined): string | null {
  const bruto = String(valor || "").trim();
  if (!bruto) return null;
  if (/^https?:\/\//i.test(bruto)) return bruto;
  if (/^[\w.-]+\.[a-z]{2,}(\/|$)/i.test(bruto)) return `https://${bruto}`;
  const conta = bruto.replace(/^@/, "");
  if (!/^[\w.-]+$/.test(conta)) return null;
  const base: Record<keyof BoutiqueRedes, string> = {
    instagram: `https://instagram.com/${conta}`,
    facebook: `https://facebook.com/${conta}`,
    twitter: `https://x.com/${conta}`,
    linkedin: `https://linkedin.com/company/${conta}`,
    youtube: `https://youtube.com/@${conta}`,
  };
  return base[rede];
}

const REDES: Array<{ chave: keyof BoutiqueRedes; nome: string; Icone: LucideIcon }> = [
  { chave: "instagram", nome: "Instagram", Icone: Instagram },
  { chave: "facebook", nome: "Facebook", Icone: Facebook },
  { chave: "twitter", nome: "Twitter / X", Icone: Twitter },
  { chave: "linkedin", nome: "LinkedIn", Icone: Linkedin },
  { chave: "youtube", nome: "YouTube", Icone: Youtube },
];

const CLASSE_DO_LINK = "block text-[12px] uppercase leading-[18px] underline-offset-2 transition-colors hover:underline";

function LinkDoRodape({ destino, children }: { destino: Destino; children: ReactNode }) {
  const alvo = destino.novaAba ? "_blank" : undefined;
  const rel = destino.novaAba || destino.externo ? "noopener noreferrer" : undefined;
  return destino.externo ? (
    <a href={destino.href} target={alvo} rel={rel} className={CLASSE_DO_LINK}>
      {children}
    </a>
  ) : (
    <Link href={destino.href} target={alvo} rel={rel} className={CLASSE_DO_LINK}>
      {children}
    </Link>
  );
}

type Coluna = { chave: string; titulo: string; conteudo: ReactNode };

export function BoutiqueRodape({
  regiao,
  slug,
  nomeDaLoja,
  logoUrl,
  logoClara,
  contato,
  redes,
  linkDoWhats,
  categorias,
  linkDaCategoria,
  paginas,
  garantias,
  publicado,
}: {
  regiao: Record<string, string>;
  slug: string;
  nomeDaLoja: string;
  logoUrl?: string | null;
  /* Rodapé escuro: a logo vira branca. */
  logoClara?: boolean;
  contato: BoutiqueContato;
  redes: BoutiqueRedes;
  linkDoWhats: string | null;
  categorias: BoutiqueCategoria[];
  linkDaCategoria: (categoria: BoutiqueCategoria) => string;
  paginas: PaginaDaLoja[];
  garantias: BoutiqueGarantia[];
  /* O rodapé publicado no editor; null = o de sempre. */
  publicado: BoutiqueRodapePublicado | null;
}) {
  const [abertas, setAbertas] = useState<Record<string, boolean>>({});

  const redesComLink = REDES.map((rede) => ({ ...rede, href: linkDaRede(rede.chave, redes[rede.chave]) })).filter(
    (rede): rede is (typeof REDES)[number] & { href: string } => Boolean(rede.href)
  );

  const colunaDoContato: Coluna | null =
    linkDoWhats || contato.telefone || contato.email
      ? {
          chave: "contato",
          titulo: "Contato",
          conteudo: (
            <div className="flex flex-col gap-4">
              {linkDoWhats ? (
                <a href={linkDoWhats} target="_blank" rel="noopener noreferrer" className={CLASSE_DO_LINK}>
                  WhatsApp {contato.whatsapp}
                </a>
              ) : null}
              {contato.telefone && String(contato.telefone).replace(/\D/g, "") !== String(contato.whatsapp || "").replace(/\D/g, "") ? (
                <a href={`tel:${String(contato.telefone).replace(/[^\d+]/g, "")}`} className={CLASSE_DO_LINK}>
                  {contato.telefone}
                </a>
              ) : null}
              {contato.email ? (
                <a href={`mailto:${contato.email}`} className={`${CLASSE_DO_LINK} normal-case`}>
                  {contato.email}
                </a>
              ) : null}
            </div>
          ),
        }
      : null;

  const colunaDasCategorias: Coluna | null = categorias.length
    ? {
        chave: "categorias",
        titulo: "Categorias",
        conteudo: (
          <div className="flex flex-col gap-4">
            {categorias.slice(0, 10).map((categoria) => (
              <Link key={categoria.id} href={linkDaCategoria(categoria)} className={CLASSE_DO_LINK}>
                {categoria.name}
              </Link>
            ))}
          </div>
        ),
      }
    : null;

  const colunaDasRedes: Coluna | null = redesComLink.length
    ? {
        chave: "redes",
        titulo: "Redes sociais",
        conteudo: (
          <div className="flex flex-col gap-4">
            {redesComLink.map(({ chave, nome, Icone, href }) => (
              <a
                key={chave}
                href={href}
                target="_blank"
                rel="noopener noreferrer"
                className="flex items-center gap-3 text-[12px] uppercase leading-[18px] underline-offset-2 hover:underline"
              >
                <Icone className="h-6 w-6 shrink-0" strokeWidth={1.5} />
                {nome}
              </a>
            ))}
          </div>
        ),
      }
    : null;

  const colunaInstitucional: Coluna = {
    chave: "institucional",
    titulo: "Institucional",
    conteudo: (
      <div className="flex flex-col gap-4">
        {paginas.slice(0, 8).map((pagina) => (
          <Link key={pagina.id} href={`/${slug}/pagina/${pagina.slug}`} className={CLASSE_DO_LINK}>
            {pagina.titulo}
          </Link>
        ))}
        <Link href={`/${slug}`} className={CLASSE_DO_LINK}>
          Todos os produtos
        </Link>
        <Link href={`/${slug}/cliente`} className={CLASSE_DO_LINK}>
          Minha conta
        </Link>
        <Link href={`/${slug}/cliente`} className={CLASSE_DO_LINK}>
          Acompanhar pedido
        </Link>
      </div>
    ),
  };

  const colunas: Coluna[] = publicado
    ? [
        publicado.sobre
          ? {
              chave: "sobre",
              titulo: `Sobre a ${nomeDaLoja}`,
              conteudo: (
                <div className="space-y-2 text-[12px] leading-[18px]">
                  {publicado.sobre.split(/\n+/).map((paragrafo, i) => (
                    <p key={i}>{paragrafo}</p>
                  ))}
                </div>
              ),
            }
          : null,
        ...publicado.colunas
          .filter((coluna) => coluna.links.length || coluna.titulo)
          .map<Coluna>((coluna) => ({
            chave: `coluna-${coluna.id}`,
            titulo: coluna.titulo,
            conteudo: (
              <div className="flex flex-col gap-4">
                {coluna.links.map((link) => (
                  <LinkDoRodape key={link.id} destino={link.destino}>
                    {link.rotulo}
                  </LinkDoRodape>
                ))}
              </div>
            ),
          })),
        publicado.mostrarContato ? colunaDoContato : null,
        publicado.mostrarCategorias ? colunaDasCategorias : null,
        publicado.mostrarRedes ? colunaDasRedes : null,
      ].filter((coluna): coluna is Coluna => Boolean(coluna))
    : [colunaDoContato, colunaDasCategorias, colunaInstitucional, colunaDasRedes].filter((coluna): coluna is Coluna =>
        Boolean(coluna)
      );

  const mostrarPagamento = publicado ? publicado.mostrarPagamento : true;
  const listaDeGarantias = garantias.filter((g) => g.title || g.subtitle).slice(0, 4);
  const colunasNoComputador = Math.min(Math.max(colunas.length, 1), 4);

  return (
    <footer {...regiao} className="mt-0" style={{ color: "var(--bq-footer-fg)" }}>
      {/* 1. Garantias */}
      {listaDeGarantias.length ? (
        <div className="border-t bg-[var(--bq-surface)] text-[var(--bq-foreground)]" style={{ borderColor: "var(--bq-footer-border)" }}>
          <div className="mx-auto grid max-w-[1600px] gap-6 px-5 py-6 sm:grid-cols-2 lg:flex lg:items-center lg:justify-around lg:gap-8 lg:px-[60px]">
            {listaDeGarantias.map((garantia, i) => {
              const Icone = ICONES_DA_GARANTIA[String(garantia.icon || "")] || BadgeCheck;
              return (
                <div key={`${garantia.title}-${i}`} className="flex items-center gap-3">
                  <Icone className="h-8 w-8 shrink-0" strokeWidth={1.2} />
                  <div className="min-w-0">
                    {garantia.title ? <p className="text-[14px] font-bold leading-tight">{garantia.title}</p> : null}
                    {garantia.subtitle ? <p className="mt-0.5 text-[12px] leading-snug">{garantia.subtitle}</p> : null}
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      ) : null}

      <div style={{ backgroundColor: "var(--bq-footer-bg)" }}>
        {/* 2. Colunas — computador */}
        {colunas.length ? (
          <div className="mx-auto hidden max-w-[1600px] px-20 pb-10 pt-10 lg:block">
            <div className="grid gap-8 border-b pb-10" style={{ gridTemplateColumns: `repeat(${colunasNoComputador}, minmax(0, 1fr))`, borderColor: "var(--bq-footer-border)" }}>
              {colunas.map((coluna) => (
                <section key={coluna.chave} className="min-w-0">
                  <h3 className="mb-6 text-[14px] font-extrabold uppercase leading-[21px]" style={{ color: "var(--bq-footer-titulo)" }}>
                    {coluna.titulo}
                  </h3>
                  {coluna.conteudo}
                </section>
              ))}
            </div>
          </div>
        ) : null}

        {/* 2. Colunas — celular: acordeão */}
        {colunas.length ? (
          <div className="lg:hidden" style={{ backgroundColor: "var(--bq-footer-acordeao)" }}>
            {colunas.map((coluna) => {
              const aberta = Boolean(abertas[coluna.chave]);
              return (
                <section key={coluna.chave} className="border-b" style={{ borderColor: "var(--bq-footer-acordeao)" }}>
                  <button
                    type="button"
                    onClick={() => setAbertas((antes) => ({ ...antes, [coluna.chave]: !antes[coluna.chave] }))}
                    aria-expanded={aberta}
                    className="flex min-h-[64px] w-full items-center gap-3 px-6 text-left text-[14px] font-extrabold uppercase"
                    style={{ color: "var(--bq-footer-titulo)" }}
                  >
                    <Plus className={`h-4 w-4 shrink-0 transition-transform duration-300 ${aberta ? "rotate-45" : ""}`} strokeWidth={1.2} />
                    {coluna.titulo}
                  </button>
                  <div
                    className="grid transition-[grid-template-rows] duration-300"
                    style={{ gridTemplateRows: aberta ? "1fr" : "0fr" }}
                  >
                    <div className="overflow-hidden">
                      <div className="px-6 pb-6 pl-[52px]">{coluna.conteudo}</div>
                    </div>
                  </div>
                </section>
              );
            })}
          </div>
        ) : null}

        {/* 3. Base */}
        <div className="mx-auto grid max-w-[1600px] items-center gap-8 px-5 py-10 lg:grid-cols-[1fr_auto_1fr] lg:px-20">
          <div className="order-2 flex flex-col items-center gap-4 lg:order-1 lg:items-start">
            {mostrarPagamento ? (
              <>
                <h3 className="text-[14px] font-extrabold uppercase" style={{ color: "var(--bq-footer-titulo)" }}>
                  Formas de pagamento
                </h3>
                <div className="flex flex-wrap items-center justify-center gap-5" style={{ color: "var(--bq-footer-titulo)" }}>
                  <span className="flex items-center gap-1.5 text-[12px]" title="Pix">
                    <IconeDoPix className="h-6 w-6" strokeWidth={1.5} />
                    Pix
                  </span>
                  <span className="flex items-center gap-1.5 text-[12px]" title="Cartão de crédito">
                    <CreditCard className="h-6 w-6" strokeWidth={1.4} />
                    Cartão
                  </span>
                  <span className="flex items-center gap-1.5 text-[12px]" title="Boleto">
                    <Barcode className="h-6 w-6" strokeWidth={1.4} />
                    Boleto
                  </span>
                </div>
              </>
            ) : null}
          </div>

          <div className="order-1 flex flex-col items-center text-center lg:order-2">
            {logoUrl ? (
              /* eslint-disable-next-line @next/next/no-img-element */
              <img src={logoUrl} alt={nomeDaLoja} className={`mb-4 max-h-[52px] w-auto max-w-[190px] object-contain ${logoClara ? "brightness-0 invert" : ""}`} />
            ) : (
              <p className="bq-revista mb-3 text-[30px] leading-none" style={{ color: "var(--bq-accent)" }}>
                {nomeDaLoja}
              </p>
            )}
            <p className="text-[13px] leading-[1.55]">
              {nomeDaLoja}
              {contato.cnpj ? ` | CNPJ: ${contato.cnpj}` : ""}
            </p>
            {contato.endereco ? <p className="max-w-[420px] text-[13px] leading-[1.55]">{contato.endereco}</p> : null}
            <p className="text-[13px] leading-[1.55]">© {new Date().getFullYear()} Direitos reservados</p>
          </div>

          <div className="order-3 flex justify-center lg:justify-end">
            <span className="inline-flex items-center gap-2.5 border px-3.5 py-2.5" style={{ borderColor: "var(--bq-footer-border)", color: "var(--bq-footer-titulo)" }}>
              <ShieldCheck className="h-6 w-6 shrink-0" strokeWidth={1.4} />
              <span className="text-left leading-tight">
                <span className="block text-[11px] font-bold uppercase tracking-[0.06em]">Compra segura</span>
                <span className="block text-[11px]">Conexão protegida</span>
              </span>
            </span>
          </div>
        </div>
      </div>
    </footer>
  );
}
