// shared.jsx — Common building blocks for the Axion deck
// All components are exported to window for cross-script use.

const { useState, useEffect, useRef, useMemo } = React;

// ── Universal slide chrome: animated logo + slide num + brand strip ──
const SlideChrome = ({ num, total, dark, showBrandStrip = true }) =>
<>
    {showBrandStrip &&
  <div className="brand-strip">
        <img src="assets/logo/full-logo-blue.png" alt="Axion" className="brand-logo" style={{ filter: dark ? 'brightness(0) invert(1)' : 'none', height: 22 }} />
        <span className="strip-divider"></span>
        <span className="partner-text">New Partner Intro · 2026</span>
      </div>
  }
    <div className="slide-num">{String(num).padStart(2, '0')} / {String(total).padStart(2, '0')}</div>
    <div className={`deck-logo ${dark ? 'dark' : ''}`}>
      <img src="assets/logo/animated-logo.gif" alt="" />
    </div>
  </>;


// ── Count-up number ──────────────────────────────────────────
const CountUp = ({ to, duration = 1400, prefix = '', suffix = '', decimals = 0, active = true }) => {
  const [val, setVal] = useState(0);
  const startedRef = useRef(false);
  useEffect(() => {
    if (!active) {setVal(0);startedRef.current = false;return;}
    if (startedRef.current) return;
    startedRef.current = true;
    let raf;
    const start = performance.now();
    const tick = (now) => {
      const t = Math.min(1, (now - start) / duration);
      const eased = 1 - Math.pow(1 - t, 3);
      setVal(to * eased);
      if (t < 1) raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, [active, to, duration]);
  const display = decimals > 0 ? val.toFixed(decimals) : Math.round(val).toLocaleString();
  return <span className="mono">{prefix}{display}{suffix}</span>;
};

// ── Use slide active state ───────────────────────────────────
const useSlideActive = (selector = ':scope') => {
  const ref = useRef(null);
  const [active, setActive] = useState(false);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const slide = el.closest('[data-deck-slide]');
    if (!slide) return;
    const update = () => setActive(slide.hasAttribute('data-deck-active'));
    update();
    const obs = new MutationObserver(update);
    obs.observe(slide, { attributes: true, attributeFilter: ['data-deck-active'] });
    return () => obs.disconnect();
  }, []);
  return [ref, active];
};

// ── Particle field background (lightweight constellation) ──
const ConstellationBG = ({ density = 0.55, opacity = 1 }) => {
  const canvasRef = useRef(null);
  useEffect(() => {
    const canvas = canvasRef.current;
    if (!canvas) return;
    const ctx = canvas.getContext('2d');
    let W = 0,H = 0,nodes = [],conns = [],parts = [],raf = 0;
    const resize = () => {
      W = canvas.width = canvas.parentElement.offsetWidth;
      H = canvas.height = canvas.parentElement.offsetHeight;
      nodes = [];conns = [];parts = [];
      const cols = 16,rows = 10;
      const gx = W / cols,gy = H / rows;
      for (let i = 0; i < cols; i++) for (let j = 0; j < rows; j++) {
        if (Math.random() > 1 - density) {
          nodes.push({
            x: (i + .5) * gx + (Math.random() - .5) * gx * .5,
            y: (j + .5) * gy + (Math.random() - .5) * gy * .5,
            r: Math.random() * 1.6 + .8,
            ph: Math.random() * Math.PI * 2,
            ps: .01 + Math.random() * .02,
            br: .3 + Math.random() * .7
          });
        }
      }
      for (let i = 0; i < nodes.length; i++) for (let j = i + 1; j < nodes.length; j++) {
        const dx = nodes[i].x - nodes[j].x,dy = nodes[i].y - nodes[j].y;
        const d = Math.sqrt(dx * dx + dy * dy);
        if (d < 160 && Math.random() > .6) conns.push({ a: i, b: j, al: .05 + Math.random() * .12 });
      }
      for (let k = 0; k < 14; k++) {
        if (conns.length) parts.push({ conn: conns[Math.floor(Math.random() * conns.length)], t: Math.random(), sp: .003 + Math.random() * .004, sz: 1.5 + Math.random() * 2, al: .6 + Math.random() * .4, trail: [] });
      }
    };
    const draw = () => {
      ctx.clearRect(0, 0, W, H);
      conns.forEach((c) => {
        const a = nodes[c.a],b = nodes[c.b];
        ctx.beginPath();ctx.moveTo(a.x, a.y);ctx.lineTo(b.x, b.y);
        ctx.strokeStyle = `rgba(0,116,217,${c.al})`;ctx.lineWidth = .5;ctx.stroke();
      });
      nodes.forEach((n) => {
        n.ph += n.ps;
        const pv = (Math.sin(n.ph) + 1) / 2;
        const al = (.4 + pv * .6) * n.br;
        ctx.beginPath();ctx.arc(n.x, n.y, n.r * 3.5, 0, Math.PI * 2);
        ctx.fillStyle = `rgba(0,116,217,${.03 + pv * .04})`;ctx.fill();
        ctx.beginPath();ctx.arc(n.x, n.y, n.r, 0, Math.PI * 2);
        ctx.fillStyle = `rgba(0,116,217,${al})`;ctx.fill();
      });
      parts.forEach((p) => {
        p.t += p.sp;
        if (p.t > 1) {p.t = 0;p.conn = conns[Math.floor(Math.random() * conns.length)];}
        const a = nodes[p.conn.a],b = nodes[p.conn.b];
        const x = a.x + (b.x - a.x) * p.t,y = a.y + (b.y - a.y) * p.t;
        p.trail.push({ x, y });
        if (p.trail.length > 12) p.trail.shift();
        for (let i = 1; i < p.trail.length; i++) {
          const ta = i / p.trail.length;
          ctx.beginPath();
          ctx.moveTo(p.trail[i - 1].x, p.trail[i - 1].y);
          ctx.lineTo(p.trail[i].x, p.trail[i].y);
          ctx.strokeStyle = `rgba(0,200,255,${ta * p.al * .55})`;
          ctx.lineWidth = p.sz * .4 * ta;
          ctx.stroke();
        }
        const g = ctx.createRadialGradient(x, y, 0, x, y, p.sz * 3);
        g.addColorStop(0, `rgba(0,210,255,${p.al * .9})`);
        g.addColorStop(.4, `rgba(0,116,217,${p.al * .35})`);
        g.addColorStop(1, 'rgba(0,116,217,0)');
        ctx.beginPath();ctx.arc(x, y, p.sz * 3, 0, Math.PI * 2);
        ctx.fillStyle = g;ctx.fill();
      });
      raf = requestAnimationFrame(draw);
    };
    resize();draw();
    const ro = new ResizeObserver(resize);
    ro.observe(canvas.parentElement);
    return () => {cancelAnimationFrame(raf);ro.disconnect();};
  }, [density]);
  return (
    <div style={{ position: 'absolute', inset: 0, opacity, pointerEvents: 'none' }}>
      <canvas ref={canvasRef} style={{ width: '100%', height: '100%', display: 'block' }} />
    </div>);

};

// ── Subtle dot grid ──────────────────────────────────────────
const DotGrid = ({ color = 'rgba(0,116,217,0.08)', size = 32 }) =>
<div style={{
  position: 'absolute', inset: 0,
  backgroundImage: `radial-gradient(${color} 1px, transparent 1px)`,
  backgroundSize: `${size}px ${size}px`,
  pointerEvents: 'none'
}} />;


// ── Floating orb glow ────────────────────────────────────────
const OrbGlow = ({ x, y, color = 'rgba(0,116,217,0.18)', size = 600 }) =>
<div style={{
  position: 'absolute', left: x, top: y,
  width: size, height: size,
  borderRadius: '50%',
  background: `radial-gradient(circle, ${color} 0%, transparent 60%)`,
  filter: 'blur(20px)',
  pointerEvents: 'none',
  transform: 'translate(-50%,-50%)'
}} />;


// ── Section title block ─────────────────────────────────────
const SectionHeading = ({ eyebrow, title, sub, dark, align = 'left', maxWidth = 1100 }) =>
<div style={{ maxWidth, textAlign: align }}>
    {eyebrow && <div className="eyebrow reveal" style={{ animationDelay: '100ms', marginBottom: 22 }}>{eyebrow}</div>}
    <h2 className="h-display reveal" style={{
    fontSize: 88,
    color: dark ? '#fff' : 'var(--navy)',
    animationDelay: '200ms',
    margin: 0
  }}>{title}</h2>
    {sub && <p className="reveal" style={{
    fontSize: 24,
    lineHeight: 1.55,
    color: dark ? 'rgba(255,255,255,0.65)' : 'var(--muted)',
    marginTop: 24,
    maxWidth: 820,
    animationDelay: '320ms',
    fontWeight: 400
  }}>{sub}</p>}
  </div>;


Object.assign(window, { SlideChrome, CountUp, useSlideActive, ConstellationBG, DotGrid, OrbGlow, SectionHeading });
