const PIcon = ({ name, size }) => {
  const C = I[name];
  return C ? <C size={size}/> : null;
};

const ScreenPlaybooks = ({ go, openId, setOpenId }) => {
  if (openId) return <PlaybookDetail id={openId} back={() => setOpenId(null)}/>;

  const { playbooks } = VELYX;

  return (
    <div className="max-w-[1360px] mx-auto px-10 py-10" data-screen-label="05 Playbooks">
      <PageHeader
        eyebrow="Aplicação"
        title="Playbooks"
        desc="Fluxos, prompts e templates prontos, organizados pelo setor do seu negócio."
      />

      <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4">
        {playbooks.map((p) => (
          <Card key={p.id} hover onClick={() => setOpenId(p.id)}
            className="p-6 flex items-start gap-5">
            <div className="w-12 h-12 rounded-[8px] bg-white/[0.04] hairline flex items-center justify-center shrink-0">
              <span className="text-ink"><PIcon name={p.icon} size={22}/></span>
            </div>
            <div className="flex-1 min-w-0">
              <div className="flex items-center gap-2 mb-1.5">
                {p.premium
                  ? <Badge tone="premium"><I.lock size={10}/> Premium</Badge>
                  : <Badge tone="accent">Incluso no plano</Badge>}
                <span className="text-mute2 text-[11.5px] font-mono ml-auto">{p.artefatos} artefatos</span>
              </div>
              <h3 className="text-[18px] font-semibold text-ink tracking-tightest mb-1">{p.sector}</h3>
              <p className="text-mute text-[13.5px] leading-relaxed">{p.desc}</p>
            </div>
          </Card>
        ))}
      </div>
    </div>
  );
};

const PLAYBOOK_TOC = [
  { id: 'intro', label: 'Introdução' },
  { id: 'arq', label: 'Arquitetura de atendimento' },
  { id: 'prompts', label: 'Prompts base' },
  { id: 'templates', label: 'Templates de mensagem' },
  { id: 'fluxos', label: 'Fluxos recomendados' },
  { id: 'cases', label: 'Cases reais' },
  { id: 'check', label: 'Checklist de go-live' },
];

const PlaybookDetail = ({ id, back }) => {
  const p = VELYX.playbooks.find(x => x.id === id);
  const [section, setSection] = React.useState('intro');

  return (
    <div className="max-w-[1180px] mx-auto px-10 py-10" data-screen-label={`Playbook · ${p.sector}`}>
      <button onClick={back}
        className="flex items-center gap-1.5 text-mute hover:text-ink t-fast text-[12.5px] mb-6">
        <I.chevLeft size={14}/> Todos os playbooks
      </button>

      <div className="grid grid-cols-[220px_1fr] gap-10">
        {/* TOC */}
        <aside className="sticky top-6 self-start">
          <div className="text-mute2 text-[10.5px] font-mono uppercase tracking-[0.12em] mb-3">Sumário</div>
          <nav className="space-y-0.5">
            {PLAYBOOK_TOC.map(t => (
              <button key={t.id} onClick={() => setSection(t.id)}
                className={`w-full text-left text-[13px] py-1.5 px-2.5 rounded-[6px] t-fast
                  ${section === t.id ? 'text-ink bg-white/[0.05]' : 'text-mute hover:text-ink'}`}>
                {t.label}
              </button>
            ))}
          </nav>

          <div className="mt-8 pt-5 border-t border-line">
            <div className="text-mute2 text-[10.5px] font-mono uppercase tracking-[0.12em] mb-2">Meta</div>
            <div className="space-y-1.5 text-[12px] text-mute">
              <div className="flex justify-between"><span>Artefatos</span><span className="font-mono text-ink">{p.artefatos}</span></div>
              <div className="flex justify-between"><span>Última revisão</span><span className="font-mono text-ink">12 abr</span></div>
              <div className="flex justify-between"><span>Mantido por</span><span className="font-mono text-ink">Velyx</span></div>
            </div>
          </div>
        </aside>

        {/* Content */}
        <article className="min-w-0">
          <div className="flex items-center gap-3 mb-3">
            <div className="w-9 h-9 rounded-[6px] bg-white/[0.04] hairline flex items-center justify-center">
              <span className="text-ink"><PIcon name={p.icon} size={18}/></span>
            </div>
            <Badge tone={p.premium ? 'premium' : 'accent'}>{p.premium ? 'Premium' : 'Incluso no plano'}</Badge>
          </div>
          <h1 className="text-[32px] font-semibold tracking-tightest text-ink mb-2 leading-[1.1]">
            Playbook · {p.sector}
          </h1>
          <p className="text-mute text-[15px] leading-relaxed max-w-2xl mb-10">{p.desc}</p>

          {section === 'intro' && (
            <div className="space-y-6 text-[14.5px] leading-[1.75] text-ink/90 max-w-[680px]">
              <p>
                Este playbook assume que você já passou pelas trilhas de Fundamentos e Arquitetura. Se pulou, volta lá — nada aqui vai fazer sentido sem aquilo.
              </p>
              <p className="text-mute">
                O que vem a seguir é a destilação do que a gente viu funcionar em mais de 40 operações de {p.sector.toLowerCase()} no Brasil nos últimos 18 meses. Não é teoria; é o que sobrou depois das coisas quebrarem.
              </p>
              <div className="p-5 rounded-[10px] hairline bg-panel">
                <div className="text-accent text-[11px] font-mono uppercase tracking-[0.12em] mb-2">Como usar</div>
                <ul className="space-y-2 text-[13.5px] text-ink/90">
                  <li>1. Lê a arquitetura até o fim antes de sair copiando prompt</li>
                  <li>2. Os prompts são ponto de partida — adapta ao tom da sua marca</li>
                  <li>3. Roda o checklist de go-live antes de expor ao cliente final</li>
                </ul>
              </div>
            </div>
          )}

          {section === 'prompts' && (
            <div className="space-y-4 max-w-[720px]">
              {['Classificador de intenção','Extração de dados do pedido','Resposta empática','Roteador pra humano'].map((t, i) => (
                <div key={i} className="p-5 rounded-[10px] hairline bg-panel">
                  <div className="flex items-center justify-between mb-2">
                    <div className="font-mono text-[11px] text-mute2 uppercase tracking-wide">Prompt 0{i+1}</div>
                    <button className="text-mute hover:text-ink t-fast flex items-center gap-1 text-[12px]"><I.copy size={13}/> Copiar</button>
                  </div>
                  <h4 className="text-ink text-[15.5px] font-semibold tracking-tightest mb-2">{t}</h4>
                  <pre className="text-mute text-[12.5px] font-mono leading-relaxed whitespace-pre-wrap bg-black/30 p-3 rounded-[6px] hairline2">
{`Você é assistente de {{empresa}}. Classifique a
intenção do cliente em uma das 6 categorias:
rastreio, troca, cobrança, cancelamento, dúvida, outros.

Retorne JSON: { "intent": "...", "confidence": 0-1 }`}
                  </pre>
                </div>
              ))}
            </div>
          )}

          {section !== 'intro' && section !== 'prompts' && (
            <div className="max-w-[680px]">
              <Placeholder className="h-[280px]">conteúdo da seção · {PLAYBOOK_TOC.find(t => t.id === section)?.label}</Placeholder>
              <p className="text-mute text-[13px] mt-4 leading-relaxed">
                Esta seção traz {PLAYBOOK_TOC.find(t => t.id === section)?.label.toLowerCase()} específico pra {p.sector.toLowerCase()}. Os artefatos completos estão disponíveis no plano atual.
              </p>
            </div>
          )}
        </article>
      </div>
    </div>
  );
};

window.ScreenPlaybooks = ScreenPlaybooks;
