/* Flying hornet that roams the page + Tweaks panel */

function HornetFlyer({ enabled }) {
  const [pos, setPos] = React.useState({ x: -100, y: 200, rot: 0 });
  const targetRef = React.useRef({ x: 200, y: 200 });
  const rafRef = React.useRef();
  const stateRef = React.useRef({ x: -100, y: 200, vx: 2, vy: 0, lastChange: 0 });

  React.useEffect(() => {
    if (!enabled) return;
    const onMove = (e) => {
      // occasionally target near cursor
      if (Math.random() < 0.02) {
        targetRef.current = {
          x: e.clientX + (Math.random() - 0.5) * 300,
          y: e.clientY + (Math.random() - 0.5) * 200,
        };
      }
    };
    window.addEventListener('mousemove', onMove);
    return () => window.removeEventListener('mousemove', onMove);
  }, [enabled]);

  React.useEffect(() => {
    if (!enabled) return;
    let t0 = performance.now();
    const tick = (t) => {
      const dt = Math.min(50, t - t0); t0 = t;
      const s = stateRef.current;
      // pick new random target occasionally
      if (t - s.lastChange > 3500) {
        s.lastChange = t;
        targetRef.current = {
          x: Math.random() * window.innerWidth,
          y: 100 + Math.random() * (window.innerHeight - 200),
        };
      }
      const dx = targetRef.current.x - s.x;
      const dy = targetRef.current.y - s.y;
      // spring toward target
      s.vx += dx * 0.0008 * dt;
      s.vy += dy * 0.0008 * dt;
      // buzzy wobble
      s.vx += (Math.random() - 0.5) * 0.4;
      s.vy += (Math.random() - 0.5) * 0.4;
      // damping
      s.vx *= 0.94;
      s.vy *= 0.94;
      s.x += s.vx;
      s.y += s.vy;
      const rot = Math.atan2(s.vy, Math.abs(s.vx)) * 15;
      const flip = s.vx < 0 ? -1 : 1;
      setPos({ x: s.x, y: s.y, rot, flip });
      rafRef.current = requestAnimationFrame(tick);
    };
    rafRef.current = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(rafRef.current);
  }, [enabled]);

  if (!enabled) return null;

  return (
    <div
      className="hornet-flyer"
      style={{
        transform: `translate(${pos.x - 28}px, ${pos.y - 28}px) scaleX(${pos.flip || 1}) rotate(${pos.rot}deg)`,
      }}
    >
      <svg viewBox="0 0 64 64" width="56" height="56">
        <defs>
          <filter id="wingblur"><feGaussianBlur stdDeviation="0.6"/></filter>
        </defs>
        {/* Wings - blurred and flapping */}
        <g filter="url(#wingblur)" opacity="0.75">
          <ellipse cx="22" cy="18" rx="14" ry="6" fill="#F2EADF" opacity="0.6">
            <animate attributeName="ry" values="6;2;6" dur="0.08s" repeatCount="indefinite"/>
          </ellipse>
          <ellipse cx="18" cy="22" rx="12" ry="5" fill="#F2EADF" opacity="0.45">
            <animate attributeName="ry" values="5;1.8;5" dur="0.08s" repeatCount="indefinite" begin="0.04s"/>
          </ellipse>
        </g>
        {/* Body */}
        <ellipse cx="36" cy="34" rx="16" ry="10" fill="#0a0a0a" stroke="#F5B800" strokeWidth="1"/>
        {/* Yellow stripes */}
        <path d="M 28,26 L 28,42 M 36,25 L 36,43 M 44,26 L 44,42" stroke="#F5B800" strokeWidth="4" fill="none" strokeLinecap="round"/>
        {/* Head */}
        <circle cx="52" cy="30" r="7" fill="#F5B800"/>
        <circle cx="54" cy="28" r="1.8" fill="#0a0a0a"/>
        {/* Stinger */}
        <path d="M 20,34 L 10,32 L 20,36 Z" fill="#0a0a0a"/>
      </svg>
    </div>
  );
}

function TweaksPanel({ active, state, setState }) {
  if (!active) return null;
  const setK = (k, v) => {
    const next = { ...state, [k]: v };
    setState(next);
    window.parent.postMessage({ type: '__edit_mode_set_keys', edits: { [k]: v } }, '*');
  };

  return (
    <div className="tweaks-panel">
      <h4>Tweaks</h4>

      <div className="tweak-row">
        <label>Palette</label>
        <div className="opts">
          <button className={state.palette === 'dark' ? 'active' : ''} onClick={() => setK('palette', 'dark')}>Dark</button>
          <button className={state.palette === 'cream' ? 'active' : ''} onClick={() => setK('palette', 'cream')}>Cream</button>
        </div>
      </div>

      <div className="tweak-row">
        <label>Accent</label>
        <div className="swatch-row">
          <div className={"swatch" + (state.accent === 'gold' ? ' active' : '')} style={{background:'#F5B800'}} onClick={() => setK('accent', 'gold')}></div>
          <div className={"swatch" + (state.accent === 'crimson' ? ' active' : '')} style={{background:'#E63946'}} onClick={() => setK('accent', 'crimson')}></div>
          <div className={"swatch" + (state.accent === 'pitch' ? ' active' : '')} style={{background:'#4ADE80'}} onClick={() => setK('accent', 'pitch')}></div>
        </div>
      </div>

      <div className="tweak-row">
        <label>Flying Hornet</label>
        <div className="opts">
          <button className={state.hornet ? 'active' : ''} onClick={() => setK('hornet', true)}>On</button>
          <button className={!state.hornet ? 'active' : ''} onClick={() => setK('hornet', false)}>Off</button>
        </div>
      </div>

      <div className="tweak-row">
        <label>Marquee Ticker</label>
        <div className="opts">
          <button className={state.marquee ? 'active' : ''} onClick={() => setK('marquee', true)}>On</button>
          <button className={!state.marquee ? 'active' : ''} onClick={() => setK('marquee', false)}>Off</button>
        </div>
      </div>

      <div className="tweak-row">
        <label>Hero Headline</label>
        <div className="opts">
          <button className={state.headline === 'fear' ? 'active' : ''} onClick={() => setK('headline', 'fear')}>Fear</button>
          <button className={state.headline === 'hive' ? 'active' : ''} onClick={() => setK('headline', 'hive')}>Hive</button>
          <button className={state.headline === 'sting' ? 'active' : ''} onClick={() => setK('headline', 'sting')}>Sting</button>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { HornetFlyer, TweaksPanel });
