// screen-teams.jsx — "Your Boys" — opponents you've swapped with.

const { useState: tU, useEffect: tE } = React;

function TeamsScreen({ onNav }) {
  const { Footer, fmtMoney, fmtDateTime } = window.PJ_UI;
  const [opps, setOpps] = tU([]);
  const [loading, setLoading] = tU(true);
  const [err, setErr] = tU(null);
  const [groups, setGroups] = tU(() => {
    try { return JSON.parse(window.localStorage.getItem('pj_teams') || '[]'); } catch (_) { return []; }
  });
  const [showAdd, setShowAdd] = tU(false);
  const [newName, setNewName] = tU('');

  tE(() => {
    (async () => {
      try {
        const list = await window.pjListMyOpponents();
        setOpps(list);
      } catch (e) { setErr(e.message || String(e)); }
      finally { setLoading(false); }
    })();
  }, []);

  const saveGroups = (next) => {
    setGroups(next);
    try { window.localStorage.setItem('pj_teams', JSON.stringify(next)); } catch (_) {}
  };

  const addGroup = () => {
    if (!newName.trim()) return;
    saveGroups([...groups, { name: newName.trim(), members: [] }]);
    setNewName('');
    setShowAdd(false);
  };

  const toggleMember = (groupIdx, handle) => {
    const next = groups.map((g, i) => {
      if (i !== groupIdx) return g;
      const members = g.members.includes(handle)
        ? g.members.filter(h => h !== handle)
        : [...g.members, handle];
      return { ...g, members };
    });
    saveGroups(next);
  };

  return (
    <div className="page">
      <div className="eyebrow gold" style={{ marginBottom: 8 }}>◆ Your boys</div>
      <h2 className="serif" style={{ fontSize: 40, lineHeight: 1, marginBottom: 8 }}>The roster.</h2>
      <p className="paper" style={{ marginBottom: 28 }}>
        Everyone you've swapped with. Group them. Track the action.
      </p>

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

      {!loading && opps.length === 0 && (
        <div className="card center" style={{ padding: 32 }}>
          <div className="serif" style={{ fontSize: 24, marginBottom: 8 }}>No counterparties yet.</div>
          <p className="paper" style={{ marginBottom: 20 }}>Run your first swap to start your roster.</p>
          <button className="btn btn-gold" onClick={() => onNav('/new')}>Start a swap</button>
        </div>
      )}

      {opps.length > 0 && (
        <section style={{ marginBottom: 32 }}>
          <div className="eyebrow gold" style={{ marginBottom: 10 }}>◆ All counterparties</div>
          {opps.map(o => (
            <div key={o.handle} className="card-row" style={{ cursor: 'default' }}>
              <div style={{ minWidth: 0, flex: 1 }}>
                <div className="serif" style={{ fontSize: 18, color: 'var(--ivory)', marginBottom: 4 }}>
                  {o.handle}
                </div>
                <div className="mono" style={{ fontSize: 11, color: 'var(--muted)', letterSpacing: '0.06em' }}>
                  {o.count} SWAP{o.count !== 1 ? 'S' : ''} · {fmtMoney(o.volume)} VOLUME · LAST {fmtDateTime(o.lastAt)}
                </div>
              </div>
              <div style={{ textAlign: 'right' }}>
                <span className="tag tag-green">ACTIVE</span>
              </div>
            </div>
          ))}
        </section>
      )}

      <section style={{ marginBottom: 28 }}>
        <div className="row-between" style={{ marginBottom: 10 }}>
          <div className="eyebrow gold">◆ Crews</div>
          <button className="btn btn-ghost" style={{ padding: '6px 12px', fontSize: 12 }} onClick={() => setShowAdd(true)}>+ Add</button>
        </div>

        {groups.length === 0 && !showAdd && (
          <p className="mono muted" style={{ fontSize: 12, letterSpacing: '0.04em' }}>
            Nickname groups like "Vegas crew" or "Sundays" to organize your roster.
          </p>
        )}

        {showAdd && (
          <div className="card" style={{ marginBottom: 14, borderColor: 'var(--line-gold)' }}>
            <div className="row" style={{ gap: 8 }}>
              <input
                className="input"
                placeholder="Crew name (e.g. Vegas Boys)"
                value={newName}
                onChange={e => setNewName(e.target.value)}
                maxLength={32}
              />
              <button className="btn btn-gold" onClick={addGroup}>Save</button>
            </div>
          </div>
        )}

        {groups.map((g, idx) => (
          <div key={idx} className="card" style={{ marginBottom: 12 }}>
            <div className="row-between" style={{ marginBottom: 10 }}>
              <div className="serif" style={{ fontSize: 20 }}>{g.name}</div>
              <div className="mono muted" style={{ fontSize: 11 }}>{g.members.length} in crew</div>
            </div>
            <div className="row" style={{ flexWrap: 'wrap', gap: 8 }}>
              {opps.map(o => (
                <button
                  key={o.handle}
                  type="button"
                  className={'chip' + (g.members.includes(o.handle) ? ' chip-on' : '')}
                  onClick={() => toggleMember(idx, o.handle)}
                >
                  {o.handle}
                </button>
              ))}
              {opps.length === 0 && (
                <span className="mono muted" style={{ fontSize: 11 }}>No counterparties yet to add.</span>
              )}
            </div>
          </div>
        ))}
      </section>

      <Footer />
    </div>
  );
}

window.TeamsScreen = TeamsScreen;
