// hint-system.jsx — subtle interaction hints for the prototype.
// Exposes:
//   <HintStyles />          — global keyframes + CSS, mount once at root
//   <HintRing active accent>— soft pulsing ring wrapper for the "next" button
//   <HintCoach />           — one-time first-run coach card (bottom-right)
//   <HintReplay />          — small "Replay tour" pill bottom-right after coach dismissed

// ─────────────────────────────────────────────────────────────
// Global styles — keyframes + helpers used across the prototype
// ─────────────────────────────────────────────────────────────
function HintStyles() {
  return (
    <style>{`
      @keyframes hintPulse {
        0%, 100% { box-shadow: 0 0 0 0 var(--hint-color, rgba(234,170,0,0.34)),
                              0 0 0 0 var(--hint-color, rgba(234,170,0,0.0)); }
        50%      { box-shadow: 0 0 0 3px var(--hint-color, rgba(234,170,0,0.12)),
                              0 0 16px 4px var(--hint-color-soft, rgba(234,170,0,0.12)); }
      }
      @keyframes hintRingPulse {
        0%   { transform: scale(0.97); opacity: 0.38; }
        70%  { transform: scale(1.12); opacity: 0;    }
        100% { transform: scale(1.12); opacity: 0;    }
      }
      @keyframes hintCoachIn {
        0%   { transform: translateY(12px); opacity: 0; }
        100% { transform: translateY(0);    opacity: 1; }
      }
      .hint-ring {
        position: relative;
        animation: hintPulse 2.8s ease-in-out infinite;
        border-radius: inherit;
      }
      .hint-ring::after {
        content: '';
        position: absolute; inset: -3px;
        border-radius: inherit;
        border: 1.2px solid var(--hint-color, rgba(234,170,0,0.38));
        animation: hintRingPulse 2.8s ease-out infinite;
        pointer-events: none;
      }
      /* Universal: anything with [data-hint="next"] gets a subtle pulse */
      [data-hint="next"] {
        position: relative;
        animation: hintPulse 2.4s ease-in-out infinite;
      }

      /* SUBTLE CLICKABLE HINT — add data-pulse="true" to any clickable.
         Inherits --hint-color from a parent (App sets it from tenant accent). */
      [data-pulse="true"] {
        position: relative;
        animation: hintPulse 2.8s ease-in-out infinite;
        cursor: pointer;
      }
      [data-pulse="true"]::after {
        content: '';
        position: absolute; inset: -3px;
        border-radius: inherit;
        border: 1.1px solid var(--hint-color, rgba(234,170,0,0.34));
        animation: hintRingPulse 2.8s ease-out infinite;
        pointer-events: none;
      }

      /* Stronger variant: ~20% more intense for high-priority CTAs */
      @keyframes hintPulseStrong {
        0%, 100% { box-shadow: 0 0 0 0 var(--hint-color, rgba(234,170,0,0.45)),
                              0 0 0 0 var(--hint-color, rgba(234,170,0,0.0)); }
        50%      { box-shadow: 0 0 0 4px var(--hint-color, rgba(234,170,0,0.18)),
                              0 0 22px 6px var(--hint-color-soft, rgba(234,170,0,0.20)); }
      }
      @keyframes hintRingPulseStrong {
        0%   { transform: scale(0.96); opacity: 0.55; }
        70%  { transform: scale(1.16); opacity: 0;    }
        100% { transform: scale(1.16); opacity: 0;    }
      }
      [data-pulse-strong="true"] {
        position: relative;
        animation: hintPulseStrong 2.4s ease-in-out infinite;
        cursor: pointer;
      }
      [data-pulse-strong="true"]::after {
        content: '';
        position: absolute; inset: -3px;
        border-radius: inherit;
        border: 1.4px solid var(--hint-color, rgba(234,170,0,0.45));
        animation: hintRingPulseStrong 2.4s ease-out infinite;
        pointer-events: none;
      }

      /* Text-only pulse: glowing label, no outline ring. For nav links and tabs. */
      @keyframes hintTextPulse {
        0%, 100% {
          color: var(--hint-text-base, inherit);
          text-shadow: 0 0 0 transparent;
        }
        50% {
          color: var(--hint-text-on, rgba(255,255,255,1));
          text-shadow: 0 0 8px var(--hint-text-glow, rgba(255,255,255,0.55)),
                       0 0 14px var(--hint-text-glow-soft, rgba(255,255,255,0.28));
        }
      }
      [data-pulse-text="true"] {
        animation: hintTextPulse 2.6s ease-in-out infinite;
        cursor: pointer;
        --hint-text-on: rgba(255, 255, 255, 1);
        --hint-text-glow: rgba(255, 255, 255, 0.55);
        --hint-text-glow-soft: rgba(255, 255, 255, 0.28);
      }

      /* Universal hover affordance for buttons */
      button:not(:disabled) { cursor: pointer; transition: filter 0.15s ease, transform 0.15s ease; }
      button:not(:disabled):hover { filter: brightness(1.08); }
      button:not(:disabled):active { transform: scale(0.98); }

      /* Subtle persistent affordance: tiny dot in top-right of every clickable card */
      [data-clickable="true"] {
        position: relative;
        transition: transform 0.18s ease, filter 0.18s ease;
      }
      [data-clickable="true"]:hover {
        transform: translateY(-1px);
        filter: brightness(1.06);
      }
      [data-clickable="true"]:active { transform: translateY(0) scale(0.995); }

      /* DISCOVER MODE — when body has data-discover, every clickable flashes */
      @keyframes hintDiscover {
        0%, 100% { box-shadow: 0 0 0 0 var(--hint-color, rgba(234,170,0,0.0)); }
        50%      { box-shadow: 0 0 0 3px var(--hint-color, rgba(234,170,0,0.55)),
                              0 0 18px 4px var(--hint-color-soft, rgba(234,170,0,0.32)); }
      }
      body[data-discover="on"] [data-clickable="true"],
      body[data-discover="on"] button:not(:disabled),
      body[data-discover="on"] [role="button"] {
        animation: hintDiscover 1.2s ease-in-out;
        animation-iteration-count: 2;
        border-radius: inherit;
      }
    `}</style>
  );
}

// ─────────────────────────────────────────────────────────────
// HintRing — wraps a clickable element with a soft pulse halo
// when `active`. Pass tenant accent color via `accent`.
// ─────────────────────────────────────────────────────────────
function HintRing({ active, accent = '#F2A900', radius = 12, children, style = {} }) {
  if (!active) return children;
  // Convert hex → rgba for the soft glow
  const hex = accent.replace('#', '');
  const r = parseInt(hex.slice(0,2), 16) || 234;
  const g = parseInt(hex.slice(2,4), 16) || 170;
  const b = parseInt(hex.slice(4,6), 16) || 0;
  const cssVars = {
    '--hint-color': `rgba(${r},${g},${b},0.38)`,
    '--hint-color-soft': `rgba(${r},${g},${b},0.20)`,
  };
  return (
    <div className="hint-ring" style={{ ...cssVars, borderRadius: radius, display: 'inline-block', ...style }}>
      {children}
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// HintCoach — first-run card. Sets localStorage on dismiss so it
// only appears once. Re-trigger via HintReplay below.
// ─────────────────────────────────────────────────────────────
function HintCoach({ accent = '#F2A900', onDismiss }) {
  const [visible, setVisible] = React.useState(() => {
    try { return !localStorage.getItem('mtn.coachSeen'); } catch (e) { return true; }
  });

  // Listen for "replay" events
  React.useEffect(() => {
    const onReplay = () => setVisible(true);
    window.addEventListener('mtn-replay-coach', onReplay);
    return () => window.removeEventListener('mtn-replay-coach', onReplay);
  }, []);

  if (!visible) return null;

  const close = () => {
    setVisible(false);
    try { localStorage.setItem('mtn.coachSeen', '1'); } catch (e) {}
    onDismiss && onDismiss();
  };

  return (
    <div style={{
      position: 'fixed', bottom: 24, right: 24,
      width: 320, padding: 18, borderRadius: 14,
      background: 'rgba(15,15,18,0.92)',
      backdropFilter: 'blur(20px) saturate(180%)',
      WebkitBackdropFilter: 'blur(20px) saturate(180%)',
      border: '1px solid rgba(255,255,255,0.10)',
      boxShadow: '0 24px 60px rgba(0,0,0,0.45), 0 0 0 1px rgba(255,255,255,0.04)',
      color: '#ECEDEE', zIndex: 10000,
      fontFamily: "'Inter', -apple-system, sans-serif",
      animation: 'hintCoachIn 0.4s cubic-bezier(0.2, 0.9, 0.3, 1) both',
    }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 10 }}>
        <div style={{
          width: 22, height: 22, borderRadius: 6,
          background: `linear-gradient(135deg, ${accent}, ${accent}99)`,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          fontSize: 12,
        }}>
          <svg width="11" height="11" viewBox="0 0 11 11" fill="none">
            <path d="M5.5 1v9M1 5.5h9" stroke="#0F1115" strokeWidth="1.6" strokeLinecap="round"/>
          </svg>
        </div>
        <div style={{ fontSize: 12, fontWeight: 700, letterSpacing: '0.04em', textTransform: 'uppercase' }}>
          Working prototype
        </div>
        <div style={{ flex: 1 }} />
        <button onClick={close} aria-label="Dismiss"
          style={{
            width: 22, height: 22, borderRadius: 6,
            background: 'transparent', border: 'none',
            color: 'rgba(255,255,255,0.5)', cursor: 'pointer',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            padding: 0,
          }}>
          <svg width="10" height="10" viewBox="0 0 10 10" fill="none">
            <path d="M2 2l6 6M8 2l-6 6" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"/>
          </svg>
        </button>
      </div>
      <div style={{ fontSize: 13, lineHeight: 1.5, color: 'rgba(255,255,255,0.85)' }}>
        Look for the <span style={{ color: accent, fontWeight: 600 }}>soft glow</span> — that's where to click next.
        Most things are real: tap tabs, cards, the tip on Home, and every nav item in the Operator Console.
      </div>
      <div style={{ display: 'flex', gap: 8, marginTop: 14 }}>
        <button onClick={close}
          style={{
            flex: 1, padding: '8px 12px', borderRadius: 8,
            background: accent, border: 'none',
            color: '#0F1115', fontWeight: 600, fontSize: 12.5,
            cursor: 'pointer', fontFamily: 'inherit',
          }}>
          Got it
        </button>
        <button onClick={close}
          style={{
            padding: '8px 12px', borderRadius: 8,
            background: 'transparent', border: '1px solid rgba(255,255,255,0.12)',
            color: 'rgba(255,255,255,0.7)', fontSize: 12.5,
            cursor: 'pointer', fontFamily: 'inherit',
          }}>
          Skip
        </button>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// HintReplay — small persistent pill bottom-right; click to
// re-show the coach card. Only renders after coach is dismissed.
// ─────────────────────────────────────────────────────────────
function HintReplay({ accent = '#F2A900' }) {
  const [seen, setSeen] = React.useState(() => {
    try { return !!localStorage.getItem('mtn.coachSeen'); } catch (e) { return false; }
  });

  React.useEffect(() => {
    const i = setInterval(() => {
      try {
        const v = !!localStorage.getItem('mtn.coachSeen');
        setSeen(prev => prev !== v ? v : prev);
      } catch(e){}
    }, 800);
    return () => clearInterval(i);
  }, []);

  if (!seen) return null;

  const replay = () => {
    try { localStorage.removeItem('mtn.coachSeen'); } catch (e) {}
    setSeen(false);
    window.dispatchEvent(new CustomEvent('mtn-replay-coach'));
  };

  return (
    <button onClick={replay}
      style={{
        position: 'fixed', bottom: 18, right: 18, zIndex: 9000,
        display: 'inline-flex', alignItems: 'center', gap: 6,
        padding: '7px 12px 7px 9px', borderRadius: 100,
        background: 'rgba(15,15,18,0.85)',
        backdropFilter: 'blur(14px)',
        WebkitBackdropFilter: 'blur(14px)',
        border: '1px solid rgba(255,255,255,0.10)',
        color: 'rgba(255,255,255,0.7)',
        fontSize: 11, fontWeight: 500, letterSpacing: '0.02em',
        cursor: 'pointer', fontFamily: "'Inter', sans-serif",
        boxShadow: '0 8px 24px rgba(0,0,0,0.3)',
      }}>
      <svg width="11" height="11" viewBox="0 0 11 11" fill="none">
        <circle cx="5.5" cy="5.5" r="4" stroke="currentColor" strokeWidth="1.2"/>
        <path d="M5.5 3.5v2l1.3 0.8" stroke={accent} strokeWidth="1.4" strokeLinecap="round"/>
      </svg>
      Show tips
    </button>
  );
}

Object.assign(window, { HintStyles, HintRing, HintCoach, HintReplay });
