/* ============================================================
   AILayers.jsx — "Uma camada de IA conectada à operação da
   sua empresa". Arquitetura vertical em 5 camadas conectadas
   por uma espinha dorsal de dados (nós luminosos + pulso).
   Densidade reduzida + divulgação progressiva. id="solucoes".
   ============================================================ */

const LAYERS = [
  {
    n: '01', key: 'canais', title: 'Canais de entrada',
    desc: 'Onde as conversas e solicitações começam.',
    tone: 'cyan',
    items: [
      { i: 'message-circle', t: 'WhatsApp' },
      { i: 'camera', t: 'Instagram' },
      { i: 'globe', t: 'Site' },
      { i: 'mail', t: 'E-mail' },
    ],
    more: [
      { i: 'send', t: 'Telegram' },
      { i: 'phone', t: 'Telefone' },
      { i: 'message-square', t: 'SMS' },
    ],
    moreLabel: 'Ver outros canais',
  },
  {
    n: '02', key: 'ia', title: 'Camada de inteligência',
    desc: 'Compreende, contextualiza e decide.',
    tone: 'core', core: true, status: 'IA em operação',
    items: [
      { i: 'bot', t: 'Agente AR' },
      { i: 'brain', t: 'Memória' },
      { i: 'layers', t: 'Contexto' },
      { i: 'list-checks', t: 'Regras' },
    ],
    more: [
      { i: 'scan-search', t: 'Análise de intenção' },
      { i: 'shield-check', t: 'Validações' },
    ],
    moreLabel: 'Ver capacidades',
  },
  {
    n: '03', key: 'integra', title: 'Automação e integração',
    desc: 'Conecta a IA às ferramentas da empresa.',
    tone: 'cyan',
    items: [
      { i: 'braces', t: 'APIs' },
      { i: 'webhook', t: 'Webhooks' },
      { i: 'workflow', t: 'n8n' },
      { i: 'database', t: 'Banco de dados' },
    ],
    seal: 'Dados protegidos e acessos controlados',
  },
  {
    n: '04', key: 'operacao', title: 'Sistemas da operação',
    desc: 'Onde o trabalho realmente acontece.',
    tone: 'blue',
    items: [
      { i: 'contact', t: 'CRM' },
      { i: 'calendar', t: 'Agenda' },
      { i: 'wallet', t: 'Financeiro' },
      { i: 'file-text', t: 'Documentos' },
    ],
    more: [
      { i: 'building-2', t: 'ERP' },
      { i: 'trending-up', t: 'Vendas' },
      { i: 'package', t: 'Estoque' },
      { i: 'layout-dashboard', t: 'Dashboards' },
    ],
    moreLabel: 'Ver mais sistemas',
  },
  {
    n: '05', key: 'resultados', title: 'Resultados operacionais',
    desc: 'O que a inteligência entrega para a empresa.',
    tone: 'green',
    items: [
      { i: 'user-check', t: 'Lead qualificado' },
      { i: 'calendar-check', t: 'Agendamento' },
      { i: 'bell-ring', t: 'Follow-up' },
      { i: 'bar-chart-3', t: 'Indicadores' },
    ],
    micro: 'CRM atualizado',
  },
];

const TONES = {
  cyan:  { accent: '#00D4FF', soft: 'rgba(0,212,255,0.12)' },
  blue:  { accent: '#4C9BFF', soft: 'rgba(0,94,255,0.14)' },
  core:  { accent: '#3D8BFF', soft: 'rgba(0,94,255,0.16)' },
  green: { accent: '#1FD17B', soft: 'rgba(31,209,123,0.14)' },
};

const AILayers = () => {
  const [open, setOpen] = React.useState({});
  React.useEffect(() => { window.lucide && window.lucide.createIcons(); });

  const toggle = (k) => setOpen(o => ({ ...o, [k]: !o[k] }));

  return (
    <section id="solucoes" style={{
      background: `radial-gradient(1100px 640px at 82% 16%, rgba(0,94,255,0.10), transparent 62%),
                   radial-gradient(820px 540px at 8% 6%, rgba(0,212,255,0.06), transparent 64%),
                   var(--ar-bg-section)`,
      padding: '116px 0', position: 'relative', overflow: 'hidden', marginTop: -1,
    }}>
      <Container style={{ position: 'relative' }}>
        <SectionHead
          align="center" maxWidth={780}
          eyebrow="ARQUITETURA DE IA CONECTADA"
          title={<>Uma camada de IA conectada à <GradText>operação da sua empresa</GradText></>}
          sub="Canais, inteligência, automações e sistemas trabalhando juntos — com contexto, controle e resultados mensuráveis."
        />

        <div className="ail-arch">
          {LAYERS.map((layer, i) => (
            <Reveal key={layer.key} delay={i * 60} style={{ width: '100%' }}>
              <LayerRow
                layer={layer}
                last={i === LAYERS.length - 1}
                toGreen={i === LAYERS.length - 2}
                isOpen={!!open[layer.key]}
                onToggle={() => toggle(layer.key)}
              />
            </Reveal>
          ))}
        </div>
      </Container>

      <style>{`
        .ail-arch { max-width: 1080px; margin: 56px auto 0; }
        .ail-row { display: grid; grid-template-columns: 66px 1fr; gap: 22px; align-items: stretch; }

        /* ---- espinha dorsal ---- */
        .ail-rail { position: relative; display: flex; justify-content: center; padding-top: 16px; }
        .ail-line { position: absolute; top: 30px; bottom: -20px; left: 50%; transform: translateX(-50%); width: 2px; border-radius: 2px; }
        .ail-node {
          position: relative; z-index: 2; width: 52px; height: 52px; border-radius: 999px;
          display: flex; align-items: center; justify-content: center; flex-shrink: 0;
          font-family: var(--ar-font-title); font-weight: 800; font-size: 19px; line-height: 1;
          background: #070B16;
        }
        .ail-pulse {
          position: absolute; left: 50%; top: 30px; width: 6px; height: 6px; margin-left: -3px;
          border-radius: 999px; opacity: 0; z-index: 1;
          animation: ailPulse 2.8s var(--ar-ease) infinite;
        }
        @keyframes ailPulse {
          0% { top: 30px; opacity: 0; }
          12% { opacity: 1; }
          88% { opacity: 1; }
          100% { top: 100%; opacity: 0; }
        }

        /* ---- painel da camada ---- */
        .ail-panel {
          border-radius: 20px; padding: 26px 28px;
          background: rgba(255,255,255,0.018);
          border: 1px solid rgba(255,255,255,0.075);
          transition: border-color 240ms var(--ar-ease), transform 240ms var(--ar-ease), background 240ms;
        }
        .ail-panel:hover { transform: translateY(-2px); border-color: rgba(0,94,255,0.5); box-shadow: 0 0 46px -16px rgba(0,94,255,0.55); }
        .ail-panel.core {
          background: linear-gradient(135deg, rgba(0,94,255,0.10), rgba(255,255,255,0.02));
          border-color: rgba(0,94,255,0.42);
          box-shadow: 0 0 48px -20px rgba(0,94,255,0.5);
        }
        .ail-panel.core:hover { border-color: rgba(0,94,255,0.6); }

        .ail-titlerow { display: flex; align-items: center; gap: 12px; flex-wrap: wrap; }
        .ail-title { font-family: var(--ar-font-title); font-weight: 700; font-size: 19px; letter-spacing: -0.01em; color: var(--ar-text-main); }
        .ail-desc { font-family: var(--ar-font-body); font-size: 15px; color: var(--ar-text-muted); margin: 5px 0 0; }

        /* ---- chips ---- */
        .ail-chips { display: flex; flex-wrap: wrap; gap: 10px; margin-top: 18px; }
        .ail-chip {
          display: inline-flex; align-items: center; gap: 9px;
          padding: 9px 14px; border-radius: 12px;
          background: rgba(255,255,255,0.04); border: 1px solid rgba(255,255,255,0.06);
          font-family: var(--ar-font-body); font-size: 14px; font-weight: 500; color: var(--ar-text-main);
          transition: background 200ms, border-color 200ms;
        }
        .ail-chip:hover { background: rgba(255,255,255,0.07); }
        .ail-chip i { width: 16px; height: 16px; flex-shrink: 0; }

        /* ---- divulgação progressiva ---- */
        .ail-extra-in { animation: ailFade 320ms var(--ar-ease) both; }
        @keyframes ailFade { from { opacity: 0; transform: translateY(-6px); } to { opacity: 1; transform: none; } }
        .ail-more-btn {
          display: inline-flex; align-items: center; gap: 7px; margin-top: 14px;
          background: none; border: none; cursor: pointer; padding: 4px 2px;
          font-family: var(--ar-font-body); font-size: 14px; font-weight: 600; color: var(--ar-cyan);
          transition: gap 180ms;
        }
        .ail-more-btn:hover { gap: 10px; }
        .ail-more-btn i { width: 16px; height: 16px; transition: transform 280ms var(--ar-ease); }
        .ail-more-btn[aria-expanded="true"] i { transform: rotate(180deg); }
        .ail-more-btn:focus-visible { outline: 2px solid var(--ar-cyan); outline-offset: 3px; border-radius: 6px; }

        /* ---- selos / status ---- */
        .ail-status {
          display: inline-flex; align-items: center; gap: 8px; padding: 6px 12px; border-radius: 999px;
          background: rgba(31,209,123,0.10); border: 1px solid rgba(31,209,123,0.30);
          font-family: var(--ar-font-body); font-size: 13px; font-weight: 600; color: #5BE3A8;
        }
        .ail-status .dot { width: 7px; height: 7px; border-radius: 999px; background: #1FD17B; box-shadow: 0 0 8px #1FD17B; animation: ailBlink 2.4s ease-in-out infinite; }
        @keyframes ailBlink { 0%,100% { opacity: 1; } 50% { opacity: 0.35; } }
        .ail-seal {
          display: inline-flex; align-items: center; gap: 9px; margin-top: 16px;
          font-family: var(--ar-font-body); font-size: 13px; color: var(--ar-text-muted);
        }
        .ail-seal i { width: 15px; height: 15px; color: #00D4FF; }
        .ail-micro {
          display: inline-flex; align-items: center; gap: 7px; margin-top: 14px;
          font-family: var(--ar-font-body); font-size: 13px; color: #5BE3A8;
        }
        .ail-micro i { width: 14px; height: 14px; }

        /* ---- responsivo ---- */
        @media (max-width: 720px) {
          .ail-arch { margin-top: 40px; }
          .ail-row { grid-template-columns: 46px 1fr; gap: 16px; }
          .ail-node { width: 40px; height: 40px; font-size: 16px; }
          .ail-line { top: 24px; }
          .ail-pulse { top: 24px; }
          .ail-panel { padding: 20px 18px; border-radius: 18px; }
          .ail-title { font-size: 17px; }
          .ail-chips { gap: 8px; }
          .ail-chip { padding: 8px 12px; font-size: 13.5px; }
        }
        @media (prefers-reduced-motion: reduce) {
          .ail-pulse, .ail-status .dot { animation: none !important; }
          .ail-pulse { display: none; }
          .ail-extra-in { animation: none !important; }
        }
      `}</style>
    </section>
  );
};

const LayerRow = ({ layer, last, toGreen, isOpen, onToggle }) => {
  const { accent } = TONES[layer.tone];
  const core = layer.core;
  const lineColor = toGreen
    ? 'linear-gradient(to bottom, rgba(0,212,255,0.4), rgba(31,209,123,0.5))'
    : 'linear-gradient(to bottom, rgba(0,212,255,0.4), rgba(0,212,255,0.12))';
  const pulseColor = toGreen ? '#1FD17B' : '#00D4FF';

  const nodeStyle = core
    ? { background: 'linear-gradient(135deg,#005EFF,#00D4FF)', color: '#fff', border: 'none', boxShadow: '0 0 20px -2px rgba(0,212,255,0.6)' }
    : { color: accent, border: `1.5px solid ${accent}`, boxShadow: `0 0 0 5px rgba(7,11,22,1), 0 0 16px -4px ${accent}` };

  const moreId = `ail-extra-${layer.key}`;

  return (
    <div className="ail-row">
      <div className="ail-rail">
        {!last && <span className="ail-line" style={{ background: lineColor }} />}
        {!last && <span className="ail-pulse" style={{ background: pulseColor, boxShadow: `0 0 10px ${pulseColor}`, animationDelay: `${(parseInt(layer.n, 10) - 1) * 0.45}s` }} />}
        <span className="ail-node" style={nodeStyle}>{layer.n}</span>
      </div>

      <div className={'ail-panel' + (core ? ' core' : '')}>
        <div className="ail-head">
          <div className="ail-titlerow">
            <span className="ail-title">{layer.title}</span>
            {layer.status && (
              <span className="ail-status"><span className="dot" />{layer.status}</span>
            )}
          </div>
          <p className="ail-desc">{layer.desc}</p>
        </div>

        <div className="ail-chips">
          {layer.items.map(it => <ChipItem key={it.t} it={it} accent={accent} core={core} />)}
        </div>

        {layer.more && (
          <React.Fragment>
            <button className="ail-more-btn" aria-expanded={isOpen} aria-controls={moreId} onClick={onToggle}>
              {isOpen ? 'Ver menos' : layer.moreLabel}
              <i data-lucide="chevron-down"></i>
            </button>
            {isOpen && (
              <div id={moreId} className="ail-chips ail-extra-in" style={{ marginTop: 12 }}>
                {layer.more.map(it => <ChipItem key={it.t} it={it} accent={accent} core={core} />)}
              </div>
            )}
          </React.Fragment>
        )}

        {layer.seal && (
          <div className="ail-seal"><i data-lucide="shield-check"></i>{layer.seal}</div>
        )}
        {layer.micro && (
          <div className="ail-micro"><i data-lucide="refresh-cw"></i>{layer.micro}</div>
        )}
      </div>
    </div>
  );
};

const ChipItem = ({ it, accent, core }) => (
  <span className="ail-chip">
    <i data-lucide={it.i} style={{ color: core ? '#7CC4FF' : accent }}></i>
    {it.t}
  </span>
);

window.AILayers = AILayers;
