/* eslint-disable */
/* ============================================================
   BEVEL — your low-poly mountain pup guide for ATHARV.OS
   Pixel-art SVG rendition (matches the site's Win95 vocabulary).
   Character bible: bevel_design_doc.md — voice, rules, restraint.
============================================================ */

function BevelSprite({ pose, eyesClosed, tongue }) {
  const C = {
    body:    '#F5EBD8',
    saddle:  '#2D3748',
    belly:   '#F0E0C8',
    ink:     '#0A1418',
    collar:  '#008080',
    pendant: '#D69E2E',
    tongue:  '#D49580',
    hi:      '#FFFFFF',
  };

  if (pose === 'sleep') {
    // Curled lying-down pose
    return (
      <svg viewBox="0 0 56 32" width="168" height="96" shapeRendering="crispEdges" className="bevel-svg">
        <ellipse cx="28" cy="29" rx="22" ry="2" fill="rgba(0,0,0,0.25)"/>
        {/* Curled body */}
        <path d="M8 24 Q8 12 22 12 L36 12 Q50 12 50 22 L50 26 L8 26 Z" fill={C.body} stroke={C.ink} strokeWidth="1"/>
        {/* Saddle */}
        <path d="M14 14 Q18 12 26 12 L36 12 Q44 12 46 18 L46 20 L14 20 Z" fill={C.saddle}/>
        {/* Belly bright */}
        <rect x="10" y="22" width="38" height="4" fill={C.belly}/>
        {/* Head resting on paws */}
        <rect x="6" y="18" width="12" height="8" fill={C.body} stroke={C.ink} strokeWidth="1"/>
        {/* Dark muzzle/mask */}
        <rect x="6" y="18" width="12" height="2" fill={C.saddle}/>
        {/* Closed eye - line */}
        <rect x="9" y="22" width="3" height="1" fill={C.ink}/>
        {/* Nose */}
        <rect x="5" y="22" width="2" height="2" fill={C.ink}/>
        {/* Floppy ear draped over head */}
        <rect x="10" y="17" width="6" height="3" fill={C.saddle}/>
        <rect x="10" y="17" width="6" height="1" fill={C.ink}/>
        {/* Tail tucked */}
        <rect x="46" y="18" width="3" height="2" fill={C.body}/>
        <rect x="48" y="16" width="3" height="2" fill={C.saddle}/>
        <rect x="48" y="15" width="3" height="1" fill={C.ink}/>
        {/* Collar */}
        <rect x="16" y="20" width="6" height="2" fill={C.collar}/>
        <rect x="19" y="21" width="1" height="1" fill={C.pendant}/>
        {/* Z particles */}
        <g className="bevel-zzz">
          <text x="22" y="8" fontFamily="'MS Sans Serif', sans-serif" fontSize="6" fill={C.ink} fontWeight="bold">z</text>
          <text x="27" y="5" fontFamily="'MS Sans Serif', sans-serif" fontSize="7" fill={C.ink} fontWeight="bold">z</text>
          <text x="33" y="2" fontFamily="'MS Sans Serif', sans-serif" fontSize="8" fill={C.ink} fontWeight="bold">z</text>
        </g>
      </svg>
    );
  }

  // SITTING pose — default
  return (
    <svg viewBox="0 0 48 44" width="168" height="154" shapeRendering="crispEdges" className="bevel-svg">
      {/* === floor shadow === */}
      <ellipse cx="24" cy="42" rx="14" ry="1.6" fill="rgba(0,0,0,0.28)"/>

      {/* === TAIL (animatable) === */}
      <g className="bevel-tail" style={{transformOrigin:'37px 27px'}}>
        <rect x="36" y="25" width="2" height="2" fill={C.body}/>
        <rect x="38" y="23" width="2" height="2" fill={C.body}/>
        <rect x="40" y="21" width="2" height="2" fill={C.saddle}/>
        <rect x="42" y="19" width="2" height="2" fill={C.saddle}/>
        {/* Outline */}
        <rect x="36" y="24" width="2" height="1" fill={C.ink}/>
        <rect x="38" y="22" width="2" height="1" fill={C.ink}/>
        <rect x="40" y="20" width="2" height="1" fill={C.ink}/>
        <rect x="42" y="18" width="2" height="1" fill={C.ink}/>
        <rect x="44" y="19" width="1" height="2" fill={C.ink}/>
        <rect x="35" y="25" width="1" height="2" fill={C.ink}/>
        <rect x="36" y="27" width="2" height="1" fill={C.ink}/>
      </g>

      {/* === BODY OUTLINE shape === */}
      {/* belly cream backdrop */}
      <rect x="20" y="24" width="18" height="12" fill={C.belly}/>
      {/* saddle on back */}
      <rect x="20" y="24" width="18" height="6" fill={C.saddle}/>
      {/* outline */}
      <rect x="19" y="24" width="1" height="12" fill={C.ink}/>
      <rect x="38" y="24" width="1" height="12" fill={C.ink}/>

      {/* === BACK LEGS (tucked beside body for sit) === */}
      <rect x="32" y="34" width="6" height="4" fill={C.belly}/>
      <rect x="32" y="38" width="6" height="1" fill={C.ink}/>
      <rect x="38" y="34" width="1" height="5" fill={C.ink}/>
      <rect x="32" y="33" width="6" height="1" fill={C.ink}/>

      {/* === FRONT LEGS === */}
      <rect x="20" y="34" width="4" height="4" fill={C.belly}/>
      <rect x="24" y="34" width="1" height="4" fill={C.ink}/>
      <rect x="20" y="38" width="4" height="1" fill={C.ink}/>
      <rect x="19" y="34" width="1" height="5" fill={C.ink}/>

      <rect x="26" y="34" width="4" height="4" fill={C.belly}/>
      <rect x="25" y="34" width="1" height="5" fill={C.ink}/>
      <rect x="30" y="34" width="1" height="4" fill={C.ink}/>
      <rect x="26" y="38" width="4" height="1" fill={C.ink}/>

      {/* === COLLAR === */}
      <rect x="19" y="22" width="16" height="2" fill={C.collar}/>
      <rect x="19" y="24" width="16" height="1" fill={C.ink}/>
      {/* Sigil pendant (4-square) below collar */}
      <g transform="translate(25 24)">
        <rect x="0" y="0" width="2" height="2" fill={C.body}/>
        <rect x="2" y="0" width="2" height="2" fill={C.pendant}/>
        <rect x="0" y="2" width="2" height="2" fill={C.collar}/>
        <rect x="2" y="2" width="2" height="2" fill={C.saddle}/>
        <rect x="-1" y="0" width="1" height="4" fill={C.ink}/>
        <rect x="4" y="0" width="1" height="4" fill={C.ink}/>
        <rect x="0" y="4" width="4" height="1" fill={C.ink}/>
      </g>

      {/* === HEAD GROUP (rotatable for head tilt) === */}
      <g className="bevel-head" style={{transformOrigin:'14px 16px'}}>
        {/* === Right ear (perky, pointing up) === */}
        <polygon points="20,4 26,4 23,10" fill={C.saddle}/>
        <polygon points="20,4 26,4 23,10" fill="none" stroke={C.ink} strokeWidth="1"/>
        <polygon points="22,6 24,6 23,8" fill={C.tongue} opacity="0.55"/>

        {/* === Left ear (floppy, hanging down side of head) === */}
        <rect x="3" y="9" width="3" height="7" fill={C.saddle}/>
        <rect x="2" y="9" width="1" height="8" fill={C.ink}/>
        <rect x="6" y="9" width="1" height="8" fill={C.ink}/>
        <rect x="3" y="16" width="3" height="1" fill={C.ink}/>
        <rect x="3" y="8" width="3" height="1" fill={C.ink}/>

        {/* === Head cream body === */}
        <rect x="6" y="9" width="16" height="13" fill={C.body}/>

        {/* === Dark mask across forehead/around eyes === */}
        <rect x="6" y="9" width="16" height="4" fill={C.saddle}/>
        {/* Mask drops down beside eyes */}
        <rect x="6" y="13" width="2" height="3" fill={C.saddle}/>
        <rect x="20" y="13" width="2" height="3" fill={C.saddle}/>

        {/* === Snout (lighter cream) === */}
        <rect x="10" y="16" width="8" height="5" fill={C.belly}/>

        {/* === Eyes === */}
        {eyesClosed ? (
          <>
            <rect x="8" y="14" width="3" height="1" fill={C.ink}/>
            <rect x="17" y="14" width="3" height="1" fill={C.ink}/>
          </>
        ) : (
          <>
            <rect x="8" y="13" width="2" height="3" fill={C.ink}/>
            <rect x="8" y="13" width="1" height="1" fill={C.hi}/>
            <rect x="17" y="13" width="2" height="3" fill={C.ink}/>
            <rect x="17" y="13" width="1" height="1" fill={C.hi}/>
          </>
        )}

        {/* === Nose === */}
        <rect x="13" y="16" width="2" height="2" fill={C.ink}/>
        <rect x="13" y="16" width="1" height="1" fill={C.saddle}/>

        {/* === Mouth === */}
        <rect x="12" y="19" width="1" height="1" fill={C.ink}/>
        <rect x="15" y="19" width="1" height="1" fill={C.ink}/>
        <rect x="13" y="20" width="2" height="1" fill={C.ink}/>

        {/* === Tongue (when excited) === */}
        {tongue && (
          <>
            <rect x="13" y="20" width="2" height="2" fill={C.tongue}/>
            <rect x="13" y="22" width="2" height="1" fill={C.ink}/>
          </>
        )}

        {/* === Head outline === */}
        <rect x="5" y="9" width="1" height="13" fill={C.ink}/>
        <rect x="22" y="9" width="1" height="13" fill={C.ink}/>
        <rect x="6" y="8" width="16" height="1" fill={C.ink}/>
        <rect x="6" y="22" width="16" height="1" fill={C.ink}/>
        {/* Mask edge */}
        <rect x="6" y="13" width="16" height="1" fill={C.ink}/>
      </g>
    </svg>
  );
}

/* =========================================================== */

function BevelBubble({ message, corner }) {
  return (
    <div className={`bevel-bubble bb-${corner}`}>
      <span dangerouslySetInnerHTML={{__html: message}}/>
      <span className="bevel-bubble-tail"/>
    </div>
  );
}

/* =========================================================== */

function BevelMascot({ phase, windows, mpPlaying, currentTrack, visible }) {
  const [pose, setPose] = React.useState('sit');
  const [action, setAction] = React.useState(null);
  const [corner, setCorner] = React.useState('br');
  const [message, setMessage] = React.useState(null);
  const [eyesClosed, setEyesClosed] = React.useState(false);
  const [tongue, setTongue] = React.useState(false);
  const [petStreak, setPetStreak] = React.useState(0);
  const [petLifetime, setPetLifetime] = React.useState(() => {
    try { return parseInt(localStorage.getItem('atharvos.bevel.pets')||'0', 10) || 0; } catch { return 0; }
  });
  const [firstVisitDone, setFirstVisitDone] = React.useState(() => {
    try { return localStorage.getItem('atharvos.bevel.greeted') === '1'; } catch { return false; }
  });
  const [sessionMinute, setSessionMinute] = React.useState(0);

  const idleTimer = React.useRef(null);
  const sleepTimer = React.useRef(null);
  const messageTimer = React.useRef(null);
  const blinkTimer = React.useRef(null);
  const actionTimer = React.useRef(null);
  const lastSpoke = React.useRef(0);
  const sessionStart = React.useRef(Date.now());

  /* ---- Helpers ---- */
  const showMessage = (msg, duration = 6000, force = false) => {
    const now = Date.now();
    // Anti-Clippy: max 1 message per 8s unless forced (pets/clicks)
    if (!force && now - lastSpoke.current < 8000) return;
    // After 5 min, silent mode unless force
    if (!force && (now - sessionStart.current) > 5 * 60 * 1000) return;
    lastSpoke.current = now;
    setMessage(msg);
    clearTimeout(messageTimer.current);
    messageTimer.current = setTimeout(() => setMessage(null), duration);
  };

  const setActionTimed = (a, dur) => {
    setAction(a);
    clearTimeout(actionTimer.current);
    actionTimer.current = setTimeout(() => setAction(null), dur);
  };

  const wake = () => {
    if (pose === 'sleep') {
      setPose('sit');
      setActionTimed('yawn', 1200);
      setTongue(true);
      setTimeout(() => setTongue(false), 900);
      showMessage('<i>yawn.</i> All quiet.', 4000);
    }
  };

  const resetIdle = () => {
    if (pose === 'sleep') wake();
    clearTimeout(idleTimer.current);
    clearTimeout(sleepTimer.current);
    idleTimer.current = setTimeout(() => {
      // Soft idle nudge — only the first time, then quiet
      showMessage("Click anything. I'll explain.", 5000);
    }, 22000);
    sleepTimer.current = setTimeout(() => {
      setPose('sleep');
      setEyesClosed(true);
      setMessage(null);
    }, 45000);
  };

  /* ---- First-visit greeting + idle setup ---- */
  React.useEffect(() => {
    if (phase !== 'desktop') return;
    const t1 = setTimeout(() => {
      if (!firstVisitDone) {
        showMessage("<i>Namaste.</i> I'm Bevel — your guide. Double-click anything.", 8000, true);
        setActionTimed('wag', 2200);
        try { localStorage.setItem('atharvos.bevel.greeted', '1'); } catch {}
        setFirstVisitDone(true);
      } else {
        showMessage('Welcome back. <i>Wag wag.</i>', 5000, true);
        setActionTimed('wag', 1800);
      }
    }, 2200);
    resetIdle();
    return () => {
      clearTimeout(t1);
      clearTimeout(idleTimer.current);
      clearTimeout(sleepTimer.current);
      clearTimeout(messageTimer.current);
      clearTimeout(blinkTimer.current);
      clearTimeout(actionTimer.current);
    };
    // eslint-disable-next-line
  }, [phase]);

  /* ---- Mouse / keyboard activity ---- */
  React.useEffect(() => {
    if (phase !== 'desktop') return;
    const handler = () => resetIdle();
    window.addEventListener('mousemove', handler, { passive: true });
    window.addEventListener('keydown', handler, { passive: true });
    window.addEventListener('click', handler, { passive: true });
    return () => {
      window.removeEventListener('mousemove', handler);
      window.removeEventListener('keydown', handler);
      window.removeEventListener('click', handler);
    };
    // eslint-disable-next-line
  }, [phase, pose]);

  /* ---- Blink loop while awake ---- */
  React.useEffect(() => {
    if (pose === 'sleep') {
      setEyesClosed(true);
      if (window.sfx) window.sfx.snoreStart();
      return () => { if (window.sfx) window.sfx.snoreStop(); };
    }
    setEyesClosed(false);
    if (window.sfx) window.sfx.snoreStop();
    const loop = () => {
      setEyesClosed(true);
      setTimeout(() => setEyesClosed(false), 120);
      blinkTimer.current = setTimeout(loop, 3000 + Math.random() * 4000);
    };
    blinkTimer.current = setTimeout(loop, 2000 + Math.random() * 3000);
    return () => clearTimeout(blinkTimer.current);
  }, [pose]);

  /* ---- Listen for window-open events ---- */
  React.useEffect(() => {
    const handler = (e) => {
      const k = (e.detail && e.detail.appKey) || '';
      if (k.startsWith('project:')) {
        showMessage("Click around — every tab tells a story.", 5000, true);
        setActionTimed('tilt-r', 800);
        return;
      }
      const dialog = {
        about:       { msg: "That's the personal page.",                       act: 'tilt-l', dur: 800 },
        mycomputer:  { msg: "That's where the projects live.",                 act: 'wag',    dur: 1500 },
        resume:      { msg: "He wrote this himself. Download if you like.",    act: 'tilt-r', dur: 800 },
        awards:      { msg: "He's modest. Look anyway.",                       act: 'jump',   dur: 1000 },
        mediaplayer: { msg: "Press play. He made the playlists.",              act: 'wag',    dur: 1500 },
        notepad:     { msg: "Field notes from the <i>pahaad.</i>",             act: 'tilt-l', dur: 800 },
        photos:      { msg: "Mountains. Mostly.",                              act: 'tilt-r', dur: 800 },
        terminal:    { msg: "He likes it down here too.",                      act: 'tilt-l', dur: 800 },
        recycle:     { msg: "Don't worry — empty. <i>Mostly.</i>",             act: 'tilt-r', dur: 800 },
        network:     { msg: "He's all over the web. Try one.",                 act: 'wag',    dur: 1500 },
        ie:          { msg: "Surfing in <i>1995</i>. Hold tight.",             act: 'tilt-l', dur: 800 },
        readme:      { msg: "Start here if it's your first visit.",            act: 'tilt-r', dur: 800 },
        experience:  { msg: "His paper trail. He's been busy.",                act: 'wag',    dur: 1500 },
        skills:      { msg: "All the dials he turned to get here.",            act: 'tilt-l', dur: 800 },
        solitaire:   { msg: "Klondike. <i>One more game.</i>",                 act: 'wag',    dur: 1500 },
      };
      const d = dialog[k];
      if (d) {
        showMessage(d.msg, 6000, true);
        setActionTimed(d.act, d.dur);
      }
    };
    window.addEventListener('atharv-os:open', handler);
    const petHandler = () => {
      // Synthetic pet via custom event (from desktop icon)
      window.__atharvPetTrigger && window.__atharvPetTrigger();
    };
    window.addEventListener('atharv-os:pet-bevel', petHandler);
    return () => {
      window.removeEventListener('atharv-os:open', handler);
      window.removeEventListener('atharv-os:pet-bevel', petHandler);
    };
    // eslint-disable-next-line
  }, []);

  /* ---- Easter-egg keyboard sniffer ---- */
  React.useEffect(() => {
    let buf = '';
    let bufTimer = null;
    const reset = () => { buf = ''; };
    const handler = (e) => {
      if (e.target && e.target.matches && e.target.matches('input, textarea, [contenteditable]')) return;
      if (!/^[a-zA-Z]$/.test(e.key)) return;
      buf = (buf + e.key.toLowerCase()).slice(-24);
      clearTimeout(bufTimer);
      bufTimer = setTimeout(reset, 1800);
      if (buf.endsWith('devarv')) {
        setActionTimed('spin', 700);
        showMessage("That's his coding handle. <i>Bork.</i>", 5000, true);
        reset();
      } else if (buf.endsWith('hackathon')) {
        setActionTimed('jump', 1100);
        setTongue(true);
        setTimeout(() => setTongue(false), 1500);
        showMessage("<i>Pahaad chad gaye!</i>", 5000, true);
        reset();
      } else if (buf.endsWith('bevel')) {
        setActionTimed('wag', 1800);
        showMessage("Yes? <i>Bork bork.</i>", 4500, true);
        reset();
      }
    };
    window.addEventListener('keydown', handler);
    return () => {
      window.removeEventListener('keydown', handler);
      clearTimeout(bufTimer);
    };
  }, []);

  /* ---- Smart corner selection — avoid the focused window ---- */
  React.useEffect(() => {
    if (phase !== 'desktop') return;
    // Find the topmost open window
    const visibleWins = (windows || []).filter(w => !w.minimized);
    if (visibleWins.length === 0) return;
    // pick window with largest z
    const top = visibleWins.reduce((a, b) => (b.z||0) > (a.z||0) ? b : a, visibleWins[0]);
    if (!top || top.x == null) return;
    const bevelW = 200, bevelH = 200;
    const taskbarH = 32;
    const vw = window.innerWidth, vh = window.innerHeight - taskbarH;
    const corners = {
      br: { x: vw - bevelW - 24, y: vh - bevelH - 8 },
      bl: { x: 24,               y: vh - bevelH - 8 },
      tr: { x: vw - bevelW - 24, y: 24 },
      tl: { x: 24,               y: 24 },
    };
    const winBox = { x: top.x, y: top.y, w: top.w || 600, h: top.h || 400 };
    const overlapScore = (c) => {
      const ox = Math.max(0, Math.min(c.x + bevelW, winBox.x + winBox.w) - Math.max(c.x, winBox.x));
      const oy = Math.max(0, Math.min(c.y + bevelH, winBox.y + winBox.h) - Math.max(c.y, winBox.y));
      return ox * oy;
    };
    const ranked = Object.entries(corners)
      .map(([k, c]) => ({ k, score: overlapScore(c) }))
      .sort((a, b) => a.score - b.score);
    if (ranked[0].score < 200 * 200 * 0.1) {
      // current corner is fine if it has no significant overlap
      if (overlapScore(corners[corner]) < 200 * 200 * 0.1) return;
    }
    setCorner(ranked[0].k);
  }, [windows, phase]);

  /* ---- Pet handler ---- */
  const handlePet = (e) => {
    if (e) { e.stopPropagation(); e.preventDefault(); }
    if (phase !== 'desktop') return;
    if (pose === 'sleep') {
      wake();
      return;
    }
    if (window.sfx) window.sfx.bork();
    resetIdle();
    const newStreak = petStreak + 1;
    setPetStreak(newStreak);
    setTimeout(() => setPetStreak(s => Math.max(0, s - 1)), 2400);

    const newLife = petLifetime + 1;
    setPetLifetime(newLife);
    try { localStorage.setItem('atharvos.bevel.pets', String(newLife)); } catch {}

    if (newStreak >= 5) {
      setActionTimed('flop', 4200);
      setPetStreak(0);
      setTongue(true);
      setTimeout(() => setTongue(false), 4000);
      showMessage('<i>flop. thump thump.</i>', 4500, true);
    } else if (newLife === 10) {
      setActionTimed('spin', 700);
      showMessage("You're his favourite. <i>Wallpaper unlocked.</i>", 6000, true);
    } else {
      setActionTimed('wag', 1500);
      const borks = ['<i>Bork!</i>', '<i>thump thump</i>', "...you're nice.", '<i>wag wag.</i>', '<i>Hii.</i>'];
      showMessage(borks[Math.floor(Math.random() * borks.length)], 3500, true);
    }
  };

  // Expose pet trigger globally so desktop icon / events can pet Bevel
  React.useEffect(() => {
    window.__atharvPetTrigger = () => handlePet();
    return () => { if (window.__atharvPetTrigger === handlePet) delete window.__atharvPetTrigger; };
  });

  /* ---- Keyboard accessibility ---- */
  const onKeyDown = (e) => {
    if (e.key === 'Enter' || e.key === ' ') { handlePet(e); }
    else if (e.key === 'Escape') { setMessage(null); }
  };

  if (!visible || phase !== 'desktop') return null;

  return (
    <div
      className={[
        'bevel',
        `bevel-${corner}`,
        `bevel-pose-${pose}`,
        action ? `bevel-act-${action}` : '',
        mpPlaying && pose !== 'sleep' && !action ? 'bevel-music' : '',
      ].filter(Boolean).join(' ')}
      onClick={handlePet}
      onKeyDown={onKeyDown}
      role="button"
      tabIndex={0}
      aria-label="Bevel, your guide. Press Enter to pet."
      title="Bevel — your guide"
    >
      <div className="bevel-frame">
        <BevelSprite pose={pose} eyesClosed={eyesClosed} tongue={tongue}/>
        {message && <BevelBubble message={message} corner={corner}/>}
      </div>
      {/* SR-only live announce */}
      <div className="bevel-sr" role="status" aria-live="polite">
        {message ? message.replace(/<[^>]+>/g, '') : ''}
      </div>
    </div>
  );
}

// Export to window scope for cross-file use
Object.assign(window, { BevelMascot, BevelSprite });
