// ============================================================
// HUNGRY HOLE 3D — Motion & juice spec + UI component sheet
// (motion + components)
// ============================================================
const { useState: useStateMo } = React;

function parseBezier(ease) {
  const m = /cubic-bezier\(([^)]+)\)/.exec(ease);
  if (!m) return null;
  const n = m[1].split(',').map(s => parseFloat(s));
  return n.length === 4 ? n : null;
}
function EaseCurve({ ease, color = 'var(--sky)' }) {
  const b = parseBezier(ease);
  const W = 50, H = 50, pad = 6;
  const sx = v => pad + v * (W - 2 * pad), sy = v => (H - pad) - v * (H - 2 * pad);
  let path;
  if (b) path = `M ${sx(0)} ${sy(0)} C ${sx(b[0])} ${sy(b[1])}, ${sx(b[2])} ${sy(b[3])}, ${sx(1)} ${sy(1)}`;
  else if (ease === 'linear') path = `M ${sx(0)} ${sy(0)} L ${sx(1)} ${sy(1)}`;
  else if (ease.includes('out')) path = `M ${sx(0)} ${sy(0)} C ${sx(0)} ${sy(0.7)}, ${sx(0.35)} ${sy(1)}, ${sx(1)} ${sy(1)}`;
  else if (ease.includes('stepped')) path = `M ${sx(0)} ${sy(0)} L ${sx(0.4)} ${sy(0.4)} L ${sx(0.4)} ${sy(0.7)} L ${sx(1)} ${sy(0.7)} L ${sx(1)} ${sy(1)}`;
  else path = `M ${sx(0)} ${sy(0)} L ${sx(1)} ${sy(0)}`; // instant
  return <svg width={W} height={H} viewBox={`0 0 ${W} ${H}`}>
    <line x1={pad} y1={H-pad} x2={W-pad} y2={H-pad} stroke="var(--line)" strokeWidth="1.5"/>
    <line x1={pad} y1={pad} x2={pad} y2={H-pad} stroke="var(--line)" strokeWidth="1.5"/>
    <path d={path} fill="none" stroke={color} strokeWidth="2.2" strokeLinecap="round"/>
  </svg>;
}

// looping mini-demo per move
function Demo({ name, tint }) {
  const box = { width: 54, height: 54, position: 'relative', display: 'grid', placeItems: 'center', overflow: 'hidden' };
  if (name.includes('squash') || name.includes('tip'))
    return <div style={box}><div style={{ animation: 'hh-demo-squash 1.2s cubic-bezier(.34,1.56,.64,1) infinite' }}><Prop type="cube" size={30} /></div></div>;
  if (name.includes('Gulp') || name.includes('crumble'))
    return <div style={box}>{[0,1,2,3,4].map(i => <span key={i} style={{ position: 'absolute', width: 7, height: 7, borderRadius: '50%', background: 'var(--slate)', '--px': `${Math.cos(i/5*6.28)*18}px`, '--py': `${Math.sin(i/5*6.28)*18}px`, animation: 'hh-puff 1.1s ease-out infinite' }} />)}</div>;
  if (name.includes('Score') || name.includes('tick'))
    return <div style={box}><div className="num" style={{ color: 'var(--sun)', fontWeight: 700, fontSize: 17, animation: 'hh-float 1.4s ease-out infinite' }}>+30</div></div>;
  if (name.includes('haptic'))
    return <div style={box}><div style={{ animation: 'hh-demo-buzz .5s ease-in-out infinite' }}><I.phone width={26} style={{ color: tint }} /></div></div>;
  if (name.includes('callout'))
    return <div style={box}><div className="disp" style={{ fontSize: 13, color: '#fff', WebkitTextStroke: '1.5px var(--coral)', animation: 'hh-pop 1.2s cubic-bezier(.34,1.56,.64,1) infinite' }}>×3</div></div>;
  if (name.includes('chime') || name.includes('pitch'))
    return <div style={{ ...box, alignItems: 'flex-end' }}><div style={{ display: 'flex', gap: 3, alignItems: 'flex-end' }}>{[0,1,2,3].map(i => <span key={i} style={{ width: 5, height: 8 + i*8, background: tint, borderRadius: 2, animation: `hh-demo-bar 1s ${i*0.12}s ease-in-out infinite` }} />)}</div></div>;
  if (name.includes('burst'))
    return <div style={box}><div style={{ position: 'absolute', width: 40, height: 40, borderRadius: '50%', border: `3px solid ${tint}`, animation: 'hh-ring 1.1s ease-out infinite' }} /></div>;
  if (name.includes('ring-pulse') || name.includes('Growth'))
    return <div style={box}><div style={{ animation: 'hh-grow-demo 1.2s ease-in-out infinite alternate' }}><HoleVisual r={16} skin="classic" /></div></div>;
  if (name.includes('Camera') || name.includes('punch'))
    return <div style={box}><div style={{ animation: 'hh-demo-punch 1.2s ease-out infinite', fontSize: 22, color: tint }}>◎</div></div>;
  if (name.includes('Star stamp'))
    return <div style={box}><div style={{ color: 'var(--sun)', animation: 'hh-stamp 1.2s cubic-bezier(.34,1.56,.64,1) infinite' }}><I.star width={28} /></div></div>;
  if (name.includes('Coin'))
    return <div style={box}><div style={{ animation: 'hh-coin 1.2s ease-out infinite' }}><Coin size={22} /></div></div>;
  if (name.includes('Confetti'))
    return <div style={box}>{[0,1,2,3].map(i => <span key={i} style={{ position: 'absolute', left: `${20+i*20}%`, top: 0, width: 6, height: 9, borderRadius: 1, background: [tint,'var(--coral)','var(--mint)','var(--sky)'][i], animation: `hh-confetti 1.4s ${i*0.12}s linear infinite` }} />)}</div>;
  if (name.includes('slow') || name.includes('Slow'))
    return <div style={box}><svg width="30" height="30" viewBox="0 0 30 30"><circle cx="15" cy="15" r="11" fill="none" stroke={tint} strokeWidth="2"/><line x1="15" y1="15" x2="15" y2="6" stroke={tint} strokeWidth="2" strokeLinecap="round" style={{ transformOrigin: '15px 15px', animation: 'hh-spin 4s linear infinite' }}/></svg></div>;
  return <EaseCurve ease="ease-out" color={tint} />;
}

function Mono({ children }) {
  return <span style={{ display: 'inline-block', padding: '3px 8px', borderRadius: 7, background: 'var(--card)', border: '1px solid var(--line)', fontSize: 11, fontWeight: 700, fontFamily: 'ui-monospace,Menlo,monospace', color: 'var(--slate)' }}>{children}</span>;
}

// ---------- Motion & Juice spec ----------
function MotionSpec({ go }) {
  const HH = window.HH;
  return (
    <Sheet title="Motion & juice" sub="Animation spec" onBack={() => go('map')}>
      {/* live loop */}
      <div className="panel" style={{ borderRadius: 26, height: 210, position: 'relative', overflow: 'hidden', marginBottom: 10, padding: 0 }}>
        <Board world={HH.WORLDS[0]} level={1} interactive={false} small onUpdate={() => {}} />
        <div className="hh-hudchip" style={{ position: 'absolute', top: 12, left: 12, gap: 7, fontFamily: 'var(--disp)', fontSize: 12.5 }}>
          <span style={{ width: 8, height: 8, borderRadius: '50%', background: 'var(--coral)', boxShadow: '0 0 6px var(--coral)', animation: 'hh-glowpulse 1.6s ease-in-out infinite' }} />Live loop — drag·eat·grow
        </div>
      </div>
      <p style={{ fontSize: 13.5, fontWeight: 600, lineHeight: 1.6, color: 'var(--slate)', margin: '6px 4px 4px' }}>
        Four reward tiers, each firing animation + sound + haptic together. Restrained particles, capped screen-shake, reduced-motion safe.
      </p>

      {HH.MOTION.map((grp) => (
        <div key={grp.group} style={{ marginTop: 20 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 12 }}>
            <span style={{ width: 10, height: 10, borderRadius: 3, background: grp.tint }} />
            <span className="disp" style={{ fontSize: 20 }}>{grp.group}</span>
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
            {grp.items.map((mv, i) => (
              <div key={mv.name} className="card fadeup" style={{ animationDelay: `${i*0.04}s`, padding: 12, display: 'flex', gap: 12, alignItems: 'center', background: '#fff' }}>
                <div style={{ width: 54, height: 54, borderRadius: 12, background: 'var(--cloud)', border: '1px solid var(--line)', flexShrink: 0, overflow: 'hidden' }}><Demo name={mv.name} tint={grp.tint} /></div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontWeight: 800, fontSize: 14.5 }}>{mv.name}</div>
                  <div style={{ display: 'flex', gap: 6, margin: '7px 0', flexWrap: 'wrap' }}><Mono>{mv.dur}</Mono><Mono>{mv.ease.replace('cubic-bezier', 'cb')}</Mono></div>
                  <div style={{ fontSize: 12, fontWeight: 600, lineHeight: 1.5, color: 'var(--slate)' }}>{mv.detail}</div>
                </div>
                <div style={{ flexShrink: 0, alignSelf: 'flex-start' }}><EaseCurve ease={mv.ease} color={grp.tint} /></div>
              </div>
            ))}
          </div>
        </div>
      ))}
      <div style={{ height: 8 }} />
    </Sheet>
  );
}

// ---------- UI Component sheet ----------
function Components({ go }) {
  const HH = window.HH;
  const [tog, setTog] = useStateMo(true);
  return (
    <Sheet title="Component sheet" sub="UI kit" onBack={() => go('map')}>
      {/* color tokens */}
      <Label style={{ marginTop: 4 }}>Color tokens</Label>
      <div className="card" style={{ padding: 16, background: '#fff' }}>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5,1fr)', gap: 10, marginBottom: 12 }}>
          {[['Sky', HH.C.sky], ['Grape', HH.C.grape], ['Sun', HH.C.sun], ['Coral', HH.C.coral], ['Mint', HH.C.mint]].map(([n, c]) => (
            <div key={n} style={{ textAlign: 'center' }}><div style={{ height: 44, borderRadius: 12, background: c, boxShadow: 'inset 0 -4px 0 rgba(0,0,0,0.12)' }} /><div style={{ fontWeight: 800, fontSize: 10.5, marginTop: 5 }}>{n}</div></div>
          ))}
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5,1fr)', gap: 10 }}>
          {[['Ink', HH.C.ink], ['Slate', HH.C.slate], ['Cloud', HH.C.cloud], ['Card', HH.C.card], ['Line', HH.C.line]].map(([n, c]) => (
            <div key={n} style={{ textAlign: 'center' }}><div style={{ height: 44, borderRadius: 12, background: c, border: '1px solid var(--line)' }} /><div style={{ fontWeight: 800, fontSize: 10.5, marginTop: 5 }}>{n}</div></div>
          ))}
        </div>
      </div>

      {/* type */}
      <Label>Typography</Label>
      <div className="card" style={{ padding: 18, background: '#fff' }}>
        <div className="disp" style={{ fontSize: 30 }}>Baloo 2 — Display</div>
        <div className="num" style={{ fontSize: 26, color: 'var(--ink)' }}>1,234,560 — Fredoka numerals</div>
        <div style={{ fontWeight: 700, fontSize: 15, color: 'var(--slate)', marginTop: 4 }}>Nunito — UI & body copy, two weights max.</div>
      </div>

      {/* buttons */}
      <Label>Buttons</Label>
      <div style={{ display: 'flex', flexWrap: 'wrap', gap: 10, marginBottom: 4 }}>
        <button className="btn sm">Primary</button>
        <button className="btn sun sm">Sun</button>
        <button className="btn mint sm">Mint</button>
        <button className="btn coral sm">Coral</button>
        <button className="btn grape sm">Grape</button>
        <button className="btn ghost sm">Ghost</button>
      </div>

      {/* chips & currency */}
      <Label>Chips · currency · stars</Label>
      <div className="card" style={{ padding: 16, background: '#fff', display: 'flex', flexWrap: 'wrap', gap: 12, alignItems: 'center' }}>
        <CurChip kind="coin" value={3240} />
        <span className="chip" style={{ gap: 6 }}><PowerIcon id="bolt" size={16} color="var(--grape)" />Power</span>
        <Stars n={2} size={22} />
        <TimerRing frac={0.65} label={38} />
        <Toggle on={tog} onClick={() => setTog(!tog)} />
      </div>

      {/* goal chips */}
      <Label>Goal types (10)</Label>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
        {Object.values(HH.GOALS).map(g => (
          <div key={g.id} className="card" style={{ padding: 12, background: '#fff', display: 'flex', alignItems: 'center', gap: 10 }}>
            <span style={{ width: 34, height: 34, borderRadius: '50%', background: g.color, color: '#fff', display: 'grid', placeItems: 'center', flexShrink: 0 }}><GoalGlyph id={g.id} size={19} color="#fff" /></span>
            <div><div style={{ fontWeight: 800, fontSize: 13 }}>{g.verb}</div></div>
          </div>
        ))}
      </div>

      {/* map nodes */}
      <Label>Map nodes</Label>
      <div className="card" style={{ padding: 16, background: '#fff', display: 'flex', gap: 18, alignItems: 'center', justifyContent: 'center' }}>
        {[['Locked', '#fff', 'lock'], ['Active', 'var(--sky)', 'active'], ['Cleared', '#fff', 'done']].map(([lbl, bg, kind]) => (
          <div key={lbl} style={{ textAlign: 'center' }}>
            <div style={{ width: 56, height: 56, borderRadius: '50%', display: 'grid', placeItems: 'center', margin: '0 auto',
              background: kind === 'active' ? `linear-gradient(180deg,#34b6ff,var(--sky))` : '#fff', border: kind === 'active' ? '3px solid var(--ink)' : '3px solid var(--line)', boxShadow: 'var(--shadow)', color: kind === 'active' ? '#fff' : 'var(--ink)' }}>
              {kind === 'lock' ? <span style={{ color: 'var(--slate)' }}><I.lock /></span> : kind === 'done' ? <span className="num disp" style={{ fontSize: 22 }}>4</span> : <GoalGlyph id="sweep" size={24} color="#fff" />}
            </div>
            {kind === 'done' && <div style={{ marginTop: 4 }}><Stars n={3} size={11} gap={1} /></div>}
            <div style={{ fontWeight: 800, fontSize: 11, marginTop: 6, color: 'var(--slate)' }}>{lbl}</div>
          </div>
        ))}
      </div>

      {/* hole skins */}
      <Label>Hole skins</Label>
      <div className="card" style={{ padding: 18, background: '#fff', display: 'flex', flexWrap: 'wrap', gap: 16, justifyContent: 'space-around' }}>
        {HH.SKINS.map(s => <div key={s.id} style={{ textAlign: 'center' }}><HoleVisual r={24} skin={s.id} /><div style={{ fontWeight: 800, fontSize: 10, marginTop: 6 }}>{s.name}</div></div>)}
      </div>
      <div style={{ height: 8 }} />
    </Sheet>
  );
}

Object.assign(window, { MotionSpec, Components, EaseCurve, Demo });
