// ============================================================================
// Home — visão geral do portal
// ============================================================================

function PageHome({ go, open }) {
  return (
    <div style={{ padding: '28px 28px 60px' }}>
      <HomeHero go={go} />
      <HomeContinue go={go} open={open} />
      <HomeFeatured open={open} go={go} />
      <HomeStrip go={go} />
      <HomeAtalhos go={go} />
    </div>
  );
}

// ---- HERO ------------------------------------------------------------------
function HomeHero({ go }) {
  return (
    <div style={{
      position: 'relative', overflow: 'hidden',
      background: 'var(--navy)', color: '#fff',
      borderRadius: 24, padding: '36px 40px',
      display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: 30, alignItems: 'center',
    }}>
      <div style={{ position: 'relative', zIndex: 2 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 18 }}>
          <Pill tone="dark" style={{ background: 'rgba(232,155,44,.2)', color: 'var(--amber-2)', borderColor: 'rgba(232,155,44,.35)' }}>
            <Icon.dot s={6} /> Portal v2.4 · ciclo mai·26
          </Pill>
          <span style={{ fontSize: 11, opacity: .65 }}>Última atualização há 12 min</span>
        </div>
        <h1 style={{
          margin: 0, fontFamily: 'Instrument Serif, serif', fontWeight: 400,
          fontSize: 54, lineHeight: 1.05, letterSpacing: '-0.02em',
        }}>
          Portal de Instruções <span style={{ color: 'var(--amber-2)', fontStyle: 'italic' }}>e Playbooks</span> Ampexx
        </h1>
        <p style={{ margin: '14px 0 22px', fontSize: 15, lineHeight: 1.55, color: 'rgba(255,253,248,.78)', maxWidth: 540 }}>
          Centralize tudo o que sua área precisa para vender, operar e atender com o padrão Ampexx — playbooks comerciais, manuais de função, trilhas de treinamento e ferramentas, sincronizados com o Google Drive.
        </p>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
          <button onClick={() => go('playbooks')} style={{
            background: 'var(--amber)', color: 'var(--navy)', padding: '12px 18px',
            borderRadius: 12, fontWeight: 700, fontSize: 13.5, display: 'inline-flex', alignItems: 'center', gap: 8,
          }}>Explorar playbooks <Icon.arrow s={14} /></button>
          <button onClick={() => go('trilhas')} style={{
            background: 'transparent', color: '#fff', padding: '12px 18px',
            borderRadius: 12, fontWeight: 600, fontSize: 13.5, border: '1px solid rgba(255,255,255,.25)',
          }}>Ver trilhas →</button>
        </div>
        <div style={{ display: 'flex', gap: 28, marginTop: 28, fontSize: 12, color: 'rgba(255,253,248,.7)' }}>
          <Stat n="42" l="documentos vivos" />
          <Stat n="08" l="trilhas ativas" />
          <Stat n="116" l="colaboradores ativos no portal" />
          <Stat n="93%" l="conclusão no onboarding" />
        </div>
      </div>
      <HeroIllustration />
    </div>
  );
}

function Stat({ n, l }) {
  return (
    <div>
      <div style={{ fontFamily: 'Instrument Serif, serif', fontSize: 30, lineHeight: 1, color: '#fff' }}>{n}</div>
      <div style={{ marginTop: 4, letterSpacing: '.04em' }}>{l}</div>
    </div>
  );
}

// Ilustração original com SVG geométrico — sol, raio e malha (sem clichês)
function HeroIllustration() {
  return (
    <div style={{ position: 'relative', height: 280 }}>
      <svg viewBox="0 0 520 320" width="100%" height="100%" style={{ position: 'absolute', inset: 0 }}>
        {/* mesh background */}
        <defs>
          <linearGradient id="g1" x1="0" x2="1">
            <stop offset="0" stopColor="#E89B2C" stopOpacity=".0"/>
            <stop offset="1" stopColor="#E89B2C" stopOpacity=".0"/>
          </linearGradient>
        </defs>
        {Array.from({ length: 12 }).map((_, i) => (
          <line key={`h${i}`} x1="0" x2="520" y1={i*28+10} y2={i*28+10} stroke="rgba(255,255,255,.05)" strokeWidth="1" />
        ))}
        {Array.from({ length: 18 }).map((_, i) => (
          <line key={`v${i}`} x1={i*30+10} x2={i*30+10} y1="0" y2="320" stroke="rgba(255,255,255,.05)" strokeWidth="1" />
        ))}

        {/* Sol em arcos */}
        <g transform="translate(310,170)">
          <circle r="70" fill="none" stroke="rgba(232,155,44,.25)" strokeWidth="1"/>
          <circle r="95" fill="none" stroke="rgba(232,155,44,.18)" strokeWidth="1"/>
          <circle r="120" fill="none" stroke="rgba(232,155,44,.12)" strokeWidth="1"/>
          <circle r="55" fill="#E89B2C"/>
          <circle r="40" fill="#F0B656"/>
          <circle r="22" fill="#FFFDF8"/>
        </g>

        {/* Raio diagonal */}
        <path d="M40 250 L150 130 L130 130 L240 30" stroke="#F0B656" strokeWidth="2" fill="none" strokeLinejoin="round" strokeLinecap="round" />
        <circle cx="40" cy="250" r="5" fill="#F0B656"/>

        {/* Painéis estilizados — geométricos */}
        <g transform="translate(50,200)">
          <rect width="160" height="60" fill="none" stroke="rgba(255,255,255,.3)" strokeWidth="1"/>
          <line x1="0" y1="20" x2="160" y2="20" stroke="rgba(255,255,255,.15)"/>
          <line x1="0" y1="40" x2="160" y2="40" stroke="rgba(255,255,255,.15)"/>
          <line x1="40" y1="0" x2="40" y2="60" stroke="rgba(255,255,255,.15)"/>
          <line x1="80" y1="0" x2="80" y2="60" stroke="rgba(255,255,255,.15)"/>
          <line x1="120" y1="0" x2="120" y2="60" stroke="rgba(255,255,255,.15)"/>
        </g>
      </svg>

      {/* Card flutuante */}
      <div style={{
        position: 'absolute', bottom: 14, right: 14,
        background: 'rgba(255,253,248,.06)', backdropFilter: 'blur(8px)',
        border: '1px solid rgba(255,255,255,.14)', borderRadius: 14,
        padding: '12px 14px', fontSize: 12, color: 'rgba(255,253,248,.8)',
        minWidth: 200,
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <Icon.book s={14} />
          <span style={{ fontWeight: 700, color: '#fff' }}>Em destaque</span>
        </div>
        <div style={{ marginTop: 8, fontSize: 13, color: '#fff', lineHeight: 1.35 }}>Playbook · Usinas de Investimento — v2.4</div>
        <div style={{ marginTop: 6, fontSize: 11 }}>12 capítulos · 38 min</div>
      </div>
    </div>
  );
}

// ---- CONTINUE ESTUDANDO ----------------------------------------------------
function HomeContinue({ open, go }) {
  return (
    <section style={{ marginTop: 36 }}>
      <SectionHead eyebrow="Continuar estudando" title="De onde você parou" action="Ver tudo" />
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 16 }}>
        {CONTINUE.map(c => {
          const pal = PRODUCT_PALETTES[c.pal];
          return (
            <Card key={c.id} hoverable onClick={() => open && open(c)} style={{ overflow: 'hidden' }}>
              <div style={{ height: 130, background: pal.bg, color: pal.ink, position: 'relative', padding: 14, display: 'flex', flexDirection: 'column', justifyContent: 'space-between' }}>
                <Pill tone="dark" style={{ background: 'rgba(0,0,0,.18)', color: pal.ink === '#fff' ? '#fff' : 'var(--ink)', borderColor: 'rgba(0,0,0,.12)' }}>
                  {c.kind}
                </Pill>
                <CoverGlyph kind={c.kind} color={pal.accent} ink={pal.ink}/>
              </div>
              <div style={{ padding: '14px 14px 16px' }}>
                <div style={{ fontWeight: 700, fontSize: 14, lineHeight: 1.3 }}>{c.title}</div>
                <div style={{ marginTop: 4, fontSize: 12, color: 'var(--ink-3)' }}>{c.chapter}</div>
                <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginTop: 12 }}>
                  <div style={{ flex: 1 }}><Progress value={c.progress} color={pal.accent}/></div>
                  <div style={{ fontSize: 11, color: 'var(--ink-3)' }}>{c.progress}%</div>
                </div>
              </div>
            </Card>
          );
        })}
      </div>
    </section>
  );
}

function CoverGlyph({ kind, color, ink }) {
  // Glyph minimalista representando o tipo de conteúdo
  if (kind === 'Playbook') {
    return (
      <svg viewBox="0 0 100 60" width="100%" height="56" style={{ alignSelf: 'flex-end' }}>
        <rect x="6" y="10" width="60" height="44" rx="3" fill="none" stroke={ink} strokeOpacity=".4"/>
        <rect x="14" y="18" width="44" height="3" fill={ink} fillOpacity=".5"/>
        <rect x="14" y="26" width="34" height="3" fill={ink} fillOpacity=".4"/>
        <rect x="14" y="34" width="40" height="3" fill={ink} fillOpacity=".4"/>
        <circle cx="80" cy="20" r="10" fill={color}/>
        <path d="M76 20 L78.5 22.5 L84 17" stroke="#fff" strokeWidth="2" fill="none" strokeLinecap="round" strokeLinejoin="round"/>
      </svg>
    );
  }
  if (kind === 'Manual') {
    return (
      <svg viewBox="0 0 100 60" width="100%" height="56" style={{ alignSelf: 'flex-end' }}>
        <rect x="12" y="6" width="44" height="50" rx="2" fill="none" stroke={ink} strokeOpacity=".4"/>
        {[14,22,30,38,46].map(y => <rect key={y} x="18" y={y} width="32" height="2.5" fill={ink} fillOpacity=".35"/>)}
        <rect x="64" y="12" width="22" height="38" rx="2" fill={color} opacity=".85"/>
        <rect x="68" y="18" width="14" height="2.5" fill="#fff" opacity=".7"/>
        <rect x="68" y="24" width="10" height="2.5" fill="#fff" opacity=".7"/>
      </svg>
    );
  }
  // Trilha
  return (
    <svg viewBox="0 0 100 60" width="100%" height="56" style={{ alignSelf: 'flex-end' }}>
      <circle cx="14" cy="20" r="5" fill={color}/>
      <circle cx="46" cy="38" r="5" fill="none" stroke={ink} strokeOpacity=".5" strokeWidth="2"/>
      <circle cx="78" cy="14" r="5" fill="none" stroke={ink} strokeOpacity=".5" strokeWidth="2"/>
      <path d="M19 20 Q30 20 30 30 T46 38 Q60 38 60 24 T78 14" stroke={ink} strokeOpacity=".4" fill="none" strokeWidth="1.5" strokeDasharray="3 3"/>
    </svg>
  );
}

// ---- DESTAQUES (Pílulas estilo cards verticais) ----------------------------
function HomeFeatured({ open, go }) {
  return (
    <section style={{ marginTop: 40 }}>
      <SectionHead eyebrow="Pílulas em alta" title="Aprendizado em até 5 minutos"
        right={<div style={{ display: 'flex', gap: 6 }}>
          <Chip active>Todas</Chip><Chip>Vendas</Chip><Chip>Operações</Chip><Chip>Atendimento</Chip>
        </div>}
        action="Ver pílulas" />
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: 16 }}>
        {PILULAS.map(p => {
          const pal = PRODUCT_PALETTES[p.pal];
          return (
            <Card key={p.id} hoverable style={{
              aspectRatio: '3 / 4.4', overflow: 'hidden', position: 'relative',
              background: pal.bg, color: pal.ink, border: 'none',
            }}>
              <div style={{ position: 'absolute', inset: 0, padding: 16, display: 'flex', flexDirection: 'column' }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                  <Pill tone="dark" style={{ background: 'rgba(0,0,0,.16)', color: pal.ink === '#fff' ? '#fff' : 'var(--ink)', borderColor: 'rgba(0,0,0,.1)' }}>
                    {p.area}
                  </Pill>
                  <AmpexxMark size={18} color={pal.ink} accent={pal.accent}/>
                </div>
                <div style={{ marginTop: 'auto' }}>
                  <PilulaShape color={pal.accent} ink={pal.ink}/>
                  <div style={{ marginTop: 14, fontFamily: 'Instrument Serif, serif', fontSize: 22, lineHeight: 1.1, letterSpacing: '-0.01em' }}>
                    {p.t}
                  </div>
                  <div style={{ marginTop: 12, display: 'flex', alignItems: 'center', justifyContent: 'space-between', fontSize: 11, opacity: .8 }}>
                    <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5 }}><Icon.play s={10}/> assistir</span>
                    <span>{p.d}</span>
                  </div>
                </div>
              </div>
            </Card>
          );
        })}
      </div>
    </section>
  );
}

function PilulaShape({ color, ink }) {
  // pequeno marker geométrico aleatório-controlado para cada pílula
  return (
    <svg viewBox="0 0 100 50" width="100%" height="60">
      <circle cx="18" cy="30" r="14" fill={color}/>
      <rect x="40" y="10" width="32" height="32" fill="none" stroke={ink} strokeOpacity=".4" strokeWidth="1.5"/>
      <line x1="40" y1="10" x2="72" y2="42" stroke={ink} strokeOpacity=".4" strokeWidth="1.5"/>
      <circle cx="86" cy="20" r="3" fill={ink} fillOpacity=".5"/>
      <circle cx="92" cy="32" r="3" fill={color}/>
    </svg>
  );
}

function Chip({ children, active }) {
  return (
    <button style={{
      padding: '5px 12px', borderRadius: 999, fontSize: 12, fontWeight: 600,
      background: active ? 'var(--ink)' : 'transparent',
      color: active ? '#fff' : 'var(--ink-2)',
      border: active ? '1px solid var(--ink)' : '1px solid var(--line)',
    }}>{children}</button>
  );
}

// ---- Strip Trilhas ---------------------------------------------------------
function HomeStrip({ go }) {
  return (
    <section style={{ marginTop: 40 }}>
      <SectionHead eyebrow="Trilhas oficiais" title="Caminhos de desenvolvimento" action="Ver trilhas" />
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 16 }}>
        {TRILHAS.slice(0, 3).map(t => <TrilhaCard key={t.id} t={t} go={go}/>)}
      </div>
    </section>
  );
}

// ---- Atalhos / Estrutura do portal -----------------------------------------
function HomeAtalhos({ go }) {
  const items = [
    { id: 'playbooks',   label: '01 · Playbooks de Vendas',   sub: '4 produtos · 1 em rascunho', icon: 'book' },
    { id: 'manuais',     label: '02 · Manuais de Funções',    sub: '7 funções comerciais', icon: 'doc' },
    { id: 'manuais',     label: '03 · Manuais Operacionais',  sub: '9 processos cobertos', icon: 'doc' },
    { id: 'trilhas',     label: '04 · Treinamento e Desenvolvimento', sub: '5 trilhas ativas', icon: 'path' },
    { id: 'ferramentas', label: '05 · Ferramentas e Sistemas', sub: '8 ferramentas mapeadas', icon: 'tool' },
    { id: 'modelos',     label: '06 · Modelos e Templates',   sub: '6 modelos prontos', icon: 'tag' },
    { id: 'politicas',   label: '07 · Políticas internas',    sub: 'Padrões Ampexx', icon: 'shield' },
    { id: 'home',        label: '08 · Materiais de apoio',    sub: 'Apresentações e FAQ', icon: 'building' },
  ];
  return (
    <section style={{ marginTop: 40 }}>
      <SectionHead eyebrow="Estrutura do portal" title="Como o conhecimento Ampexx está organizado" />
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 12 }}>
        {items.map((it, i) => {
          const IconC = Icon[it.icon];
          return (
            <Card key={i} hoverable onClick={() => go(it.id)} style={{ padding: 16, display: 'flex', flexDirection: 'column', gap: 14, minHeight: 120 }}>
              <div style={{ width: 32, height: 32, borderRadius: 8, background: 'var(--bg-2)', display: 'grid', placeItems: 'center', color: 'var(--navy)' }}>
                <IconC s={18}/>
              </div>
              <div>
                <div style={{ fontSize: 13.5, fontWeight: 700, letterSpacing: '-0.01em' }}>{it.label}</div>
                <div style={{ fontSize: 12, color: 'var(--ink-3)', marginTop: 3 }}>{it.sub}</div>
              </div>
            </Card>
          );
        })}
      </div>
    </section>
  );
}

window.PageHome = PageHome;
window.CoverGlyph = CoverGlyph;
window.TrilhaCardHome = TrilhaCard; // also exposes
function TrilhaCard({ t, go }) {
  const tones = {
    'navy':       { bg: 'var(--navy)',  ink: '#fff',          glow: 'var(--amber)' },
    'navy-amber': { bg: 'var(--navy-2)',ink: '#fff',          glow: 'var(--amber-2)' },
    'leaf':       { bg: '#1F4F37',      ink: '#fff',          glow: '#9CC9B0' },
    'rust':       { bg: '#7B341A',      ink: '#fff',          glow: '#F0B656' },
  };
  const tone = tones[t.tone] || tones.navy;
  return (
    <Card hoverable onClick={() => go && go('trilhas')} style={{
      background: tone.bg, color: tone.ink, border: 'none', padding: 22, position: 'relative', overflow: 'hidden', minHeight: 200,
    }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
        <Pill tone="dark" style={{ background: 'rgba(255,255,255,.1)', color: '#fff', borderColor: 'rgba(255,255,255,.18)' }}>Trilha · {t.tag}</Pill>
        <AmpexxMark size={22} color={tone.ink} accent={tone.glow} />
      </div>
      <div style={{ marginTop: 18 }}>
        <div style={{ fontSize: 18, fontWeight: 700, letterSpacing: '-0.01em' }}>{t.title}</div>
        <div style={{ marginTop: 6, fontSize: 12, color: 'rgba(255,255,255,.7)', lineHeight: 1.45 }}>{t.desc}</div>
      </div>
      <div style={{ marginTop: 18, display: 'flex', alignItems: 'center', gap: 12, fontSize: 11, color: 'rgba(255,255,255,.65)' }}>
        <span>{t.items} conteúdos</span><span>·</span><span>{t.hours}</span>
      </div>
      <div style={{ marginTop: 14, display: 'flex', alignItems: 'center', gap: 8 }}>
        <button style={{
          padding: '8px 14px', borderRadius: 8, background: 'rgba(255,255,255,.1)', border: '1px solid rgba(255,255,255,.18)',
          color: '#fff', fontSize: 12, fontWeight: 600,
        }}>Ver trilha →</button>
      </div>
      {/* glow */}
      <div style={{ position: 'absolute', right: -50, bottom: -50, width: 180, height: 180, borderRadius: 999, background: `radial-gradient(circle, ${tone.glow}33, transparent 70%)` }}/>
    </Card>
  );
}
window.TrilhaCard = TrilhaCard;
