// Bento grid — 13 feature cards, mosaic layout
const { Reveal: Reveal_b, Stagger: Stagger_b, StaggerItem: StaggerItem_b, Container: Container_b, Section: Section_b, Eyebrow: Eyebrow_b, Pill: Pill_b } = window.UI;
const { motion: mb } = window.framerMotion || {};

// Tiny inline mockups for bento cards
function MiniAgenda() {
  const colors = ['#0EA5E9', '#10B981', '#F59E0B', '#8B5CF6'];
  return (
    <div className="rounded-lg overflow-hidden bg-ink-950 border border-ink-700/60 p-2.5 grid grid-cols-4 gap-1" style={{ background: '#0A0F1C' }}>
      {Array.from({length: 32}).map((_, i) => {
        const filled = (i * 7 + 3) % 5 < 3;
        const c = colors[i % 4];
        return <div key={i} className="rounded-sm h-4" style={{ background: filled ? c + '30' : 'transparent', borderLeft: filled ? `2px solid ${c}` : 'none' }}/>;
      })}
    </div>
  );
}

function MiniProntuario() {
  return (
    <div className="rounded-lg bg-ink-950 border border-ink-700/60 p-3 space-y-1.5" style={{ background: '#0A0F1C' }}>
      <div className="flex gap-1 text-[8px]"><span className="px-1.5 py-0.5 rounded bg-cyan-500/15 text-cyan-300 border border-cyan-500/20 font-mono">H93.1</span><span className="px-1.5 py-0.5 rounded bg-ink-800 text-ink-300 font-mono">Z00.0</span></div>
      <div className="space-y-1">
        <div className="h-1.5 rounded-full bg-ink-800 w-full"/>
        <div className="h-1.5 rounded-full bg-ink-800 w-[88%]"/>
        <div className="h-1.5 rounded-full bg-ink-800 w-[72%]"/>
        <div className="h-1.5 rounded-full bg-cyan-500/40 w-[60%]"/>
      </div>
      <div className="flex items-center gap-1 pt-0.5"><div className="w-3 h-3 rounded-sm bg-cyan-500/30 border border-cyan-500/40"/><div className="text-[8px] text-cyan-300">Assinado ICP-Brasil</div></div>
    </div>
  );
}

function MiniAudio() {
  return (
    <div className="rounded-lg bg-ink-950 border border-ink-700/60 p-2" style={{ background: '#0A0F1C' }}>
      <svg viewBox="0 0 120 60" className="w-full">
        {[0,1,2,3,4].map(i => <line key={i} x1="10" y1={10+i*10} x2="115" y2={10+i*10} stroke="#1E293B" strokeWidth="0.5"/>)}
        <polyline points="15,15 30,18 50,22 70,28 90,38 110,48" fill="none" stroke="#F43F5E" strokeWidth="1.2"/>
        {[15,30,50,70,90,110].map((x,i) => <circle key={i} cx={x} cy={[15,18,22,28,38,48][i]} r="2" stroke="#F43F5E" strokeWidth="1" fill="none"/>)}
        <polyline points="15,12 30,15 50,18 70,24 90,32 110,42" fill="none" stroke="#0EA5E9" strokeWidth="1.2"/>
      </svg>
    </div>
  );
}

function MiniReceita() {
  return (
    <div className="rounded-lg bg-ink-950 border border-ink-700/60 p-2.5 space-y-1.5" style={{ background: '#0A0F1C' }}>
      {['Loratadina 10mg · 1cp/dia · 30 dias', 'Mometasona spray · 2x/dia', 'Dipirona 500mg · SOS'].map((t, i) => (
        <div key={i} className="flex items-start gap-1.5">
          <span className="w-3 h-3 rounded-sm bg-cyan-500/20 border border-cyan-500/40 flex-shrink-0 mt-0.5 flex items-center justify-center text-[7px] text-cyan-300">℞</span>
          <div className="text-[9px] text-ink-300 leading-tight">{t}</div>
        </div>
      ))}
    </div>
  );
}

function MiniFinanceiro() {
  return (
    <div className="rounded-lg bg-ink-950 border border-ink-700/60 p-2.5" style={{ background: '#0A0F1C' }}>
      <svg viewBox="0 0 120 50" className="w-full">
        {[24,32,28,38,30,42,36,48].map((h, i) => (
          <rect key={i} x={6 + i*14} y={50-h} width="8" height={h} rx="1" fill={i === 7 ? '#0EA5E9' : '#1E293B'}/>
        ))}
      </svg>
      <div className="flex items-center justify-between text-[9px] mt-1">
        <span className="text-ink-400">Líquido</span>
        <span className="font-mono font-semibold text-emerald-400">R$ 32.4k</span>
      </div>
    </div>
  );
}

function MiniIA() {
  return (
    <div className="rounded-lg bg-gradient-to-br from-cyan-500/10 to-brand-600/10 border border-cyan-500/20 p-2.5" style={{ background: 'linear-gradient(135deg, rgba(14,165,233,0.1), rgba(15,50,77,0.1))' }}>
      <div className="flex items-center gap-1.5 mb-1.5">
        <div className="w-4 h-4 rounded bg-gradient-to-br from-cyan-400 to-brand-600 flex items-center justify-center">
          <svg viewBox="0 0 24 24" className="w-2.5 h-2.5 text-white" fill="currentColor"><path d="m12 3-1.9 5.6L3 11.8l5.8 1.9L12 21l1.9-5.7L21 12l-5.8-1.9z"/></svg>
        </div>
        <div className="text-[9px] font-semibold text-cyan-300">Sugestão</div>
      </div>
      <div className="space-y-1 text-[9px] text-ink-200">
        <div className="flex justify-between"><span>H93.1 Zumbido</span><span className="text-cyan-300 tabular">92%</span></div>
        <div className="h-1 rounded-full bg-ink-800 overflow-hidden"><div className="h-full bg-cyan-400" style={{width: '92%'}}/></div>
      </div>
    </div>
  );
}

function MiniSUS() {
  return (
    <div className="rounded-lg bg-ink-950 border border-ink-700/60 p-2 grid grid-cols-3 gap-1" style={{ background: '#0A0F1C' }}>
      {['AIH', 'APAC', 'BPA-I', 'TISS-7', 'TISS-8', 'OPM'].map(t => (
        <div key={t} className="rounded text-[8px] text-center py-1 bg-brand-600/20 text-brand-200 border border-brand-500/20 font-mono">{t}</div>
      ))}
    </div>
  );
}

function MiniConvenio() {
  return (
    <div className="rounded-lg bg-ink-950 border border-ink-700/60 p-2 space-y-1" style={{ background: '#0A0F1C' }}>
      {[['Unimed', '60%'], ['Bradesco', '65%'], ['SUS', '100%']].map(([n,p]) => (
        <div key={n} className="flex items-center justify-between text-[9px]">
          <span className="text-ink-200">{n}</span>
          <span className="font-mono text-cyan-300">{p}</span>
        </div>
      ))}
    </div>
  );
}

function MiniEstoque() {
  return (
    <div className="rounded-lg bg-ink-950 border border-ink-700/60 p-2 space-y-1" style={{ background: '#0A0F1C' }}>
      {[['AASI Phonak Audéo P50', 12, 'ok'], ['Olivas silicone M', 3, 'low'], ['Otoscópio descartável', 87, 'ok']].map(([n, q, s]) => (
        <div key={n} className="flex items-center justify-between text-[9px]">
          <span className="text-ink-200 truncate flex-1">{n}</span>
          <span className={`font-mono tabular ${s === 'low' ? 'text-amber-400' : 'text-ink-300'}`}>{q}</span>
        </div>
      ))}
    </div>
  );
}

function MiniTV() {
  return (
    <div className="rounded-lg bg-gradient-to-br from-brand-700 to-brand-800 border border-brand-500/30 p-2.5 text-center">
      <div className="text-[7px] uppercase tracking-widest text-white/70">Senha</div>
      <div className="font-display font-bold text-cyan-300 tabular text-2xl leading-none">P-042</div>
      <div className="text-[8px] text-white/80 mt-0.5">Cons. 03</div>
    </div>
  );
}

function MiniMigracao() {
  return (
    <div className="rounded-lg bg-ink-950 border border-ink-700/60 p-2.5" style={{ background: '#0A0F1C' }}>
      <div className="flex items-center gap-1.5 mb-1.5">
        <span className="text-[9px] font-mono text-amber-400">Sistema antigo</span>
        <svg className="w-2.5 h-2.5 text-cyan-400" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M5 12h14M13 5l7 7-7 7"/></svg>
        <span className="text-[9px] font-mono text-cyan-300">Cliniset</span>
      </div>
      <div className="grid grid-cols-3 gap-1 text-[8px]">
        <div><div className="text-ink-400">Pacientes</div><div className="font-mono text-emerald-400">156k</div></div>
        <div><div className="text-ink-400">Agendas</div><div className="font-mono text-emerald-400">35k</div></div>
        <div><div className="text-ink-400">Docs</div><div className="font-mono text-emerald-400">340k</div></div>
      </div>
    </div>
  );
}

function MiniLGPD() {
  return (
    <div className="rounded-lg bg-ink-950 border border-ink-700/60 p-2.5 space-y-1.5" style={{ background: '#0A0F1C' }}>
      {['Schema isolado', 'Auditoria completa', 'Direito ao esquecimento'].map(t => (
        <div key={t} className="flex items-center gap-1.5 text-[9px] text-ink-200">
          <I.Check className="w-2.5 h-2.5 text-emerald-500"/>{t}
        </div>
      ))}
    </div>
  );
}

function MiniRoles() {
  const roles = [['DA', 'Dono', '#0EA5E9'], ['MD', 'Médico', '#10B981'], ['FN', 'Fono', '#F59E0B'], ['RC', 'Recep.', '#8B5CF6']];
  return (
    <div className="rounded-lg bg-ink-950 border border-ink-700/60 p-2 grid grid-cols-2 gap-1" style={{ background: '#0A0F1C' }}>
      {roles.map(([i, n, c]) => (
        <div key={n} className="flex items-center gap-1.5 px-1.5 py-1 rounded bg-ink-900">
          <div className="w-4 h-4 rounded text-[7px] flex items-center justify-center font-bold text-white" style={{ background: c }}>{i}</div>
          <span className="text-[9px] text-ink-200">{n}</span>
        </div>
      ))}
    </div>
  );
}

// Bento card primitive
function BentoCard({ icon, title, subtitle, bullets, span = '', mock, badge, accent = false }) {
  return (
    <div className={`group relative rounded-2xl border border-ink-200/70 dark:border-ink-800 bg-white dark:bg-ink-900/70 p-6 shadow-card hover:shadow-float dark:hover:shadow-float-dark hover:-translate-y-1 transition-all duration-300 overflow-hidden ${span} ${accent ? 'ring-1 ring-cyan-500/20' : ''}`}>
      {accent && <div className="absolute -top-20 -right-20 w-60 h-60 rounded-full bg-cyan-500/10 blur-3xl pointer-events-none"/>}
      <div className="relative flex items-start justify-between gap-4">
        <div className="flex items-center gap-2.5">
          <div className={`w-9 h-9 rounded-xl flex items-center justify-center ${accent ? 'bg-gradient-to-br from-cyan-400 to-brand-600 text-white' : 'bg-ink-100 dark:bg-ink-800 text-ink-700 dark:text-ink-200'}`}>{icon}</div>
          <div>
            <div className="text-[15px] font-semibold tracking-tight text-ink-900 dark:text-white">{title}</div>
            {subtitle && <div className="text-[11px] text-ink-500 dark:text-ink-400 mt-0.5">{subtitle}</div>}
          </div>
        </div>
        {badge}
      </div>
      {mock && <div className="relative mt-5">{mock}</div>}
      {bullets && (
        <ul className="relative mt-5 space-y-2">
          {bullets.map((b, i) => (
            <li key={i} className="flex items-start gap-2 text-[13px] text-ink-600 dark:text-ink-300 leading-snug">
              <I.Check className="w-3.5 h-3.5 text-emerald-500 mt-0.5 flex-shrink-0"/> <span>{b}</span>
            </li>
          ))}
        </ul>
      )}
    </div>
  );
}

function BentoGrid() {
  return (
    <Section_b id="funcionalidades" className="py-24 lg:py-32">
      <Container_b>
        <Reveal>
          <div className="max-w-3xl">
            <Eyebrow_b>Funcionalidades</Eyebrow_b>
            <h2 className="font-display font-bold text-[clamp(2rem,4.4vw,3.5rem)] tracking-tight leading-[1.05] mt-3 text-pretty">Tudo que uma clínica de Otorrino e Fono precisa. Em um só lugar.</h2>
            <p className="mt-4 text-[16px] text-ink-600 dark:text-ink-300 max-w-2xl">13 módulos integrados — agenda, prontuário, audiometria, repasse, IA Clínica, NFS-e. Sem add-ons, sem cobrança extra, sem integração frágil entre 4 sistemas.</p>
          </div>
        </Reveal>

        <Stagger_b className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4 mt-14" staggerChildren={0.06}>
          {/* Row 1 */}
          <StaggerItem_b className="lg:col-span-2 lg:row-span-2">
            <BentoCard
              icon={<I.Calendar className="w-4 h-4"/>}
              title="Agenda inteligente"
              subtitle="Multi-profissional · check-in · fila ao vivo"
              accent
              badge={<Pill_b tone="cyan">Destaque</Pill_b>}
              mock={<MiniAgenda/>}
              bullets={[
                'Cores estáveis por profissional, fila de atendimento ao vivo no header',
                'Status automático: ATRASADO 30 min após o horário, NO-SHOW no dia seguinte',
                'Check-in via QR Code, totem, WhatsApp ou recepção',
                'Confirmação por WhatsApp 1 dia antes (campanhas em massa)',
              ]}
            />
          </StaggerItem_b>
          <StaggerItem_b>
            <BentoCard
              icon={<I.FileText className="w-4 h-4"/>}
              title="Prontuário eletrônico"
              mock={<MiniProntuario/>}
              bullets={['Templates por especialidade', 'CID-10 nativo · ICP-Brasil', 'Histórico imutável após assinatura']}
            />
          </StaggerItem_b>
          <StaggerItem_b>
            <BentoCard
              icon={<I.Activity className="w-4 h-4"/>}
              title="Audiometria & Imitanciometria"
              mock={<MiniAudio/>}
              bullets={['Editor visual com gráfico interativo', 'Tritonal e classificação automática', 'Vídeo-laringo com timeline anotada']}
            />
          </StaggerItem_b>

          {/* Row 2 */}
          <StaggerItem_b>
            <BentoCard
              icon={<I.Pill className="w-4 h-4"/>}
              title="Receitas digitais"
              mock={<MiniReceita/>}
              bullets={['3.000+ medicamentos pré-cadastrados', 'Receituário simples + controlado', 'Modelos por médico (favoritos)']}
            />
          </StaggerItem_b>
          <StaggerItem_b>
            <BentoCard
              icon={<I.Stamp className="w-4 h-4"/>}
              title="Impressos SUS / TISS"
              mock={<MiniSUS/>}
              bullets={['AIH, APAC, BPA-I/C, OPM, FM', 'Guias 7/8/9 TISS · SP-SADT', 'Histórico legado preservado']}
            />
          </StaggerItem_b>

          {/* Row 3 — IA spans 2 */}
          <StaggerItem_b className="lg:col-span-2">
            <BentoCard
              icon={<I.Sparkles className="w-4 h-4"/>}
              title="IA Clínica"
              subtitle="Sugestões em tempo real — privadas, auditáveis"
              accent
              badge={<Pill_b tone="cyan">Novo · Claude</Pill_b>}
              mock={<MiniIA/>}
              bullets={[
                'Sugestões de evolução baseadas no histórico do paciente',
                'Auto-preenchimento de CID-10 a partir do texto livre',
                'Tradução de exames técnicos para linguagem do paciente',
                'Análise de risco e prioridade por sintomas',
              ]}
            />
          </StaggerItem_b>
          <StaggerItem_b>
            <BentoCard
              icon={<I.Building className="w-4 h-4"/>}
              title="Convênios & Tabelas"
              mock={<MiniConvenio/>}
              bullets={['ANS · contrato · reajuste em massa', 'Grupos de procedimento', 'SIGTAP, CBHPM, TUSS importadas']}
            />
          </StaggerItem_b>
          <StaggerItem_b>
            <BentoCard
              icon={<I.Wallet className="w-4 h-4"/>}
              title="Financeiro & Repasse"
              mock={<MiniFinanceiro/>}
              bullets={['Regra prioritária: procedimento → grupo → tipo', 'Fechamento mensal com snapshot imutável', 'NFS-e municipal (emissão · cancelamento)']}
            />
          </StaggerItem_b>

          {/* Row 4 */}
          <StaggerItem_b>
            <BentoCard
              icon={<I.Box className="w-4 h-4"/>}
              title="Estoque"
              mock={<MiniEstoque/>}
              bullets={['Lote e validade', 'Alerta de estoque mínimo', 'Movimentações com histórico']}
            />
          </StaggerItem_b>
          <StaggerItem_b>
            <BentoCard
              icon={<I.Tv className="w-4 h-4"/>}
              title="Painel TV"
              mock={<MiniTV/>}
              bullets={['Chamada por TV com som', 'Senha por tipo (consulta/prioridade)', 'QR Code do paciente em tela']}
            />
          </StaggerItem_b>
          <StaggerItem_b>
            <BentoCard
              icon={<I.Database className="w-4 h-4"/>}
              title="Migração total"
              subtitle="Do sistema antigo, em poucas semanas"
              mock={<MiniMigracao/>}
              bullets={['Importação completa do sistema antigo', '156k pacientes · 340k documentos legados', 'Zero downtime, zero perda']}
            />
          </StaggerItem_b>
          <StaggerItem_b>
            <BentoCard
              icon={<I.Shield className="w-4 h-4"/>}
              title="Privacidade & LGPD"
              mock={<MiniLGPD/>}
              bullets={['Dados isolados por clínica', 'Auditoria de acessos', 'Exportação e exclusão de dados']}
            />
          </StaggerItem_b>
          <StaggerItem_b className="lg:col-span-2">
            <BentoCard
              icon={<I.Users className="w-4 h-4"/>}
              title="Permissões granulares"
              subtitle="Papéis customizáveis por clínica"
              mock={<MiniRoles/>}
              bullets={[
                'Dono, Admin, Médico, Fono, Recepção, Financeiro, Estagiário',
                'Flag "Profissional Executante" independente do papel — Owner que atende, Admin que não',
              ]}
            />
          </StaggerItem_b>
        </Stagger_b>
      </Container_b>
    </Section_b>
  );
}

window.SectionsBento = { BentoGrid };
