// screen-profile.jsx — /p/[handle] — player profile with reputation.

const { useState: pU, useEffect: pE } = React;

function ProfileScreen({ handle, onNav }) {
  const { Footer, fmtMoney, fmtPct, fmtDateTime } = window.PJ_UI;
  const [rep, setRep] = pU(null);
  const [openListings, setOpenListings] = pU([]);
  const [recentSwaps, setRecentSwaps] = pU([]);
  const [loading, setLoading] = pU(true);
  const [err, setErr] = pU(null);
  const [addedToStable, setAddedToStable] = pU(false);

  pE(() => {
    (async () => {
      if (!handle) { setErr('No handle in URL.'); setLoading(false); return; }
      try {
        const [listings, swaps] = await Promise.all([
          window.pjListingsByPlayerHandle(handle),
          window.pjGetPlayerRecentSwaps(handle, 10)
        ]);
        // Look up reputation against the device that actually owns the
        // most recent listing/swap — prevents handle spoofing on a fresh
        // device from inheriting another device's reputation.
        let deviceId = null;
        if (listings && listings.length > 0 && listings[0].player_device_id) {
          deviceId = listings[0].player_device_id;
        }
        const r = await window.pjGetReputation(handle, deviceId || window.pjDeviceId);
        setRep(r);
        setOpenListings(listings);
        setRecentSwaps(swaps);
      } catch (e) {
        setErr(e.message || String(e));
      } finally {
        setLoading(false);
      }
    })();
  }, [handle]);

  // Check current stable
  pE(() => {
    try {
      const groups = JSON.parse(window.localStorage.getItem('pj_teams') || '[]');
      const target = (handle || '').toLowerCase();
      const here = groups.some(g => (g.members || []).some(m => (m || '').toLowerCase() === target));
      setAddedToStable(here);
    } catch (_) {}
  }, [handle]);

  const addToStable = () => {
    try {
      const groups = JSON.parse(window.localStorage.getItem('pj_teams') || '[]');
      let next = groups.slice();
      if (next.length === 0) {
        next = [{ name: 'My Stable', members: [handle] }];
      } else {
        const first = { ...next[0] };
        if (!(first.members || []).some(m => (m || '').toLowerCase() === handle.toLowerCase())) {
          first.members = [...(first.members || []), handle];
        }
        next[0] = first;
      }
      window.localStorage.setItem('pj_teams', JSON.stringify(next));
      setAddedToStable(true);
    } catch (_) {}
  };

  if (loading) {
    return (
      <div className="page">
        <p className="mono" style={{ color: 'var(--text-3)', textAlign: 'center', marginTop: 60 }}>
          Loading @{handle}…
        </p>
      </div>
    );
  }

  if (err) {
    return (
      <div className="page">
        <div className="card" style={{
          borderColor: 'rgba(255,77,94,0.5)', background: 'var(--red-soft)',
          padding: 14, borderRadius: 10
        }}>
          <div className="mono" style={{ fontSize: 12, color: '#ff8a9c' }}>{err}</div>
        </div>
        <button className="btn btn-ghost btn-block btn-lg" style={{ marginTop: 18 }} onClick={() => onNav('/browse')}>
          Back to marketplace
        </button>
      </div>
    );
  }

  const locked = rep ? (rep.locked_count || 0) : 0;
  const settled = rep ? (rep.settled_count || 0) : 0;
  const volume = rep ? (rep.total_volume || 0) : 0;
  const paidRate = rep ? rep.paid_rate : 1;
  const paidRatePct = Math.round((paidRate || 0) * 100);

  const repColor = locked === 0
    ? 'var(--text-3)'
    : paidRate >= 0.95 ? 'var(--green)' : '#FFB84D';

  // Verified = reputation row exists for the device that owns this handle.
  // If no locks yet for this device + handle pair, anyone can claim the handle.
  const verifiedByDevice = rep && rep.verified;
  const viewerIsOwner = rep && rep.device_id === window.pjDeviceId;

  return (
    <div className="page">
      <button
        type="button"
        onClick={() => onNav('/browse')}
        className="mono"
        style={{
          all: 'unset', cursor: 'pointer',
          fontSize: 11, letterSpacing: '0.14em', color: 'var(--text-3)',
          textTransform: 'uppercase', marginBottom: 16, display: 'inline-block'
        }}
      >← Marketplace</button>

      {/* Identity header */}
      <div style={{ marginBottom: 24 }}>
        <div style={{
          display: 'flex', alignItems: 'center', gap: 14, marginBottom: 12
        }}>
          <div style={{
            width: 56, height: 56, borderRadius: 14,
            background: 'linear-gradient(180deg, #1F262E, #0F1318)',
            border: '1px solid var(--green-line)',
            boxShadow: '0 0 18px var(--green-glow-2)',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            fontFamily: 'var(--font-display)', fontSize: 24, fontWeight: 800,
            color: 'var(--green)', textShadow: '0 0 12px var(--green-glow)'
          }}>{(handle || '?')[0].toUpperCase()}</div>
          <div style={{ minWidth: 0, flex: 1 }}>
            <h2 style={{
              fontFamily: 'var(--font-display)', fontSize: 30, fontWeight: 800,
              letterSpacing: '-0.025em', lineHeight: 1, margin: 0, color: 'var(--text)'
            }}>@{handle}</h2>
            <div className="mono" style={{
              fontSize: 10, letterSpacing: '0.14em', textTransform: 'uppercase',
              color: verifiedByDevice ? repColor : 'var(--text-3)', marginTop: 6
            }}>
              {verifiedByDevice
                ? (viewerIsOwner ? 'VERIFIED ON THIS DEVICE' : 'VERIFIED BY DEVICE')
                : 'UNVERIFIED — ANYONE CAN CLAIM THIS HANDLE'}
            </div>
          </div>
        </div>

        {!addedToStable && (
          <button
            type="button"
            onClick={addToStable}
            className="btn btn-ghost btn-block"
            style={{ marginTop: 4 }}
          >
            + Add to my stable
          </button>
        )}
        {addedToStable && (
          <div className="mono" style={{
            fontSize: 11, letterSpacing: '0.14em', color: 'var(--green)',
            textTransform: 'uppercase', textAlign: 'center', padding: '8px 0'
          }}>✓ In your stable</div>
        )}
      </div>

      {/* Stats grid */}
      <div style={{
        display: 'grid', gridTemplateColumns: '1fr 1fr 1fr',
        gap: 8, marginBottom: 28
      }}>
        <Stat label="Locked" value={locked} />
        <Stat label="Paid" value={settled + ' of ' + locked} />
        <Stat label="Paid rate" value={paidRatePct + '%'} highlight={paidRate >= 0.95} />
      </div>
      <div style={{
        background: 'var(--bg-1)', border: '1px solid rgba(255,255,255,0.06)',
        borderRadius: 12, padding: 16, marginBottom: 28
      }}>
        <div className="mono" style={{
          fontSize: 10, letterSpacing: '0.14em', color: 'var(--text-3)',
          textTransform: 'uppercase', marginBottom: 6
        }}>Total dollar volume settled</div>
        <div style={{
          fontFamily: 'var(--font-display)', fontSize: 28, fontWeight: 800,
          color: 'var(--text)', letterSpacing: '-0.02em'
        }}>{fmtMoney(volume)}</div>
      </div>

      {/* Open listings */}
      <section style={{ marginBottom: 32 }}>
        <div className="mono" style={{
          fontSize: 11, letterSpacing: '0.14em', color: 'var(--green)',
          textTransform: 'uppercase', marginBottom: 12
        }}>◆ Open listings ({openListings.length})</div>

        {openListings.length === 0 && (
          <p style={{ color: 'var(--text-3)', fontSize: 14 }}>
            @{handle} has no action listed right now.
          </p>
        )}

        <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
          {openListings.map(l => {
            const remaining = Number(l.pct_available) - (Number(l.amount_taken) || 0);
            return (
              <div key={l.id} style={{
                background: 'var(--bg-1)', border: '1px solid rgba(255,255,255,0.06)',
                borderRadius: 12, padding: 14
              }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
                  <div style={{ minWidth: 0, flex: 1 }}>
                    <div style={{ fontSize: 14, color: 'var(--text)', fontWeight: 600, marginBottom: 2 }}>
                      {l.tournament_name}
                    </div>
                    <div className="mono" style={{
                      fontSize: 10, letterSpacing: '0.12em', color: 'var(--text-3)',
                      textTransform: 'uppercase'
                    }}>
                      {l.buy_in ? fmtMoney(l.buy_in) : 'BUY-IN TBD'} · {Number(l.markup).toFixed(2)}X
                    </div>
                  </div>
                  <div style={{ textAlign: 'right', marginLeft: 12 }}>
                    <div style={{
                      fontFamily: 'var(--font-display)', fontSize: 18, fontWeight: 800,
                      color: 'var(--green)'
                    }}>{remaining.toFixed(0)}%</div>
                  </div>
                </div>
                <button
                  type="button"
                  onClick={() => window.PJ_MARKETPLACE_ACCEPT(l, onNav)}
                  className="btn btn-ghost btn-block"
                  style={{ marginTop: 10 }}
                >
                  Back this listing →
                </button>
              </div>
            );
          })}
        </div>
      </section>

      {/* Recent locked swaps */}
      <section style={{ marginBottom: 32 }}>
        <div className="mono" style={{
          fontSize: 11, letterSpacing: '0.14em', color: 'var(--green)',
          textTransform: 'uppercase', marginBottom: 12
        }}>◆ Recent locks</div>
        {recentSwaps.length === 0 && (
          <p style={{ color: 'var(--text-3)', fontSize: 14 }}>No locked swaps yet.</p>
        )}
        {recentSwaps.map(s => (
          <div key={s.id} style={{
            padding: '12px 0', borderBottom: '1px solid rgba(255,255,255,0.06)',
            display: 'flex', justifyContent: 'space-between', alignItems: 'baseline'
          }}>
            <div style={{ minWidth: 0, flex: 1 }}>
              <div style={{ fontSize: 14, color: 'var(--text)' }}>{s.tournament_name}</div>
              <div className="mono" style={{
                fontSize: 10, letterSpacing: '0.12em', color: 'var(--text-3)',
                textTransform: 'uppercase', marginTop: 2
              }}>
                vs ████ · {fmtDateTime(s.locked_at || s.created_at)}
              </div>
            </div>
            <div style={{ textAlign: 'right', marginLeft: 12 }}>
              <div className="mono" style={{ color: 'var(--text)', fontSize: 13 }}>
                {fmtPct(s.originator_pct)}
              </div>
              <div className="mono" style={{
                fontSize: 9, letterSpacing: '0.12em', textTransform: 'uppercase',
                color: s.status === 'settled' ? 'var(--green)' : 'var(--text-3)'
              }}>{s.status}</div>
            </div>
          </div>
        ))}
      </section>

      <Footer />
    </div>
  );
}

function Stat({ label, value, highlight }) {
  return (
    <div style={{
      background: 'var(--bg-1)', border: '1px solid rgba(255,255,255,0.06)',
      borderRadius: 12, padding: 14, textAlign: 'center'
    }}>
      <div style={{
        fontFamily: 'var(--font-display)', fontSize: 22, fontWeight: 800,
        color: highlight ? 'var(--green)' : 'var(--text)',
        letterSpacing: '-0.02em',
        textShadow: highlight ? '0 0 14px var(--green-glow-2)' : 'none'
      }}>{value}</div>
      <div className="mono" style={{
        fontSize: 9, letterSpacing: '0.14em', textTransform: 'uppercase',
        color: 'var(--text-3)', marginTop: 4
      }}>{label}</div>
    </div>
  );
}

window.ProfileScreen = ProfileScreen;
