// brownie/page-bakery.jsx — Page 1: HUD + big tappable brownie + orbiting cursor bots.

function BoostCountdown({ until }) {
  const { useState, useEffect } = React;
  const [now, setNow] = useState(() => Date.now());
  useEffect(() => {
    const id = setInterval(() => setNow(Date.now()), 1000);
    return () => clearInterval(id);
  }, []);
  const ms = Math.max(0, new Date(until).getTime() - now);
  const s = Math.floor(ms / 1000);
  const h = Math.floor(s / 3600);
  const m = Math.floor((s % 3600) / 60);
  const sec = s % 60;
  const text = h > 0 ? `${h}h ${m}m` : m > 0 ? `${m}m ${sec}s` : `${sec}s`;
  return <span className="boost-countdown">{text}</span>;
}

function PageBakery({ engine }) {
  const { state, tap, bps, tapValue } = engine;
  const [gains, setGains] = React.useState([]);
  const [bursts, setBursts] = React.useState([]);
  const nextId = React.useRef(1);
  const wrapRef = React.useRef(null);

  const onTap = (e) => {
    tap();
    const wrap = wrapRef.current;
    if (!wrap) return;
    const rect = wrap.getBoundingClientRect();
    const cx = (e.clientX || (e.touches && e.touches[0]?.clientX) || rect.left + rect.width / 2) - rect.left;
    const cy = (e.clientY || (e.touches && e.touches[0]?.clientY) || rect.top + rect.height / 2) - rect.top;
    const id = nextId.current++;

    setGains(g => [...g, { id, x: cx, y: cy, v: tapValue }]);
    setTimeout(() => setGains(g => g.filter(x => x.id !== id)), 1000);

    // Crumb burst — 5 little crumbs flying out
    const newBursts = Array.from({ length: 5 }).map((_, i) => {
      const ang = (Math.PI * 2 * i) / 5 + Math.random() * 0.4;
      const dist = 30 + Math.random() * 26;
      return {
        id: id * 10 + i,
        x: cx, y: cy,
        dx: Math.cos(ang) * dist,
        dy: Math.sin(ang) * dist - 12,
      };
    });
    setBursts(b => [...b, ...newBursts]);
    setTimeout(() => {
      const ids = new Set(newBursts.map(b => b.id));
      setBursts(b => b.filter(x => !ids.has(x.id)));
    }, 720);
  };

  const botCount = Math.min(12, state.producers.spoon || 0);

  return (
    <div className="be-page">
      <div className="bakery-bg" />

      <div className="hud">
        <div className="hud-title">{state.bakeryName || 'Brownie Empire'}</div>
        <div className="hud-count">
          {window.beFmt(Math.floor(state.crumbs))}
          <small>crumbs</small>
        </div>
        <div className="hud-bps">
          <b>{window.beFmt(bps)}</b> per second
        </div>
      </div>

      {bps > 0 && (
        <div className="bps-chip">+{window.beFmt(tapValue)} per tap</div>
      )}

      {engine.boostMult > 1 && (
        <div className="boost-chip">
          <span className="boost-bolt">⚡</span>
          <span>2× BOOST</span>
          <BoostCountdown until={state.boostUntil} />
        </div>
      )}

      {/* drifting bg particles */}
      {Array.from({ length: 10 }).map((_, i) => {
        const left = 8 + ((i * 91) % 84);
        const dur = 6 + (i % 5) * 1.4;
        const delay = (i * 0.7) % 6;
        return (
          <div
            key={i}
            className="bakery-particle"
            style={{ left: `${left}%`, top: '70%', '--dur': `${dur}s`, '--delay': `${delay}s` }}
          />
        );
      })}

      <div className="hero-stage">
        <div className="hero-rays" />
        <div className="hero-glow" />

        <div className="brownie-wrap" ref={wrapRef}>
          {/* steam puffs */}
          {Array.from({ length: 3 }).map((_, i) => (
            <div
              key={`steam-${i}`}
              className="steam"
              style={{
                left: `${42 + i * 8}%`,
                '--sdur': `${3.2 + i * 0.4}s`,
                '--sdelay': `${i * 1.1}s`,
              }}
            />
          ))}
          <div className="brownie" onClick={onTap}>
            <BrownieSVG />
          </div>

          {gains.map(g => (
            <div key={g.id} className="gain" style={{ left: g.x, top: g.y }}>
              +{window.beFmt(g.v)}
            </div>
          ))}
          {bursts.map(b => (
            <div
              key={b.id}
              className="crumb-burst"
              style={{ left: b.x, top: b.y, '--dx': `${b.dx}px`, '--dy': `${b.dy}px` }}
            />
          ))}
        </div>

        {/* Orbiting cursor bots */}
        {Array.from({ length: botCount }).map((_, i) => {
          const angle = (i / Math.max(1, botCount)) * 360;
          const duration = 10 + (i % 3) * 2;
          return (
            <div
              key={i}
              className="cursor-bot-orbit"
              style={{
                width: 30, height: 30,
                transform: `translate(-50%,-50%) rotate(${angle}deg)`,
                '--spin-dur': `${duration}s`,
              }}
            >
              <div style={{
                position: 'absolute',
                left: '50%', top: 0,
                transform: `translate(-50%, -135px) rotate(${-angle}deg)`,
              }}>
                <CursorBotSVG />
              </div>
            </div>
          );
        })}
      </div>

      <div className="shelf-wrap">
        <div className="plate" />
      </div>
    </div>
  );
}

Object.assign(window, { PageBakery });
