// ===== Error states · 404 / 500 / Trial expirado / Upgrade =====

function ErrorShell({ children }) {
  return (
    <div className="min-h-full bg-surface-1 grid place-items-center p-6 md:p-10">
      <div className="w-full max-w-2xl">{children}</div>
    </div>
  );
}

function NotFoundIllustration() {
  return (
    <svg viewBox="0 0 280 180" className="w-full max-w-sm mx-auto h-auto" aria-hidden>
      <defs>
        <linearGradient id="ill404" x1="0" y1="0" x2="1" y2="1">
          <stop offset="0%" stopColor="rgb(159 232 112)" stopOpacity="0.35" />
          <stop offset="100%" stopColor="rgb(159 232 112)" stopOpacity="0" />
        </linearGradient>
      </defs>
      <rect x="40" y="40" width="200" height="120" rx="12" fill="url(#ill404)" />
      <g fontFamily="DM Serif Display" fontSize="76" fill="rgb(15 30 58)" textAnchor="middle">
        <text x="140" y="112">4 4</text>
      </g>
      <circle cx="140" cy="100" r="22" fill="rgb(15 30 58)" />
      <path d="M140 88 L154 100 L140 112 Z" fill="rgb(159 232 112)" />
      <line x1="62" y1="160" x2="218" y2="160" stroke="rgb(229 227 218)" strokeWidth="2" strokeDasharray="4 6" />
    </svg>
  );
}

function ScreenError404({ goHome }) {
  return (
    <ErrorShell>
      <NotFoundIllustration />
      <div className="text-center mt-6">
        <div className="pl-num text-xs uppercase tracking-[0.14em] text-pleita-stone-2 mb-2">Erro 404</div>
        <h1 className="font-display text-4xl md:text-5xl text-pleita-ink leading-tight">Esta página não foi licitada<span className="text-pleita-lime">.</span></h1>
        <p className="text-sm text-pleita-stone mt-3 max-w-md mx-auto">O endereço que você buscou não existe ou foi movido. Talvez você queira voltar pro radar de oportunidades.</p>
        <div className="flex flex-wrap justify-center gap-3 mt-7">
          <button onClick={goHome} className="rounded-full bg-pleita-lime text-pleita-ink px-5 py-2.5 text-sm font-semibold hover:bg-pleita-lime-2">← Voltar pra home</button>
          <button className="rounded-full border border-pleita-line text-pleita-ink px-5 py-2.5 text-sm font-medium hover:bg-surface-2">Reportar problema</button>
        </div>
        <div className="mt-10 pt-8 border-t border-pleita-line/60">
          <div className="pl-num text-[10px] uppercase tracking-wider text-pleita-stone-2 mb-3">Talvez você esteja procurando</div>
          <div className="flex flex-wrap gap-2 justify-center">
            {["Editais", "Cofre de Certidões", "Peças Jurídicas", "Pós-Vitória", "Preços", "Blog"].map((s) => (
              <button key={s} className="text-xs text-pleita-stone px-3 py-1.5 rounded-full border border-pleita-line bg-surface-card hover:bg-surface-2 hover:text-pleita-ink">{s}</button>
            ))}
          </div>
        </div>
      </div>
    </ErrorShell>
  );
}

function ScreenError500({ goHome }) {
  return (
    <ErrorShell>
      <div className="text-center">
        <div className="mx-auto size-24 rounded-full grid place-items-center mb-6" style={{ background: "rgb(220 38 38 / .12)" }}>
          <svg viewBox="0 0 24 24" className="size-12 text-verdict-stop" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round">
            <path d="M10.29 3.86 1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0Z" /><line x1="12" y1="9" x2="12" y2="13" /><line x1="12" y1="17" x2="12.01" y2="17" />
          </svg>
        </div>
        <div className="pl-num text-xs uppercase tracking-[0.14em] text-pleita-stone-2 mb-2">Erro 500 · servidor</div>
        <h1 className="font-display text-4xl md:text-5xl text-pleita-ink leading-tight">Algo travou do nosso lado<span className="text-pleita-lime">.</span></h1>
        <p className="text-sm text-pleita-stone mt-3 max-w-md mx-auto">Nosso time foi notificado automaticamente. Tente novamente em alguns minutos — seus dados estão seguros.</p>

        <div className="mt-7 rounded-[10px] bg-surface-card border border-pleita-line p-5 max-w-md mx-auto text-left">
          <div className="pl-num text-[10px] uppercase tracking-wider text-pleita-stone-2 mb-2">ID do incidente · cite ao suporte</div>
          <div className="pl-num text-sm text-pleita-ink select-all break-all">INC-2026-05-17-A4F2D9</div>
        </div>

        <div className="flex flex-wrap justify-center gap-3 mt-7">
          <button onClick={() => location.reload()} className="rounded-full bg-pleita-lime text-pleita-ink px-5 py-2.5 text-sm font-semibold hover:bg-pleita-lime-2">↻ Tentar novamente</button>
          <button onClick={goHome} className="rounded-full border border-pleita-line text-pleita-ink px-5 py-2.5 text-sm font-medium hover:bg-surface-2">Ir pra home</button>
          <button className="rounded-full border border-pleita-line text-pleita-ink px-5 py-2.5 text-sm font-medium hover:bg-surface-2">Ver status público →</button>
        </div>
      </div>
    </ErrorShell>
  );
}

function ScreenTrialExpired({ goHome }) {
  return (
    <ErrorShell>
      <div className="rounded-[10px] overflow-hidden border border-pleita-line shadow-pl-md bg-surface-card">
        <div className="px-8 py-7 relative overflow-hidden" style={{ background: "linear-gradient(135deg, rgb(var(--pleita-ink)), rgb(var(--pleita-ink-2)))" }}>
          <div aria-hidden className="absolute -right-12 -top-12 size-56 rounded-full" style={{ background: "rgb(159 232 112 / .14)" }} />
          <div className="relative text-pleita-paper">
            <div className="pl-num text-[10px] uppercase tracking-wider text-pleita-lime mb-2">⏱ Trial expirado</div>
            <h1 className="font-display text-3xl md:text-4xl leading-tight">7 dias passaram voando<span className="text-pleita-lime">.</span></h1>
            <p className="text-sm text-pleita-paper/70 mt-3 max-w-lg">Você usou a Pleita por uma semana e analisou <span className="text-pleita-paper font-semibold">4 editais</span>. Pra continuar, escolha um plano abaixo — pode cancelar quando quiser, em 1 clique.</p>
          </div>
        </div>

        <div className="p-6 grid sm:grid-cols-2 gap-3">
          <button className="text-left rounded-[10px] border-2 border-pleita-lime bg-pleita-lime/8 p-5 hover:bg-pleita-lime/15 transition-colors">
            <div className="flex items-center justify-between mb-2">
              <span className="text-2xl">🚀</span>
              <span className="pl-num text-[10px] uppercase tracking-wider px-2 py-1 rounded-full font-semibold bg-pleita-lime text-pleita-ink">recomendado</span>
            </div>
            <div className="font-display text-lg text-pleita-ink">Em Marcha</div>
            <div className="pl-num text-2xl font-semibold text-pleita-ink mt-2">R$ 197<span className="text-sm text-pleita-stone-2">/mês</span></div>
            <div className="text-xs text-pleita-stone-2 mt-1">editais ilimitados + 6 agentes</div>
          </button>
          <button className="text-left rounded-[10px] border border-pleita-line bg-surface-card p-5 hover:bg-surface-2 transition-colors">
            <div className="text-2xl mb-2">🌱</div>
            <div className="font-display text-lg text-pleita-ink">Primeira Licitação</div>
            <div className="pl-num text-2xl font-semibold text-pleita-ink mt-2">R$ 49<span className="text-sm text-pleita-stone-2">/mês</span></div>
            <div className="text-xs text-pleita-stone-2 mt-1">3 editais/mês · Coach incluso</div>
          </button>
        </div>

        <div className="px-6 pb-6 flex items-center justify-between gap-4 flex-wrap">
          <button onClick={goHome} className="pl-num text-xs text-pleita-stone-2 hover:text-pleita-ink">Continuar usando em modo somente-leitura →</button>
          <div className="flex items-center gap-2 pl-num text-[11px] text-pleita-stone-2">
            <span className="text-verdict-go">✓</span>cancele em 1 clique
            <span className="text-verdict-go ml-2">✓</span>NF emitida
          </div>
        </div>
      </div>
    </ErrorShell>
  );
}

function ScreenUpgrade({ goHome }) {
  // Modal "Recurso bloqueado — upgrade obrigatório"
  return (
    <ErrorShell>
      <div className="rounded-[10px] bg-surface-card border border-pleita-line shadow-pl-md overflow-hidden">
        <header className="px-8 py-6 border-b border-pleita-line bg-surface-2/40 flex items-center gap-4">
          <div className="size-12 rounded-xl bg-pleita-lime grid place-items-center text-2xl shrink-0">🔒</div>
          <div>
            <div className="pl-num text-[10px] uppercase tracking-wider text-pleita-stone-2 mb-0.5">Recurso premium</div>
            <h1 className="font-display text-2xl text-pleita-ink leading-tight">Cockpit Pós-Vitória disponível no plano Veterano</h1>
          </div>
        </header>
        <div className="p-8">
          <p className="text-sm text-pleita-stone leading-relaxed max-w-xl">O Cockpit guia você por todas as etapas após a homologação — assinatura, empenho, NF, pagamento. É o nosso maior diferencial e não está incluído no seu plano atual.</p>

          <div className="grid sm:grid-cols-2 gap-3 mt-6">
            {[
              ["🏆", "7 etapas guiadas",       "do contrato à NF emitida"],
              ["📊", "Inteligência financeira", "tempo médio de pagamento do órgão"],
              ["💰", "Antecipação de recebíveis", "via parceiros fintech"],
              ["🎓", "Coach pós-vitória",      "próximo passo sugerido"],
            ].map(([i, t, d]) => (
              <div key={t} className="rounded-md border border-pleita-line/60 p-3">
                <div className="text-xl">{i}</div>
                <div className="text-sm text-pleita-ink font-medium mt-1">{t}</div>
                <div className="pl-num text-[11px] text-pleita-stone-2">{d}</div>
              </div>
            ))}
          </div>

          <div className="mt-6 pt-6 border-t border-pleita-line/60 flex items-center justify-between gap-4 flex-wrap">
            <div>
              <div className="font-display text-2xl text-pleita-ink">R$ 497<span className="pl-num text-sm text-pleita-stone-2">/mês</span></div>
              <div className="pl-num text-[11px] text-pleita-stone-2">+ R$ 300 vs. seu plano atual</div>
            </div>
            <div className="flex gap-2">
              <button onClick={goHome} className="rounded-full border border-pleita-line text-pleita-ink px-4 py-2 text-sm hover:bg-surface-2">Talvez depois</button>
              <button className="rounded-full bg-pleita-lime text-pleita-ink px-5 py-2 text-sm font-semibold hover:bg-pleita-lime-2">Fazer upgrade →</button>
            </div>
          </div>
        </div>
      </div>
    </ErrorShell>
  );
}

function ScreenErrors() {
  const [variant, setVariant] = React.useState("404");
  const variants = [
    { id: "404",     label: "404"           },
    { id: "500",     label: "500"           },
    { id: "trial",   label: "Trial expirado"},
    { id: "upgrade", label: "Upgrade"       },
  ];
  return (
    <div className="h-full overflow-y-auto scrollbar-pl bg-surface-1">
      <div className="sticky top-0 z-10 bg-surface-1/95 backdrop-blur border-b border-pleita-line/60 px-4 md:px-8 py-3 flex items-center gap-3 flex-wrap">
        <span className="pl-num text-[10px] uppercase tracking-[0.14em] text-pleita-stone-2 mr-2">estados de erro</span>
        <div className="flex items-center gap-1 rounded-full border border-pleita-line bg-surface-2 p-1">
          {variants.map((v) => (
            <button key={v.id} onClick={() => setVariant(v.id)} className={`pl-num text-[11px] uppercase tracking-wider px-3 py-1 rounded-full transition-colors ${variant === v.id ? "bg-pleita-ink text-pleita-paper" : "text-pleita-stone-2 hover:text-pleita-ink"}`}>{v.label}</button>
          ))}
        </div>
      </div>
      {variant === "404"     && <ScreenError404     goHome={() => {}} />}
      {variant === "500"     && <ScreenError500     goHome={() => {}} />}
      {variant === "trial"   && <ScreenTrialExpired goHome={() => {}} />}
      {variant === "upgrade" && <ScreenUpgrade      goHome={() => {}} />}
    </div>
  );
}

window.ScreenErrors = ScreenErrors;
