// PROVE — modal components.
// Stake / Comments / Reactions. Web modals (centered overlay).
// Mobile-web variants slide up from the bottom (bottom-sheet).

const { useState: useStateM, useEffect: useEffectM } = React;

// ─────────────────────────────────────────────────────────────
// Modal — base centered overlay w/ coral drag handle
// ─────────────────────────────────────────────────────────────
function Modal({ open, onClose, width = 480, sheet = false, children }) {
  if (!open) return null;
  return (
    <div
      onClick={onClose}
      style={{
        position: 'absolute', inset: 0,
        background: 'rgba(0,0,0,0.7)',
        backdropFilter: 'blur(4px)',
        display: 'flex',
        alignItems: sheet ? 'flex-end' : 'center',
        justifyContent: 'center',
        zIndex: 100,
        animation: 'prove-fade-in 0.18s ease-out',
      }}>
      <div
        onClick={(e) => e.stopPropagation()}
        style={{
          width: sheet ? '100%' : width,
          maxWidth: sheet ? 'none' : '90%',
          background: 'linear-gradient(180deg, #161616 0%, #111111 100%)',
          border: '1px solid rgba(255,255,255,0.12)',
          borderRadius: sheet
            ? '20px 20px 0 0'
            : 'var(--radius-modal)',
          padding: 28,
          color: '#fff',
          boxShadow: '0 32px 80px rgba(0,0,0,0.6), 0 0 0 1px rgba(255,255,255,0.06)',
          animation: sheet
            ? 'prove-modal-in 0.22s cubic-bezier(.2,.7,.3,1)'
            : 'prove-modal-in 0.2s ease-out',
          transformOrigin: sheet ? 'bottom center' : 'center',
        }}>
        {/* drag handle */}
        <div style={{
          display: 'flex', justifyContent: 'center', marginBottom: 12,
        }}>
          <div style={{
            width: 40, height: 4, borderRadius: 2,
            background: 'var(--coral)',
          }} />
        </div>
        {children}
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// StakeModal — opens on Back/Doubt click.
// Toggle between Back/Doubt, slider w/ presets, payout preview, confirm.
// ─────────────────────────────────────────────────────────────
function StakeModal({ open, onClose, proof, initialSide = 'back', onConfirm, sheet }) {
  const [side, setSide] = useStateM(initialSide);
  const [amount, setAmount] = useStateM(25);
  const D = window.PROVE_DATA;
  const u = proof && D.byHandle[proof.user];

  useEffectM(() => { if (open) setSide(initialSide); }, [open, initialSide]);

  if (!proof) return null;

  // Mock odds calc
  const baseBack = proof.back;
  const baseDoubt = proof.doubt;
  const myBack = side === 'back' ? amount : 0;
  const myDoubt = side === 'doubt' ? amount : 0;
  const liveBack = baseBack + myBack;
  const liveDoubt = baseDoubt + myDoubt;
  const otherSide = side === 'back' ? baseDoubt : baseBack;
  const mySide = side === 'back' ? liveBack : liveDoubt;
  const payout = Math.round(amount + (amount / mySide) * otherSide);

  const presets = [5, 10, 25, 50, 100];

  return (
    <Modal open={open} onClose={onClose} width={460} sheet={sheet}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 18 }}>
        <Avatar user={u} size={36} />
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontSize: 14, fontWeight: 600, color: '#fff' }}>{u.handle}</div>
          <div style={{ fontSize: 11, color: 'var(--text-2)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
            {proof.caption}
          </div>
        </div>
        <MonoNum size={12} color="var(--text-3)">day {proof.day}</MonoNum>
      </div>

      {/* Back / Doubt segmented toggle */}
      <div style={{
        display: 'grid', gridTemplateColumns: '1fr 1fr',
        background: 'var(--surface)', borderRadius: 999, padding: 4,
        marginBottom: 20,
        border: '1px solid var(--border)',
      }}>
        {['back', 'doubt'].map((s) => (
          <button key={s} onClick={() => setSide(s)}
            style={{
              height: 44, padding: '0 16px',
              background: side === s ? (s === 'back' ? 'var(--coral)' : 'rgba(255,255,255,0.18)') : 'transparent',
              color: side === s ? (s === 'back' ? '#0D0D0D' : '#fff') : 'var(--text-2)',
              border: 'none', borderRadius: 999,
              fontSize: 13, fontWeight: 700,
              letterSpacing: 0.06 + 'em', textTransform: 'uppercase',
              cursor: 'pointer', fontFamily: 'inherit',
              transition: 'all 0.12s',
            }}>{s}</button>
        ))}
      </div>

      {/* Amount label */}
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 14 }}>
        <span style={{ fontSize: 11, color: 'var(--text-2)', letterSpacing: 0.1 + 'em', textTransform: 'uppercase', fontWeight: 600 }}>
          Stake amount
        </span>
        <MonoNum size={32} weight={700} color="var(--coral)">{amount}</MonoNum>
      </div>

      {/* Preset pills */}
      <div style={{ display: 'flex', gap: 8, marginBottom: 16 }}>
        {presets.map((p) => (
          <button key={p} onClick={() => setAmount(p)}
            style={{
              flex: 1, height: 44,
              background: amount === p ? 'var(--coral)' : 'var(--surface)',
              color: amount === p ? '#0D0D0D' : '#fff',
              border: amount === p ? '1px solid var(--coral)' : '1px solid var(--border)',
              borderRadius: 999,
              fontFamily: 'var(--mono)', fontSize: 13, fontWeight: 700,
              cursor: 'pointer',
              transition: 'all 0.12s',
            }}>{p}</button>
        ))}
      </div>

      {/* Slider */}
      <input type="range" min={1} max={100} value={amount}
        onChange={(e) => setAmount(parseInt(e.target.value, 10))}
        style={{
          width: '100%', height: 4, borderRadius: 4,
          background: 'var(--surface)', accentColor: 'var(--coral)',
          marginBottom: 22,
        }} />

      {/* Live odds bar */}
      <div style={{ marginBottom: 20 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 8 }}>
          <span style={{ fontSize: 10, color: 'var(--text-3)', letterSpacing: 0.12 + 'em', textTransform: 'uppercase', fontWeight: 600 }}>Live split (incl. your stake)</span>
          <MonoNum size={11} color="var(--text-3)">{(liveBack + liveDoubt).toLocaleString()} coins</MonoNum>
        </div>
        <OddsBar back={liveBack} doubt={liveDoubt} height={10} />
      </div>

      {/* Payout preview */}
      <div style={{
        background: 'linear-gradient(135deg, rgba(255,97,85,0.08), transparent)',
        border: '1px solid rgba(255,97,85,0.2)',
        borderRadius: 12,
        padding: '16px 18px',
        marginBottom: 20,
        display: 'flex', justifyContent: 'space-between', alignItems: 'center',
      }}>
        <span style={{ fontSize: 12, color: 'var(--text-2)', fontFamily: 'var(--mono)' }}>
          if {side === 'back' ? 'proven' : 'missed'}: you earn
        </span>
        <MonoNum size={28} weight={700} color="var(--coral)">{payout} coins</MonoNum>
      </div>

      {/* Confirm */}
      <button
        onClick={() => { onConfirm && onConfirm(side, amount); onClose && onClose(); }}
        style={{
          width: '100%', height: 52,
          background: 'var(--coral)',
          color: '#0D0D0D',
          border: 'none', borderRadius: 999,
          fontSize: 14, fontWeight: 700,
          letterSpacing: 0.06 + 'em', textTransform: 'uppercase',
          cursor: 'pointer', fontFamily: 'inherit',
        }}>
        Stake {amount} coins · {side}
      </button>
    </Modal>
  );
}

// ─────────────────────────────────────────────────────────────
// CommentsModal
// ─────────────────────────────────────────────────────────────
function CommentsModal({ open, onClose, proof, sheet }) {
  const D = window.PROVE_DATA;
  const [input, setInput] = useStateM('');
  const seed = proof ? proof.id : 'p1';
  const comments = [
    { user: 'devon.r', text: 'absolute beast hours.', t: '14m' },
    { user: 'priya_s', text: 'PR + bad sleep + posting it? respect.', t: '32m' },
    { user: 'rae.h',   text: 'okay i’m backing this', t: '1h' },
    { user: 'tomas.lin', text: 'form check at 2:14', t: '2h' },
    { user: 'amara_o', text: 'doubters in shambles', t: '3h' },
    { user: 'kev.do',  text: 'day 47. unreal.', t: '4h' },
  ];

  return (
    <Modal open={open} onClose={onClose} width={520} sheet={sheet}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 14 }}>
        <h3 style={{
          fontFamily: 'var(--display)', fontSize: 18, fontWeight: 700,
          margin: 0, textTransform: 'uppercase', letterSpacing: '-0.02em',
        }}>Comments</h3>
        <MonoNum size={12} color="var(--text-3)">{comments.length} · day {proof?.day}</MonoNum>
      </div>

      <div style={{
        maxHeight: 320, overflowY: 'auto',
        display: 'flex', flexDirection: 'column', gap: 14,
        paddingRight: 4, marginBottom: 16,
        borderBottom: '1px solid var(--border)', paddingBottom: 14,
      }}>
        {comments.map((c, i) => {
          const u = D.byHandle[c.user];
          return (
            <div key={i} style={{ display: 'flex', gap: 10 }}>
              <Avatar user={u} size={28} />
              <div style={{ flex: 1 }}>
                <div style={{ display: 'flex', gap: 8, alignItems: 'baseline' }}>
                  <span style={{ fontSize: 13, fontWeight: 600, color: '#fff' }}>{u.handle}</span>
                  <MonoNum size={10} color="var(--text-3)">{c.t}</MonoNum>
                </div>
                <div style={{ fontSize: 13, color: 'rgba(255,255,255,0.8)', marginTop: 2, lineHeight: 1.4 }}>{c.text}</div>
              </div>
            </div>
          );
        })}
      </div>

      <div style={{ display: 'flex', gap: 8 }}>
        <input
          value={input}
          onChange={(e) => setInput(e.target.value)}
          placeholder="Add a comment…"
          style={{
            flex: 1,
            background: 'var(--surface)',
            border: '1px solid var(--border)',
            borderRadius: 999,
            padding: '10px 16px',
            color: '#fff', fontFamily: 'inherit', fontSize: 13,
            outline: 'none',
          }}
        />
        <button
          onClick={() => setInput('')}
          style={{
            padding: '0 16px',
            background: 'var(--coral)', color: '#0D0D0D',
            border: 'none', borderRadius: 999,
            cursor: 'pointer',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
          }}>
          <svg width="16" height="16" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
            <path d="M2 8 L14 2 L8 14 L7 9 Z" fill="#0D0D0D" />
          </svg>
        </button>
      </div>
    </Modal>
  );
}

// ─────────────────────────────────────────────────────────────
// ReactionsModal — 4×2 grid of reactions w/ counts.
// ─────────────────────────────────────────────────────────────
function ReactionsModal({ open, onClose, sheet }) {
  const reactions = [
    { emoji: '🔥', label: 'Fire',    count: 124 },
    { emoji: '💪', label: 'Strong',  count: 88 },
    { emoji: '👀', label: 'Watching', count: 41 },
    { emoji: '⚡', label: 'Locked in', count: 33 },
    { emoji: '🧊', label: 'Cold',     count: 18 },
    { emoji: '🏆', label: 'Champion', count: 12 },
    { emoji: '🪙', label: 'Coined',   count: 9 },
    { emoji: '☠️', label: 'Dead',     count: 4 },
  ];

  return (
    <Modal open={open} onClose={onClose} width={460} sheet={sheet}>
      <h3 style={{
        fontFamily: 'var(--display)', fontSize: 18, fontWeight: 700,
        margin: '0 0 18px', textTransform: 'uppercase', letterSpacing: '-0.02em',
      }}>React</h3>

      <div style={{
        display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 8,
      }}>
        {reactions.map((r) => (
          <button key={r.emoji}
            style={{
              padding: '14px 0 10px',
              background: 'var(--surface)',
              border: '1px solid var(--border)',
              borderRadius: 12,
              cursor: 'pointer', fontFamily: 'inherit',
              display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4,
              transition: 'all 0.12s',
            }}
            onMouseEnter={(e) => e.currentTarget.style.borderColor = 'var(--border-hi)'}
            onMouseLeave={(e) => e.currentTarget.style.borderColor = 'var(--border)'}
          >
            <span style={{ fontSize: 24 }}>{r.emoji}</span>
            <MonoNum size={11} color="var(--text-2)">{r.count}</MonoNum>
            <span style={{ fontSize: 9, color: 'var(--text-3)', letterSpacing: 0.08 + 'em', textTransform: 'uppercase' }}>
              {r.label}
            </span>
          </button>
        ))}
      </div>
    </Modal>
  );
}

// ─────────────────────────────────────────────────────────────
// Confirm modal — destructive actions.
// ─────────────────────────────────────────────────────────────
function ConfirmModal({ open, onClose, title, body, confirmLabel = 'Confirm', destructive }) {
  return (
    <Modal open={open} onClose={onClose} width={400}>
      <h3 style={{
        fontFamily: 'var(--display)', fontSize: 22, fontWeight: 800,
        margin: '0 0 10px', textTransform: 'uppercase', letterSpacing: '-0.02em',
        color: destructive ? 'var(--coral)' : '#fff',
      }}>{title}</h3>
      <p style={{ fontSize: 14, color: 'var(--text-2)', lineHeight: 1.5, margin: '0 0 22px' }}>{body}</p>
      <div style={{ display: 'flex', gap: 8 }}>
        <button onClick={onClose} style={{
          flex: 1, padding: '12px',
          background: 'var(--surface)', color: '#fff',
          border: '1px solid var(--border)', borderRadius: 999,
          fontFamily: 'inherit', fontSize: 13, fontWeight: 600,
          cursor: 'pointer',
        }}>Cancel</button>
        <button onClick={onClose} style={{
          flex: 1, padding: '12px',
          background: 'var(--coral)', color: '#0D0D0D',
          border: '1px solid var(--coral)', borderRadius: 999,
          fontFamily: 'inherit', fontSize: 13, fontWeight: 700,
          letterSpacing: 0.04 + 'em', textTransform: 'uppercase',
          cursor: 'pointer',
        }}>{confirmLabel}</button>
      </div>
    </Modal>
  );
}

Object.assign(window, { Modal, StakeModal, CommentsModal, ReactionsModal, ConfirmModal });
