// screen-swap.jsx — Swap detail screen. Handles 3 states x 2 roles.

const { useState: sU, useEffect: sE, useMemo: sM, useCallback: sC } = React;

function SwapScreen({ swapId, role, token, onNav }) {
  const { Field, QRCodeBlock, StatRow, Footer } = window.PJ_UI;
  const { fmtMoney, fmtPct, fmtDateTime } = window.PJ_UI;

  const [swap, setSwap] = sU(null);
  const [loading, setLoading] = sU(true);
  const [err, setErr] = sU(null);
  const [acceptorHandle, setAcceptorHandle] = sU(window.pjGetHandle() || '');
  const [signing, setSigning] = sU(false);
  const [locking, setLocking] = sU(false);
  const [showCounter, setShowCounter] = sU(false);

  const refresh = sC(async () => {
    try {
      const s = await window.pjGetSwap(swapId);
      setSwap(s);
      setLoading(false);
    } catch (e) { setErr(e.message || String(e)); setLoading(false); }
  }, [swapId]);

  sE(() => { refresh(); }, [refresh]);

  // Realtime subscription
  sE(() => {
    if (!swapId) return;
    const unsub = window.pjSubscribeSwap(swapId, (next) => setSwap(next));
    return unsub;
  }, [swapId]);

  // Polling fallback every 3s if pending
  sE(() => {
    if (!swap || swap.status !== 'pending') return;
    const t = setInterval(refresh, 3000);
    return () => clearInterval(t);
  }, [swap && swap.status, refresh]);

  if (loading) {
    return (
      <div className="page">
        <p className="mono muted" style={{ textAlign: 'center', marginTop: 60 }}>Loading swap…</p>
      </div>
    );
  }
  if (err || !swap) {
    return (
      <div className="page">
        <div className="card" style={{ borderColor: 'rgba(231,76,60,0.5)' }}>
          <div className="mono" style={{ fontSize: 12, color: 'var(--red-bright)' }}>
            {err || 'Swap not found.'}
          </div>
        </div>
        <button className="btn btn-ghost btn-block btn-lg" style={{ marginTop: 18 }} onClick={() => onNav('/')}>Back home</button>
      </div>
    );
  }

  // ---------- Shared: terms summary block ----------
  const TermsSummary = () => (
    <div className="stack-sm" style={{ marginTop: 8 }}>
      <StatRow label="Tournament" value={swap.tournament_name} />
      <StatRow label="Buy-in" value={fmtMoney(swap.buy_in)} mono />
      <StatRow label="Originator gives" value={fmtPct(swap.originator_pct) + ' of ' + (swap.originator_handle || '—')} />
      <StatRow label="Acceptor gives"  value={fmtPct(swap.acceptor_pct) + ' of ' + (swap.acceptor_handle || 'TBD')} />
      <StatRow label="Markup" value={(Number(swap.markup) || 1).toFixed(2) + 'x'} mono />
      {Array.isArray(swap.terms) && swap.terms.length > 0 && (
        <StatRow label="Conditions" value={swap.terms.join(', ')} />
      )}
      {swap.notes && (
        <div style={{ padding: '10px 0' }}>
          <div className="mono" style={{ fontSize: 11, letterSpacing: '0.14em', textTransform: 'uppercase', color: 'var(--muted)', marginBottom: 6 }}>Notes</div>
          <div style={{ color: 'var(--paper)', fontSize: 14 }}>{swap.notes}</div>
        </div>
      )}
    </div>
  );

  // ---------- LOCKED state ----------
  if (swap.status === 'locked') {
    const oSig = swap.originator_signature || {};
    const aSig = swap.acceptor_signature || {};
    return (
      <div className="page">
        <div className="locked-stamp">
          <div className="word">LOCKED</div>
          <span className="check">✓</span>
          <div className="mono" style={{ fontSize: 11, letterSpacing: '0.18em', color: 'var(--gold-deep)', marginTop: 6 }}>
            {fmtDateTime(swap.locked_at)}
          </div>
        </div>

        <TermsSummary />

        <div className="divider-glyph">◆ Signatures ◆</div>

        <div className="stack">
          <SignatureCard label="Originator" sig={oSig} handle={swap.originator_handle} />
          <SignatureCard label="Acceptor"   sig={aSig} handle={swap.acceptor_handle} />
        </div>

        <div className="stack" style={{ marginTop: 24 }}>
          <button className="btn btn-ghost btn-block btn-lg" onClick={() => {
            const url = window.location.origin + '/s/' + swap.id;
            if (navigator.share) {
              navigator.share({ title: 'Poker Jamie — Locked swap', url }).catch(() => {});
            } else if (navigator.clipboard) {
              navigator.clipboard.writeText(url);
              alert('Link copied');
            }
          }}>Share record</button>
          <button className="btn btn-ghost btn-block btn-lg" onClick={() => onNav('/swaps')}>My swaps</button>
        </div>

        <Footer />
      </div>
    );
  }

  // ---------- ACCEPTOR scanning a pending swap ----------
  // Acceptor identified by role=acceptor query OR by NOT being on this device when no signature yet.
  const isOriginatorDevice = swap.originator_device_id === window.pjDeviceId;
  const effectiveRole = role || (isOriginatorDevice ? 'originator' : 'acceptor');

  if (swap.status === 'pending' && effectiveRole === 'acceptor' && !swap.acceptor_signature) {
    return (
      <div className="page">
        <div className="eyebrow gold" style={{ marginBottom: 8 }}>◆ You've been invited to a swap</div>
        <h2 className="serif" style={{ fontSize: 36, lineHeight: 1, marginBottom: 6 }}>Review the terms.</h2>
        <p className="paper" style={{ marginBottom: 18 }}>
          {(swap.originator_handle || 'Someone')} wants to swap with you. Read carefully — once you sign, only you and them can unlock.
        </p>

        <div className="card card-gold">
          <TermsSummary />
        </div>

        <div style={{ marginTop: 22 }}>
          <Field label="Your handle">
            <input
              className="input"
              placeholder="e.g. theonethatcalled"
              value={acceptorHandle}
              onChange={e => setAcceptorHandle(e.target.value)}
              maxLength={32}
              autoCapitalize="off"
              autoCorrect="off"
              spellCheck={false}
            />
          </Field>
        </div>

        {err && (
          <div className="card" style={{ borderColor: 'rgba(231,76,60,0.5)', background: 'var(--red-tint)', marginBottom: 16 }}>
            <div className="mono" style={{ fontSize: 12, color: 'var(--red-bright)' }}>{err}</div>
          </div>
        )}

        <div className="stack">
          <button
            className="btn btn-gold btn-block btn-xl"
            disabled={!acceptorHandle.trim() || signing || !token}
            onClick={async () => {
              if (!token) { setErr('Missing security token. Re-scan the QR.'); return; }
              setSigning(true); setErr(null);
              try {
                window.pjSetHandle(acceptorHandle.trim());
                const next = await window.pjAcceptorSign(swap.id, acceptorHandle.trim(), token);
                setSwap(next);
              } catch (e) { setErr(e.message || String(e)); }
              finally { setSigning(false); }
            }}
          >
            {signing ? 'Signing…' : 'Accept & Sign'}
          </button>
          <button className="btn btn-ghost btn-block btn-lg" onClick={() => setShowCounter(true)}>
            Counter-propose
          </button>
        </div>

        {showCounter && (
          <div className="card" style={{ marginTop: 20, borderColor: 'var(--line-gold)' }}>
            <div className="eyebrow gold" style={{ marginBottom: 10 }}>◆ Counter-propose</div>
            <p style={{ fontSize: 14, color: 'var(--paper)' }}>
              Tell them what you want changed in person, or start a fresh swap from scratch with your terms.
            </p>
            <div className="stack" style={{ marginTop: 14 }}>
              <button className="btn btn-block" onClick={() => onNav('/new')}>Start a new swap</button>
              <button className="btn btn-ghost btn-block" onClick={() => setShowCounter(false)}>Cancel</button>
            </div>
          </div>
        )}

        <Footer />
      </div>
    );
  }

  // ---------- ORIGINATOR waiting / ready to final-lock ----------
  if (swap.status === 'pending' && effectiveRole === 'originator') {
    const url = (typeof window !== 'undefined' ? window.location.origin : 'https://pokerjamie.com')
      + '/s/' + swap.id + '?role=acceptor&token=' + (swap.secret_token || token || '');

    if (!swap.acceptor_signature) {
      return (
        <div className="page">
          <div className="eyebrow gold" style={{ marginBottom: 8 }}>◆ Hand them your phone</div>
          <h2 className="serif" style={{ fontSize: 40, lineHeight: 1, marginBottom: 6 }}>Scan to lock.</h2>
          <p className="paper" style={{ marginBottom: 8 }}>
            Have {swap.originator_handle ? 'your counterparty' : 'them'} scan this. They review, sign, then you final-lock.
          </p>

          <QRCodeBlock text={url} size={300} caption="SCAN TO LOCK" />

          <div className="center" style={{ marginTop: 8 }}>
            <button
              className="btn btn-ghost"
              onClick={() => { if (navigator.clipboard) { navigator.clipboard.writeText(url); alert('Link copied'); } }}
            >Copy link instead</button>
          </div>

          <div className="card" style={{ marginTop: 24 }}>
            <TermsSummary />
          </div>

          <div style={{ marginTop: 22, textAlign: 'center' }} className="mono muted">
            <span className="waiting-dot"></span> Waiting for them to scan…
          </div>

          <Footer />
        </div>
      );
    }

    // Acceptor signed — show review + FINAL LOCK
    return (
      <div className="page">
        <div className="eyebrow gold" style={{ marginBottom: 8 }}>◆ They signed</div>
        <h2 className="serif" style={{ fontSize: 36, lineHeight: 1, marginBottom: 8 }}>
          {swap.acceptor_handle} signed. Review one last time.
        </h2>
        <p className="paper" style={{ marginBottom: 18 }}>This is your final check. Hit lock and the record is sealed.</p>

        <div className="card card-gold">
          <TermsSummary />
          <hr className="rule-gold" style={{ margin: '12px 0' }} />
          <SignatureCard label="Acceptor" sig={swap.acceptor_signature || {}} handle={swap.acceptor_handle} compact />
        </div>

        {err && (
          <div className="card" style={{ borderColor: 'rgba(231,76,60,0.5)', background: 'var(--red-tint)', marginTop: 16 }}>
            <div className="mono" style={{ fontSize: 12, color: 'var(--red-bright)' }}>{err}</div>
          </div>
        )}

        <div className="stack" style={{ marginTop: 22 }}>
          <button
            className="btn btn-gold btn-block btn-xl"
            disabled={locking}
            onClick={async () => {
              setLocking(true); setErr(null);
              try {
                const next = await window.pjFinalLock(swap.id);
                setSwap(next);
              } catch (e) { setErr(e.message || String(e)); }
              finally { setLocking(false); }
            }}
          >
            {locking ? 'Locking…' : 'FINAL LOCK'}
          </button>
          <button className="btn btn-ghost btn-block" onClick={() => onNav('/')}>Walk away</button>
        </div>

        <Footer />
      </div>
    );
  }

  // ---------- Settled / cancelled / unknown ----------
  return (
    <div className="page">
      <div className="card">
        <div className="eyebrow muted">Status</div>
        <div className="serif" style={{ fontSize: 28, marginTop: 6 }}>{(swap.status || 'unknown').toUpperCase()}</div>
      </div>
      <div style={{ marginTop: 20 }}><TermsSummary /></div>
      <button className="btn btn-ghost btn-block btn-lg" style={{ marginTop: 24 }} onClick={() => onNav('/swaps')}>My swaps</button>
      <Footer />
    </div>
  );
}

function SignatureCard({ label, sig, handle, compact }) {
  const { fmtDateTime } = window.PJ_UI;
  return (
    <div style={{ padding: compact ? '10px 0' : '14px', border: compact ? 'none' : '1px solid var(--line)', background: compact ? 'transparent' : 'var(--felt-2)' }}>
      <div className="eyebrow gold" style={{ marginBottom: 6 }}>◆ {label} signature</div>
      <div className="serif" style={{ fontSize: 22, color: 'var(--ivory)', marginBottom: 6 }}>{handle || sig.handle || '—'}</div>
      <div className="mono" style={{ fontSize: 11, color: 'var(--muted)', letterSpacing: '0.06em' }}>
        <div>SIGNED {fmtDateTime(sig.signed_at)}</div>
        {sig.gps && <div>GPS {sig.gps.lat.toFixed(4)}, {sig.gps.lng.toFixed(4)} (±{Math.round(sig.gps.accuracy)}m)</div>}
        {sig.device_id && <div>DEVICE {String(sig.device_id).slice(0, 8)}…</div>}
      </div>
    </div>
  );
}

window.SwapScreen = SwapScreen;
