// Introducer view — a read-only "My introductions" surface for a partner who
// forwarded their invite link. Reached at /?view=introducer when the signed-in
// session's email is on the introducers allowlist (auth.isIntroducer). All data
// comes from /api/introducer/invites, which scopes strictly to this caller's
// own tree and redacts to firm + status + NDA + date. Nudge posts an invite id
// back; the server resolves the recipient and never exposes their email here.

function IntroducerStatusPill({ status }) {
  const map = {
    active:            { label: 'Active',           color: 'var(--success)', border: 'var(--success)' },
    pending_approval:  { label: 'Pending approval', color: 'var(--gold-dark)', border: 'var(--gold)' },
  };
  const s = map[status] || map.active;
  return (
    <span className="mono" style={{
      display: 'inline-block', fontSize: 10, letterSpacing: '0.06em',
      padding: '2px 8px', borderRadius: 20, color: s.color,
      border: `1px solid ${s.border}`,
    }}>{s.label}</span>
  );
}

function IntroducerStat({ n, label, color }) {
  return (
    <div style={{ flex: 1, padding: '14px 18px', borderRight: '1px solid var(--border)' }}>
      <div className="mono" style={{ fontSize: 24, lineHeight: 1, marginBottom: 6, color: color || 'var(--text-primary)' }}>{n}</div>
      <div className="mono" style={{ fontSize: 10, letterSpacing: '0.1em', textTransform: 'uppercase', color: 'var(--text-tertiary)' }}>{label}</div>
    </div>
  );
}

function IntroducerView({ identity, onExit }) {
  const [state, setState] = React.useState('loading'); // loading | ready | unauthorized | error
  const [summary, setSummary] = React.useState({ introduced: 0, active: 0, signed_nda: 0, pending: 0 });
  const [invites, setInvites] = React.useState([]);
  const [me, setMe] = React.useState(null);
  const [error, setError] = React.useState(null);
  const [nudgeState, setNudgeState] = React.useState({}); // id -> 'sending' | 'sent' | 'throttled' | 'failed'

  const load = React.useCallback(async () => {
    setState('loading'); setError(null);
    try {
      const r = await fetch('/api/introducer/invites', { credentials: 'include' });
      if (r.status === 401) { setState('unauthorized'); return; }
      if (!r.ok) { const b = await r.json().catch(() => ({})); setError(b.error || `HTTP ${r.status}`); setState('error'); return; }
      const data = await r.json();
      setSummary(data.summary || { introduced: 0, active: 0, signed_nda: 0, pending: 0 });
      setInvites(data.invites || []);
      setMe(data.introducer || null);
      setState('ready');
    } catch (e) { setError(e.message); setState('error'); }
  }, []);

  React.useEffect(() => { load(); }, [load]);

  const nudge = async (id) => {
    setNudgeState(s => ({ ...s, [id]: 'sending' }));
    try {
      const r = await fetch('/api/introducer/nudge', {
        method: 'POST', credentials: 'include',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ invite_id: id }),
      });
      const data = await r.json().catch(() => ({}));
      const outcome = data.status === 'sent' ? 'sent'
        : data.status === 'throttled' ? 'throttled'
        : data.status === 'rate_limited' ? 'rate_limited'
        : 'failed';
      setNudgeState(s => ({ ...s, [id]: outcome }));
    } catch (e) {
      setNudgeState(s => ({ ...s, [id]: 'failed' }));
    }
  };

  const displayName = me?.name || identity?.name || (me?.email || identity?.email || 'Introducer');

  return (
    <div style={{ minHeight: '100vh', background: 'var(--bg)', padding: '36px 24px' }}>
      <div style={{ maxWidth: 880, margin: '0 auto' }}>
        <div className="section-num" style={{ marginBottom: 16 }}>
          <span>[ INTRODUCTIONS ]</span><span className="div" />
          <span className="mono" style={{ fontSize: 11, color: 'var(--gold-dark)' }}>INTRODUCER · {displayName}</span>
        </div>

        <div className="admin-page-header" style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 24 }}>
          <div>
            <h1 style={{ fontSize: 32, letterSpacing: '-0.025em', fontWeight: 400, margin: '0 0 4px' }}>My introductions</h1>
            <p style={{ fontSize: 13, color: 'var(--text-secondary)', margin: 0, maxWidth: 620 }}>
              The people who came into the Arb Capital data room through your link. You see firm, status, and NDA state. Nudge sends them a friendly reminder on your behalf.
            </p>
          </div>
          <div style={{ display: 'flex', gap: 8 }}>
            <button className="btn btn-sm" onClick={load} disabled={state === 'loading'}>{state === 'loading' ? '…' : '↻ Refresh'}</button>
            {onExit && <button className="btn btn-ghost btn-sm" onClick={onExit}>↻ Back to room</button>}
          </div>
        </div>

        {state === 'unauthorized' && (
          <Brackets style={{ padding: 32, border: '1px solid var(--border)', background: 'var(--bg-card)', textAlign: 'center' }}>
            <div style={{ fontSize: 15, marginBottom: 8 }}>Sign in to see your introductions</div>
            <p style={{ fontSize: 13, color: 'var(--text-secondary)', margin: 0 }}>
              Open your personal magic-link email to sign in, then reload this page. Introducer access is tied to your own login.
            </p>
          </Brackets>
        )}

        {state === 'error' && (
          <div style={{ padding: 12, border: '1px solid var(--error)', color: 'var(--error)', fontFamily: 'var(--font-mono)', fontSize: 12 }}>{error}</div>
        )}

        {(state === 'ready' || state === 'loading') && state !== 'unauthorized' && (
          <>
            {/* Summary strip */}
            <div style={{ display: 'flex', border: '1px solid var(--border)', borderRadius: 9, overflow: 'hidden', marginBottom: 20 }}>
              <IntroducerStat n={summary.introduced} label="Introduced" />
              <IntroducerStat n={summary.active} label="Active" color="var(--success)" />
              <IntroducerStat n={summary.signed_nda} label="Signed NDA" color="var(--gold-dark)" />
              <div style={{ flex: 1, padding: '14px 18px' }}>
                <div className="mono" style={{ fontSize: 24, lineHeight: 1, marginBottom: 6, color: 'var(--gold-dark)' }}>{summary.pending}</div>
                <div className="mono" style={{ fontSize: 10, letterSpacing: '0.1em', textTransform: 'uppercase', color: 'var(--text-tertiary)' }}>Pending approval</div>
              </div>
            </div>

            <Brackets style={{ background: 'var(--bg-card)', border: '1px solid var(--border)' }}>
              {state === 'loading' ? (
                <div style={{ padding: 40, textAlign: 'center', color: 'var(--text-tertiary)', fontFamily: 'var(--font-mono)', fontSize: 11, letterSpacing: '0.12em' }}>LOADING…</div>
              ) : invites.length === 0 ? (
                <div style={{ padding: 40, textAlign: 'center', color: 'var(--text-tertiary)', fontSize: 13 }}>
                  No introductions yet. When someone opens the room through your link, they appear here.
                </div>
              ) : (
                <div className="admin-tbl-wrap"><table className="tbl">
                  <thead>
                    <tr>
                      <th style={{ width: 30 }}></th>
                      <th>Firm / org</th>
                      <th>Status</th>
                      <th>NDA</th>
                      <th>Invited</th>
                      <th></th>
                    </tr>
                  </thead>
                  <tbody>
                    {invites.map((r, i) => {
                      const ns = nudgeState[r.id];
                      return (
                        <tr key={r.id}>
                          <td><span className="mono" style={{ fontSize: 9, color: 'var(--text-tertiary)' }}>{String(i+1).padStart(2,'0')}</span></td>
                          <td><span style={{ fontSize: 13, color: r.firm ? 'var(--text-primary)' : 'var(--text-tertiary)' }}>{r.firm || 'Personal email'}</span></td>
                          <td><IntroducerStatusPill status={r.status} /></td>
                          <td>
                            {r.nda_signed
                              ? <span className="mono" style={{ fontSize: 10, color: 'var(--gold-dark)' }}>Signed{r.nda_signed_at ? ' · ' + relTime(r.nda_signed_at) : ''}</span>
                              : <span className="mono" style={{ fontSize: 10, color: 'var(--text-tertiary)' }}>—</span>}
                          </td>
                          <td><span className="mono" style={{ fontSize: 11, color: 'var(--text-tertiary)' }}>{relTime(r.created_at)}</span></td>
                          <td style={{ whiteSpace: 'nowrap' }}>
                            {!r.nudgeable ? (
                              <span className="mono" style={{ fontSize: 10, color: 'var(--text-tertiary)' }}>awaiting approval</span>
                            ) : ns === 'sent' ? (
                              <span className="mono" style={{ fontSize: 11, color: 'var(--success)' }}>✓ Nudged</span>
                            ) : ns === 'throttled' ? (
                              <span className="mono" style={{ fontSize: 10, color: 'var(--text-tertiary)' }} title="Already nudged recently">recently nudged</span>
                            ) : ns === 'rate_limited' ? (
                              <span className="mono" style={{ fontSize: 10, color: 'var(--text-tertiary)' }} title="You've sent a lot of nudges — try again a little later">try later</span>
                            ) : ns === 'failed' ? (
                              <button className="btn btn-ghost btn-sm" style={{ padding: '4px 10px', color: 'var(--error)', borderColor: 'var(--error)' }} onClick={() => nudge(r.id)}>Retry</button>
                            ) : (
                              <button className="btn btn-ghost btn-sm" disabled={ns === 'sending'}
                                style={{ padding: '4px 10px' }} onClick={() => nudge(r.id)}>
                                {ns === 'sending' ? '…' : 'Nudge'}
                              </button>
                            )}
                          </td>
                        </tr>
                      );
                    })}
                  </tbody>
                </table></div>
              )}
            </Brackets>

            <p className="mono" style={{ fontSize: 10, color: 'var(--text-tertiary)', marginTop: 14, paddingLeft: 12, borderLeft: '2px solid var(--border)' }}>
              You never see a contact's email address. Nudges are rate-limited, so a person will only be reminded once within a short window.
            </p>
          </>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { IntroducerView });
