// manifesto.jsx — Section 2: sticky scroll reveal
// 4 panels left / sticky visual right that swaps per panel

const PANELS = [
  {
    n: '01',
    kicker: 'Méthode',
    title: 'Le métier définit l’outil, jamais l’inverse.',
    body: 'La majorité des solutions du marché imposent leur logique à votre organisation. Notre approche prend le chemin contraire : nous analysons vos processus, modélisons votre donnée, puis concevons un outil parfaitement aligné sur votre métier — sans dette technique de configuration.',
    visual: 'compare',
  },
  {
    n: '02',
    kicker: 'Exécution',
    title: 'Un code lisible, documenté, pérenne.',
    body: 'TypeScript, Cloudflare Workers, Airtable comme source de vérité. Pas de framework superflu, pas de sur-ingénierie. Un code revu, testé et versionné, qui peut être repris par toute équipe technique sans rupture de service.',
    visual: 'code',
  },
  {
    n: '03',
    kicker: 'Système',
    title: 'Des infrastructures qui fonctionnent en autonomie.',
    body: 'Une fois en production, l’infrastructure opère sans intervention manuelle. Webhooks, tâches planifiées, supervision continue : vos équipes utilisent l’outil, vos données restent intègres, vos automatisations s’exécutent en continu.',
    visual: 'arch',
  },
  {
    n: '04',
    kicker: 'Format',
    title: 'Un interlocuteur unique, du brief à la production.',
    body: 'Pas de chef de projet à relancer, pas de sous-traitance opaque. Vous échangez directement avec la personne qui conçoit, développe et déploie votre solution. Cycle court, décisions rapides, qualité maîtrisée.',
    visual: 'timeline',
  },
];

// ── Visuals ─────────────────────────────────────────────────────────────────

function VisualCompare() {
  return (
    <div className="vis vis-compare">
      <div className="vis-frame vis-bad">
        <div className="vis-frame-h">
          <span className="vis-tag mono">SaaS générique</span>
          <span className="vis-tag-x mono">14 onglets · 18 % utilisés</span>
        </div>
        <div className="vis-bad-grid">
          {Array.from({length: 18}).map((_, i) => (
            <div key={i} className={`vis-bad-cell ${i % 5 === 0 ? 'used' : ''}`}></div>
          ))}
        </div>
        <div className="vis-frame-foot mono dim">configurations.json · 2.4 MB</div>
      </div>

      <div className="vis-divider">
        <span className="vis-vs mono">vs</span>
      </div>

      <div className="vis-frame vis-good">
        <div className="vis-frame-h">
          <span className="vis-tag mono">Application sur-mesure</span>
          <span className="vis-tag-x mono accent">3 vues · 100 % utilisées</span>
        </div>
        <div className="vis-good-rows">
          <div className="vgood-row">
            <span className="vgood-dot"></span>
            <span className="vgood-label">Pipeline commercial</span>
            <span className="vgood-bar" style={{width: '78%'}}></span>
          </div>
          <div className="vgood-row">
            <span className="vgood-dot"></span>
            <span className="vgood-label">Recommandations</span>
            <span className="vgood-bar" style={{width: '54%'}}></span>
          </div>
          <div className="vgood-row">
            <span className="vgood-dot"></span>
            <span className="vgood-label">Nurturing automatisé</span>
            <span className="vgood-bar" style={{width: '92%'}}></span>
          </div>
          <div className="vgood-row">
            <span className="vgood-dot"></span>
            <span className="vgood-label">Suivi clients</span>
            <span className="vgood-bar" style={{width: '67%'}}></span>
          </div>
        </div>
        <div className="vis-frame-foot mono accent">aligné sur le métier · zéro documentation requise</div>
      </div>
    </div>
  );
}

function VisualCode() {
  const lines = [
    [['kw', 'export'], ['k', ' '], ['kw', 'async'], ['k', ' '], ['kw', 'function'], ['k', ' '], ['fn', 'syncContact'], ['p', '(payload) {']],
    [['k', '  '], ['kw', 'const'], ['k', ' '], ['var', 'record'], ['k', ' = '], ['kw', 'await'], ['k', ' '], ['lib', 'airtable'], ['k', '.upsert({']],
    [['k', '    '], ['prop', 'email'], ['k', ': payload.email,']],
    [['k', '    '], ['prop', 'pipeline'], ['k', ': '], ['str', '\'qualified\''], ['k', ',']],
    [['k', '    '], ['prop', 'lastSeen'], ['k', ': '], ['kw', 'new'], ['k', ' '], ['fn', 'Date'], ['k', '().toISOString(),']],
    [['k', '  });']],
    [['k', '']],
    [['k', '  '], ['kw', 'await'], ['k', ' '], ['lib', 'hubspot'], ['k', '.contacts.update(record.id, {']],
    [['k', '    '], ['prop', 'lifecyclestage'], ['k', ': '], ['str', '\'opportunity\''], ['k', ',']],
    [['k', '  });']],
    [['k', '']],
    [['k', '  '], ['kw', 'return'], ['k', ' { '], ['prop', 'ok'], ['k', ': '], ['lit', 'true'], ['k', ' };']],
    [['k', '}']],
  ];
  return (
    <div className="vis vis-code">
      <div className="code-window">
        <div className="code-h">
          <span className="dots"><i></i><i></i><i></i></span>
          <span className="code-tab mono">workers/sync-contact.ts</span>
          <span className="code-status mono"><span className="green-dot"></span> deployed</span>
        </div>
        <div className="code-body">
          {lines.map((line, i) => (
            <div key={i} className="code-line">
              <span className="code-ln mono">{String(i+1).padStart(2,'0')}</span>
              <span className="code-content mono">
                {line.map((tok, j) => <span key={j} className={`tok-${tok[0]}`}>{tok[1]}</span>)}
              </span>
            </div>
          ))}
        </div>
        <div className="code-foot mono">
          <span><span className="green-dot"></span> 0 errors</span>
          <span className="dim">·</span>
          <span className="dim">98 lines</span>
          <span className="dim">·</span>
          <span className="dim">TypeScript</span>
        </div>
      </div>
    </div>
  );
}

function VisualArch() {
  // Cloudflare worker at center, satellites around
  const sats = [
    { id: 'airtable', label: 'Airtable',     angle: -90, dist: 130 },
    { id: 'hubspot',  label: 'HubSpot',      angle: -18, dist: 130 },
    { id: 'webflow',  label: 'Webflow',      angle: 54,  dist: 130 },
    { id: 'fillout',  label: 'Fillout',      angle: 126, dist: 130 },
    { id: 'mail',     label: 'Resend',       angle: 198, dist: 130 },
  ];
  return (
    <div className="vis vis-arch">
      <svg viewBox="-200 -200 400 400" className="arch-svg">
        <defs>
          <radialGradient id="hub-glow">
            <stop offset="0%" stopColor="var(--accent)" stopOpacity="0.5" />
            <stop offset="60%" stopColor="var(--accent)" stopOpacity="0.08" />
            <stop offset="100%" stopColor="var(--accent)" stopOpacity="0" />
          </radialGradient>
          <linearGradient id="link-grad" x1="0" x2="1">
            <stop offset="0%" stopColor="var(--accent)" stopOpacity="0.7" />
            <stop offset="100%" stopColor="var(--accent)" stopOpacity="0.05" />
          </linearGradient>
        </defs>

        {/* Glow */}
        <circle cx="0" cy="0" r="160" fill="url(#hub-glow)" />

        {/* Orbits */}
        <circle cx="0" cy="0" r="130" fill="none" stroke="rgba(255,255,255,0.06)" strokeDasharray="2 4" />
        <circle cx="0" cy="0" r="80"  fill="none" stroke="rgba(255,255,255,0.05)" strokeDasharray="2 4" />

        {/* Links */}
        {sats.map((s) => {
          const x = Math.cos((s.angle * Math.PI) / 180) * s.dist;
          const y = Math.sin((s.angle * Math.PI) / 180) * s.dist;
          return (
            <g key={s.id}>
              <line x1="0" y1="0" x2={x} y2={y} stroke="url(#link-grad)" strokeWidth="1" />
              <circle cx={x} cy={y} r="3" fill="var(--accent)">
                <animate attributeName="opacity" values="0.4;1;0.4" dur="2.4s"
                         begin={`${(sats.indexOf(s) * 0.4)}s`} repeatCount="indefinite" />
              </circle>
            </g>
          );
        })}

        {/* Hub */}
        <g>
          <rect x="-46" y="-22" width="92" height="44" rx="8"
                fill="rgba(168,85,247,0.12)" stroke="var(--accent)" strokeWidth="1" />
          <text x="0" y="-3" textAnchor="middle" fontSize="9" fill="#fafafa"
                fontFamily="Geist Mono" letterSpacing="0.04em">CF · WORKER</text>
          <text x="0" y="11" textAnchor="middle" fontSize="7" fill="#a1a1aa"
                fontFamily="Geist Mono">routes / cron / queue</text>
        </g>

        {/* Satellite labels */}
        {sats.map((s) => {
          const x = Math.cos((s.angle * Math.PI) / 180) * s.dist;
          const y = Math.sin((s.angle * Math.PI) / 180) * s.dist;
          const dx = x > 0 ? 10 : (x < -5 ? -10 : 0);
          const dy = y > 5 ? 14 : (y < -5 ? -8 : 4);
          const anchor = x > 5 ? 'start' : (x < -5 ? 'end' : 'middle');
          return (
            <text key={s.id} x={x + dx} y={y + dy} textAnchor={anchor}
                  fontSize="9" fill="#a1a1aa" fontFamily="Geist Mono"
                  letterSpacing="0.04em">{s.label}</text>
          );
        })}
      </svg>
      <div className="arch-cap mono">infra · 7j/7 · 99.98%</div>
    </div>
  );
}

function VisualTimeline() {
  const phases = [
    { key: 'kickoff', label: 'Kickoff',     d: 'J1',     w: 8 },
    { key: 'archi',   label: 'Architecture',d: 'J1\u2013J7', w: 18 },
    { key: 'dev',     label: 'Développement',d: 'J7\u2013J35', w: 42 },
    { key: 'prod',    label: 'Mise en prod',d: 'J35\u2013J42',w: 22 },
    { key: 'ops',     label: 'Suivi',       d: 'continu',w: 10 },
  ];
  return (
    <div className="vis vis-timeline">
      <div className="tl-head mono">
        <span>Cycle projet · 6 semaines moyenne</span>
        <span className="dim">une seule personne</span>
      </div>
      <div className="tl-track">
        <div className="tl-axis"></div>
        {phases.map((p, i) => (
          <div key={p.key} className={`tl-phase tl-${p.key}`} style={{flex: p.w}}>
            <div className="tl-bar">
              <span className="tl-bar-fill"></span>
            </div>
            <div className="tl-meta">
              <span className="tl-num mono">0{i+1}</span>
              <span className="tl-label">{p.label}</span>
              <span className="tl-d mono dim">{p.d}</span>
            </div>
          </div>
        ))}
      </div>
      <div className="tl-actor">
        <div className="tl-actor-line">
          <span className="tl-actor-dot"></span>
          <span className="tl-actor-line-fill"></span>
        </div>
        <div className="tl-actor-lbl mono">Maxime · brief → archi → dev → prod → ops</div>
      </div>
    </div>
  );
}

function PanelVisual({ which }) {
  return (
    <div className="vis-stage">
      <div className={`vis-slot ${which === 'compare' ? 'active' : ''}`}><VisualCompare /></div>
      <div className={`vis-slot ${which === 'code' ? 'active' : ''}`}><VisualCode /></div>
      <div className={`vis-slot ${which === 'arch' ? 'active' : ''}`}><VisualArch /></div>
      <div className={`vis-slot ${which === 'timeline' ? 'active' : ''}`}><VisualTimeline /></div>
    </div>
  );
}

// ── Manifesto section ───────────────────────────────────────────────────────
function Manifesto() {
  const [active, setActive] = React.useState(0);
  const stickyRef = React.useRef(null);
  const panelsRef = React.useRef([]);

  React.useEffect(() => {
    const els = panelsRef.current.filter(Boolean);
    if (!els.length) return;
    const io = new IntersectionObserver((entries) => {
      // Find the most-visible panel
      let best = active;
      let bestRatio = 0;
      for (const e of entries) {
        if (e.intersectionRatio > bestRatio) {
          bestRatio = e.intersectionRatio;
          best = Number(e.target.dataset.idx);
        }
      }
      if (bestRatio > 0.3) setActive(best);
    }, { threshold: [0.3, 0.5, 0.7], rootMargin: '-30% 0px -30% 0px' });
    els.forEach((el) => io.observe(el));
    return () => io.disconnect();
  }, []);

  return (
    <section id="manifesto" className="manifesto" data-screen-label="02 Manifesto" data-reveal="up">
      <div className="man-head">
        <span className="mono small dim">N° 02 / 05 — Manifesto</span>
        <h2 className="man-eyebrow">
          Quatre principes <em className="serif">non négociables.</em>
        </h2>
      </div>

      <div className="man-grid">
        <div className="man-left">
          {PANELS.map((p, i) => (
            <article key={i}
                     ref={(el) => (panelsRef.current[i] = el)}
                     data-idx={i}
                     className={`man-panel ${i === active ? 'is-active' : ''}`}>
              <div className="man-panel-meta">
                <span className="mono small dim">— {p.kicker}</span>
                <span className="mono small dim">0{i+1} / 04</span>
              </div>
              <h3 className="man-panel-title">
                {p.title}
              </h3>
              <p className="man-panel-body">{p.body}</p>
              <div className="man-progress">
                <span className="man-progress-line"></span>
                <span className="man-progress-fill"></span>
              </div>
            </article>
          ))}
        </div>

        <div className="man-right" ref={stickyRef}>
          <div className="man-sticky">
            <div className="man-sticky-h">
              <span className="mono small dim">VISUEL · {String(active + 1).padStart(2,'0')} / 04</span>
              <span className="mono small accent">— {PANELS[active].kicker}</span>
            </div>
            <PanelVisual which={PANELS[active].visual} />
            <div className="man-sticky-foot mono small dim">
              {PANELS[active].title.replace(/\.$/, '')}
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

window.Manifesto = Manifesto;
