// shared.jsx- shared slide primitives, chrome, mini diagram
const { useState, useEffect, useRef, useMemo } = React;

// === Slide chrome (top bar with section indicator) ===
function Chrome({ section, slide, total, sectionLabel }) {
  return (
    <div className="chrome">
      <div className="chrome-left">
        {sectionLabel && <span className="chrome-section">§ {sectionLabel}</span>}
      </div>
      <div className="chrome-right">
        {String(slide).padStart(2,'0')} / {String(total).padStart(2,'0')}
      </div>
    </div>
  );
}

// === Mini system diagram (corner)- clickable to expand ===
function MiniDiagram({ stage = 1, lit, chips, hidden, highlight }) {
  const [open, setOpen] = useState(false);
  const html = useMemo(() => window.ConsoleVisual({ size: 'mini', stage, lit, highlight }), [stage, JSON.stringify(lit), highlight]);
  const fullHtml = useMemo(() => window.ConsoleVisual({ size: 'full', stage, lit, highlight }), [stage, JSON.stringify(lit), highlight]);
  if (hidden) return null;
  return (
    <>
      <div className="mini-diagram"
           onClick={() => setOpen(true)}
           style={{cursor:'zoom-in'}}
           title="Click to expand"
           dangerouslySetInnerHTML={{ __html: html }} />
      {open && (
        <div onClick={() => setOpen(false)}
             style={{
               position:'absolute', inset:0, zIndex: 9999,
               background:'rgba(5,3,3,0.92)', backdropFilter:'blur(8px)',
               display:'flex', alignItems:'center', justifyContent:'center',
               cursor:'zoom-out', padding:'80px 120px',
             }}>
          <div style={{width:'100%', maxWidth:1400, height:'100%'}}
               dangerouslySetInnerHTML={{ __html: fullHtml }}/>
          <div style={{
            position:'absolute', top:30, right:40,
            fontFamily:'JetBrains Mono', fontSize:13, letterSpacing:'0.2em',
            color:'var(--text-2)',
          }}>CLICK ANYWHERE TO CLOSE ✕</div>
        </div>
      )}
    </>
  );
}

// === Bullet with hover tooltip ===
function Bullet({ children, tip, warn }) {
  return (
    <li className={warn ? 'warn' : ''}>
      <span>{children}</span>
      {tip && <div className="tip">{tip}</div>}
    </li>
  );
}

// === Bullets container ===
function Bullets({ items }) {
  return (
    <ul className="bullets">
      {items.map((it, i) => (
        <Bullet key={i} tip={it.tip} warn={it.warn}>{it.text}</Bullet>
      ))}
    </ul>
  );
}

// === Code block with simple syntax highlighting ===
function CodeBlock({ lang = "ts", children, label }) {
  return (
    <div className="code">
      {label && <div className="code-header">{label}</div>}
      <div className="code-body" dangerouslySetInnerHTML={{ __html: children }} />
    </div>
  );
}

// === Placeholder block ===
function Placeholder({ label, children, style }) {
  return (
    <div className="placeholder" style={style}>
      <div>
        <div className="placeholder-label">{label}</div>
        {children && <div style={{marginTop:12, fontSize:13, color:'var(--text-3)'}}>{children}</div>}
      </div>
    </div>
  );
}

// === Animation speed hook (driven by tweaks) ===
// Returns a number: 0 means paused, otherwise speed multiplier.
// Use `useAnimSpeed()` for the raw number, or `useAnimSpeed.paused` boolean
// helpers below in interval gating: if (speed < 0.05) return;
function useAnimSpeed() {
  const [speed, setSpeed] = useState(() => {
    const v = parseFloat(localStorage.getItem('mastra-anim-speed') || '0.5');
    return isNaN(v) ? 0.5 : v;
  });
  useEffect(() => {
    const onMsg = (e) => {
      if (e.data && e.data.type === '__anim_speed') {
        setSpeed(e.data.value);
        localStorage.setItem('mastra-anim-speed', String(e.data.value));
      }
    };
    window.addEventListener('message', onMsg);
    const onStorage = () => {
      const v = parseFloat(localStorage.getItem('mastra-anim-speed') || '0.5');
      if (!isNaN(v)) setSpeed(v);
    };
    window.addEventListener('storage', onStorage);
    window.addEventListener('mastra-anim-speed', onStorage);
    return () => {
      window.removeEventListener('message', onMsg);
      window.removeEventListener('storage', onStorage);
      window.removeEventListener('mastra-anim-speed', onStorage);
    };
  }, []);
  useEffect(() => {
    document.documentElement.style.setProperty('--anim-speed', String(Math.max(0.05, speed)));
  }, [speed]);
  return speed;
}

// === Reset key per slide (resets animations on slide change) ===
function useSlideResetKey(slideId) {
  const [key, setKey] = useState(0);
  useEffect(() => {
    const onMsg = (e) => {
      if (e.data && typeof e.data.slideIndexChanged === 'number') {
        setKey(k => k + 1);
      }
    };
    window.addEventListener('message', onMsg);
    return () => window.removeEventListener('message', onMsg);
  }, []);
  return key;
}

// Expose
Object.assign(window, { Chrome, MiniDiagram, Bullet, Bullets, CodeBlock, Placeholder, useAnimSpeed, useSlideResetKey });
