// ===== Estados · empty, loading, toasts, dialogs =====

function StSection({ title, sub, children }) {
  return (
    <section className="mb-12">
      <div className="mb-5">
        <h2 className="font-display text-2xl text-pleita-ink leading-tight">{title}<span className="text-pleita-lime">.</span></h2>
        {sub && <p className="text-sm text-pleita-stone mt-1">{sub}</p>}
      </div>
      {children}
    </section>
  );
}

function StFrame({ label, children, w = "100%", h = "320px" }) {
  return (
    <div>
      <div className="pl-num text-[10px] uppercase tracking-wider text-pleita-stone-2 mb-2">{label}</div>
      <div className="rounded-xl border border-pleita-line bg-surface-card overflow-hidden grid place-items-center" style={{ width: w, height: h }}>
        {children}
      </div>
    </div>
  );
}

// ---------- Empty states ----------
function EmptyEditais() {
  return (
    <div className="text-center px-6">
      <div className="text-5xl opacity-60 mb-3">🌧️</div>
      <div className="font-display text-lg text-pleita-ink">Nada matchou hoje</div>
      <p className="text-xs text-pleita-stone-2 mt-2 max-w-sm mx-auto leading-relaxed">Aconteceu de não haver editais compatíveis nos últimos 15 minutos. Volta em algumas horas — o Caça-Editais continua varrendo.</p>
      <button className="mt-4 pl-num text-xs text-pleita-info hover:underline">Ajustar filtros →</button>
    </div>
  );
}
function EmptyKanban() {
  return (
    <div className="text-center px-6">
      <div className="text-5xl opacity-60 mb-3">🪨</div>
      <div className="font-display text-lg text-pleita-ink">Kanban vazio</div>
      <p className="text-xs text-pleita-stone-2 mt-2 max-w-sm mx-auto leading-relaxed">Você ainda não trouxe nenhum edital pra cá. Vá em <b className="text-pleita-ink">Editais</b> e clique em "salvar pra avaliar".</p>
      <button className="mt-4 pl-num text-xs px-4 py-2 rounded-md bg-pleita-ink text-pleita-paper">Ir pra Editais</button>
    </div>
  );
}
function EmptyCofre() {
  return (
    <div className="text-center px-6">
      <div className="text-5xl opacity-60 mb-3">📭</div>
      <div className="font-display text-lg text-pleita-ink">Seu cofre tá vazio</div>
      <p className="text-xs text-pleita-stone-2 mt-2 max-w-sm mx-auto leading-relaxed">Vamos começar pelo essencial: CNPJ, CND federal e Trabalhista. Pode emitir agora.</p>
      <button className="mt-4 pl-num text-xs px-4 py-2 rounded-md bg-pleita-lime text-pleita-ink font-medium">Emitir os 3 essenciais</button>
    </div>
  );
}
function EmptyResultados() {
  return (
    <div className="text-center px-6">
      <div className="text-5xl opacity-60 mb-3">🌱</div>
      <div className="font-display text-lg text-pleita-ink">Sem resultados ainda</div>
      <p className="text-xs text-pleita-stone-2 mt-2 max-w-sm mx-auto leading-relaxed">Sua primeira vitória aparece aqui. Em média, novos clientes vencem o primeiro contrato em 47 dias.</p>
    </div>
  );
}
function ErrorState() {
  return (
    <div className="text-center px-6">
      <div className="text-5xl opacity-70 mb-3">⚠️</div>
      <div className="font-display text-lg text-pleita-ink">Não consegui carregar</div>
      <p className="text-xs text-pleita-stone-2 mt-2 max-w-sm mx-auto leading-relaxed">Tentativa #2 falhou — o portal PNCP devolveu erro 503. Vou tentar de novo em 30 segundos.</p>
      <div className="mt-4 flex gap-2 justify-center">
        <button className="pl-num text-xs px-3 py-1.5 rounded-md border border-pleita-line text-pleita-ink hover:bg-surface-2">Tentar agora</button>
        <button className="pl-num text-xs px-3 py-1.5 rounded-md bg-pleita-ink text-pleita-paper">Avisar suporte</button>
      </div>
    </div>
  );
}

// ---------- Loading skeletons ----------
function SkBar({ w = "100%", h = 12, dark = false }) {
  return <div className="rounded animate-pulse" style={{ width: w, height: h, background: dark ? "rgb(var(--pleita-line) / .6)" : "rgb(var(--pleita-line) / .9)" }} />;
}
function SkeletonTable() {
  return (
    <div className="w-full p-5 space-y-3">
      <SkBar w="40%" h={20} />
      <SkBar w="100%" h={12} />
      <SkBar w="92%"  h={12} />
      <SkBar w="88%"  h={12} />
      <SkBar w="78%"  h={12} />
      <div className="grid grid-cols-3 gap-3 pt-2">
        <SkBar h={36} /><SkBar h={36} /><SkBar h={36} />
      </div>
    </div>
  );
}
function SkeletonAgent() {
  return (
    <div className="w-full p-5 flex items-start gap-4">
      <div className="size-12 rounded-xl bg-pleita-line animate-pulse" />
      <div className="flex-1 space-y-2">
        <SkBar w="40%" h={14} />
        <SkBar w="80%" h={10} />
        <SkBar w="65%" h={10} />
      </div>
      <div className="size-10 rounded-full bg-pleita-line animate-pulse" />
    </div>
  );
}
function SkeletonCardGrid() {
  return (
    <div className="grid grid-cols-2 gap-3 p-5 w-full">
      {Array.from({ length: 4 }).map((_, i) => (
        <div key={i} className="rounded-xl border border-pleita-line bg-surface-1 p-4 space-y-3">
          <SkBar w="35%" h={10} />
          <SkBar w="60%" h={22} />
          <SkBar w="100%" h={8} />
        </div>
      ))}
    </div>
  );
}
function LoadingHunter() {
  return (
    <div className="text-center px-6">
      <div className="size-12 rounded-full border-4 border-pleita-line border-t-pleita-lime animate-spin mx-auto" />
      <div className="font-display text-lg text-pleita-ink mt-4">Varrendo 9 portais…</div>
      <div className="pl-num text-[11px] text-pleita-stone-2 mt-1 max-w-xs mx-auto">PNCP · BEC-SP · Compras.gov · BLL · PCP-MG · ComprasNet · 3 outros</div>
    </div>
  );
}

// ---------- Toasts ----------
function Toast({ tone, title, msg, ico }) {
  const map = {
    go:      { bg: "bg-verdict-go/10",      bd: "border-verdict-go/40",      fg: "text-verdict-go" },
    caution: { bg: "bg-verdict-caution/10", bd: "border-verdict-caution/40", fg: "text-verdict-caution" },
    stop:    { bg: "bg-verdict-stop/10",    bd: "border-verdict-stop/40",    fg: "text-verdict-stop" },
    info:    { bg: "bg-pleita-info/10",     bd: "border-pleita-info/40",     fg: "text-pleita-info" },
  };
  const m = map[tone];
  return (
    <div className={`rounded-xl border ${m.bd} ${m.bg} shadow-pl-sm backdrop-blur p-4 flex items-start gap-3 max-w-md`}>
      <div className={`size-9 rounded-md grid place-items-center ${m.fg}`}>{ico}</div>
      <div className="flex-1 min-w-0">
        <div className="text-sm text-pleita-ink font-medium">{title}</div>
        <div className="pl-num text-[11px] text-pleita-stone-2 mt-0.5">{msg}</div>
      </div>
      <button className="size-6 grid place-items-center text-pleita-stone-2 hover:text-pleita-ink"><Icons.X className="size-3" /></button>
    </div>
  );
}

// ---------- Dialogs ----------
function DialogConfirm() {
  return (
    <div className="w-[420px] max-w-full rounded-2xl bg-surface-card border border-pleita-line shadow-pl-md p-6">
      <div className="text-3xl mb-3">⚠️</div>
      <h3 className="font-display text-lg text-pleita-ink">Cancelar participação?</h3>
      <p className="text-sm text-pleita-stone mt-2 leading-relaxed">Você está prestes a desistir do pregão TRF 3ª. O robô de lances vai parar imediatamente e não dá pra voltar atrás.</p>
      <div className="flex gap-2 mt-5 justify-end">
        <button className="pl-num text-sm px-4 py-2 rounded-md text-pleita-stone-2 hover:text-pleita-ink">Voltar</button>
        <PleitaButton variant="ink">Sim, cancelar</PleitaButton>
      </div>
    </div>
  );
}
function DialogDestructive() {
  return (
    <div className="w-[440px] max-w-full rounded-2xl bg-surface-card border border-verdict-stop/30 shadow-pl-md p-6">
      <div className="size-10 rounded-full bg-verdict-stop/15 grid place-items-center text-verdict-stop text-lg mb-3">!</div>
      <h3 className="font-display text-lg text-pleita-ink">Excluir tenant da Pleita</h3>
      <p className="text-sm text-pleita-stone mt-2 leading-relaxed">Essa ação é <b>permanente</b>. Todos os dados da Souza Engenharia serão apagados em até 30 dias (LGPD). Digite <code className="pl-num text-xs px-1 rounded bg-surface-2">SOUZA</code> pra confirmar.</p>
      <input className="w-full mt-4 px-3 py-2.5 rounded-md border border-verdict-stop/30 bg-surface-1 pl-num text-sm" placeholder="SOUZA" />
      <div className="flex gap-2 mt-5 justify-end">
        <button className="pl-num text-sm px-4 py-2 rounded-md text-pleita-stone-2 hover:text-pleita-ink">Cancelar</button>
        <button className="pl-num text-sm px-4 py-2 rounded-md bg-verdict-stop text-white">Excluir tenant</button>
      </div>
    </div>
  );
}

function ScreenStates() {
  return (
    <div className="h-full overflow-y-auto scrollbar-pl bg-surface-1">
      <div className="max-w-7xl mx-auto px-4 md:px-8 py-10">
        <header className="mb-10">
          <div className="pl-num text-xs uppercase tracking-[0.18em] text-pleita-stone-2">Design system</div>
          <h1 className="font-display text-4xl md:text-5xl text-pleita-ink mt-1 leading-tight">Estados<span className="text-pleita-lime">.</span></h1>
          <p className="text-sm text-pleita-stone mt-2 max-w-2xl">Empty, loading, toasts e dialogs — o que aparece quando não tem nada, quando está pensando, quando dá certo e quando o usuário precisa confirmar.</p>
        </header>

        <StSection title="Vazios" sub="Cada empty state ensina o próximo passo. Nunca apenas “sem dados”.">
          <div className="grid md:grid-cols-2 lg:grid-cols-3 gap-4">
            <StFrame label="editais · zero match">          <EmptyEditais /></StFrame>
            <StFrame label="kanban · primeira vez">          <EmptyKanban /></StFrame>
            <StFrame label="cofre · nada anexado">           <EmptyCofre /></StFrame>
            <StFrame label="resultados · ainda sem vitórias"><EmptyResultados /></StFrame>
            <StFrame label="erro · portal indisponível">     <ErrorState /></StFrame>
            <StFrame label="loading · varrendo portais">     <LoadingHunter /></StFrame>
          </div>
        </StSection>

        <StSection title="Skeletons" sub="Esqueletos durante carregamento — ritmo de pulse 2s.">
          <div className="grid md:grid-cols-3 gap-4">
            <StFrame label="lista densa" h="220px"><SkeletonTable /></StFrame>
            <StFrame label="agent card"  h="120px"><SkeletonAgent /></StFrame>
            <StFrame label="card grid"   h="280px"><SkeletonCardGrid /></StFrame>
          </div>
        </StSection>

        <StSection title="Toasts" sub="Auto-dismiss em 5s. Sempre top-right. Empilháveis até 3.">
          <div className="grid md:grid-cols-2 gap-3">
            <Toast tone="go"      ico="✓" title="Pregão arrematado · R$ 312.000" msg="Adjudicação prevista em 14 dias." />
            <Toast tone="caution" ico="!" title="CND Federal vence em 6 dias"     msg="Vou tentar emitir automaticamente amanhã." />
            <Toast tone="stop"    ico="✕" title="Falha ao enviar peça"           msg="O portal devolveu erro 503 — tentando novamente." />
            <Toast tone="info"    ico="ℹ" title="Novo edital match 92%"           msg="TRF 3ª · locação de impressoras · abertura 26 mai." />
          </div>
        </StSection>

        <StSection title="Dialogs" sub="Modal com backdrop escuro. Confirmação destrutiva exige digitar palavra.">
          <div className="grid md:grid-cols-2 gap-4">
            <StFrame label="confirmação simples" h="280px"><DialogConfirm /></StFrame>
            <StFrame label="ação destrutiva"      h="340px"><DialogDestructive /></StFrame>
          </div>
        </StSection>

        <StSection title="Inline notices" sub="Pra avisos contextuais dentro da própria página — não interrompem.">
          <div className="space-y-3 max-w-2xl">
            {[
              { tone: "info",    ico: "💡", t: "Modo Iniciante está ligado",         d: "Termos técnicos estão sendo traduzidos. Você pode desligar nas Configurações." },
              { tone: "caution", ico: "⚠️", t: "1 documento prestes a vencer",       d: "CND Federal vence em 6 dias. Vou emitir automaticamente em 2 dias." },
              { tone: "stop",    ico: "🛑", t: "Habilitação pendente · prazo curto", d: "Você precisa anexar o Balanço 2025 nas próximas 23h ou perde o pregão." },
              { tone: "go",      ico: "🏆", t: "Você venceu Campinas",                d: "Próximo passo: assinar o contrato em até 14 dias." },
            ].map((n, i) => {
              const map = { info: "border-pleita-info/30 bg-pleita-info/5", caution: "border-verdict-caution/30 bg-verdict-caution/5", stop: "border-verdict-stop/30 bg-verdict-stop/5", go: "border-verdict-go/30 bg-verdict-go/5" };
              return (
                <div key={i} className={`rounded-xl border p-4 flex items-start gap-3 ${map[n.tone]}`}>
                  <span className="text-lg shrink-0">{n.ico}</span>
                  <div className="flex-1">
                    <div className="text-sm text-pleita-ink font-medium">{n.t}</div>
                    <div className="text-xs text-pleita-stone mt-0.5 leading-relaxed">{n.d}</div>
                  </div>
                </div>
              );
            })}
          </div>
        </StSection>
      </div>
    </div>
  );
}

Object.assign(window, { ScreenStates });
