// system-modals.jsx — Tenant-colored system modals.
//
//   • ConfirmActionSheet   — iOS-style action sheet with a few choices
//   • RewardCelebrationModal — trophy moment with confetti burst
//   • ConfettiBurst        — particle burst animation
//   • pickBoldTenantColor  — picks whichever tenant color reads as commanding
//                            (saturated + dark enough to take white text)

// ─────────────────────────────────────────────────────────────────────
// Color helper — given two hex colors, pick the one with lower luminance.
// Falls back to the second if both are too light.
// ─────────────────────────────────────────────────────────────────────
function _luminance(hex) {
  const h = (hex || '#000').replace('#', '');
  const n = parseInt(h.length === 3 ? h.split('').map(c => c + c).join('') : h, 16);
  const r = ((n >> 16) & 255) / 255;
  const g = ((n >>  8) & 255) / 255;
  const b = ((n)       & 255) / 255;
  return 0.299 * r + 0.587 * g + 0.114 * b;
}

// Pick the tenant color that should anchor a bold modal: red on Utah/OSU/RSL,
// navy on WVU/Kentucky, etc. Falls back to a dark tenant-tinted base if both
// candidates read too pale.
function pickBoldTenantColor() {
  const p = WVU.gold;   // tenant primary  (mutated by applyTenantToDS)
  const s = WVU.blue;   // tenant secondary
  const lp = _luminance(p);
  const ls = _luminance(s);
  // Prefer the darker of the two unless it's too gray (we want saturated)
  if (lp < 0.45) return p;
  if (ls < 0.45) return s;
  // both too light — use ink2 with primary tint
  return WVU.ink2;
}

// ─────────────────────────────────────────────────────────────────────
// CONFETTI BURST — fires once on mount. Lightweight CSS-only confetti.
// 30 particles in tenant palette, exploding outward + falling.
// ─────────────────────────────────────────────────────────────────────
function ConfettiBurst({ originY = 0.32, count = 36 }) {
  const palette = [
    WVU.gold, WVU.goldLite, WVU.cream, '#FFFFFF',
    WVU.blueLite || '#3F6FB3', '#FFC107',
  ];
  const particles = React.useMemo(() => Array.from({ length: count }, (_, i) => {
    const angle = (Math.PI * 2 * i) / count + (Math.random() - 0.5) * 0.4;
    const dist  = 90 + Math.random() * 130;       // px outward
    const dx    = Math.cos(angle) * dist;
    const dy    = Math.sin(angle) * dist;
    const drop  = 240 + Math.random() * 160;      // additional fall after burst
    const size  = 6 + Math.random() * 6;
    const rot1  = (Math.random() - 0.5) * 720;
    const rot2  = rot1 + (Math.random() - 0.5) * 720;
    return {
      id: i,
      color: palette[i % palette.length],
      dx, dy, drop, size, rot1, rot2,
      shape: i % 3 === 0 ? 'circle' : 'rect',
      delay: Math.random() * 80,
    };
  }), [count]);

  return (
    <div style={{
      position: 'absolute', inset: 0,
      pointerEvents: 'none', zIndex: 5,
      overflow: 'visible',
    }}>
      <style>{`
        @keyframes mtnConfettiBurst_x { from { transform: translate(0, 0) rotate(0deg); opacity: 1; } to { transform: var(--mtn-confetti-to); opacity: 0; } }
      `}</style>
      {particles.map(p => (
        <div key={p.id} style={{
          position: 'absolute',
          left: '50%',
          top: `${originY * 100}%`,
          width: p.size,
          height: p.shape === 'rect' ? p.size * 0.5 : p.size,
          background: p.color,
          borderRadius: p.shape === 'circle' ? '50%' : 2,
          '--mtn-confetti-to': `translate(${p.dx}px, ${p.dy + p.drop}px) rotate(${p.rot2}deg)`,
          animation: `mtnConfettiBurst_x 1400ms cubic-bezier(0.18, 0.62, 0.32, 1) ${p.delay}ms forwards`,
          boxShadow: `0 0 6px ${p.color}66`,
          willChange: 'transform, opacity',
        }} />
      ))}
    </div>
  );
}

// ─────────────────────────────────────────────────────────────────────
// CONFIRM ACTION SHEET — iOS-style bold prompt
//   props:
//     title:    string (uppercase preferred)
//     options:  [{ label, onClick, destructive?, primary? }]
//     onCancel: () => void  (renders "Cancel" row + backdrop tap)
// ─────────────────────────────────────────────────────────────────────
function ConfirmActionSheet({ title, options = [], onCancel, accentBg }) {
  const bg = accentBg || pickBoldTenantColor();
  return (
    <div onClick={onCancel} style={{
      position: 'absolute', inset: 0, zIndex: 200,
      background: 'rgba(0,0,0,0.45)',
      backdropFilter: 'blur(4px)', WebkitBackdropFilter: 'blur(4px)',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      padding: 16,
      animation: 'mtnFade 200ms ease-out',
    }}>
      <div onClick={(e) => e.stopPropagation()} style={{
        width: '100%', maxWidth: 320,
        borderRadius: 18, overflow: 'hidden',
        boxShadow: '0 24px 60px rgba(0,0,0,0.55), 0 0 0 1px rgba(255,255,255,0.06)',
        background: bg,
      }}>
        {/* Title row — tall, all-caps, white */}
        <div style={{
          padding: '20px 18px 18px',
          background: `linear-gradient(180deg, ${bg}, ${_shade(bg, -0.12)})`,
          textAlign: 'center',
          borderBottom: '0.5px solid rgba(255,255,255,0.14)',
        }}>
          <div style={{
            fontFamily: DS.sans, fontSize: 16, fontWeight: 900,
            color: '#fff', letterSpacing: '0.04em',
            lineHeight: 1.15, textTransform: 'uppercase',
            textShadow: '0 1px 2px rgba(0,0,0,0.25)',
          }}>{title}</div>
        </div>

        {/* Option rows */}
        {options.map((opt, i) => (
          <button
            key={i}
            onClick={(e) => { e.stopPropagation(); opt.onClick && opt.onClick(); }}
            style={{
              display: 'block', width: '100%',
              padding: '17px 16px',
              background: _shade(bg, -0.08 - i * 0.06),
              border: 'none',
              borderTop: i > 0 ? '0.5px solid rgba(255,255,255,0.14)' : 'none',
              fontFamily: DS.sans, fontSize: 17, fontWeight: 700,
              color: '#fff', letterSpacing: '-0.005em',
              cursor: 'pointer', textAlign: 'center',
              transition: 'background 120ms ease',
            }}
            onMouseDown={(e) => { e.currentTarget.style.filter = 'brightness(0.92)'; }}
            onMouseUp={(e) => { e.currentTarget.style.filter = 'brightness(1)'; }}
            onMouseLeave={(e) => { e.currentTarget.style.filter = 'brightness(1)'; }}
          >{opt.label}</button>
        ))}

        {/* Cancel row — black/gray ghost */}
        {onCancel && (
          <button
            onClick={(e) => { e.stopPropagation(); onCancel(); }}
            style={{
              display: 'block', width: '100%',
              padding: '15px 16px',
              background: 'rgba(0,0,0,0.55)',
              border: 'none',
              borderTop: '0.5px solid rgba(255,255,255,0.10)',
              fontFamily: DS.sans, fontSize: 16, fontWeight: 500,
              color: 'rgba(255,255,255,0.65)', letterSpacing: '-0.005em',
              cursor: 'pointer', textAlign: 'center',
            }}
          >Cancel</button>
        )}
      </div>
    </div>
  );
}

// Mix hex toward black/white by amount t in [-1, 1].
function _shade(hex, t) {
  const h = (hex || '#000').replace('#', '');
  const n = parseInt(h.length === 3 ? h.split('').map(c => c + c).join('') : h, 16);
  let r = (n >> 16) & 255, g = (n >> 8) & 255, b = n & 255;
  if (t < 0) { r = r * (1 + t); g = g * (1 + t); b = b * (1 + t); }
  else       { r = r + (255 - r) * t; g = g + (255 - g) * t; b = b + (255 - b) * t; }
  return '#' + [r, g, b].map(v => Math.max(0, Math.min(255, Math.round(v))).toString(16).padStart(2, '0')).join('');
}

// ─────────────────────────────────────────────────────────────────────
// REWARD CELEBRATION MODAL — trophy moment with confetti
//   props:
//     points:  number (e.g. 500)
//     title:   string  ("You earned 500 points!")
//     sub:     string  ("Thanks for checking in. Go Mountaineers!")
//     onClose: () => void  (called on tap-anywhere or after auto-dismiss)
//     accentBg: optional override
// ─────────────────────────────────────────────────────────────────────
function RewardCelebrationModal({ points, title, sub, onClose, accentBg, autoDismissMs = 3800 }) {
  const bg = accentBg || pickBoldTenantColor();
  const titleText = title || `You earned ${points} points!`;

  // Auto-dismiss after a beat so the user doesn't have to tap twice
  React.useEffect(() => {
    if (!autoDismissMs) return;
    const t = setTimeout(() => onClose && onClose(), autoDismissMs);
    return () => clearTimeout(t);
  }, [autoDismissMs, onClose]);

  return (
    <div onClick={onClose} style={{
      position: 'absolute', inset: 0, zIndex: 220,
      background: 'rgba(0,0,0,0.55)',
      backdropFilter: 'blur(6px)', WebkitBackdropFilter: 'blur(6px)',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      padding: 16,
      animation: 'mtnFade 280ms ease-out',
    }}>
      <div onClick={(e) => e.stopPropagation()} style={{
        position: 'relative',
        width: '100%', maxWidth: 290,
        borderRadius: 22, overflow: 'visible',
        background: `linear-gradient(170deg, ${bg}, ${_shade(bg, -0.18)})`,
        boxShadow: `0 28px 70px rgba(0,0,0,0.6), 0 0 0 1px rgba(255,255,255,0.08), inset 0 1px 0 rgba(255,255,255,0.18)`,
        padding: '38px 24px 32px',
        textAlign: 'center',
      }}>
        {/* Trophy icon — large, white, with subtle gold glow */}
        <div style={{
          position: 'relative',
          display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
          width: 88, height: 88, borderRadius: 44,
          background: 'rgba(255,255,255,0.10)',
          marginBottom: 18,
          boxShadow: `0 6px 20px rgba(0,0,0,0.25), inset 0 1px 0 rgba(255,255,255,0.2)`,
          animation: 'mtnTrophyPop 600ms cubic-bezier(0.34, 1.56, 0.64, 1) both',
        }}>
          <svg width="46" height="46" viewBox="0 0 56 56" fill="none">
            {/* handles */}
            <path d="M12 12H6a6 6 0 006 6" stroke="#fff" strokeWidth="3" fill="none" strokeLinecap="round"/>
            <path d="M44 12h6a6 6 0 01-6 6" stroke="#fff" strokeWidth="3" fill="none" strokeLinecap="round"/>
            {/* cup */}
            <path d="M12 6h32v14a16 16 0 01-32 0V6z" fill="#fff"/>
            {/* stem */}
            <rect x="24" y="34" width="8" height="8" fill="#fff"/>
            {/* base */}
            <rect x="16" y="42" width="24" height="6" rx="1.5" fill="#fff"/>
          </svg>
        </div>

        <div style={{
          fontFamily: DS.sans, fontSize: 18, fontWeight: 800,
          color: '#fff', letterSpacing: '-0.01em', lineHeight: 1.22,
          textShadow: '0 1px 2px rgba(0,0,0,0.25)',
        }}>{titleText}</div>

        {sub && (
          <div style={{
            fontFamily: DS.sans, fontSize: 14, fontWeight: 500,
            color: 'rgba(255,255,255,0.88)', marginTop: 10,
            lineHeight: 1.4, letterSpacing: '-0.005em',
          }}>{sub}</div>
        )}

        {/* Confetti behind everything */}
        <ConfettiBurst originY={0.28} count={42} />

        <style>{`
          @keyframes mtnTrophyPop {
            0%   { transform: scale(0.4); opacity: 0; }
            60%  { transform: scale(1.12); opacity: 1; }
            100% { transform: scale(1); opacity: 1; }
          }
        `}</style>
      </div>
    </div>
  );
}

Object.assign(window, { ConfirmActionSheet, RewardCelebrationModal, ConfettiBurst, pickBoldTenantColor });
