// team-page.jsx — Team management (admins + referral partners)

function TeamPage({ theme }) {
  const [data, setData]       = React.useState(null);
  const [loading, setLoading] = React.useState(true);
  const [error, setError]     = React.useState('');
  const [sheet, setSheet]     = React.useState(null); // 'invite-admin' | 'invite-referral' | 'edit'
  const [activeMember, setActiveMember] = React.useState(null);
  const [tab, setTab]         = React.useState('admins'); // 'admins' | 'referrals'

  const load = React.useCallback(async () => {
    setLoading(true); setError('');
    try {
      const res = await api.admin.team();
      setData(res);
    } catch (e) {
      setError(e.message || 'Failed to load team.');
    } finally {
      setLoading(false);
    }
  }, []);

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

  const closeSheet = (changed) => {
    setSheet(null);
    setActiveMember(null);
    if (changed) load();
  };

  if (loading) return (
    <div style={{ flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center', flexDirection: 'column', gap: 14 }}>
      <div style={{
        width: 32, height: 32, borderRadius: 99,
        border: `2.5px solid ${theme.rule}`, borderTopColor: theme.surface,
        animation: 'spin 0.8s linear infinite',
      }}/>
      <div style={{ fontSize: 13, color: theme.inkMute }}>Loading team…</div>
    </div>
  );

  if (error) return (
    <div style={{ flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center', flexDirection: 'column', gap: 12 }}>
      <Icon name="info" size={28} color={theme.inkMute}/>
      <div style={{ fontSize: 13, color: theme.inkMute }}>{error}</div>
      <button onClick={load} style={{ fontSize: 13, color: theme.surface, fontWeight: 600 }}>Retry</button>
    </div>
  );

  const admins   = data?.admins   || [];
  const referrals = data?.referrals || [];
  const members  = tab === 'admins' ? admins : referrals;

  return (
    <div style={{ flex: 1, display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
      {/* Header */}
      <div style={{
        padding: '20px 28px 16px',
        background: theme.raised,
        borderBottom: `1px solid ${theme.rule}`,
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
      }}>
        <div>
          <div style={{ fontSize: 10, color: theme.inkMute, fontWeight: 600, letterSpacing: 1.6, textTransform: 'uppercase' }}>
            Team management
          </div>
          <h2 className="serif" style={{ fontSize: 24, fontWeight: 500, color: theme.ink, margin: '4px 0 0', letterSpacing: -0.3 }}>
            Your team
          </h2>
        </div>
        <div style={{ display: 'flex', gap: 8 }}>
          <button onClick={() => setSheet('invite-referral')} style={{
            padding: '8px 14px', borderRadius: 8,
            background: theme.raised, color: theme.ink,
            border: `1px solid ${theme.rule}`,
            fontSize: 12, fontWeight: 600,
            display: 'flex', alignItems: 'center', gap: 6,
          }}>
            <Icon name="plus" size={12} color={theme.ink} strokeWidth={2}/>
            Add referral partner
          </button>
          <button onClick={() => setSheet('invite-admin')} style={{
            padding: '8px 14px', borderRadius: 8,
            background: theme.surface, color: theme.onSurface,
            fontSize: 12, fontWeight: 600,
            display: 'flex', alignItems: 'center', gap: 6,
          }}>
            <Icon name="plus" size={12} color={theme.onSurface} strokeWidth={2}/>
            Invite team member
          </button>
        </div>
      </div>

      {/* Tab nav */}
      <div style={{
        padding: '0 28px',
        borderBottom: `1px solid ${theme.rule}`,
        background: theme.raised,
        display: 'flex', gap: 4,
      }}>
        {[
          { id: 'admins',   label: `Team members (${admins.length})` },
          { id: 'referrals',label: `Referral partners (${referrals.length})` },
        ].map(t => (
          <button key={t.id} onClick={() => setTab(t.id)} style={{
            padding: '12px 14px',
            fontSize: 13, fontWeight: 600,
            color: tab === t.id ? theme.surface : theme.inkDim,
            borderBottom: `2px solid ${tab === t.id ? theme.surface : 'transparent'}`,
            marginBottom: -1,
          }}>{t.label}</button>
        ))}
      </div>

      {/* Member list */}
      <div className="scroll" style={{ flex: 1, overflowY: 'auto', padding: '20px 28px 40px' }}>
        {members.length === 0 ? (
          <div style={{
            padding: '64px 40px', textAlign: 'center', color: theme.inkMute,
          }}>
            <div style={{
              width: 56, height: 56, borderRadius: 16, margin: '0 auto 14px',
              background: theme.canvas2, border: `1px solid ${theme.rule}`,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
            }}><Icon name="user" size={22} color={theme.inkDim}/></div>
            <div className="serif" style={{ fontSize: 18, color: theme.ink, fontWeight: 500 }}>
              {tab === 'admins' ? 'No team members yet' : 'No referral partners yet'}
            </div>
            <div style={{ fontSize: 13, color: theme.inkMute, marginTop: 6 }}>
              {tab === 'admins'
                ? 'Invite teammates to access the operations console.'
                : 'Add referral partners to give them read-only access to their clients.'}
            </div>
          </div>
        ) : (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
            {members.map(m => (
              <MemberCard
                key={m.id} member={m} theme={theme} tab={tab}
                onEdit={() => { setActiveMember(m); setSheet('edit'); }}
                onRefresh={load}
              />
            ))}
          </div>
        )}
      </div>

      {/* Sheets */}
      {sheet === 'invite-admin'    && <InviteAdminSheet    theme={theme} onClose={closeSheet}/>}
      {sheet === 'invite-referral' && <InviteReferralSheet theme={theme} onClose={closeSheet}/>}
      {sheet === 'edit' && activeMember && <EditMemberSheet theme={theme} member={activeMember} onClose={closeSheet}/>}
    </div>
  );
}

// ─── Member card ─────────────────────────────────────────────
function MemberCard({ member, theme, tab, onEdit, onRefresh }) {
  const [loading, setLoading] = React.useState(false);

  const statusColor = {
    active:   { dot: '#2F6A4F', bg: '#DBE7DC', fg: '#173C2C', label: 'Active' },
    invited:  { dot: '#9B6B2F', bg: '#EFDFC5', fg: '#4E3414', label: 'Invited' },
    disabled: { dot: '#9C9385', bg: '#EFE7D4', fg: '#6B6452', label: 'Disabled' },
  }[member.status] || { dot: '#9C9385', bg: '#EFE7D4', fg: '#6B6452', label: member.status };

  const toggleStatus = async () => {
    setLoading(true);
    try {
      if (member.status === 'disabled') {
        await api.admin.enableMember(member.id);
      } else {
        await api.admin.disableMember(member.id);
      }
      onRefresh();
    } catch (e) {
      alert(e.message || 'Action failed.');
    } finally {
      setLoading(false);
    }
  };

  const resendInvite = async () => {
    setLoading(true);
    try {
      await api.admin.resendInvite(member.id);
      alert(`Invitation resent to ${member.email}`);
    } catch (e) {
      alert(e.message || 'Failed to resend invite.');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div style={{
      background: theme.raised, border: `1px solid ${theme.rule}`,
      borderRadius: 12, padding: '16px 18px',
      display: 'flex', alignItems: 'center', gap: 16,
      opacity: member.status === 'disabled' ? 0.6 : 1,
    }}>
      {/* Avatar */}
      <div style={{
        width: 44, height: 44, borderRadius: 99, flexShrink: 0,
        background: `linear-gradient(135deg, ${theme.accent.solid}, ${theme.accent.ink})`,
        color: '#fff', fontSize: 14, fontWeight: 700,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        fontFamily: 'Newsreader, serif',
      }}>{member.initials}</div>

      {/* Info */}
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap' }}>
          <div style={{ fontSize: 14, fontWeight: 600, color: theme.ink }}>{member.name}</div>
          <span style={{
            fontSize: 10, fontWeight: 700, letterSpacing: 0.5,
            padding: '2px 7px', borderRadius: 99,
            background: statusColor.bg, color: statusColor.fg,
            display: 'flex', alignItems: 'center', gap: 4,
          }}>
            <span style={{ width: 5, height: 5, borderRadius: 99, background: statusColor.dot }}/>
            {statusColor.label.toUpperCase()}
          </span>
        </div>
        <div style={{ fontSize: 12, color: theme.inkMute, marginTop: 3 }}>
          {member.email}
          {member.phone ? ` · ${member.phone}` : ''}
        </div>
        <div style={{ fontSize: 11.5, color: theme.inkDim, marginTop: 3 }}>
          {tab === 'admins' ? (
            <>
              {member.role_title || 'Specialist'}
              {' · '}
              <span className="tnum">Caseload {member.caseload}/{member.capacity}</span>
              {member.rep_status === 'pto' && (
                <span style={{ marginLeft: 6, fontSize: 10, fontWeight: 700, color: '#7A2E11', background: '#F5DFC9', padding: '1px 5px', borderRadius: 99 }}>PTO</span>
              )}
            </>
          ) : (
            <>
              {member.source_name || '—'}
              {' · '}
              <span className="tnum">{member.clients_referred} clients referred</span>
            </>
          )}
        </div>
        {member.last_login_at && (
          <div style={{ fontSize: 11, color: theme.inkMute, marginTop: 3 }}>
            Last login: {new Date(member.last_login_at).toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' })}
          </div>
        )}
      </div>

      {/* Actions */}
      <div style={{ display: 'flex', gap: 6, flexShrink: 0 }}>
        {tab === 'referrals' && member.source_id && (
          <button onClick={() => {
            navigator.clipboard.writeText(`https://calculator.debtlift.co?ref=${member.source_id}`);
            alert('Referral link copied!');
          }} style={{
            padding: '7px 12px', borderRadius: 8,
            background: '#DBE7DC', color: '#173C2C',
            border: '1px solid #BBD6BC',
            fontSize: 11.5, fontWeight: 600,
          }}>
            Copy link
          </button>
        )}
        {member.status === 'invited' && (
          <button onClick={resendInvite} disabled={loading} style={{
            padding: '7px 12px', borderRadius: 8,
            background: theme.canvas2, color: theme.inkDim,
            border: `1px solid ${theme.rule}`,
            fontSize: 11.5, fontWeight: 600,
          }}>
            {loading ? '…' : 'Resend invite'}
          </button>
        )}
        <button onClick={onEdit} style={{
          padding: '7px 12px', borderRadius: 8,
          background: theme.canvas2, color: theme.inkDim,
          border: `1px solid ${theme.rule}`,
          fontSize: 11.5, fontWeight: 600,
          display: 'flex', alignItems: 'center', gap: 5,
        }}>
          <Icon name="gear" size={12} color={theme.inkDim}/>
          Edit
        </button>
        <button onClick={toggleStatus} disabled={loading} style={{
          padding: '7px 12px', borderRadius: 8,
          background: member.status === 'disabled' ? '#DBE7DC' : '#FEF2F2',
          color: member.status === 'disabled' ? '#173C2C' : '#DC2626',
          border: `1px solid ${member.status === 'disabled' ? '#BBD6BC' : '#FECACA'}`,
          fontSize: 11.5, fontWeight: 600,
        }}>
          {loading ? '…' : member.status === 'disabled' ? 'Enable' : 'Disable'}
        </button>
      </div>
    </div>
  );
}

// ─── Invite admin sheet ───────────────────────────────────────
function InviteAdminSheet({ theme, onClose }) {
  const [name, setName]         = React.useState('');
  const [email, setEmail]       = React.useState('');
  const [phone, setPhone]       = React.useState('');
  const [title, setTitle]       = React.useState('');
  const [capacity, setCapacity] = React.useState('45');
  const [loading, setLoading]   = React.useState(false);
  const [error, setError]       = React.useState('');

  const submit = async () => {
    if (!name.trim() || !email.trim()) { setError('Name and email are required.'); return; }
    setLoading(true); setError('');
    try {
      await api.admin.inviteAdmin({
        name: name.trim(),
        email: email.trim(),
        phone: phone.trim() || null,
        role_title: title.trim() || 'Specialist',
        capacity: parseInt(capacity) || 45,
      });
      onClose(true);
    } catch (e) {
      setError(e.message || 'Failed to send invite.');
    } finally {
      setLoading(false);
    }
  };

  return (
    <SheetShell theme={theme} title="Invite team member" subtitle="Admin access" onClose={() => onClose(false)}
      footer={<>
        <button onClick={() => onClose(false)} style={teamBtn(theme, 'ghost')}>Cancel</button>
        <button onClick={submit} disabled={loading} style={teamBtn(theme, 'primary')}>{loading ? 'Sending…' : 'Send invitation'}</button>
      </>}
    >
      {error && <div style={{ marginBottom: 14, padding: '10px 14px', background: '#FEF2F2', border: '1px solid #FECACA', borderRadius: 8, fontSize: 13, color: '#DC2626' }}>{error}</div>}

      <div style={{
        padding: '12px 14px', borderRadius: 10, marginBottom: 18,
        background: '#EAF1FB', border: '1px solid #BDD0F0',
        fontSize: 12.5, color: '#1F4A8B', lineHeight: 1.5,
      }}>
        An invitation email will be sent with a one-time activation code. They'll set their own password on first login.
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
        <Field label="Full name">
          <TextInput theme={theme} value={name} onChange={setName} placeholder="First Last"/>
        </Field>
        <Field label="Email">
          <TextInput theme={theme} value={email} onChange={setEmail} placeholder="name@debtlift.co"/>
        </Field>
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
        <Field label="Phone (optional)">
          <TextInput theme={theme} value={phone} onChange={setPhone} placeholder="+1 (555) 555-0100" mono/>
        </Field>
        <Field label="Role title">
          <TextInput theme={theme} value={title} onChange={setTitle} placeholder="Negotiator"/>
        </Field>
      </div>
      <Field label="Caseload capacity" hint="Maximum number of active clients.">
        <TextInput theme={theme} value={capacity} onChange={setCapacity} placeholder="45" mono/>
      </Field>
    </SheetShell>
  );
}

// ─── Invite referral sheet ────────────────────────────────────
function InviteReferralSheet({ theme, onClose }) {
  const [name, setName]         = React.useState('');
  const [email, setEmail]       = React.useState('');
  const [phone, setPhone]       = React.useState('');
  const [sourceName, setSource] = React.useState('');
  const [loading, setLoading]   = React.useState(false);
  const [error, setError]       = React.useState('');

  const submit = async () => {
    if (!name.trim() || !email.trim() || !sourceName.trim()) {
      setError('Name, email, and company name are required.');
      return;
    }
    setLoading(true); setError('');
    try {
      await api.admin.inviteReferral({
        name: name.trim(),
        email: email.trim(),
        phone: phone.trim() || null,
        source_name: sourceName.trim(),
      });
      onClose(true);
    } catch (e) {
      setError(e.message || 'Failed to send invite.');
    } finally {
      setLoading(false);
    }
  };

  return (
    <SheetShell theme={theme} title="Add referral partner" subtitle="Read-only access" onClose={() => onClose(false)}
      footer={<>
        <button onClick={() => onClose(false)} style={teamBtn(theme, 'ghost')}>Cancel</button>
        <button onClick={submit} disabled={loading} style={teamBtn(theme, 'primary')}>{loading ? 'Sending…' : 'Send invitation'}</button>
      </>}
    >
      {error && <div style={{ marginBottom: 14, padding: '10px 14px', background: '#FEF2F2', border: '1px solid #FECACA', borderRadius: 8, fontSize: 13, color: '#DC2626' }}>{error}</div>}

      <div style={{
        padding: '12px 14px', borderRadius: 10, marginBottom: 18,
        background: '#FAF6EC', border: '1px solid #E2C77B',
        fontSize: 12.5, color: '#7A5A1B', lineHeight: 1.5,
      }}>
        Referral partners get read-only access to clients they referred. Internal notes and write actions are hidden.
      </div>

      <Field label="Company / source name" hint="How this referral source appears in client records.">
        <TextInput theme={theme} value={sourceName} onChange={setSource} placeholder="Atlas Brokers"/>
      </Field>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
        <Field label="Contact name">
          <TextInput theme={theme} value={name} onChange={setName} placeholder="First Last"/>
        </Field>
        <Field label="Email">
          <TextInput theme={theme} value={email} onChange={setEmail} placeholder="partner@company.com"/>
        </Field>
      </div>
      <Field label="Phone (optional)">
        <TextInput theme={theme} value={phone} onChange={setPhone} placeholder="+1 (555) 555-0100" mono/>
      </Field>
    </SheetShell>
  );
}

// ─── Edit member sheet ────────────────────────────────────────
function EditMemberSheet({ theme, member, onClose }) {
  const [name, setName]         = React.useState(member.name);
  const [phone, setPhone]       = React.useState(member.phone || '');
  const [title, setTitle]       = React.useState(member.role_title || '');
  const [capacity, setCapacity] = React.useState(String(member.capacity || 45));
  const [repStatus, setRepStatus] = React.useState(member.rep_status || 'available');
  const [sourceName, setSource] = React.useState(member.source_name || '');
  const [loading, setLoading]   = React.useState(false);
  const [error, setError]       = React.useState('');

  const submit = async () => {
    setLoading(true); setError('');
    try {
      const body = { name: name.trim(), phone: phone.trim() || null };
      if (member.role === 'admin') {
        body.role_title  = title.trim() || 'Specialist';
        body.capacity    = parseInt(capacity) || 45;
        body.rep_status  = repStatus;
      }
      if (member.role === 'referral') {
        body.source_name = sourceName.trim();
      }
      await api.admin.updateMember(member.id, body);
      onClose(true);
    } catch (e) {
      setError(e.message || 'Failed to update.');
    } finally {
      setLoading(false);
    }
  };

  return (
    <SheetShell theme={theme} title="Edit team member" subtitle={member.email} onClose={() => onClose(false)}
      footer={<>
        <button onClick={() => onClose(false)} style={teamBtn(theme, 'ghost')}>Cancel</button>
        <button onClick={submit} disabled={loading} style={teamBtn(theme, 'primary')}>{loading ? 'Saving…' : 'Save changes'}</button>
      </>}
    >
      {error && <div style={{ marginBottom: 14, padding: '10px 14px', background: '#FEF2F2', border: '1px solid #FECACA', borderRadius: 8, fontSize: 13, color: '#DC2626' }}>{error}</div>}

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
        <Field label="Full name">
          <TextInput theme={theme} value={name} onChange={setName} placeholder="First Last"/>
        </Field>
        <Field label="Phone">
          <TextInput theme={theme} value={phone} onChange={setPhone} placeholder="+1 (555) 555-0100" mono/>
        </Field>
      </div>

      {member.role === 'admin' && <>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 100px', gap: 12 }}>
          <Field label="Role title">
            <TextInput theme={theme} value={title} onChange={setTitle} placeholder="Negotiator"/>
          </Field>
          <Field label="Capacity">
            <TextInput theme={theme} value={capacity} onChange={setCapacity} placeholder="45" mono/>
          </Field>
        </div>
        <Field label="Status">
          <Select theme={theme} value={repStatus} onChange={setRepStatus} options={[
            { value: 'available', label: 'Available' },
            { value: 'pto',       label: 'PTO' },
            { value: 'inactive',  label: 'Inactive' },
          ]}/>
        </Field>
      </>}

      {member.role === 'referral' && (
        <Field label="Company / source name">
          <TextInput theme={theme} value={sourceName} onChange={setSource} placeholder="Atlas Brokers"/>
        </Field>
      )}
    </SheetShell>
  );
}

function teamBtn(theme, kind) {
  if (kind === 'primary') return {
    padding: '10px 18px', borderRadius: 9,
    background: theme.surface, color: theme.onSurface,
    fontSize: 13, fontWeight: 600,
  };
  return {
    padding: '10px 18px', borderRadius: 9,
    background: 'transparent', color: theme.inkDim,
    fontSize: 13, fontWeight: 500,
  };
}

Object.assign(window, { TeamPage });
