/* ============================================================
   Pip the Penguin — SunFront × World Cup 2026 campaign mascot.

   Two exports (globals, no build step):
     <PenguinIcon size={32} />            static, scalable — use as logo / favicon / chips
     <PenguinMascot ref={r} size={130} /> interactive character with an imperative API:
        r.current.greet()            time-aware hello + wave + bubble
        r.current.wave()             flipper wave
        r.current.celebrate(msg)     jump + sparkles + (optional speech bubble)
        r.current.success(msg)       happy cheer
        r.current.error(msg)         worried shake + sweat drop
        r.current.think(on, msg)     persistent "loading / saving" pose (true to start, false to stop)
        r.current.say(msg, ms)       speech bubble only
        r.current.reset()            back to idle

   Idle life (automatic): breathing bob, periodic blink, occasional look-around,
   and pupils that subtly track the cursor. Honors prefers-reduced-motion.
   ============================================================ */

const { forwardRef, useImperativeHandle } = React; // useState/useEffect/useRef are global (components.jsx)

/* ---- palette (on-brand) ---- */
const PENG = {
  body:   '#262e4a',
  bodyHi: '#323c61',
  belly:  '#ffffff',
  beak:   '#F15623',
  beakDk: '#C74315',
  feet:   '#F15623',
  cheek:  '#F9A07B',
  scarf:  '#F15623',
  scarfHi:'#FFD2C2',
  pupil:  '#171d33',
  spark:  '#FFC83D',
};

/* ---- keyframes injected once ---- */
const PENGUIN_CSS = `
@keyframes peng-bob   { 0%,100%{transform:translateY(0)} 50%{transform:translateY(-3px)} }
@keyframes peng-jump  { 0%,100%{transform:translateY(0)} 30%{transform:translateY(-16px)} 55%{transform:translateY(2px)} 75%{transform:translateY(-4px)} }
@keyframes peng-shake { 0%,100%{transform:translateX(0) rotate(0)} 20%{transform:translateX(-5px) rotate(-3deg)} 40%{transform:translateX(5px) rotate(3deg)} 60%{transform:translateX(-4px) rotate(-2deg)} 80%{transform:translateX(4px) rotate(2deg)} }
@keyframes peng-wave  { 0%,100%{transform:rotate(0)} 25%{transform:rotate(-34deg)} 50%{transform:rotate(-14deg)} 75%{transform:rotate(-34deg)} }
@keyframes peng-flap  { 0%,100%{transform:rotate(-18deg)} 50%{transform:rotate(-46deg)} }
@keyframes peng-spark { 0%{opacity:0;transform:scale(0.3)} 40%{opacity:1;transform:scale(1.15)} 100%{opacity:0;transform:scale(0.6)} }
@keyframes peng-drop  { 0%{opacity:0;transform:translateY(-4px) scale(.7)} 30%{opacity:1} 100%{opacity:0;transform:translateY(16px) scale(1)} }
@keyframes peng-dots  { 0%{opacity:0;transform:translateY(6px) scale(.5)} 35%{opacity:1;transform:translateY(0) scale(1)} 100%{opacity:0;transform:translateY(-8px) scale(.7)} }
@keyframes peng-bubble{ from{opacity:0;transform:translate(-50%,6px) scale(.92)} to{opacity:1;transform:translate(-50%,0) scale(1)} }
.peng-root{ cursor:pointer; -webkit-tap-highlight-color:transparent; user-select:none; }
.peng-bob   { animation:peng-bob 3.4s ease-in-out infinite; transform-origin:50% 100%; }
.peng-jump  { animation:peng-jump 0.7s cubic-bezier(.3,.8,.3,1) 1; transform-origin:50% 100%; }
.peng-shake { animation:peng-shake 0.5s ease-in-out 1; transform-origin:50% 90%; }
.peng-flipperL{ transform-origin:58px 120px; }
.peng-flipperR{ transform-origin:142px 120px; }
.peng-wave  { animation:peng-wave 0.9s ease-in-out infinite; }
.peng-flap  { animation:peng-flap 0.5s ease-in-out infinite; }
.peng-spark { animation:peng-spark 0.9s ease-out infinite; }
.peng-drop  { animation:peng-drop 1.1s ease-in infinite; }
.peng-dot   { animation:peng-dots 1.4s ease-in-out infinite; }
.peng-eyes  { transition:transform 0.12s ease; transform-origin:center; }
.peng-pupils{ transition:transform 0.18s cubic-bezier(.2,.7,.2,1); }
.peng-head  { transition:transform 0.3s cubic-bezier(.2,.7,.2,1); transform-origin:100px 110px; }
@media (prefers-reduced-motion: reduce){
  .peng-bob,.peng-jump,.peng-shake,.peng-wave,.peng-flap,.peng-spark,.peng-drop,.peng-dot{ animation:none !important; }
}`;

function injectPenguinCSS() {
  if (typeof document === 'undefined') return;
  if (document.getElementById('penguin-css')) return;
  const s = document.createElement('style');
  s.id = 'penguin-css';
  s.textContent = PENGUIN_CSS;
  document.head.appendChild(s);
}

/* brows per mood: [leftPath, rightPath] in viewBox coords */
const BROWS = {
  idle:      ['M70 74 q9 -4 18 -1',  'M112 73 q9 -3 18 1'],
  happy:     ['M68 70 q10 -7 20 -2', 'M112 68 q10 -5 20 2'],
  worried:   ['M70 70 q10 5 19 0',   'M111 70 q9 5 19 -1'],
  think:     ['M70 73 q9 -5 18 -2',  'M114 76 q8 -1 17 3'],
};

/* The artwork. Pure presentational — driven entirely by props. */
function PenguinSVG({ size = 130, mood = 'idle', blink = false, look = { x: 0, y: 0 }, waving = false }) {
  const brow = BROWS[mood] || BROWS.idle;
  const happy = mood === 'happy';
  const worried = mood === 'error' || mood === 'worried';
  const think = mood === 'think';
  const px = (look.x || 0), py = (look.y || 0);

  return (
    <svg viewBox="0 0 200 230" width={size} height={size * 230 / 200} className="peng-svg" aria-hidden="true">
      <defs>
        <radialGradient id="pengBelly" cx="50%" cy="42%" r="62%">
          <stop offset="0%" stopColor="#ffffff" />
          <stop offset="100%" stopColor="#eef1f8" />
        </radialGradient>
        <linearGradient id="pengBody" x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor={PENG.bodyHi} />
          <stop offset="100%" stopColor={PENG.body} />
        </linearGradient>
      </defs>

      {/* soft ground shadow */}
      <ellipse cx="100" cy="214" rx="52" ry="9" fill="#110618" opacity="0.12" />

      {/* feet */}
      <g>
        <path d="M76 196 q-16 4 -20 13 q-1 6 9 6 l20 0 q4 -1 3 -6 l-2 -13 z" fill={PENG.feet} />
        <path d="M124 196 q16 4 20 13 q1 6 -9 6 l-20 0 q-4 -1 -3 -6 l2 -13 z" fill={PENG.feet} />
      </g>

      {/* ---- character (animatable group) ---- */}
      <g className="peng-body-grp">
        {/* body */}
        <path d="M100 36
                 C61 36 44 70 44 116
                 C44 170 64 202 100 202
                 C136 202 156 170 156 116
                 C156 70 139 36 100 36 Z"
              fill="url(#pengBody)" />
        {/* belly */}
        <path d="M100 78 C77 78 66 100 66 134 C66 168 80 192 100 192 C120 192 134 168 134 134 C134 100 123 78 100 78 Z"
              fill="url(#pengBelly)" />

        {/* flippers */}
        <g className={`peng-flipperL ${waving ? 'peng-wave' : (think ? '' : (happy ? 'peng-flap' : ''))}`}>
          <path d="M50 104 q-22 14 -16 48 q3 12 13 6 q10 -8 14 -28 z" fill={PENG.body} />
        </g>
        <g className={`peng-flipperR ${happy ? 'peng-flap' : ''}`}>
          <path d="M150 104 q22 14 16 48 q-3 12 -13 6 q-10 -8 -14 -28 z" fill={PENG.body} />
        </g>

        {/* scarf (campaign flair) */}
        <g>
          <path d="M64 150 q36 18 72 0 l0 14 q-36 18 -72 0 z" fill={PENG.scarf} />
          <path d="M64 150 q36 18 72 0" fill="none" stroke={PENG.scarfHi} strokeWidth="3" opacity="0.8" />
          <path d="M128 160 l14 30 q-9 6 -18 1 l-6 -26 z" fill={PENG.scarf} />
          <path d="M128 168 l11 22" stroke={PENG.scarfHi} strokeWidth="3" fill="none" opacity="0.8" />
        </g>

        {/* ---- head features ---- */}
        <g className="peng-head" style={{ transform: think ? 'rotate(-7deg)' : 'rotate(0deg)' }}>
          {/* cheeks */}
          <ellipse cx="74" cy="118" rx="9" ry="6" fill={PENG.cheek} opacity={worried ? 0.5 : 0.85} />
          <ellipse cx="126" cy="118" rx="9" ry="6" fill={PENG.cheek} opacity={worried ? 0.5 : 0.85} />

          {/* eyes */}
          <g className="peng-eyes" style={{ transform: blink ? 'scaleY(0.12)' : 'scaleY(1)', transformBox: 'fill-box' }}>
            <circle cx="82" cy="98" r="14" fill="#fff" stroke="#e4e7f0" strokeWidth="1" />
            <circle cx="118" cy="98" r="14" fill="#fff" stroke="#e4e7f0" strokeWidth="1" />
            <g className="peng-pupils" style={{ transform: `translate(${px}px, ${py}px)` }}>
              <circle cx="82" cy="99" r={happy ? 6.5 : (worried ? 5 : 7)} fill={PENG.pupil} />
              <circle cx="118" cy="99" r={happy ? 6.5 : (worried ? 5 : 7)} fill={PENG.pupil} />
              <circle cx="85" cy="96" r="2.2" fill="#fff" />
              <circle cx="121" cy="96" r="2.2" fill="#fff" />
            </g>
          </g>

          {/* brows */}
          <path d={brow[0]} fill="none" stroke={PENG.pupil} strokeWidth="3.4" strokeLinecap="round" />
          <path d={brow[1]} fill="none" stroke={PENG.pupil} strokeWidth="3.4" strokeLinecap="round" />

          {/* beak */}
          {happy ? (
            <g>
              <path d="M86 116 q14 14 28 0 q-14 8 -28 0 z" fill={PENG.beakDk} />
              <path d="M88 114 q12 4 24 0 l-2 4 q-10 3 -20 0 z" fill={PENG.beak} />
            </g>
          ) : worried ? (
            <g>
              <path d="M92 116 q8 -6 16 0 q-8 -2 -16 0 z" fill={PENG.beak} />
              <ellipse cx="100" cy="122" rx="6" ry="4.5" fill={PENG.beakDk} />
            </g>
          ) : (
            <path d="M100 110 l13 9 l-13 8 l-13 -8 z" fill={PENG.beak} stroke={PENG.beakDk} strokeWidth="1" />
          )}
        </g>
      </g>

      {/* ---- mood accessories ---- */}
      {happy && (
        <g fill={PENG.spark}>
          <path className="peng-spark" style={{ transformOrigin: '36px 60px', animationDelay: '0s' }}   d="M36 50 l3 8 l8 3 l-8 3 l-3 8 l-3 -8 l-8 -3 l8 -3 z" />
          <path className="peng-spark" style={{ transformOrigin: '166px 64px', animationDelay: '.25s' }} d="M166 56 l2.4 6 l6 2.4 l-6 2.4 l-2.4 6 l-2.4 -6 l-6 -2.4 l6 -2.4 z" />
          <path className="peng-spark" style={{ transformOrigin: '100px 20px', animationDelay: '.5s' }}  d="M100 13 l2.2 5.5 l5.5 2.2 l-5.5 2.2 l-2.2 5.5 l-2.2 -5.5 l-5.5 -2.2 l5.5 -2.2 z" />
        </g>
      )}
      {worried && (
        <path className="peng-drop" style={{ transformOrigin: '146px 78px' }}
              d="M146 72 q5 8 5 12 a5 5 0 0 1 -10 0 q0 -4 5 -12 z" fill="#39b6f0" />
      )}
      {think && (
        <g fill={PENG.scarf}>
          <circle className="peng-dot" style={{ animationDelay: '0s' }}   cx="150" cy="58" r="4" />
          <circle className="peng-dot" style={{ animationDelay: '.25s' }} cx="162" cy="48" r="5" />
          <circle className="peng-dot" style={{ animationDelay: '.5s' }}  cx="175" cy="40" r="6" />
        </g>
      )}
    </svg>
  );
}

/* Static icon — no state, no listeners. Safe for logos / favicons / chips. */
function PenguinIcon({ size = 36, style }) {
  return (
    <span style={{ display: 'inline-flex', lineHeight: 0, ...style }}>
      <PenguinSVG size={size} mood="idle" />
    </span>
  );
}

/* Interactive mascot with imperative handle. */
const PenguinMascot = forwardRef(function PenguinMascot(
  { size = 130, trackCursor = true, floating = false, onClick, greetOnMount = false, bubbleBelow = false, bubbleRight = false }, ref
) {
  injectPenguinCSS();
  const [mood, setMood] = useState('idle');       // idle | happy | error | think | worried
  const [anim, setAnim] = useState('');           // '' | jump | shake (one-shot body anims)
  const [waving, setWaving] = useState(false);
  const [blink, setBlink] = useState(false);
  const [look, setLook] = useState({ x: 0, y: 0 });
  const [bubble, setBubble] = useState(null);
  const wrapRef = useRef(null);
  const timers = useRef([]);
  const thinking = useRef(false);

  const clearTimers = () => { timers.current.forEach(clearTimeout); timers.current = []; };
  const after = (ms, fn) => { const t = setTimeout(fn, ms); timers.current.push(t); return t; };

  const toIdle = () => { if (!thinking.current) { setMood('idle'); setAnim(''); setWaving(false); } };

  const showBubble = (msg, ms = 15000) => {
    if (!msg) return;
    setBubble(msg);
    after(ms, () => setBubble(null));
  };

  /* ---- imperative API ---- */
  useImperativeHandle(ref, () => ({
    say(msg, ms) { showBubble(msg, ms); },
    wave() { thinking.current = false; setMood('happy'); setWaving(true); after(1800, toIdle); },
    celebrate(msg) { thinking.current = false; setMood('happy'); setAnim('jump'); setWaving(false); showBubble(msg, 15000); after(750, () => setAnim('')); after(1700, toIdle); },
    success(msg) { this.celebrate(msg || 'Done! 🎉'); },
    error(msg) { thinking.current = false; setMood('error'); setAnim('shake'); showBubble(msg, 15000); after(550, () => setAnim('')); after(2600, toIdle); },
    think(on, msg) {
      thinking.current = !!on;
      if (on) { setMood('think'); setWaving(false); setAnim(''); if (msg) setBubble(msg); }
      else { setBubble(null); toIdle(); }
    },
    greet() {
      const h = new Date().getHours();
      const part = h < 5 ? 'Burning the midnight oil?' : h < 12 ? 'Good morning!' : h < 17 ? 'Good afternoon!' : h < 22 ? 'Good evening!' : 'Working late?';
      let name = '';
      try { const s = JSON.parse(sessionStorage.getItem('sf_admin_session') || 'null'); if (s && s.username) name = ', ' + s.username; } catch (e) {}
      thinking.current = false; setMood('happy'); setWaving(true);
      showBubble(`${part}${name} 🐧`, 15000);
      after(2200, toIdle);
    },
    reset() { thinking.current = false; clearTimers(); setMood('idle'); setAnim(''); setWaving(false); setBubble(null); },
  }), []);

  /* ---- idle life: blink + look-around ---- */
  useEffect(() => {
    let alive = true;
    const blinkLoop = () => {
      if (!alive) return;
      setBlink(true);
      setTimeout(() => setBlink(false), 140);
      setTimeout(blinkLoop, 2400 + Math.random() * 3200);
    };
    const bt = setTimeout(blinkLoop, 1500);
    const lookLoop = () => {
      if (!alive) return;
      if (!trackCursor && mood === 'idle') setLook({ x: (Math.random() * 6 - 3), y: (Math.random() * 4 - 2) });
      setTimeout(lookLoop, 2600 + Math.random() * 2600);
    };
    const lt = setTimeout(lookLoop, 2000);
    return () => { alive = false; clearTimeout(bt); clearTimeout(lt); };
  }, [trackCursor, mood]);

  /* ---- cursor tracking ---- */
  useEffect(() => {
    if (!trackCursor) return;
    const onMove = (e) => {
      const el = wrapRef.current; if (!el) return;
      const r = el.getBoundingClientRect();
      const cx = r.left + r.width / 2, cy = r.top + r.height * 0.42;
      const dx = e.clientX - cx, dy = e.clientY - cy;
      const d = Math.max(Math.hypot(dx, dy), 1);
      setLook({ x: Math.max(-4, Math.min(4, dx / d * 4)), y: Math.max(-3, Math.min(3, dy / d * 3)) });
    };
    window.addEventListener('mousemove', onMove, { passive: true });
    return () => window.removeEventListener('mousemove', onMove);
  }, [trackCursor]);

  useEffect(() => {
    if (greetOnMount) { const t = setTimeout(() => { ref && ref.current && ref.current.greet(); }, 600); return () => clearTimeout(t); }
  }, []); // eslint-disable-line

  useEffect(() => () => clearTimers(), []);

  const bodyAnimClass = anim === 'jump' ? 'peng-jump' : anim === 'shake' ? 'peng-shake' : 'peng-bob';

  const handleClick = (e) => {
    if (thinking.current) return;
    setMood('happy'); setAnim('jump'); after(750, () => setAnim('')); after(1500, toIdle);
    onClick && onClick(e);
  };

  const wrapStyle = floating
    ? { position: 'fixed', right: 22, bottom: 22, zIndex: 50, width: size }
    : { position: 'relative', width: size, display: 'inline-block' };

  return (
    <div ref={wrapRef} className="peng-root" style={wrapStyle}
         onClick={handleClick} role="button" tabIndex={0}
         aria-label="Pip the penguin mascot"
         onKeyDown={(e) => { if (e.key === 'Enter' || e.key === ' ') handleClick(e); }}>
      {bubble && (
        <div style={{
          position: 'absolute',
          ...(bubbleRight
            ? { right: 0 }
            : { left: '50%', transform: 'translateX(-50%)' }
          ),
          ...(bubbleBelow ? { top: '100%', marginTop: 8 } : { bottom: '100%', marginBottom: 8 }),
          background: '#fff', color: 'var(--ink, #110618)',
          border: '1.5px solid var(--grey-200, #e5e5e5)', borderRadius: 12,
          padding: '8px 12px', fontSize: 13, fontWeight: 600,
          whiteSpace: 'normal', wordBreak: 'break-word',
          boxShadow: '0 6px 22px rgba(17,6,24,0.14)', animation: 'peng-bubble 0.28s cubic-bezier(.2,.7,.2,1) both',
          fontFamily: "'DM Sans', system-ui, sans-serif", pointerEvents: 'none',
          width: 'max-content', maxWidth: 220, lineHeight: 1.4,
        }}>
          {bubble}
          <span style={{
            position: 'absolute',
            ...(bubbleRight
              ? { right: Math.round(size / 2) - 7, left: 'auto', transform: 'none' }
              : { left: '50%', transform: 'translateX(-50%)' }
            ),
            width: 0, height: 0, borderLeft: '7px solid transparent', borderRight: '7px solid transparent',
            ...(bubbleBelow
              ? { bottom: '100%', borderBottom: '8px solid #fff', filter: 'drop-shadow(0 -1px 0 rgba(0,0,0,0.06))' }
              : { top: '100%', borderTop: '8px solid #fff', filter: 'drop-shadow(0 1px 0 rgba(0,0,0,0.06))' }
            ),
          }} />
        </div>
      )}
      <div className={bodyAnimClass} style={{ transformOrigin: '50% 100%' }}>
        <PenguinSVG size={size} mood={mood} blink={blink} look={look} waving={waving} />
      </div>
    </div>
  );
});

Object.assign(window, { PenguinIcon, PenguinMascot, PenguinSVG });
