// map.jsx — the GTM system map (hero) and the module zoom sections below it.
// Map: seven numbered modules around one knowledge hub, wired together, each card a small live screen.
// Modules: one section per module, each with three counters, one moving picture and its agents.
// All numbers are illustrative.

const MOD = {
  persona: { n: '01', c: '#db2777', icon: 'user' },
  shorts:  { n: '02', c: '#ea580c', icon: 'video' },
  publish: { n: '03', c: '#7c3aed', icon: 'send' },
  b2c:     { n: '04', c: '#2563eb', icon: 'users' },
  b2b:     { n: '05', c: '#0d9488', icon: 'building' },
  trust:   { n: '06', c: '#ca8a04', icon: 'linkedin' },
  deals:   { n: '07', c: '#16a34a', icon: 'handshake' },
  live:    { n: 'LIVE', c: '#475569', icon: 'bolt' },
  owner:   { n: '✓', c: '#E8643C', icon: 'bell' },
};
const MAP_W = 1200, MAP_H = 930;
const HUB = { x: 600, y: 528, rx: 205, ry: 112 };
const SLOT = {
  persona: { x: 20, y: 150, w: 370, h: 232, ax: 205, ay: 382, a: 218 },
  shorts:  { x: 415, y: 150, w: 370, h: 232, ax: 600, ay: 382, a: 270 },
  publish: { x: 810, y: 150, w: 370, h: 232, ax: 995, ay: 382, a: 322 },
  b2c:     { x: 20, y: 415, w: 300, h: 226, ax: 320, ay: 528, a: 180 },
  b2b:     { x: 880, y: 415, w: 300, h: 226, ax: 880, ay: 528, a: 0 },
  trust:   { x: 20, y: 676, w: 370, h: 232, ax: 205, ay: 676, a: 142 },
  deals:   { x: 415, y: 676, w: 370, h: 232, ax: 600, ay: 676, a: 90 },
  live:    { x: 810, y: 676, w: 370, h: 232, ax: 995, ay: 676, a: 38 },
};
const ORDER = ['persona', 'shorts', 'publish', 'b2c', 'b2b', 'trust', 'deals', 'live'];

function nodeOf(k) {
  const a = SLOT[k].a * Math.PI / 180;
  return { x: HUB.x + HUB.rx * Math.cos(a), y: HUB.y + HUB.ry * Math.sin(a) };
}
function wireOf(k) {
  const s = SLOT[k], n = nodeOf(k);
  if (k === 'b2c' || k === 'b2b') return `M ${s.ax} ${s.ay} H ${n.x}`;
  const mid = s.ay < HUB.y ? s.ay + 18 : s.ay - 18;
  return `M ${s.ax} ${s.ay} V ${mid} H ${n.x} V ${n.y}`;
}
// deterministic pseudo-random so the hub looks the same on every render
function prng(seed) { let x = seed; return () => (x = (x * 16807) % 2147483647) / 2147483647; }
const HUB_DOTS = (() => {
  const r = prng(7), pts = [];
  for (let i = 0; i < 90; i++) {
    const a = r() * Math.PI * 2, d = Math.sqrt(r()) * 70;
    pts.push({ x: HUB.x + Math.cos(a) * d * 1.25, y: HUB.y + Math.sin(a) * d * 0.9, c: ORDER[Math.floor(r() * 7)], o: r() });
  }
  return pts;
})();

function Agents({ list, c }) {
  return (
    <div className="mc-agents">
      {list.map((a, i) => (
        <span key={i} className="mc-agent"><i className="ic" style={{ color: c }}>{IC.sparkles}</i>{a}<span className="mc-live" /></span>
      ))}
    </div>
  );
}

function MiniUI({ k, m }) {
  const u = m.ui;
  if (k === 'persona') return (
    <div className="mu mu-persona">
      <div className="mu-avatar"><video src="assets/angles/ai-clone.mp4" poster="assets/angles/ai-clone.jpg" autoPlay muted loop playsInline preload="metadata" /></div>
      <div className="mu-col">
        <b>{u.who}</b>
        <div className="mu-wave">{Array.from({ length: 22 }).map((_, i) => <span key={i} style={{ animationDelay: `${(i % 7) * 0.12}s` }} />)}</div>
        <small>{u.voice}</small>
        <div className="mu-chips">{u.chips.map((c, i) => <span key={i}>{c}</span>)}</div>
      </div>
    </div>
  );
  if (k === 'shorts') return (
    <div className="mu mu-shorts">
      {['ip-story', 'product', 'personal-ip'].map((v) => (
        <div key={v} className="mu-tile"><video src={`assets/angles/${v}.mp4`} poster={`assets/angles/${v}.jpg`} autoPlay muted loop playsInline preload="metadata" /></div>
      ))}
      <div className="mu-col">
        <small>{u.today}</small>
        <b className="mu-big">{u.count}</b>
        <div className="mu-bar"><span /></div>
      </div>
    </div>
  );
  if (k === 'publish') {
    const plats = [IC.ig, IC.tiktok, IC.yt, IC.fb, IC.threads, IC.linkedin];
    const colors = ['#E1306C', '#111', '#FF0033', '#1877F2', '#111', '#0A66C2'];
    return (
      <div className="mu mu-publish">
        {u.week.map((d, i) => (
          <div key={i} className="mu-day">
            <small>{d}</small>
            {[0, 1, 2].map((j) => {
              const p = (i * 2 + j) % plats.length;
              return <span key={j} className="mu-slot" style={{ animationDelay: `${(i * 3 + j) * 0.35}s`, color: colors[p] }}><i className="ic">{plats[p]}</i></span>;
            })}
          </div>
        ))}
      </div>
    );
  }
  if (k === 'b2c') return (
    <div className="mu mu-chat">
      <div className="mu-bubble in">{u.q}</div>
      <div className="mu-bubble ai"><i className="ic" style={{ color: '#06C755' }}>{IC.line}</i>{u.a}</div>
      <div className="mu-row"><small>{u.signups}</small><div className="mu-bar"><span /></div></div>
    </div>
  );
  if (k === 'b2b') return (
    <div className="mu mu-leads">
      {u.rows.map((r, i) => (
        <div key={i} className="mu-lead">
          <i className="ic">{IC.building}</i><span>{r}</span>
          <em style={{ '--w': `${[94, 88, 81][i]}%` }}><b /></em><small>{[94, 88, 81][i]}</small>
        </div>
      ))}
      <div className="mu-status">
        <span><i className="ic">{IC.mail}</i>{u.mail}</span>
        <span className="calling"><i className="ic">{IC.phone}</i>{u.call}</span>
      </div>
    </div>
  );
  if (k === 'trust') return (
    <div className="mu mu-post">
      <div className="mu-thumb"><video src="assets/angles/personal-ip.mp4" poster="assets/angles/personal-ip.jpg" autoPlay muted loop playsInline preload="metadata" /><i className="ic">{IC.play}</i></div>
      <div className="mu-col">
        <div className="mu-plats"><i className="ic" style={{ color: '#0A66C2' }}>{IC.linkedin}</i><i className="ic" style={{ color: '#FF0033' }}>{IC.yt}</i></div>
        <b>{u.post}</b>
        <small><i className="ic">{IC.eye}</i> {u.views}</small>
      </div>
    </div>
  );
  if (k === 'deals') return (
    <div className="mu mu-deals">
      <div className="mu-cal">
        <small>{u.meetings}</small>
        <div className="mu-grid">
          {Array.from({ length: 15 }).map((_, i) => (
            <span key={i} className={[2, 6, 8, 11, 13].includes(i) ? 'on' : ''} style={{ animationDelay: `${i * 0.25}s` }}>
              {[2, 6, 8, 11, 13].includes(i) && <i className="ic">{IC.user}</i>}
            </span>
          ))}
        </div>
      </div>
      <div className="mu-contract">
        <small>{u.quote}</small>
        <b>{u.amount}</b>
        <span className="mu-signed"><i className="ic">{IC.signature}</i>{u.signed}</span>
      </div>
    </div>
  );
  if (k === 'live') return (
    <div className="mu mu-feed">
      <div className="mu-feed-track">
        {[...u.rows, ...u.rows].map((r, i) => (
          <div key={i} className="mu-feed-row" style={{ '--rc': MOD[r[3]].c }}>
            <small>{r[0]}</small><i className="ic">{IC[MOD[r[3]].icon]}</i><span><b>{r[1]}</b> {r[2]}</span>
          </div>
        ))}
      </div>
    </div>
  );
  return null;
}

function MapCard({ k, m, style }) {
  const md = MOD[k];
  return (
    <article className={`mc mc-${k}`} style={{ ...style, '--mc': md.c }}>
      <header className="mc-head">
        <span className="mc-n">{md.n}</span>
        <span className="mc-name">{m.name}</span>
        <span className="mc-count"><span className="mc-live" />{m.status}</span>
      </header>
      <MiniUI k={k} m={m} />
      {m.agents && <Agents list={m.agents} c={md.c} />}
    </article>
  );
}

function MapHub({ t, wide }) {
  const mp = t.map;
  return (
    <svg className="map-svg" viewBox={wide ? `0 0 ${MAP_W} ${MAP_H}` : `${HUB.x - 260} ${HUB.y - 150} 520 300`} aria-hidden="true">
      {wide && ORDER.map((k) => (
        <g key={'w' + k}>
          <path d={wireOf(k)} className="map-wire" style={{ stroke: MOD[k].c }} />
          <path d={wireOf(k)} className="map-wire-flow" style={{ stroke: MOD[k].c }} />
          <circle r="4" fill={MOD[k].c}>
            <animateMotion dur={`${2.4 + ORDER.indexOf(k) * 0.3}s`} repeatCount="indefinite" path={wireOf(k)} keyPoints="1;0" keyTimes="0;1" calcMode="linear" />
          </circle>
        </g>
      ))}
      {HUB_DOTS.map((d, i) => {
        const near = HUB_DOTS[(i * 7 + 3) % HUB_DOTS.length];
        return <line key={'l' + i} x1={d.x} y1={d.y} x2={near.x} y2={near.y} className="hub-line" />;
      })}
      {HUB_DOTS.map((d, i) => (
        <circle key={'d' + i} cx={d.x} cy={d.y} r={1.6 + d.o * 1.6} fill={MOD[d.c].c} className="hub-dot" style={{ animationDelay: `${d.o * 3}s` }} />
      ))}
      {ORDER.map((k) => {
        const n = nodeOf(k), a = SLOT[k].a * Math.PI / 180;
        const fan = Array.from({ length: 7 }).map((_, j) => {
          const aa = a + Math.PI + (j - 3) * 0.16, len = 34 + (j % 3) * 10;
          return { x: n.x + Math.cos(aa) * len, y: n.y + Math.sin(aa) * len * 0.8 };
        });
        return (
          <g key={'n' + k}>
            {fan.map((f, j) => (
              <g key={j}>
                <line x1={n.x} y1={n.y} x2={f.x} y2={f.y} stroke={MOD[k].c} strokeOpacity=".45" strokeWidth="1" />
                <circle cx={f.x} cy={f.y} r="2.4" fill={j % 2 ? '#0A0A0A' : MOD[k].c} className="hub-dot" style={{ animationDelay: `${j * 0.4}s` }} />
              </g>
            ))}
            <circle cx={n.x} cy={n.y} r="15" fill="#fff" stroke={MOD[k].c} strokeWidth="1.6" />
            <text x={n.x} y={n.y + 4} textAnchor="middle" className="hub-num" style={{ fill: MOD[k].c }}>{MOD[k].n === 'LIVE' ? '●' : MOD[k].n}</text>
          </g>
        );
      })}
      <circle cx={HUB.x} cy={HUB.y} r="54" className="hub-core" />
      <circle cx={HUB.x} cy={HUB.y} r="54" className="hub-ring" />
      <text x={HUB.x} y={HUB.y - 1} textAnchor="middle" className="hub-title" textLength={mp.hub.title.length > 6 ? 88 : undefined} lengthAdjust="spacingAndGlyphs">{mp.hub.title}</text>
      <text x={HUB.x} y={HUB.y + 17} textAnchor="middle" className="hub-sub" textLength={mp.hub.sub.length > 14 ? 92 : undefined} lengthAdjust="spacingAndGlyphs">{mp.hub.sub}</text>
    </svg>
  );
}

function SystemMap({ t }) {
  const mp = t.map;
  const ref = React.useRef(null);
  const [w, setW] = React.useState(1200);
  React.useEffect(() => {
    const el = ref.current;
    const ro = new ResizeObserver(() => setW(el.clientWidth));
    ro.observe(el); setW(el.clientWidth);
    return () => ro.disconnect();
  }, []);
  const wide = w >= 980;
  const s = w / MAP_W;
  const head = (
    <div className="map-head">
      <div className="map-kicker">{mp.kicker}</div>
      <div className="map-title">{mp.title}</div>
      <div className="map-bar">
        <div className="map-status">{mp.status.map((x, i) => <span key={i}><i className="mc-live" />{x}</span>)}</div>
        <div className="map-totals">{mp.totals.map((x, i) => <span key={i}><b>{x.n}</b> {x.k}</span>)}</div>
      </div>
    </div>
  );
  return (
    <div className="map" ref={ref}>
      {wide ? (
        <div className="map-stage" style={{ height: MAP_H * s }}>
          <div className="map-scene" style={{ width: MAP_W, height: MAP_H, transform: `scale(${s})` }}>
            {head}
            <MapHub t={t} wide />
            {ORDER.map((k) => (
              <MapCard key={k} k={k} m={mp.mods[k]} style={{ left: SLOT[k].x, top: SLOT[k].y, width: SLOT[k].w, height: SLOT[k].h }} />
            ))}
            {ORDER.filter((k) => k !== 'live').map((k) => {
              const n = nodeOf(k), a = SLOT[k].a * Math.PI / 180;
              const side = SLOT[k].a === 0 || SLOT[k].a === 180;
              const lx = side ? n.x : n.x + Math.cos(a) * 64, ly = side ? n.y - 30 : n.y + Math.sin(a) * 44;
              return <div key={'lab' + k} className="map-label" style={{ left: lx, top: ly, color: MOD[k].c }}>{mp.mods[k].short}</div>;
            })}
          </div>
        </div>
      ) : (
        <div className="map-narrow">
          {head}
          <div className="map-hub-narrow"><MapHub t={t} wide={false} /></div>
          <div className="map-list">
            {ORDER.map((k) => <MapCard key={k} k={k} m={mp.mods[k]} />)}
          </div>
        </div>
      )}
    </div>
  );
}

// ───────── module sections ─────────

function useInView(ref, threshold = 0.15) {
  const [seen, setSeen] = React.useState(false);
  React.useEffect(() => {
    const io = new IntersectionObserver(([e]) => { if (e.isIntersecting) { setSeen(true); io.disconnect(); } }, { threshold });
    if (ref.current) io.observe(ref.current);
    return () => io.disconnect();
  }, []);
  return seen;
}

function CountUp({ to, suf = '', run }) {
  const [v, setV] = React.useState(0);
  React.useEffect(() => {
    if (!run) return;
    if (window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches) { setV(to); return; }
    let raf, t0;
    const step = (now) => {
      t0 = t0 || now;
      const k = Math.min(1, (now - t0) / 1400), e = 1 - Math.pow(1 - k, 3);
      setV(Math.round(to * e));
      if (k < 1) raf = requestAnimationFrame(step);
    };
    raf = requestAnimationFrame(step);
    return () => cancelAnimationFrame(raf);
  }, [run, to]);
  return <>{v.toLocaleString('en-US')}{suf}</>;
}

function Conveyor({ m }) {
  const stIcons = [IC.writing, IC.mic, IC.video, IC.scissors];
  const plats = [[IC.ig, '#E1306C'], [IC.tiktok, '#111'], [IC.yt, '#FF0033'], [IC.fb, '#1877F2'], [IC.threads, '#111'], [IC.linkedin, '#0A66C2']];
  return (
    <div className="conv" aria-hidden="true">
      <div className="conv-brain"><i className="ic">{IC.brain}</i></div>
      <div className="conv-line">
        <div className="conv-stations">
          {m.stations.map((s, i) => (
            <div key={i} className="conv-st" style={{ animationDelay: `${i * 0.7}s` }}><i className="ic">{stIcons[i]}</i><span>{s}</span></div>
          ))}
        </div>
        <div className="conv-belt">
          {Array.from({ length: 6 }).map((_, i) => (
            <span key={i} className="conv-item" style={{ animationDelay: `${-i * 1}s` }}><i className="ic">{IC.play}</i></span>
          ))}
        </div>
      </div>
      <div className="conv-plats">
        {plats.map(([g, c], i) => <span key={i} style={{ color: c, animationDelay: `${i * 0.5}s` }}><i className="ic">{g}</i></span>)}
      </div>
    </div>
  );
}

function PhoneBrief({ m }) {
  const p = m.phone;
  return (
    <div className="phone-brief" aria-hidden="true">
      <div className="pb-notch" />
      <div className="pb-date">{p.day}</div>
      <div className="pb-time">7:00</div>
      <div className="pb-notes">
        {p.notes.map((n, i) => (
          <div key={i} className="pb-note" style={{ animationDelay: `${0.4 + i * 0.9}s` }}>
            <span className="pb-app" style={{ color: n.c }}><i className="ic">{IC[n.ic]}</i></span>
            <div><b>{n.app}</b><span>{n.t}</span></div>
            <small>{n.ago}</small>
          </div>
        ))}
      </div>
      <div className="pb-approve" style={{ animationDelay: `${0.4 + p.notes.length * 0.9}s` }}>
        <div><b>{p.approve.t}</b><span>{p.approve.s}</span></div>
        <button tabIndex={-1}>{p.approve.b}</button>
      </div>
    </div>
  );
}

function ModuleVisual({ k, m, t }) {
  if (k === 'persona') return <KnowledgeBrain t={t} />;
  if (k === 'shorts') return <Conveyor m={m} />;
  if (k === 'b2c' || k === 'b2b') return <div className="mod-funnel"><FunnelPanel kind={k} t={t} /></div>;
  if (k === 'owner') return <PhoneBrief m={m} />;
  return null;
}

function ModuleBlock({ m, i, t, note }) {
  const ref = React.useRef(null);
  const seen = useInView(ref);
  const color = MOD[m.k].c;
  const icons = m.kpiIcons.map((x) => IC[x]);
  return (
    <section ref={ref} className={`mod${i % 2 ? ' flip' : ''}${seen ? ' seen' : ''}`} style={{ '--mc': color }} id={`mod-${m.k}`}>
      <div className="wrap mod-inner">
        <div className="mod-copy">
          <div className="mod-badge"><span>{m.n}</span>{m.title}</div>
          <h3 className="mod-caption">{m.caption}</h3>
          <p className="mod-body">{m.body}</p>
          {m.kpis.length > 0 && (
            <>
              <div className="mod-kpis">
                {m.kpis.map((kp, j) => (
                  <div key={j} className="mod-kpi">
                    <div className="mod-kpi-top"><small>{kp.l}</small><i className="ic">{icons[j]}</i></div>
                    <b><CountUp to={kp.v} suf={kp.suf || ''} run={seen} /></b>
                  </div>
                ))}
              </div>
              <div className="mod-note">{note}</div>
            </>
          )}
          <div className="mod-agents">
            {m.agents.map((a, j) => <span key={j}><i className="ic">{IC.sparkles}</i>{a}</span>)}
          </div>
        </div>
        <div className="mod-visual"><ModuleVisual k={m.k} m={m} t={t} /></div>
      </div>
    </section>
  );
}

function Modules({ t }) {
  const md = t.modules;
  return (
    <div id="system" className="mods">
      <div className="wrap">
        <div className="why">
          <div className="why-big">
            <b>100×</b>
            <span>{md.bigLabel}</span>
          </div>
          <div>
            <div className="eyebrow">{md.eyebrow}</div>
            <h2 className="h-1" style={{ marginTop: 18 }}>{md.title}</h2>
            <p className="lede" style={{ marginTop: 22 }}>{md.lede}</p>
          </div>
        </div>
        <div className="why-grid">
          {md.why.map((w, j) => (
            <div key={j} className="why-card">
              <div className="why-top"><i className="ic">{IC[w.i]}</i><span>{w.h}</span><b>{w.x}</b></div>
              <div className="why-from">{w.from}</div>
              <div className="why-arrow"><i className="ic">{IC.arrow}</i></div>
              <div className="why-to">{w.to}</div>
            </div>
          ))}
        </div>
        <p className="why-note">{md.whyNote}</p>
      </div>
      {md.list.map((m, i) => <ModuleBlock key={m.k} m={m} i={i} t={t} note={md.note} />)}
    </div>
  );
}

Object.assign(window, { SystemMap, Modules });
