// hero-orbit-cinematic.jsx — Hero "buraco negro" cinematográfico.
//
// Layout estático aqui (DOM + posições iniciais via CSS custom props).
// A coreografia (timeline GSAP — atração → sucção → reveal → loop) vive em
// `animations.js` via `window.FH.buildCinematicHero(stageEl, { variant })`.
//
// Ícones reais (não emoji) do diretório `assets/tools/` — ferramentas
// paralelas que o flipper usa hoje no dia a dia (planilhas, WhatsApp,
// portais, CRMs, drives, AI, etc.) que serão consolidadas no Flipper Hub.

function HeroOrbitCinematic({ variant = 'blackHole' }) {
  const stageRef = React.useRef(null);

  // 30 ferramentas (TODAS as fornecidas) distribuídas em 3 anéis
  // concêntricos com offsets entre anéis pra reduzir alinhamento visual.
  //
  //   Inner (r=145): 8 tools — 45° entre cada
  //   Mid   (r=215): 11 tools — ~32.7° entre cada, offset 22° vs inner
  //   Outer (r=285): 11 tools — ~32.7° entre cada, offset 8° vs inner
  //
  // Os 8 primeiros (inner) são os mais reconhecíveis e absorvidos um a
  // um durante a sucção sequencial. Os outros 22 imploram juntos.
  const tools = [
    // Inner ring — 8 ícones mais icônicos
    { key: 'wa',      name: 'WhatsApp',     icon: 'whatsapp.jpg',         angle:   0, r: 145, depth: 0 },
    { key: 'excel',   name: 'Excel',        icon: 'excel.png',            angle:  45, r: 145, depth: 0 },
    { key: 'gd',      name: 'Drive',        icon: 'google_drive.png',     angle:  90, r: 145, depth: 0 },
    { key: 'pdf',     name: 'PDF',          icon: 'adobe_pdf.png',        angle: 135, r: 145, depth: 0 },
    { key: 'pix',     name: 'Pix',          icon: 'pix.png',              angle: 180, r: 145, depth: 0 },
    { key: 'word',    name: 'Word',         icon: 'word.png',             angle: 225, r: 145, depth: 0 },
    { key: 'gcal',    name: 'Calendar',     icon: 'google_calendar.png',  angle: 270, r: 145, depth: 0 },
    { key: 'mail',    name: 'E-mail',       icon: 'email.webp',           angle: 315, r: 145, depth: 0 },
    // Mid ring (11 tools)
    { key: 'gmaps',   name: 'Maps',         icon: 'google_maps.png',      angle:  22, r: 215, depth: 1 },
    { key: 'tg',      name: 'Telegram',     icon: 'telegram.jpeg',        angle:  55, r: 215, depth: 1 },
    { key: 'inst',    name: 'Instagram',    icon: 'instagram.png',        angle:  87, r: 215, depth: 1 },
    { key: 'fb',      name: 'Facebook',     icon: 'facebook.webp',        angle: 120, r: 215, depth: 1 },
    { key: 'olx',     name: 'OLX',          icon: 'olx.png',              angle: 152, r: 215, depth: 1 },
    { key: 'viva',    name: 'Viva Real',    icon: 'viva_real.png',        angle: 185, r: 215, depth: 1 },
    { key: 'zap',     name: 'Zap',          icon: 'zap.jpg',              angle: 218, r: 215, depth: 1 },
    { key: 'chaves',  name: 'Chaves Mão',   icon: 'chaves_na_mao.png',    angle: 250, r: 215, depth: 1 },
    { key: 'monday',  name: 'Monday',       icon: 'monday_crm.webp',      angle: 282, r: 215, depth: 1 },
    { key: 'asana',   name: 'Asana',        icon: 'asana_crm.png',        angle: 315, r: 215, depth: 1 },
    { key: 'click',   name: 'ClickUp',      icon: 'click_up_crm.png',     angle: 348, r: 215, depth: 1 },
    // Outer ring (11 tools)
    { key: 'notas',   name: 'Notas',        icon: 'notas_apple.png',      angle:   8, r: 285, depth: 2 },
    { key: 'canva',   name: 'Canva',        icon: 'canva.png',            angle:  41, r: 285, depth: 2 },
    { key: 'dbox',    name: 'Dropbox',      icon: 'dropbox.png',          angle:  74, r: 285, depth: 2 },
    { key: 'odrive',  name: 'OneDrive',     icon: 'one_drive.webp',       angle: 107, r: 285, depth: 2 },
    { key: 'gpt',     name: 'GPT',          icon: 'gpt.jpg',              angle: 140, r: 285, depth: 2 },
    { key: 'ibge',    name: 'IBGE',         icon: 'ibge.jpg',             angle: 173, r: 285, depth: 2 },
    { key: 'azul',    name: 'Conta Azul',   icon: 'conta_azul.png',       angle: 205, r: 285, depth: 2 },
    { key: 'omie',    name: 'Omie',         icon: 'omie.png',             angle: 238, r: 285, depth: 2 },
    { key: 'split',   name: 'Splitwise',    icon: 'split_wise.png',       angle: 270, r: 285, depth: 2 },
    { key: 'autent',  name: 'Autentique',   icon: 'autentique.webp',      angle: 303, r: 285, depth: 2 },
    { key: 'trello',  name: 'Trello',       icon: 'trello.png',           angle: 336, r: 285, depth: 2 },
  ];

  // Cards do reveal final (features unificadas do Flipper Hub).
  // Cada um tem ícone, label e hint — visual estilo Linear/Stripe sidebar.
  const Icons = (window.Icons || {});
  const features = [
    { key: 'garimpo', label: 'Garimpo',    hint: 'Listagens, leilões e oportunidades em uma única vista', icon: Icons.IconSearch },
    { key: 'doc',     label: 'Jurídico',   hint: 'Matrícula, ITBI, escritura e contratos rastreados',      icon: Icons.IconShield },
    { key: 'fin',     label: 'Financeiro', hint: 'Aportes, custos, repasses e margem por imóvel',          icon: Icons.IconCoins },
    { key: 'obra',    label: 'Reforma',    hint: 'Cronograma, custos e prestadores acompanhados',          icon: Icons.IconHammer },
    { key: 'crm',     label: 'Comercial',  hint: 'Leads, propostas e parceiros conectados ao ativo',       icon: Icons.IconHandshake },
    { key: 'res',     label: 'Resultado',  hint: 'TIR, ROI e fluxo de caixa real, em tempo real',          icon: Icons.IconChart },
  ];

  // Boot timeline GSAP quando o stage monta ou variant muda.
  React.useEffect(() => {
    if (!stageRef.current || !window.FH || !window.FH.buildCinematicHero) return;
    const teardown = window.FH.buildCinematicHero(stageRef.current, { variant });
    return teardown;
  }, [variant]);

  return (
    <div ref={stageRef} className="hoc-stage" data-variant={variant} aria-hidden="true">
      {/* Ambient atmosphere — gradient azul + ruído */}
      <div className="hoc-bg" />
      <div className="hoc-grain" />

      {/* Event horizon — anéis sutis de distorção em volta do logo */}
      <div className="hoc-event-horizon">
        <span className="eh-ring eh-r1" />
        <span className="eh-ring eh-r2" />
        <span className="eh-ring eh-r3" />
      </div>

      {/* Linhas de gravidade — SVG paths que conectam ferramentas ao centro,
          desenhados em arco. GSAP anima drawSVG / opacity por linha. */}
      <svg className="hoc-gravity" viewBox="-450 -450 900 900" preserveAspectRatio="xMidYMid meet">
        <defs>
          <radialGradient id="grav-fade" cx="50%" cy="50%" r="50%">
            <stop offset="0%"  stopColor="rgba(58,130,246,0.55)" />
            <stop offset="60%" stopColor="rgba(58,130,246,0.20)" />
            <stop offset="100%" stopColor="rgba(58,130,246,0)" />
          </radialGradient>
        </defs>
        {tools.map((t) => {
          const rad = (t.angle * Math.PI) / 180;
          const x = Math.cos(rad) * t.r;
          const y = Math.sin(rad) * t.r;
          // Curva (quadratic) — control point bowed perpendicular pra dar arco.
          const perpX = -Math.sin(rad) * 80;
          const perpY = Math.cos(rad) * 80;
          const cx = x * 0.5 + perpX;
          const cy = y * 0.5 + perpY;
          return (
            <path
              key={t.key}
              d={`M ${x.toFixed(1)} ${y.toFixed(1)} Q ${cx.toFixed(1)} ${cy.toFixed(1)} 0 0`}
              className="hoc-grav-line"
              data-key={t.key}
              fill="none"
              stroke="url(#grav-fade)"
              strokeWidth="1.2"
            />
          );
        })}
      </svg>

      {/* Halos de impacto — disparam a cada absorção */}
      <div className="hoc-halo h1" />
      <div className="hoc-halo h2" />
      <div className="hoc-halo h3" />
      <div className="hoc-halo h4" />

      {/* Logo central — Flipper Hub.
          DOM aninhado para separar transformações:
          .hoc-logo       → posição
          .hoc-logo-scale → crescimento contínuo (single tween, smooth)
          .hoc-logo-bump  → bump sutil a cada absorção (overlay sobre o scale)
          Os scales se multiplicam → bump nunca briga com o crescimento.
          .hoc-logo-wordmark → "Flipper Hub" emerge ao lado no climax. */}
      <div className="hoc-logo">
        <div className="hoc-logo-scale">
          <div className="hoc-logo-bump">
            <div className="hoc-logo-row">
              <div className="hoc-logo-inner">
                <img src="assets/logo-app-icon-blue.png" alt="" />
              </div>
              <div className="hoc-logo-wordmark">Flipper Hub</div>
            </div>
            <div className="hoc-logo-flare" />
          </div>
        </div>
      </div>

      {/* Ferramentas orbitando + sendo absorvidas */}
      <div className="hoc-tools">
        {tools.map((t) => {
          const rad = (t.angle * Math.PI) / 180;
          const x = Math.cos(rad) * t.r;
          const y = Math.sin(rad) * t.r;
          return (
            <div
              key={t.key}
              className={`hoc-tool depth-${t.depth}`}
              data-key={t.key}
              style={{ '--x': `${x.toFixed(1)}px`, '--y': `${y.toFixed(1)}px` }}>
              <div className="hoc-tool-icon">
                <img src={`assets/tools/${t.icon}`} alt={t.name} draggable="false" />
              </div>
            </div>
          );
        })}
      </div>

      {/* Reveal — logo dockado à esquerda + cards de features à direita.
          Sem headline duplicada (a H1 do hero já fala). */}
      <div className="hoc-reveal">
        <div className="hoc-feature-grid">
          {features.map((f, i) => {
            const Ico = f.icon;
            return (
              <div key={f.key} className="hoc-feature" style={{ '--i': i }}>
                <div className="hoc-feature-ico">{Ico ? <Ico size={16} /> : null}</div>
                <div className="hoc-feature-body">
                  <div className="t">{f.label}</div>
                  <div className="h">{f.hint}</div>
                </div>
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
}

window.HeroOrbitCinematic = HeroOrbitCinematic;
