// ===== Brand components =====

// Logo oficial — "P" geométrico com play lime + wordmark "Pleita."
function LogoMark({ size = 22, onDark = false, className = "" }) {
  const ink = onDark ? "rgb(var(--pleita-paper))" : "rgb(var(--pleita-ink))";
  return (
    <svg viewBox="0 0 64 64" width={size} height={size} className={className} aria-hidden="true">
      {/* "P" — haste vertical + bojo */}
      <path
        d="M10 6 L10 58 L22 58 L22 40 L34 40 C46.15 40 56 32.36 56 23 C56 13.64 46.15 6 34 6 Z"
        fill={ink}
      />
      {/* Play triangle lime, centrado no bojo */}
      <path d="M28 14 L44 23 L28 32 Z" fill="rgb(var(--pleita-lime))" />
    </svg>
  );
}

function Logo({ size = 22, variant = "wordmark", onDark = false, className = "" }) {
  if (variant === "mark") return <LogoMark size={size} onDark={onDark} className={className} />;
  const inkText = onDark ? "text-pleita-paper" : "text-pleita-ink";
  return (
    <span className={`inline-flex items-center gap-2 leading-none ${className}`}>
      <LogoMark size={Math.round(size * 1.15)} onDark={onDark} />
      <span className={`font-display font-medium ${inkText}`} style={{ fontSize: size, letterSpacing: "-0.015em" }}>
        Pleita<span className="text-pleita-lime">.</span>
      </span>
    </span>
  );
}

const VERDICT_META = {
  go:      { dot: "#16A34A", label: "PARTICIPE",     emoji: "🟢", bg: "bg-verdict-go/10",      fg: "text-verdict-go" },
  caution: { dot: "#F59E0B", label: "CUIDADO",       emoji: "🟡", bg: "bg-verdict-caution/15", fg: "text-verdict-caution" },
  stop:    { dot: "#DC2626", label: "NÃO PARTICIPE", emoji: "🔴", bg: "bg-verdict-stop/10",    fg: "text-verdict-stop" },
};

function VerdictBadge({ verdict, size = "md", hideEmoji = false }) {
  const m = VERDICT_META[verdict];
  const classes = size === "sm" ? "text-[10px] px-2 py-1" : size === "lg" ? "text-xs px-3 py-1.5" : "text-[11px] px-2.5 py-1";
  return (
    <span className={`inline-flex items-center gap-1.5 rounded-full font-semibold uppercase tracking-wider pl-num ${classes} ${m.bg} ${m.fg}`}>
      {!hideEmoji && <span className="text-base leading-none">{m.emoji}</span>}
      {m.label}
    </span>
  );
}

function VerdictHero({ verdict, diameter = 110 }) {
  const m = VERDICT_META[verdict];
  return (
    <div
      className="rounded-full grid place-items-center"
      style={{
        width: diameter, height: diameter,
        background: `radial-gradient(circle, ${m.dot}26 0%, transparent 70%)`,
        border: `1px solid ${m.dot}55`,
      }}
    >
      <div className="rounded-full" style={{ width: diameter * 0.62, height: diameter * 0.62, background: m.dot, boxShadow: `0 0 28px ${m.dot}66` }} />
    </div>
  );
}

function PleitaButton({ variant = "lime", size = "md", className = "", children, ...props }) {
  const sizes = { sm: "text-xs px-3 py-1.5 gap-1.5", md: "text-sm px-4 py-2 gap-2", lg: "text-sm px-5 py-2.5 gap-2" };
  const variants = {
    lime:  "bg-pleita-lime text-pleita-ink hover:bg-pleita-lime-2 hover:-translate-y-px",
    ink:   "bg-pleita-ink text-pleita-paper hover:bg-pleita-ink-2",
    ghost: "bg-transparent text-pleita-stone hover:text-pleita-ink hover:bg-pleita-paper-2/60 border border-pleita-line",
  };
  return (
    <button className={`inline-flex items-center justify-center font-medium rounded-full transition-all duration-200 ${sizes[size]} ${variants[variant]} ${className}`} {...props}>
      {children}
    </button>
  );
}

function AgentCard({ agentKey, score, compact, highlight }) {
  const a = AGENTS[agentKey];
  return (
    <article className={`rounded-2xl bg-surface-card border ${a.border} ${highlight ? "ring-2 ring-pleita-lime/40" : ""} p-5 hover:shadow-pl-md transition-shadow`}>
      <header className="flex items-start justify-between">
        <div className="flex items-center gap-3">
          <div className="size-10 rounded-xl bg-surface-2 grid place-items-center text-xl">{a.emoji}</div>
          <div>
            <div className="font-display font-medium text-pleita-ink">{a.name}</div>
            <div className="pl-num text-[10px] uppercase tracking-wider text-pleita-stone-2">{a.model}</div>
          </div>
        </div>
        {score != null && (
          <div className="text-right">
            <div className="pl-num text-[9px] uppercase tracking-wider text-pleita-stone-2">score</div>
            <div className="pl-num font-semibold text-base text-pleita-ink">{score}</div>
          </div>
        )}
      </header>
      {!compact && <p className="text-sm text-pleita-stone mt-3 leading-snug">{a.role}.</p>}
    </article>
  );
}

function SectionHeader({ eyebrow, title, description, actions }) {
  return (
    <header className="flex items-end justify-between flex-wrap gap-4 mb-6">
      <div className="max-w-2xl">
        {eyebrow && <div className="pl-num text-xs uppercase tracking-[0.14em] text-pleita-stone-2 mb-2">{eyebrow}</div>}
        <h1 className="font-display font-medium text-2xl md:text-3xl text-pleita-ink leading-tight tracking-tight">{title}</h1>
        {description && <p className="text-sm text-pleita-stone mt-2 leading-relaxed">{description}</p>}
      </div>
      {actions && <div className="flex items-center gap-2">{actions}</div>}
    </header>
  );
}

// ===== App shell components =====

function Sidebar({ beginnerMode, setBeginnerMode, active = "editais", mobileOpen = false, onCloseMobile }) {
  const NAV = beginnerMode ? [
    { id: "editais",     emoji: "🔎", label: "Oportunidades" },
    { id: "matches",     emoji: "🎯", label: "Minhas escolhas" },
    { id: "habilitacao", emoji: "📋", label: "Meus documentos" },
    { id: "pecas",       emoji: "⚖️", label: "Cartas e ofícios" },
    { id: "pos",         emoji: "🏆", label: "Depois da vitória" },
    { id: "analytics",   emoji: "📊", label: "Meus resultados" },
    { id: "avisos",      emoji: "🔔", label: "Avisos" },
  ] : [
    { id: "editais",     emoji: "📡", label: "Editais" },
    { id: "matches",     emoji: "🎯", label: "Meus Matches" },
    { id: "habilitacao", emoji: "📋", label: "Habilitação" },
    { id: "pecas",       emoji: "⚖️", label: "Peças Jurídicas" },
    { id: "pos",         emoji: "🏆", label: "Pós-Vitória" },
    { id: "analytics",   emoji: "📊", label: "Analytics" },
    { id: "avisos",      emoji: "🔔", label: "Avisos" },
  ];
  return (
    <aside
      className={`w-[240px] shrink-0 border-r border-pleita-line bg-surface-card flex flex-col z-40 transition-transform md:translate-x-0 md:relative ${
        mobileOpen ? "fixed inset-y-0 left-0 translate-x-0 shadow-pl-md" : "fixed inset-y-0 left-0 -translate-x-full md:translate-x-0"
      }`}
    >
      <div className="px-5 pt-6 pb-5 flex items-center justify-between">
        <Logo size={20} />
        <button onClick={onCloseMobile} aria-label="Fechar menu" className="md:hidden size-8 rounded-md hover:bg-surface-2 grid place-items-center text-pleita-stone-2">✕</button>
      </div>
      <div className="px-3 pb-4">
        <button
          onClick={() => setBeginnerMode(!beginnerMode)}
          className={`w-full flex items-center justify-between gap-3 rounded-xl px-3 py-2.5 transition-colors ${beginnerMode ? "bg-pleita-lime/30" : "bg-surface-2 hover:bg-surface-2/70"}`}
        >
          <div className="flex items-center gap-2 min-w-0">
            <span className="text-base">🎓</span>
            <div className="min-w-0">
              <div className="text-sm text-pleita-ink leading-tight font-medium">Modo Iniciante</div>
              <div className="pl-num text-[10px] text-pleita-stone-2">{beginnerMode ? "ligado" : "desligado"}</div>
            </div>
          </div>
          <span className={`relative w-9 h-5 rounded-full transition-colors ${beginnerMode ? "bg-pleita-ink" : "bg-pleita-line"}`}>
            <span className={`absolute top-0.5 size-4 rounded-full bg-white transition-transform ${beginnerMode ? "translate-x-4" : "translate-x-0.5"}`} />
          </span>
        </button>
      </div>
      <nav className="px-2 flex-1 overflow-y-auto scrollbar-pl">
        <ul className="space-y-0.5">
          {NAV.map((it) => {
            const isActive = it.id === active;
            return (
              <li key={it.id}>
                <button className={`w-full flex items-center gap-3 px-3 py-2 rounded-xl text-sm transition-colors ${isActive ? "bg-pleita-paper-2 text-pleita-ink" : "text-pleita-stone hover:bg-pleita-paper-2/60 hover:text-pleita-ink"}`}>
                  <span className={`text-base ${beginnerMode ? "opacity-100" : "opacity-0 -ml-3 transition-all"}`}>{it.emoji}</span>
                  <span>{it.label}</span>
                  {isActive && <span className="ml-auto size-1.5 rounded-full bg-pleita-lime" />}
                </button>
              </li>
            );
          })}
        </ul>
        <div className="my-3 mx-3 border-t border-pleita-line" />
        <ul className="space-y-0.5">
          <li className="px-3 pb-1 pl-num text-[10px] uppercase tracking-[0.14em] text-pleita-stone-2">Empresa</li>
          <li>
            <button className="w-full flex items-center gap-2 px-3 py-2 rounded-xl text-sm text-pleita-ink hover:bg-pleita-paper-2/60">
              <span className="size-6 rounded-md bg-pleita-ink text-pleita-paper grid place-items-center pl-num text-[10px] font-semibold">SE</span>
              <span className="truncate">Souza Engenharia</span>
              <Icons.ChevronDown className="size-3.5 ml-auto text-pleita-stone-2" />
            </button>
          </li>
          <li><button className="w-full flex items-center gap-3 px-3 py-2 rounded-xl text-sm text-pleita-stone hover:bg-pleita-paper-2/60 hover:text-pleita-ink">⚙️<span>Configurações</span></button></li>
        </ul>
      </nav>
      <div className="p-3 border-t border-pleita-line flex items-center gap-3">
        <span className="size-8 rounded-full bg-pleita-ink text-pleita-paper grid place-items-center pl-num text-xs font-semibold">MS</span>
        <div className="min-w-0">
          <div className="text-xs text-pleita-ink truncate">Marcos Souza</div>
          <div className="pl-num text-[10px] text-pleita-stone-2 truncate">marcos@souzaeng.com.br</div>
        </div>
      </div>
    </aside>
  );
}

function Topbar({ crumb, onOpenMobileNav }) {
  return (
    <header className="h-[60px] border-b border-pleita-line bg-surface-1/80 backdrop-blur flex items-center px-4 md:px-6 gap-3 md:gap-6 sticky top-0 z-10">
      <button
        onClick={onOpenMobileNav}
        aria-label="Abrir menu"
        className="md:hidden size-9 rounded-md hover:bg-surface-2 grid place-items-center text-pleita-stone"
      >
        <svg viewBox="0 0 24 24" className="size-5" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><line x1="3" y1="6" x2="21" y2="6"/><line x1="3" y1="12" x2="21" y2="12"/><line x1="3" y1="18" x2="21" y2="18"/></svg>
      </button>
      <div className="hidden md:flex items-center gap-2 text-sm text-pleita-stone-2">
        {crumb.map((c, i) => (
          <React.Fragment key={i}>
            {i > 0 && <Icons.ChevronRight className="size-3.5" />}
            <span className={i === crumb.length - 1 ? "text-pleita-ink" : ""}>{c}</span>
          </React.Fragment>
        ))}
      </div>
      <div className="flex-1 max-w-md md:mx-auto">
        <button className="w-full flex items-center gap-2 rounded-full border border-pleita-line bg-surface-2/40 px-3 md:px-4 py-2 text-sm text-pleita-stone-2 hover:bg-surface-2/70 transition-colors">
          <Icons.Search className="size-4 shrink-0" />
          <span className="flex-1 text-left truncate"><span className="hidden sm:inline">Buscar editais, peças, agentes…</span><span className="sm:hidden">Buscar…</span></span>
          <span className="pl-num text-[10px] px-1.5 py-0.5 rounded border border-pleita-line text-pleita-stone-2 hidden md:inline">⌘K</span>
        </button>
      </div>
      <div className="flex items-center gap-1">
        <button className="size-9 grid place-items-center rounded-full hover:bg-surface-2 text-pleita-stone relative">
          <Icons.Bell className="size-4" />
          <span className="absolute top-2 right-2 size-1.5 rounded-full bg-pleita-lime" />
        </button>
        <button className="size-9 grid place-items-center rounded-full hover:bg-surface-2 text-pleita-stone"><Icons.HelpCircle className="size-4" /></button>
        <span className="size-8 rounded-full bg-pleita-ink text-pleita-paper grid place-items-center pl-num text-xs font-semibold ml-1">MS</span>
      </div>
    </header>
  );
}

Object.assign(window, { Logo, VerdictBadge, VerdictHero, PleitaButton, AgentCard, SectionHeader, Sidebar, Topbar, VERDICT_META });
