/* global React, C, Screen, Avatar, Pill, Chevron, Close, RosterRow, STANDINGS, GOLFERS */
// sheets.jsx — extra in-app sheets that open via window.appNav.openSheet(...)
//
//   'member-lineup'  — tapping a row on the leaderboard or in a matchup
//   'member-picker'  — picking a friend to compare against / copy from

function useSheetPayload() {
  return window.useStore((s) => s.sheetPayload) || {};
}

// ─── A friend's lineup, opened from Standings or Matchup ──────────
function MemberLineupSheet() {
  const m = useSheetPayload();
  const close = () => { const n = window.appNav; if (n) n.closeSheet(); };
  const [lineup, setLineup] = React.useState(null);
  const [loading, setLoading] = React.useState(true);

  React.useEffect(() => {
    const api = window.cambamApi;
    if (!api || !api.isConfigured?.() || !m.memberId) { setLoading(false); return; }
    let cancelled = false;
    (async () => {
      try {
        const t = await api.currentTournament?.();
        if (!t || cancelled) { setLoading(false); return; }
        const data = await api.loadMemberLineup(m.memberId, t.id);
        if (!cancelled) { setLineup(data || null); setLoading(false); }
      } catch (e) { console.warn('member lineup load failed', e); if (!cancelled) setLoading(false); }
    })();
    return () => { cancelled = true; };
  }, [m.memberId]);

  const golfers = (lineup?.lineup_golfers || []).slice().sort((a, b) => a.slot - b.slot);
  const used = lineup?.cap_used ?? golfers.reduce((acc, g) => acc + (g.price || 0), 0);

  return (
    <Screen label="Member Lineup" bottomNav={null} scroll={false}>
      <div style={{ position: 'absolute', inset: 0, background: 'rgba(0,0,0,0.55)' }} />
      <div style={{
        position: 'absolute', left: 0, right: 0, bottom: 0,
        height: 'calc(100% - 56px)',
        background: C.surface,
        borderTopLeftRadius: 16, borderTopRightRadius: 16,
        display: 'flex', flexDirection: 'column', overflow: 'hidden',
      }}>
        <div style={{ display: 'flex', justifyContent: 'center', padding: '8px 0 4px', flexShrink: 0 }}>
          <div style={{ width: 36, height: 4, borderRadius: 999, background: C.hairline }} />
        </div>

        <div style={{
          padding: '8px 16px 12px', display: 'flex', alignItems: 'center', gap: 12, flexShrink: 0,
        }}>
          <Avatar name={m.name || 'Member'} size={44} tone={m.tone || 1} champion={m.champion} />
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ font: '700 18px/22px Inter', color: C.text }}>{m.name || 'Member'}</div>
            <div style={{ font: '400 13px/18px Inter', color: C.text2, marginTop: 1 }}>
              {m.handle || '@member'} · Rank {m.rank || '—'} · {m.status || 'on the course'}
            </div>
          </div>
          <button aria-label="Close member lineup" onClick={close} style={{
            width: 32, height: 32, borderRadius: 999, background: C.surface2,
            border: 'none', cursor: 'pointer', color: C.text2,
            display: 'flex', alignItems: 'center', justifyContent: 'center',
          }}><Close size={16} /></button>
        </div>

        <div style={{
          margin: '0 16px 12px', padding: '12px 14px', borderRadius: 12, background: C.surface2,
          display: 'flex', alignItems: 'baseline', justifyContent: 'space-between',
        }}>
          <div>
            <div style={{ font: '500 11px/16px Inter', textTransform: 'uppercase', letterSpacing: 0.04 * 11, color: C.text3 }}>Points</div>
            <div className="tnum" style={{ font: '700 24px/28px Inter', color: C.emerald }}>{Number(m.points || 0).toFixed(1)}</div>
          </div>
          <div style={{ textAlign: 'right' }}>
            <div style={{ font: '500 11px/16px Inter', textTransform: 'uppercase', letterSpacing: 0.04 * 11, color: C.text3 }}>Cap used</div>
            <div className="tnum" style={{ font: '600 18px/22px Inter', color: C.text }}>${used || 0} / $200</div>
          </div>
        </div>

        <div style={{ flex: 1, overflow: 'auto', paddingBottom: 24 }}>
          {loading ? (
            <div style={{ padding: '20px 24px', color: C.text3, font: '400 13px/18px Inter', textAlign: 'center' }}>Loading…</div>
          ) : golfers.length === 0 ? (
            <div style={{ padding: '20px 24px', color: C.text2, font: '400 13px/18px Inter', textAlign: 'center' }}>
              {m.memberId ? "Lineup hidden until lock or not recorded." : "Tap a member from standings to see their lineup."}
            </div>
          ) : golfers.map((g, i) => (
            <React.Fragment key={g.slot || i}>
              <RosterRow
                name={g.golfer_name}
                country=""
                price={g.price}
                points={0}
                tone={1}
                status=""
                onClick={() => { const n = window.appNav; if (n) n.openSheet('golfer-detail', { name: g.golfer_name, golferId: g.golfer_id, price: g.price }); }}
              />
              {i < golfers.length - 1 && <div style={{ height: 8 }} />}
            </React.Fragment>
          ))}
        </div>
      </div>
    </Screen>
  );
}

// ─── Pick a member to copy / compare against ─────────────────────
function MemberPickerSheet() {
  const payload = useSheetPayload();
  const me = window.useStore((s) => s.me) || {};
  const close = () => { const n = window.appNav; if (n) n.closeSheet(); };
  const [q, setQ] = React.useState('');
  const [allMembers, setAllMembers] = React.useState([]);
  const [tournament, setTournament] = React.useState(null);

  React.useEffect(() => {
    const api = window.cambamApi;
    if (!api || !api.isConfigured?.()) return;
    let cancelled = false;
    (async () => {
      try {
        const [ms, t] = await Promise.all([api.loadAllMembers(), api.currentTournament?.()]);
        if (cancelled) return;
        setAllMembers((ms || []).filter((m) => !m.is_suspended));
        setTournament(t || null);
      } catch (e) { console.warn('member picker load failed', e); }
    })();
    return () => { cancelled = true; };
  }, []);

  const members = allMembers
    .filter((m) => m.id !== me.id)
    .filter((m) => !q || (m.display_name || '').toLowerCase().includes(q.toLowerCase()) || (m.handle || '').toLowerCase().includes(q.toLowerCase()));

  const pick = async (member) => {
    if (payload.purpose === 'copy-lineup') {
      // Copy the member's locked lineup into your draft (RLS-gated: only after lock).
      if (!tournament) { window.STORE.toast('No tournament selected'); close(); return; }
      try {
        const ln = await window.cambamApi.loadMemberLineup(member.id, tournament.id);
        const golfers = (ln?.lineup_golfers || []).slice().sort((a, b) => a.slot - b.slot);
        if (!golfers.length) { window.STORE.toast(`${member.display_name || member.handle}'s lineup is hidden until lock.`); close(); return; }
        const slots = Array(6).fill(null);
        for (const g of golfers) {
          if (g.slot >= 1 && g.slot <= 6) {
            slots[g.slot - 1] = { name: g.golfer_name, golferId: g.golfer_id, price: g.price, country: '', points: 0, tone: 1, status: 'Copied' };
          }
        }
        window.STORE.set((s) => ({ ...s, lineupDraft: { ...s.lineupDraft, pga: { ...s.lineupDraft.pga, slots } } }));
        window.STORE.toast(`Copied ${member.display_name || member.handle}'s lineup`);
      } catch (e) { console.warn('copy lineup failed', e); window.STORE.toast('Copy failed'); }
    } else if (payload.purpose === 'matchup-opponent') {
      window.STORE.patch('matchup', { opponentHandle: member.handle });
      window.STORE.toast(`Now comparing vs ${member.display_name || member.handle}`);
    }
    close();
  };

  const title = payload.purpose === 'copy-lineup' ? 'Copy a lineup'
              : payload.purpose === 'matchup-opponent' ? 'Pick opponent'
              : 'Pick a member';

  return (
    <Screen label="Member Picker" bottomNav={null} scroll={false}>
      <div style={{ position: 'absolute', inset: 0, background: 'rgba(0,0,0,0.55)' }} />
      <div style={{
        position: 'absolute', left: 0, right: 0, bottom: 0,
        height: 'calc(100% - 80px)',
        background: C.surface,
        borderTopLeftRadius: 16, borderTopRightRadius: 16,
        display: 'flex', flexDirection: 'column', overflow: 'hidden',
      }}>
        <div style={{ display: 'flex', justifyContent: 'center', padding: '8px 0 4px', flexShrink: 0 }}>
          <div style={{ width: 36, height: 4, borderRadius: 999, background: C.hairline }} />
        </div>
        <div style={{
          padding: '8px 16px 12px', display: 'flex', alignItems: 'center', justifyContent: 'space-between',
          flexShrink: 0,
        }}>
          <div style={{ font: '600 18px/24px Inter', color: C.text }}>{title}</div>
          <button aria-label="Close member picker" onClick={close} style={{
            width: 32, height: 32, borderRadius: 999, background: C.surface2,
            border: 'none', cursor: 'pointer', color: C.text2,
            display: 'flex', alignItems: 'center', justifyContent: 'center',
          }}><Close size={16} /></button>
        </div>

        <div style={{ padding: '0 16px 12px', flexShrink: 0 }}>
          <input
            type="text" placeholder="Search members…"
            value={q} onChange={(e) => setQ(e.target.value)}
            style={{
              width: '100%', height: 40, padding: '0 14px',
              background: C.surface2, border: 'none', borderRadius: 999,
              color: C.text, font: '400 14px/20px Inter', outline: 'none',
            }}
          />
        </div>

        <div style={{ flex: 1, overflow: 'auto' }}>
          {members.length === 0 ? (
            <div style={{ padding: '24px 16px', textAlign: 'center', color: C.text3, font: '400 13px/18px Inter' }}>
              {allMembers.length <= 1 ? 'You\'re the only member so far — invite friends from Admin.' : 'No matching members.'}
            </div>
          ) : members.map((m, i) => (
            <button key={m.id || m.handle || i} onClick={() => pick(m)} style={{
              width: '100%', textAlign: 'left',
              padding: '10px 16px',
              display: 'flex', alignItems: 'center', gap: 12,
              background: 'transparent', border: 'none', cursor: 'pointer',
            }}>
              <Avatar name={m.display_name || m.handle} size={36} tone={m.avatar_tone || 1} champion={!!m.champion} />
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ font: '600 15px/20px Inter', color: C.text }}>{m.display_name || m.handle || '—'}</div>
                <div style={{ font: '400 12px/16px Inter', color: C.text2 }}>{m.handle || ''}{m.role && m.role !== 'member' ? ` · ${m.role}` : ''}</div>
              </div>
              <Chevron dir="right" size={14} />
            </button>
          ))}
        </div>
      </div>
    </Screen>
  );
}

Object.assign(window, { MemberLineupSheet, MemberPickerSheet });
