// screens-admin-donors.jsx — Donor management workspace for the operator
// console. Table of donors → detail drawer with giving history, benefits,
// open concierge requests, and the message thread (the other side of the
// fan-facing Donor Hub conversation).

const ADMIN_DONORS = [
  {
    id: 'd1', name: 'Derek Callahan', initials: 'DC', tier: 'Gold Club',
    total: 48750, lastGift: '$5,000 · Oct 14', since: 2019,
    status: 'active', openRequests: 1, email: 'derek.callahan@protonmail.com',
    seats: 'Sec 108 · Row 14', rep: 'Lindsay M.',
    history: [
      { when: 'Oct 14, 2026', what: 'Annual fund · football', amt: '$5,000' },
      { when: 'Mar 02, 2026', what: 'NIL collective gift', amt: '$2,500' },
      { when: 'Nov 21, 2025', what: 'Facilities campaign', amt: '$10,000' },
      { when: 'Sep 05, 2025', what: 'Annual fund · football', amt: '$5,000' },
    ],
    requests: [
      { id: 'r1', what: 'Bowl-game travel package · 2 seats', when: '2d ago', state: 'OPEN' },
    ],
    thread: [
      { from: 'donor', body: 'Hi Lindsay — any word on the bowl travel package? Want to lock in two seats.', t: '2d ago' },
      { from: 'rep',   body: 'Hi Derek! Allocations open Friday. Gold Club gets first pick — I\u2019ll hold two until Monday.', t: '1d ago' },
      { from: 'donor', body: 'Perfect, thank you!', t: '1d ago' },
    ],
  },
  {
    id: 'd2', name: 'Patricia Wendell', initials: 'PW', tier: 'Mountaineer Society',
    total: 215000, lastGift: '$50,000 · Sep 28', since: 2008,
    status: 'active', openRequests: 0, email: 'p.wendell@wendellgroup.com',
    seats: 'Suite 4', rep: 'Lindsay M.',
    history: [
      { when: 'Sep 28, 2026', what: 'Facilities campaign · naming', amt: '$50,000' },
      { when: 'Feb 11, 2026', what: 'Annual fund · all sports', amt: '$25,000' },
    ],
    requests: [],
    thread: [
      { from: 'rep', body: 'Patricia — the locker-room plaque mockups are ready when you are.', t: '5d ago' },
    ],
  },
  {
    id: 'd3', name: 'Marcus Boyd', initials: 'MB', tier: 'Blue & Gold Fund',
    total: 12400, lastGift: '$1,200 · Oct 02', since: 2021,
    status: 'active', openRequests: 1, email: 'mboyd84@gmail.com',
    seats: 'Sec 212 · Row 6', rep: 'Aaron T.',
    history: [
      { when: 'Oct 02, 2026', what: 'Annual fund · basketball', amt: '$1,200' },
      { when: 'Oct 01, 2025', what: 'Annual fund · basketball', amt: '$1,200' },
    ],
    requests: [
      { id: 'r2', what: 'Seat upgrade inquiry · lower bowl', when: '6h ago', state: 'OPEN' },
    ],
    thread: [
      { from: 'donor', body: 'Looking to move to the lower bowl next season if anything opens up.', t: '6h ago' },
    ],
  },
  {
    id: 'd4', name: 'Helen Okafor', initials: 'HO', tier: 'Gold Club',
    total: 67300, lastGift: '$7,500 · Aug 19', since: 2014,
    status: 'lapsing', openRequests: 0, email: 'h.okafor@okafordental.com',
    seats: 'Sec 105 · Row 2', rep: 'Aaron T.',
    history: [
      { when: 'Aug 19, 2026', what: 'Annual fund · football', amt: '$7,500' },
      { when: 'Aug 12, 2025', what: 'Annual fund · football', amt: '$7,500' },
    ],
    requests: [],
    thread: [],
  },
  {
    id: 'd5', name: 'Jim & Carol Pruitt', initials: 'JP', tier: 'Blue & Gold Fund',
    total: 8900, lastGift: '$500 · Jun 30', since: 2017,
    status: 'lapsed', openRequests: 0, email: 'jcpruitt@aol.com',
    seats: '—', rep: 'Unassigned',
    history: [
      { when: 'Jun 30, 2025', what: 'Annual fund', amt: '$500' },
    ],
    requests: [],
    thread: [],
  },
];

function DonorsWorkspace({ T, accent, fontMono, pendingTenant }) {
  const [selId, setSelId] = React.useState(null);
  const sel = ADMIN_DONORS.find(d => d.id === selId) || null;
  const [draft, setDraft] = React.useState('');
  const [sent, setSent] = React.useState({}); // { donorId: [msgs] }

  const totalRaised = ADMIN_DONORS.reduce((s, d) => s + d.total, 0);
  const openReqs = ADMIN_DONORS.reduce((s, d) => s + d.openRequests, 0);

  const statusChip = (s) => ({
    active:  { label: 'Active',  fg: '#1A8A4E', dot: '#22C55E' },
    lapsing: { label: 'Lapsing', fg: '#B45309', dot: '#F59E0B' },
    lapsed:  { label: 'Lapsed',  fg: T.textFaint, dot: T.textFaint },
  }[s] || { label: s, fg: T.textDim, dot: T.textFaint });

  const send = () => {
    if (!draft.trim() || !sel) return;
    setSent(prev => ({ ...prev, [sel.id]: [...(prev[sel.id] || []), { from: 'rep', body: draft.trim(), t: 'now' }] }));
    setDraft('');
  };

  return (
    <div style={{ padding: '20px 24px', display: 'flex', gap: 18, alignItems: 'flex-start' }}>
      {/* ── Left: table ── */}
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ marginBottom: 16 }}>
          <div style={{ fontSize: 19, fontWeight: 700, letterSpacing: '-0.015em' }}>Donors · {pendingTenant.short}</div>
          <div style={{ fontSize: 12.5, color: T.textDim, marginTop: 4 }}>
            {ADMIN_DONORS.length} donors · ${(totalRaised / 1000).toFixed(0)}K lifetime · {openReqs} open requests
          </div>
        </div>

        {/* header row */}
        <div style={{
          display: 'grid', gridTemplateColumns: '2fr 1.2fr 1fr 1.2fr 0.9fr', gap: 10,
          padding: '8px 14px', fontSize: 10.5, fontWeight: 700,
          color: T.textFaint, letterSpacing: '0.08em', textTransform: 'uppercase',
          fontFamily: fontMono,
        }}>
          <span>Donor</span><span>Tier</span><span>Lifetime</span><span>Last gift</span><span>Status</span>
        </div>

        {ADMIN_DONORS.map(d => {
          const on = d.id === selId;
          const sc = statusChip(d.status);
          return (
            <button key={d.id} onClick={() => setSelId(on ? null : d.id)} style={{
              display: 'grid', gridTemplateColumns: '2fr 1.2fr 1fr 1.2fr 0.9fr', gap: 10,
              alignItems: 'center', width: '100%', textAlign: 'left',
              padding: '12px 14px', marginBottom: 4,
              background: on ? (T.isDark ? 'rgba(255,255,255,0.06)' : 'rgba(15,17,21,0.05)') : 'transparent',
              border: `1px solid ${on ? T.border : 'transparent'}`,
              borderRadius: 9, cursor: 'pointer', color: T.text,
            }}>
              <span style={{ display: 'flex', alignItems: 'center', gap: 10, minWidth: 0 }}>
                <span style={{
                  width: 28, height: 28, borderRadius: 14, flexShrink: 0,
                  background: accent, color: '#fff',
                  display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                  fontSize: 10.5, fontWeight: 800,
                }}>{d.initials}</span>
                <span style={{ minWidth: 0 }}>
                  <span style={{ display: 'block', fontSize: 13, fontWeight: 600, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
                    {d.name}
                    {d.openRequests > 0 && (
                      <span style={{
                        marginLeft: 7, padding: '1px 6px', borderRadius: 8,
                        background: 'rgba(245,158,11,0.14)', color: '#B45309',
                        fontSize: 9.5, fontWeight: 800, fontFamily: fontMono,
                      }}>{d.openRequests}</span>
                    )}
                  </span>
                  <span style={{ display: 'block', fontSize: 10.5, color: T.textFaint, marginTop: 1 }}>Since {d.since} · {d.rep}</span>
                </span>
              </span>
              <span style={{ fontSize: 12, color: T.textDim }}>{d.tier}</span>
              <span style={{ fontSize: 12.5, fontWeight: 700, fontFamily: fontMono }}>${d.total.toLocaleString()}</span>
              <span style={{ fontSize: 12, color: T.textDim }}>{d.lastGift}</span>
              <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5, fontSize: 11.5, fontWeight: 600, color: sc.fg }}>
                <span style={{ width: 5, height: 5, borderRadius: 3, background: sc.dot }} />
                {sc.label}
              </span>
            </button>
          );
        })}
      </div>

      {/* ── Right: detail drawer ── */}
      <div style={{
        width: 340, flexShrink: 0,
        border: `1px solid ${T.border}`, borderRadius: 12,
        background: T.isDark ? 'rgba(255,255,255,0.02)' : '#fff',
        overflow: 'hidden',
      }}>
        {!sel ? (
          <div style={{ padding: '38px 22px', textAlign: 'center' }}>
            <div style={{ fontSize: 13, fontWeight: 600, color: T.textDim }}>Select a donor</div>
            <div style={{ fontSize: 11.5, color: T.textFaint, marginTop: 4, lineHeight: 1.4 }}>
              Giving history, open requests, and the message thread appear here.
            </div>
          </div>
        ) : (
          <div>
            {/* header */}
            <div style={{ padding: '16px 16px 12px', borderBottom: `1px solid ${T.borderSoft}` }}>
              <div style={{ fontSize: 15, fontWeight: 700 }}>{sel.name}</div>
              <div style={{ fontSize: 11, color: T.textFaint, marginTop: 2, fontFamily: fontMono }}>{sel.email}</div>
              <div style={{ display: 'flex', gap: 6, marginTop: 9, flexWrap: 'wrap' }}>
                {[sel.tier, sel.seats, `Rep · ${sel.rep}`].map((c, i) => (
                  <span key={i} style={{
                    padding: '3px 8px', borderRadius: 6, fontSize: 10.5, fontWeight: 600,
                    background: T.isDark ? 'rgba(255,255,255,0.06)' : 'rgba(15,17,21,0.05)',
                    color: T.textDim, border: `1px solid ${T.borderSoft}`,
                  }}>{c}</span>
                ))}
              </div>
            </div>

            {/* giving history */}
            <div style={{ padding: '12px 16px', borderBottom: `1px solid ${T.borderSoft}` }}>
              <div style={{ fontSize: 10.5, fontWeight: 700, color: T.textFaint, letterSpacing: '0.08em', textTransform: 'uppercase', fontFamily: fontMono, marginBottom: 8 }}>
                Giving · ${sel.total.toLocaleString()} lifetime
              </div>
              {sel.history.map((h, i) => (
                <div key={i} style={{ display: 'flex', justifyContent: 'space-between', gap: 10, padding: '5px 0', fontSize: 12 }}>
                  <span style={{ color: T.textDim, minWidth: 0, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{h.what}</span>
                  <span style={{ fontWeight: 700, fontFamily: fontMono, flexShrink: 0 }}>{h.amt}</span>
                </div>
              ))}
            </div>

            {/* open requests */}
            {sel.requests.length > 0 && (
              <div style={{ padding: '12px 16px', borderBottom: `1px solid ${T.borderSoft}` }}>
                <div style={{ fontSize: 10.5, fontWeight: 700, color: '#B45309', letterSpacing: '0.08em', textTransform: 'uppercase', fontFamily: fontMono, marginBottom: 8 }}>
                  Open requests
                </div>
                {sel.requests.map(r => (
                  <div key={r.id} style={{
                    padding: '9px 11px', borderRadius: 8,
                    background: 'rgba(245,158,11,0.08)', border: '1px solid rgba(245,158,11,0.25)',
                    fontSize: 12, color: T.text,
                  }}>
                    <div style={{ fontWeight: 600 }}>{r.what}</div>
                    <div style={{ fontSize: 10.5, color: T.textFaint, marginTop: 2 }}>{r.when} · concierge queue</div>
                  </div>
                ))}
              </div>
            )}

            {/* message thread */}
            <div style={{ padding: '12px 16px 14px' }}>
              <div style={{ fontSize: 10.5, fontWeight: 700, color: T.textFaint, letterSpacing: '0.08em', textTransform: 'uppercase', fontFamily: fontMono, marginBottom: 8 }}>
                Messages
              </div>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 6, maxHeight: 190, overflow: 'auto' }} className="op-noscrollbar">
                {[...sel.thread, ...(sent[sel.id] || [])].map((m, i) => (
                  <div key={i} style={{
                    alignSelf: m.from === 'rep' ? 'flex-end' : 'flex-start',
                    maxWidth: '88%',
                    padding: '7px 10px', borderRadius: 10,
                    background: m.from === 'rep' ? accent : (T.isDark ? 'rgba(255,255,255,0.07)' : 'rgba(15,17,21,0.06)'),
                    color: m.from === 'rep' ? '#fff' : T.text,
                    fontSize: 12, lineHeight: 1.4,
                  }}>
                    {m.body}
                    <div style={{ fontSize: 9, opacity: 0.6, marginTop: 3, fontFamily: fontMono }}>{m.t}</div>
                  </div>
                ))}
                {sel.thread.length === 0 && !(sent[sel.id] || []).length && (
                  <div style={{ fontSize: 11.5, color: T.textFaint }}>No messages yet.</div>
                )}
              </div>
              {/* compose */}
              <div style={{ display: 'flex', gap: 6, marginTop: 10 }}>
                <input
                  value={draft}
                  onChange={e => setDraft(e.target.value)}
                  onKeyDown={e => { if (e.key === 'Enter') send(); }}
                  placeholder={`Message ${sel.name.split(' ')[0]}…`}
                  style={{
                    flex: 1, minWidth: 0, padding: '8px 11px', borderRadius: 8,
                    background: T.isDark ? 'rgba(255,255,255,0.05)' : '#fff',
                    border: `1px solid ${T.border}`, outline: 'none',
                    color: T.text, fontSize: 12, fontFamily: 'inherit',
                  }}
                />
                <button onClick={send} style={{
                  padding: '8px 14px', borderRadius: 8, border: 'none', cursor: 'pointer',
                  background: accent, color: '#fff', fontSize: 11.5, fontWeight: 700,
                }}>Send</button>
              </div>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { DonorsWorkspace });
