// screens-provider.jsx — Psychologist dashboard + Admin verification

// ===========================================================
//  PENDING APPROVAL — must be defined BEFORE ProviderScreen
// ===========================================================
function PendingApprovalScreen({ authUser, onRefresh }) {
  const { t } = useLang();
  const [checking, setChecking] = useState(false);
  const [checked, setChecked] = useState(false);

  async function checkStatus() {
    setChecking(true);
    try {
      const raw = localStorage.getItem('psyche-auth');
      const token = raw ? JSON.parse(raw).token : null;
      const r = await fetch('/api/auth/me', { headers: { Authorization: 'Bearer ' + token } });
      const data = await r.json();
      if (data.user && data.user.approved) {
        if (onRefresh) onRefresh();
      } else {
        setChecked(true);
      }
    } catch (e) {}
    setChecking(false);
  }

  return (
    <div className="page narrow" style={{ paddingTop: 60 }}>
      <div className="card" style={{ padding: '48px 52px', textAlign: 'center' }}>
        <div style={{ width: 72, height: 72, borderRadius: 20, background: 'var(--psy-accent-soft)', display: 'grid', placeItems: 'center', margin: '0 auto 24px' }}>
          <Icon name="pending" style={{ fontSize: 36, color: 'var(--psy-accent)' }} />
        </div>
        <h1 className="display" style={{ fontSize: 32, fontWeight: 600, marginBottom: 12 }}>
          {t('pending_h1')}
        </h1>
        <p style={{ color: 'var(--fg2)', fontSize: 16, lineHeight: 1.6, maxWidth: 480, margin: '0 auto 32px' }}>
          {t('pending_body')} <strong style={{ color: 'var(--psy-ink)' }}>{authUser ? authUser.email : ''}</strong> {t('pending_body2')}
        </p>

        <button className="btn primary" onClick={checkStatus} disabled={checking} style={{ marginBottom: 12 }}>
          {checking ? t('pending_checking') : t('pending_check_btn')}
        </button>

        {checked && (
          <p style={{ color: 'var(--fg2)', fontSize: 14, marginTop: 8 }}>
            {t('pending_still')}
          </p>
        )}

        <div style={{ marginTop: 40, padding: 20, background: 'var(--psy-surface)', borderRadius: 16, textAlign: 'left' }}>
          <h3 style={{ fontFamily: 'var(--font-display)', fontSize: 16, fontWeight: 600, margin: '0 0 12px' }}>{t('pending_next_h')}</h3>
          {[
            { icon: 'verified_user', text: t('pending_step1') },
            { icon: 'mark_email_read', text: t('pending_step2') },
            { icon: 'public', text: t('pending_step3') },
          ].map(function(s, i) {
            return (
              <div key={i} style={{ display: 'flex', gap: 12, alignItems: 'flex-start', padding: '8px 0', borderTop: i > 0 ? '1px solid var(--psy-rule)' : 'none' }}>
                <Icon name={s.icon} style={{ color: 'var(--psy-leaf)', flexShrink: 0, marginTop: 2 }} />
                <span style={{ fontSize: 14, color: 'var(--psy-ink)', lineHeight: 1.5 }}>{s.text}</span>
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
}

// ===========================================================
//  CLIENT PROFILE MODAL
// ===========================================================
function ClientProfileModal({ client, psyId, onClose }) {
  // client = { user_id, user_name, user_email, bookings: [] }
  const { lang } = useLang();
  const el = lang === 'el';
  const [journal, setJournal] = useState(null);
  const [loading, setLoading] = useState(true);
  const [emergency, setEmergency] = useState(null); // null=loading, {shared,contacts}

  useEffect(() => {
    if (!client?.user_id) return;
    const token = JSON.parse(localStorage.getItem('psyche-auth') || '{}').token || '';
    const hdrs = { Authorization: 'Bearer ' + token };
    fetch('/api/clients/' + client.user_id + '/journal', { headers: hdrs })
      .then(r => r.json())
      .then(d => setJournal(Array.isArray(d) ? d : []))
      .catch(() => setJournal([]))
      .finally(() => setLoading(false));
    fetch('/api/clients/' + client.user_id + '/emergency', { headers: hdrs })
      .then(r => r.ok ? r.json() : null)
      .then(d => setEmergency(d || { shared: false, contacts: [] }))
      .catch(() => setEmergency({ shared: false, contacts: [] }));
  }, [client?.user_id]);

  const MOODS = ['', el ? 'Δύσκολα' : 'Tough', el ? 'Βαριά' : 'Heavy', el ? 'Εντάξει' : 'Okay', el ? 'Καλά' : 'Good', el ? 'Φωτεινά' : 'Bright'];
  const MOOD_COLORS = ['', '#EF4444', '#F97316', '#EAB308', '#22C55E', '#10B981'];
  const MOOD_ICONS = ['', '😞', '😔', '😐', '🙂', '😊'];

  function fmtDate(d) {
    return new Date(d + 'T12:00:00').toLocaleDateString(el ? 'el-GR' : 'en-GB', { day: 'numeric', month: 'short', year: 'numeric' });
  }

  const initials = (client.user_name || '?').split(' ').map(w => w[0]).slice(0, 2).join('').toUpperCase();

  return (
    <div style={{
      position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.4)', zIndex: 100,
      display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 20,
    }} onClick={e => e.target === e.currentTarget && onClose()}>
      <div style={{
        background: 'white', borderRadius: 20, width: '100%', maxWidth: 560,
        maxHeight: '85vh', display: 'flex', flexDirection: 'column',
        boxShadow: 'var(--elev-4)',
      }}>
        {/* Header */}
        <div style={{ padding: '24px 28px 20px', borderBottom: '1px solid var(--psy-rule)', display: 'flex', gap: 16, alignItems: 'center' }}>
          <div style={{
            width: 52, height: 52, borderRadius: '50%', flexShrink: 0,
            background: 'linear-gradient(135deg, #d6dcf3, #2581eb)',
            display: 'grid', placeItems: 'center',
            fontWeight: 700, fontSize: 18, color: 'white',
          }}>{initials}</div>
          <div style={{ flex: 1 }}>
            <div style={{ fontWeight: 700, fontSize: 18, color: 'var(--psy-ink)' }}>{client.user_name}</div>
            <div style={{ fontSize: 13, color: 'var(--fg2)', marginTop: 2, display: 'flex', gap: 12, flexWrap: 'wrap', alignItems: 'center' }}>
              <span>{client.bookings?.length || 0} {el ? 'συνεδρίες' : 'sessions'}</span>
              {emergency?.phone && (
                <a href={'tel:' + emergency.phone} style={{ color: 'var(--psy-accent)', fontWeight: 600, textDecoration: 'none' }}>
                  <Icon name="call" style={{ fontSize: 13, verticalAlign: -2, marginRight: 3 }} />{emergency.phone}
                </a>
              )}
            </div>
          </div>
          <button className="btn ghost sm" onClick={onClose} style={{ padding: '6px 10px' }}>
            <Icon name="close" className="sm" />
          </button>
        </div>

        {/* Sessions summary */}
        {client.bookings?.length > 0 && (
          <div style={{ padding: '16px 28px', borderBottom: '1px solid var(--psy-rule)', display: 'flex', gap: 12, flexWrap: 'wrap' }}>
            {client.bookings.map((b, i) => (
              <span key={i} style={{
                fontSize: 12, padding: '4px 10px', borderRadius: 99,
                background: b.status === 'confirmed' ? 'var(--psy-accent-soft)' : 'var(--psy-surface)',
                color: b.status === 'confirmed' ? 'var(--psy-accent)' : 'var(--fg2)',
                fontWeight: 500,
              }}>
                {b.date} · {b.time} · {b.mode === 'online' ? (el ? 'Online' : 'Online') : (el ? 'Δια ζώσης' : 'In-person')}
              </span>
            ))}
          </div>
        )}

        {/* Emergency contacts */}
        {emergency && emergency.shared && emergency.contacts.length > 0 && (
          <div style={{ padding: '16px 28px', borderBottom: '1px solid var(--psy-rule)' }}>
            <div style={{ fontWeight: 700, fontSize: 14, marginBottom: 10, color: '#DC2626', display: 'flex', alignItems: 'center', gap: 6 }}>
              <Icon name="emergency" style={{ fontSize: 18 }} />
              {el ? 'Επαφές Έκτακτης Ανάγκης' : 'Emergency Contacts'}
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
              {emergency.contacts.map((c, i) => (
                <div key={i} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '8px 14px', background: '#FEF2F2', borderRadius: 10, border: '1px solid #FECACA' }}>
                  <span style={{ fontSize: 13, fontWeight: 600, color: 'var(--psy-ink)' }}>{c.name || '—'}</span>
                  <a href={'tel:' + c.phone} style={{ fontSize: 13, color: '#DC2626', fontWeight: 600, textDecoration: 'none' }}>{c.phone}</a>
                </div>
              ))}
            </div>
          </div>
        )}

        {/* Journal */}
        <div style={{ flex: 1, overflowY: 'auto', padding: '20px 28px' }}>
          <div style={{ fontWeight: 700, fontSize: 15, marginBottom: 14, color: 'var(--psy-ink)' }}>
            <Icon name="auto_stories" style={{ verticalAlign: -4, marginRight: 6, color: 'var(--psy-accent)' }} />
            {el ? 'Κοινό Ημερολόγιο Διάθεσης' : 'Shared Mood Journal'}
          </div>
          {loading ? (
            <p style={{ color: 'var(--fg3)', fontSize: 14 }}>{el ? 'Φόρτωση...' : 'Loading...'}</p>
          ) : journal?.length === 0 ? (
            <div style={{ textAlign: 'center', padding: '32px 0', color: 'var(--fg3)' }}>
              <Icon name="auto_stories" style={{ fontSize: 36, display: 'block', margin: '0 auto 10px', opacity: 0.3 }} />
              <p style={{ fontSize: 14, margin: 0 }}>
                {el ? 'Ο χρήστης δεν έχει μοιραστεί κάποια εγγραφή ακόμα.' : 'No shared journal entries yet.'}
              </p>
            </div>
          ) : (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
              {journal.map((e, i) => (
                <div key={i} style={{
                  display: 'flex', gap: 14, padding: '12px 16px',
                  background: 'var(--psy-surface)', borderRadius: 12,
                  borderLeft: '3px solid ' + (MOOD_COLORS[e.mood] || '#ccc'),
                }}>
                  <div style={{ fontSize: 22, flexShrink: 0 }}>{MOOD_ICONS[e.mood] || '•'}</div>
                  <div style={{ flex: 1 }}>
                    <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 4 }}>
                      <span style={{ fontWeight: 600, fontSize: 13, color: MOOD_COLORS[e.mood] }}>
                        {MOODS[e.mood] || e.mood}
                      </span>
                      <span style={{ fontSize: 12, color: 'var(--fg3)' }}>{fmtDate(e.date)}</span>
                    </div>
                    {e.note && <p style={{ fontSize: 13, color: 'var(--fg2)', margin: 0, lineHeight: 1.5 }}>{e.note}</p>}
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

// ===========================================================
//  PROVIDER DASHBOARD (the psychologist-side view)
// ===========================================================
// ── Decline modal ────────────────────────────────────────────
function DeclineModal({ booking, onDecline, onClose }) {
  const [reason, setReason] = React.useState('');
  const [altTime, setAltTime] = React.useState('');
  const [loading, setLoading] = React.useState(false);

  async function submit() {
    setLoading(true);
    await onDecline(booking.id, reason, altTime);
    setLoading(false);
    onClose();
  }

  return (
    <div onClick={onClose} style={{ position: 'fixed', inset: 0, zIndex: 50, background: 'rgba(15,21,37,0.5)', backdropFilter: 'blur(4px)', display: 'grid', placeItems: 'center', padding: 16 }}>
      <div onClick={function(e) { e.stopPropagation(); }} style={{ background: 'white', borderRadius: 20, padding: '32px 36px', maxWidth: 440, width: '100%', boxShadow: '0 20px 60px rgba(15,21,37,0.2)' }}>
        <h3 className="display" style={{ fontSize: 20, fontWeight: 600, marginBottom: 6 }}>Decline this request</h3>
        <p style={{ color: 'var(--fg2)', fontSize: 14, marginBottom: 20 }}>
          <strong>{booking.user_name || 'Client'}</strong> requested <strong>{booking.date} at {booking.time}</strong> ({booking.mode}).
        </p>

        <div className="field-label">Reason (optional — shown to the client)</div>
        <textarea className="textarea" style={{ minHeight: 80, marginTop: 6 }}
          placeholder="e.g. I am fully booked on that day."
          value={reason} onChange={function(e) { setReason(e.target.value); }} />

        <div className="field-label" style={{ marginTop: 14 }}>Suggest an alternative time (optional)</div>
        <input className="input" style={{ marginTop: 6 }}
          placeholder="e.g. Thursday 5 Jun at 11:00 online"
          value={altTime} onChange={function(e) { setAltTime(e.target.value); }} />

        <div style={{ display: 'flex', gap: 10, marginTop: 22, justifyContent: 'flex-end' }}>
          <button className="btn ghost" onClick={onClose}>Cancel</button>
          <button className="btn primary" onClick={submit} disabled={loading}
            style={{ background: 'var(--color-error)', borderColor: 'var(--color-error)' }}>
            {loading ? 'Declining...' : 'Decline request'}
          </button>
        </div>
      </div>
    </div>
  );
}

// ── Provider dashboard ────────────────────────────────────────
function ProviderScreen({ setRoute, openEditProfile, authUser, onRefresh }) {
  const { t, lang } = useLang();
  const el = lang === 'el';
  // Unapproved psychologist — show waiting screen (skip for admin)
  if (authUser && authUser.approved === false && authUser.role !== 'admin') {
    return <PendingApprovalScreen authUser={authUser} onRefresh={onRefresh} />;
  }

  // Load own profile from API
  const [ownProfile, setOwnProfile] = React.useState(null);
  React.useEffect(function() {
    API.getMyProfile().then(function(p) { if (p) setOwnProfile(p); }).catch(function() {});
  }, []);

  const firstName = authUser ? authUser.name.split(' ')[0] : 'Your';

  // Real incoming booking requests
  const [bookings, setBookings] = React.useState([]);
  const [upcomingSessions, setUpcomingSessions] = React.useState([]);
  const [declineTarget, setDeclineTarget] = React.useState(null);
  const [clientModal, setClientModal] = React.useState(null); // { user_id, user_name, bookings[] }

  function getToken() {
    try { return JSON.parse(localStorage.getItem('psyche-auth') || '{}').token; } catch { return null; }
  }
  function authHdrs() {
    return { 'Content-Type': 'application/json', Authorization: 'Bearer ' + getToken() };
  }

  React.useEffect(function() {
    fetch('/api/bookings/incoming', { headers: authHdrs() })
      .then(function(r) { return r.json(); })
      .then(function(d) { if (Array.isArray(d)) setBookings(d); })
      .catch(function() {});
    fetch('/api/bookings/upcoming', { headers: authHdrs() })
      .then(function(r) { return r.json(); })
      .then(function(d) { if (Array.isArray(d)) setUpcomingSessions(d); })
      .catch(function() {});
  }, []);

  async function acceptBooking(id) {
    await fetch('/api/bookings/' + id + '/accept', { method: 'POST', headers: authHdrs() });
    setBookings(function(prev) { return prev.filter(function(b) { return b.id !== id; }); });
  }

  async function declineBooking(id, reason, altTime) {
    await fetch('/api/bookings/' + id + '/decline', {
      method: 'POST', headers: authHdrs(),
      body: JSON.stringify({ reason: reason, alt_time: altTime }),
    });
    setBookings(function(prev) { return prev.filter(function(b) { return b.id !== id; }); });
  }

  return (
    <div className="page wide">
      {declineTarget && (
        <DeclineModal
          booking={declineTarget}
          onDecline={declineBooking}
          onClose={function() { setDeclineTarget(null); }}
        />
      )}
      {clientModal && (
        <ClientProfileModal
          client={clientModal}
          onClose={() => setClientModal(null)}
        />
      )}

      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 24 }}>
        <div>
          <span className="eyebrow muted">{t('provider_eyebrow')}</span>
          <h1 className="display" style={{ fontSize: 36, marginTop: 6 }}>{t('provider_good_morning')} {firstName}.</h1>
          <p style={{ color: 'var(--fg2)', marginTop: 6, fontSize: 15 }}>
            {bookings.length > 0
              ? <><strong style={{ color: 'var(--psy-accent)' }}>{bookings.length} {bookings.length !== 1 ? t('provider_requests_pl') : t('provider_requests')}</strong> {t('provider_waiting')}</>
              : t('provider_no_pending')}
          </p>
        </div>
        <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap' }}>
          <button className="btn ghost" onClick={function() { openEditProfile && openEditProfile(ownProfile ? ownProfile.id : null); }}><Icon name="edit" className="sm" /> {t('provider_edit_profile')}</button>
          <button className="btn ghost" onClick={() => ownProfile && setRoute('book', ownProfile.id)} disabled={!ownProfile} title="See exactly what clients see when they book with you">
            <Icon name="preview" className="sm" /> {el ? 'Προεπισκόπηση κράτησης' : 'Preview booking page'}
          </button>
          <button className="btn primary" onClick={() => setRoute('availability')}><Icon name="event_available" className="sm" /> {t('provider_update_avail')}</button>
        </div>
      </div>

      {/* Stats */}
      <div className="dash">
        <div className="stat">
          <span className="num">{upcomingSessions.length || 0}</span>
          <div className="label">{t('provider_stat_views')}</div>
          <div className="delta" style={{ color: 'var(--fg3)' }}>{el ? 'Επιβεβαιωμένες επερχόμενες συνεδρίες' : 'Confirmed upcoming sessions'}</div>
        </div>
        <div className="stat">
          <span className="num">{ownProfile ? ownProfile.rating || '—' : '—'}</span>
          <div className="label">{t('provider_stat_rating')} · {ownProfile ? (ownProfile.reviewCount || 0) : 0} {t('provider_stat_reviews')}</div>
          <div className="delta">{t('provider_verified_only')}</div>
        </div>
        <div className="stat" style={{ cursor: bookings.length > 0 ? 'pointer' : 'default' }}
          onClick={() => bookings.length > 0 && document.getElementById('booking-requests')?.scrollIntoView({ behavior: 'smooth', block: 'start' })}>
          <span className="num" style={{ color: bookings.length > 0 ? 'var(--psy-accent)' : undefined }}>{bookings.length}</span>
          <div className="label">{el ? 'Αιτήματα κράτησης' : 'Pending requests'}</div>
          <div className="delta" style={{ color: 'var(--fg3)' }}>{el ? 'Αναμένουν την απάντησή σας' : 'Awaiting your response'}</div>
        </div>
      </div>

      {/* Upgrade banner */}
      <div style={{
        display: 'flex', alignItems: 'center', justifyContent: 'space-between', flexWrap: 'wrap', gap: 12,
        background: 'var(--psy-accent-soft)', border: '1.5px solid var(--psy-accent)',
        borderRadius: 16, padding: '14px 20px', marginTop: 24,
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
          <Icon name="stars" style={{ color: 'var(--psy-accent)', fontSize: 22 }} />
          <div>
            <span style={{ fontWeight: 700, fontSize: 14, color: 'var(--psy-accent)' }}>
              {t('nav_for_psychologists') || 'Professional & Premium plans — Coming soon'}
            </span>
            <span style={{ fontSize: 13, color: 'var(--fg2)', marginLeft: 8 }}>
              · {t('provider_upgrade_sub')}
            </span>
          </div>
        </div>
        <button className="btn accent sm" onClick={() => setRoute('pricing')}>
          {t('provider_see_plans')}
          <Icon name="arrow_forward" className="sm" style={{ marginLeft: 4 }} />
        </button>
      </div>

      {/* Booking requests + Today's schedule */}
      <div style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: 24, marginTop: 32 }}>
        <div id="booking-requests" className="card" style={{ padding: 0 }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', padding: '18px 22px 14px', borderBottom: '1px solid var(--psy-rule)' }}>
            <h3 className="display" style={{ fontSize: 20, fontWeight: 600 }}>{t('provider_booking_req')}</h3>
            <span style={{ fontSize: 12, color: 'var(--fg2)' }}>{bookings.length} {t('provider_pending')}</span>
          </div>

          {bookings.length === 0 && (
            <div style={{ padding: '28px 22px', textAlign: 'center', color: 'var(--fg3)', fontSize: 14 }}>
              <Icon name="event_available" style={{ fontSize: 28, display: 'block', margin: '0 auto 10px' }} />
              {t('provider_no_requests')}
            </div>
          )}

          {bookings.map(function(b) {
            var dateStr = b.date ? new Date(b.date).toLocaleDateString(el ? 'el-GR' : 'en-GB', { weekday: 'short', day: 'numeric', month: 'short' }) : b.date;
            var initials = (b.user_name || 'U').split(' ').map(function(w) { return w[0]; }).join('').slice(0, 2).toUpperCase();
            return (
              <div key={b.id} style={{ padding: '14px 22px', borderTop: '1px solid var(--psy-rule)' }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 10 }}>
                  <div className="avatar-sm" style={{ background: avatarBg('c'), cursor: 'pointer' }} onClick={() => setClientModal({ user_id: b.user_id, user_name: b.user_name, bookings: [b] })}>{initials}</div>
                  <div style={{ flex: 1 }}>
                    <div style={{ fontWeight: 600, fontSize: 14, cursor: 'pointer', textDecoration: 'underline dotted' }} onClick={() => setClientModal({ user_id: b.user_id, user_name: b.user_name, bookings: [b] })}>{b.user_name || 'Client'}</div>
                    <div style={{ fontSize: 12, color: 'var(--fg2)', marginTop: 2 }}>
                      <Icon name={b.mode === 'online' ? 'videocam' : 'meeting_room'} className="sm" style={{ verticalAlign: -3 }} />
                      {' '}{dateStr} {el ? 'στις' : 'at'} {b.time} &middot; {b.mode === 'online' ? t('lbl_online') : t('lbl_inperson')}
                    </div>
                  </div>
                  <span className="tag accent" style={{ fontSize: 10, padding: '2px 8px' }}>{el ? 'ΝΕΟ' : 'NEW'}</span>
                </div>
                <div style={{ display: 'flex', gap: 8 }}>
                  <button className="btn primary sm" style={{ flex: 1 }}
                    onClick={function() { acceptBooking(b.id); }}>
                    <Icon name="check" className="sm" /> {t('provider_accept')}
                  </button>
                  <button className="btn ghost sm" style={{ flex: 1, color: 'var(--color-error)' }}
                    onClick={function() { setDeclineTarget(b); }}>
                    <Icon name="close" className="sm" /> {t('provider_decline')}
                  </button>
                  <button className="btn ghost sm" onClick={function() { setRoute('chat'); }}>
                    <Icon name="chat_bubble_outline" className="sm" />
                  </button>
                </div>
              </div>
            );
          })}
        </div>

        <div className="card" style={{ padding: 0 }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', padding: '18px 22px 14px', borderBottom: '1px solid var(--psy-rule)' }}>
            <h3 className="display" style={{ fontSize: 20, fontWeight: 600 }}>{el ? 'Επόμενες συνεδρίες' : 'Upcoming sessions'}</h3>
            <span style={{ fontSize: 12, color: 'var(--fg2)' }}>{upcomingSessions.length} {t('provider_sessions')}</span>
          </div>

          {upcomingSessions.length === 0 && (
            <div style={{ padding: '28px 22px', textAlign: 'center', color: 'var(--fg3)', fontSize: 14 }}>
              <Icon name="event_note" style={{ fontSize: 28, display: 'block', margin: '0 auto 10px' }} />
              {el ? 'Δεν υπάρχουν επερχόμενες συνεδρίες' : 'No upcoming sessions yet'}
            </div>
          )}

          {upcomingSessions.map(function(b, i) {
            var today = new Date().toISOString().slice(0, 10);
            var tomorrow = new Date(Date.now() + 86400000).toISOString().slice(0, 10);
            var locale = el ? 'el-GR' : 'en-GB';
            var dayLabel = b.date === today
              ? (el ? 'Σήμερα' : 'Today')
              : b.date === tomorrow
                ? (el ? 'Αύριο' : 'Tomorrow')
                : new Date(b.date).toLocaleDateString(locale, { weekday: 'short', day: 'numeric', month: 'short' });
            var initials = (b.user_name || 'C').split(' ').map(function(w) { return w[0]; }).join('').slice(0, 2).toUpperCase();
            return (
              <div key={b.id} style={{ padding: '14px 22px', borderTop: i ? '1px solid var(--psy-rule)' : 0 }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                    <div className="avatar-sm" style={{ background: avatarBg('c'), fontSize: 11, cursor: 'pointer' }} onClick={() => setClientModal({ user_id: b.user_id, user_name: b.user_name, bookings: upcomingSessions.filter(s => s.user_id === b.user_id) })}>{initials}</div>
                    <strong style={{ fontSize: 14, cursor: 'pointer', textDecoration: 'underline dotted' }} onClick={() => setClientModal({ user_id: b.user_id, user_name: b.user_name, bookings: upcomingSessions.filter(s => s.user_id === b.user_id) })}>{b.user_name || 'Client'}</strong>
                  </div>
                  {b.mode === 'online' && (
                    <button className="btn accent sm" style={{ fontSize: 12, padding: '4px 10px' }}
                      onClick={function() { setRoute('video-call', { id: String(b.id) }); }}>
                      <Icon name="videocam" className="sm" /> {el ? 'Σύνδεση' : 'Join'}
                    </button>
                  )}
                </div>
                <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 5, fontSize: 13, color: 'var(--fg2)' }}>
                  <Icon name="schedule" className="sm" /> {dayLabel} · {b.time}
                  <span className="bullet">·</span>
                  <Icon name={b.mode === 'online' ? 'videocam' : 'meeting_room'} className="sm" />
                  {b.mode === 'online' ? (el ? 'Online' : 'Online') : (el ? 'Δια ζώσης' : 'In-person')}
                </div>
              </div>
            );
          })}
        </div>
      </div>

      {/* Latest review + quick links */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 24, marginTop: 24 }}>
        <div className="card" style={{ padding: 24 }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 14 }}>
            <h3 className="display" style={{ fontSize: 18, fontWeight: 600 }}>{t('provider_latest_review')}</h3>
            <span style={{ color: 'var(--fg3)', fontSize: 13 }}>{t('provider_no_reviews')}</span>
          </div>
          <div style={{ padding: '28px 0', textAlign: 'center' }}>
            <Icon name="rate_review" style={{ fontSize: 32, color: 'var(--fg3)', display: 'block', margin: '0 auto 10px' }} />
            <div style={{ fontSize: 13, color: 'var(--fg3)', lineHeight: 1.55 }}>
              {t('provider_review_note').split('\n').map(function(line, i) { return i === 0 ? line : <React.Fragment key={i}><br />{line}</React.Fragment>; })}
            </div>
          </div>
        </div>

        <div className="card" style={{ padding: 24 }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 14 }}>
            <h3 className="display" style={{ fontSize: 18, fontWeight: 600 }}>{t('provider_resources')}</h3>
            <span style={{ fontSize: 12, color: 'var(--fg2)' }}>{t('provider_from_learn')}</span>
          </div>
          <p style={{ fontSize: 13, color: 'var(--fg2)', lineHeight: 1.55, marginBottom: 14 }}>
            {t('provider_share_note')}
          </p>
          {[
            { title: 'What to expect from your first session', icon: 'help_outline' },
            { title: 'CBT explained: what it is and how it helps', icon: 'psychology' },
            { title: 'How to get the most out of therapy', icon: 'lightbulb' },
          ].map(function(a, i) {
            return (
              <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '9px 0', borderTop: '1px solid var(--psy-rule)' }}>
                <Icon name={a.icon} style={{ color: 'var(--psy-accent)', fontSize: 18, flexShrink: 0 }} />
                <span style={{ fontSize: 13, fontWeight: 500, color: 'var(--psy-ink)' }}>{a.title}</span>
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
}

// ===========================================================
//  APPLICATION DETAIL MODAL (admin view of a pending application)
// ===========================================================
function ApplicationDetailModal({ app, onApprove, onReject, onClose }) {
  const [approving, setApproving] = React.useState(false);
  const [rejecting, setRejecting] = React.useState(false);

  async function handleApprove() {
    setApproving(true);
    await onApprove(app.id, app.name);
    onClose();
  }
  async function handleReject() {
    setRejecting(true);
    await onReject(app.id, app.name);
    onClose();
  }

  function InfoRow({ label, value, highlight }) {
    return (
      <div style={{ padding: '10px 0', borderBottom: '1px solid var(--psy-rule)' }}>
        <div style={{ fontSize: 11, fontWeight: 600, color: 'var(--fg3)', textTransform: 'uppercase', letterSpacing: '0.07em', marginBottom: 3 }}>{label}</div>
        <div style={{ fontSize: 14, color: highlight ? 'var(--psy-accent)' : 'var(--psy-ink)', fontWeight: highlight ? 600 : 400 }}>{value || <span style={{ color: 'var(--fg3)', fontStyle: 'italic' }}>Not provided</span>}</div>
      </div>
    );
  }

  const appliedDate = app.created_at
    ? new Date(app.created_at).toLocaleString('en-GB', { day: 'numeric', month: 'long', year: 'numeric', hour: '2-digit', minute: '2-digit' })
    : '—';

  return (
    <div onClick={onClose} style={{ position: 'fixed', inset: 0, zIndex: 60, background: 'rgba(15,21,37,0.6)', backdropFilter: 'blur(4px)', display: 'grid', placeItems: 'center', padding: 16 }}>
      <div onClick={function(e) { e.stopPropagation(); }} style={{ background: 'white', borderRadius: 24, width: '100%', maxWidth: 620, maxHeight: '90vh', overflow: 'auto', boxShadow: '0 24px 64px rgba(15,21,37,0.25)' }}>

        {/* Header */}
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '20px 28px', borderBottom: '1px solid var(--psy-rule)', position: 'sticky', top: 0, background: 'white', zIndex: 1 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
            <div className="avatar-sm" style={{ background: avatarBg('b'), width: 44, height: 44, borderRadius: 14, fontSize: 16 }}>
              {app.name.split(' ').map(function(w) { return w[0]; }).join('').slice(0, 2).toUpperCase()}
            </div>
            <div>
              <div style={{ fontSize: 11, fontWeight: 600, color: 'var(--psy-accent)', textTransform: 'uppercase', letterSpacing: '0.07em' }}>Pending application</div>
              <h2 className="display" style={{ fontSize: 22, fontWeight: 600, marginTop: 2 }}>{app.name}</h2>
            </div>
          </div>
          <button onClick={onClose} style={{ appearance: 'none', border: 0, background: 'var(--psy-surface)', width: 34, height: 34, borderRadius: '50%', cursor: 'pointer', display: 'grid', placeItems: 'center', color: 'var(--fg2)' }}>
            <Icon name="close" className="sm" />
          </button>
        </div>

        {/* Body */}
        <div style={{ padding: '24px 28px' }}>

          {/* Email-not-verified warning */}
          {!app.email_verified && (
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '10px 14px', background: '#FEF3C7', borderRadius: 12, marginBottom: 20, fontSize: 13, color: '#92400E', fontWeight: 600 }}>
              <Icon name="warning" className="sm" /> Email address has not been verified yet.
            </div>
          )}

          {/* Application info */}
          <h3 style={{ fontSize: 13, fontWeight: 700, color: 'var(--fg3)', textTransform: 'uppercase', letterSpacing: '0.08em', marginBottom: 4 }}>Application details</h3>
          <div style={{ marginBottom: 24 }}>
            <InfoRow label="Full name" value={app.name} />
            <InfoRow label="Email" value={app.email} />
            <InfoRow label="District" value={app.district} />
            <InfoRow label="Credentials / title" value={app.credentials} highlight={!!app.credentials} />
            <InfoRow label="Licence number (ΠΣΨΨ)" value={app.license_number} highlight={!!app.license_number} />
            <InfoRow label="Applied" value={appliedDate} />
            <InfoRow label="Email verified" value={app.email_verified ? 'Yes ✓' : 'No — not yet clicked the link'} />
          </div>

          {/* Uploaded documents */}
          <h3 style={{ fontSize: 13, fontWeight: 700, color: 'var(--fg3)', textTransform: 'uppercase', letterSpacing: '0.08em', marginBottom: 12 }}>Uploaded documents</h3>
          {app.documents && app.documents.length > 0 ? (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8, marginBottom: 24 }}>
              {app.documents.map(function(doc, i) {
                const isImage = /\.(jpg|jpeg|png|gif|webp)$/i.test(doc.originalName);
                return (
                  <a key={i} href={doc.path} target="_blank" rel="noreferrer"
                    style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '12px 16px', background: 'var(--psy-surface)', borderRadius: 12, border: '1px solid var(--psy-rule)', textDecoration: 'none', color: 'var(--psy-ink)' }}>
                    <Icon name={isImage ? 'image' : 'picture_as_pdf'} style={{ fontSize: 22, color: isImage ? 'var(--psy-accent)' : '#DC2626' }} />
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ fontWeight: 600, fontSize: 14, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{doc.originalName}</div>
                      <div style={{ fontSize: 12, color: 'var(--fg3)', marginTop: 2 }}>{(doc.size / 1024).toFixed(0)} KB</div>
                    </div>
                    <Icon name="open_in_new" className="sm" style={{ color: 'var(--fg3)', flexShrink: 0 }} />
                  </a>
                );
              })}
            </div>
          ) : (
            <div style={{ padding: '16px 20px', background: 'var(--psy-surface)', borderRadius: 12, marginBottom: 24, fontSize: 14, color: 'var(--fg3)', display: 'flex', alignItems: 'center', gap: 10 }}>
              <Icon name="folder_open" style={{ color: 'var(--fg3)' }} />
              No documents uploaded by this applicant.
            </div>
          )}

          {/* ΠΣΨΨ registry check */}
          <div style={{ padding: '16px 20px', background: 'var(--psy-surface)', borderRadius: 14, border: '1px solid var(--psy-rule)' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 8 }}>
              <Icon name="verified_user" style={{ color: 'var(--psy-leaf)' }} />
              <strong style={{ fontSize: 14 }}>Verify against ΠΣΨΨ registry</strong>
            </div>
            <p style={{ fontSize: 13, color: 'var(--fg2)', lineHeight: 1.5, margin: '0 0 10px' }}>
              Cross-check the licence number <strong>{app.license_number || '(none provided)'}</strong> against the Cyprus Psychologists Board registry.
            </p>
            <a href="https://www.psyboard.org.cy/en/psyboard/registered-psychologists/" target="_blank" rel="noreferrer"
              style={{ display: 'inline-flex', alignItems: 'center', gap: 6, fontSize: 13, fontWeight: 600, color: 'var(--psy-accent)', textDecoration: 'none' }}>
              Open ΠΣΨΨ registry <Icon name="open_in_new" className="sm" />
            </a>
          </div>
        </div>

        {/* Footer actions */}
        <div style={{ display: 'flex', justifyContent: 'flex-end', gap: 10, padding: '16px 28px', borderTop: '1px solid var(--psy-rule)', position: 'sticky', bottom: 0, background: 'white' }}>
          <button className="btn ghost" onClick={onClose}>Close</button>
          <button className="btn ghost" style={{ color: 'var(--color-error)', borderColor: 'var(--color-error)' }}
            onClick={handleReject} disabled={rejecting}>
            {rejecting ? 'Rejecting…' : 'Reject application'}
          </button>
          <button className="btn primary" onClick={handleApprove} disabled={approving}
            style={{ background: 'var(--psy-leaf)', borderColor: 'var(--psy-leaf)' }}>
            <Icon name="verified" className="sm" /> {approving ? 'Approving…' : 'Approve & publish'}
          </button>
        </div>
      </div>
    </div>
  );
}

// ===========================================================
//  ADMIN — VERIFICATION QUEUE (real data from API)
// ===========================================================
// ── Reject confirmation modal (replaces browser confirm()) ────
function RejectConfirmModal({ title, body, confirmLabel, onConfirm, onClose }) {
  const [loading, setLoading] = React.useState(false);
  async function handleConfirm() {
    setLoading(true);
    await onConfirm();
    setLoading(false);
    onClose();
  }
  return (
    <div onClick={onClose} style={{ position: 'fixed', inset: 0, zIndex: 70, background: 'rgba(15,21,37,0.5)', backdropFilter: 'blur(4px)', display: 'grid', placeItems: 'center', padding: 16 }}>
      <div onClick={function(e) { e.stopPropagation(); }} style={{ background: 'white', borderRadius: 20, padding: '32px 36px', maxWidth: 420, width: '100%', boxShadow: '0 20px 60px rgba(15,21,37,0.2)' }}>
        <div style={{ width: 44, height: 44, borderRadius: 12, background: '#FEE2E2', display: 'grid', placeItems: 'center', marginBottom: 16 }}>
          <Icon name="delete_forever" style={{ color: 'var(--color-error)', fontSize: 22 }} />
        </div>
        <h3 className="display" style={{ fontSize: 19, fontWeight: 600, marginBottom: 8 }}>{title}</h3>
        <p style={{ color: 'var(--fg2)', fontSize: 14, lineHeight: 1.55, marginBottom: 24 }}>{body}</p>
        <div style={{ display: 'flex', gap: 10, justifyContent: 'flex-end' }}>
          <button className="btn ghost" onClick={onClose}>Cancel</button>
          <button className="btn primary" disabled={loading}
            style={{ background: 'var(--color-error)', borderColor: 'var(--color-error)' }}
            onClick={handleConfirm}>
            {loading ? 'Removing…' : (confirmLabel || 'Confirm')}
          </button>
        </div>
      </div>
    </div>
  );
}

function AdminScreen({ openEditProfile, setToast, setRoute }) {
  const { t } = useLang();
  const [pending, setPending] = useState([]);
  const [verifiedCount, setVerifiedCount] = useState(0);
  const [loading, setLoading] = useState(true);
  const [selectedApp, setSelectedApp] = useState(null); // application detail modal

  // Pending reviews
  const [pendingReviews, setPendingReviews] = useState([]);
  const [reviewsLoading, setReviewsLoading] = useState(true);
  const [rejectModal, setRejectModal] = useState(null); // { title, body, confirmLabel, onConfirm }

  // All profiles management
  const [allProfiles, setAllProfiles] = useState([]);
  const [profilesLoading, setProfilesLoading] = useState(true);

  // Availability inspector
  const [availInfo, setAvailInfo]   = useState({}); // { [psyId]: {loading, rows, error} }
  const [availReset, setAvailReset] = useState({}); // { [psyId]: 'idle'|'saving'|'done'|'error' }

  // Plan interest / waitlist
  const [planInterest, setPlanInterest] = useState([]);
  const [planInterestLoading, setPlanInterestLoading] = useState(true);

  // Audit log
  const [adminTab, setAdminTab] = useState('verification'); // 'verification' | 'audit'
  const [auditLog, setAuditLog] = useState([]);
  const [auditLoading, setAuditLoading] = useState(false);
  const [auditFilter, setAuditFilter] = useState('');

  function getToken() {
    try { return JSON.parse(localStorage.getItem('psyche-auth') || '{}').token; } catch { return null; }
  }
  function authHeaders() {
    return { 'Content-Type': 'application/json', Authorization: 'Bearer ' + getToken() };
  }

  useEffect(() => {
    // Load pending applications
    fetch('/api/admin/pending', { headers: authHeaders() })
      .then(r => r.json())
      .then(data => { setPending(Array.isArray(data) ? data : []); setLoading(false); })
      .catch(() => setLoading(false));
    // Load real verified count from the profiles API
    fetch('/api/psychologists')
      .then(r => r.json())
      .then(data => { setVerifiedCount(Array.isArray(data) ? data.length : 0); })
      .catch(() => {});
    // Load pending reviews
    fetch('/api/admin/reviews/pending', { headers: authHeaders() })
      .then(r => r.json())
      .then(data => { setPendingReviews(Array.isArray(data) ? data : []); setReviewsLoading(false); })
      .catch(() => setReviewsLoading(false));
    // Load ALL profiles for management (including hidden)
    API.getAdminPsychologists()
      .then(data => { setAllProfiles(Array.isArray(data) ? data : []); setProfilesLoading(false); })
      .catch(() => setProfilesLoading(false));
    // Load plan interest / waitlist
    fetch('/api/admin/plan-interest', { headers: authHeaders() })
      .then(r => r.json())
      .then(data => { setPlanInterest(Array.isArray(data) ? data : []); setPlanInterestLoading(false); })
      .catch(() => setPlanInterestLoading(false));
  }, []);

  function loadAudit(filter) {
    setAuditLoading(true);
    const q = filter ? '?event=' + encodeURIComponent(filter) : '';
    fetch('/api/admin/audit' + q, { headers: authHeaders() })
      .then(r => r.json())
      .then(data => { setAuditLog(Array.isArray(data) ? data : []); setAuditLoading(false); })
      .catch(() => setAuditLoading(false));
  }

  useEffect(() => { if (adminTab === 'audit' && auditLog.length === 0) loadAudit(''); }, [adminTab]);

  // Approve review — forceVerified=true lets admin manually mark as verified
  async function approveReview(reviewId, author, forceVerified) {
    await fetch('/api/admin/reviews/' + reviewId + '/approve', {
      method: 'POST', headers: authHeaders(),
      body: JSON.stringify({ force_verified: forceVerified === true }),
    });
    setPendingReviews(prev => prev.filter(r => r.id !== reviewId));
    setToast && setToast('Review by ' + author + ' approved and published.');
  }

  function rejectReview(reviewId, author) {
    setRejectModal({
      title: 'Reject this review?',
      body: 'The review by ' + author + ' will be permanently removed and will not appear on the profile.',
      confirmLabel: 'Yes, reject review',
      onConfirm: async function() {
        await fetch('/api/admin/reviews/' + reviewId + '/reject', { method: 'POST', headers: authHeaders() });
        setPendingReviews(prev => prev.filter(r => r.id !== reviewId));
        setToast && setToast('Review rejected and removed.');
      },
    });
  }

  async function approve(userId, name) {
    await fetch('/api/admin/users/' + userId + '/approve', { method: 'POST', headers: authHeaders() });
    setPending(p => p.filter(u => u.id !== userId));
    setVerifiedCount(c => c + 1);
    setToast && setToast(name.split(' ')[0] + ' approved — profile is now live in the directory.');
  }

  async function toggleVisibility(profileId, currentVisible) {
    try {
      await API.saveAdminProfile(profileId, { visible: !currentVisible });
      setAllProfiles(prev => prev.map(p => p.id === profileId ? { ...p, visible: !currentVisible } : p));
      setVerifiedCount(c => currentVisible ? c - 1 : c + 1);
      setToast && setToast(currentVisible ? 'Profile hidden from the directory.' : 'Profile is now visible in the directory.');
    } catch (e) {
      setToast && setToast('Failed to update visibility: ' + e.message);
    }
  }

  async function checkAvailability(psyId) {
    setAvailInfo(prev => ({ ...prev, [psyId]: { loading: true, rows: null, error: null } }));
    try {
      const data = await API.getAdminAvailability(psyId);
      setAvailInfo(prev => ({ ...prev, [psyId]: { loading: false, rows: data.rows || [], error: null } }));
    } catch (e) {
      setAvailInfo(prev => ({ ...prev, [psyId]: { loading: false, rows: null, error: e.message } }));
    }
  }

  async function clearAvailability(psyId) {
    setAvailReset(prev => ({ ...prev, [psyId]: 'saving' }));
    try {
      await API.resetAdminAvailability(psyId, []); // empty = clear all
      setAvailInfo(prev => ({ ...prev, [psyId]: { loading: false, rows: [], error: null } }));
      setAvailReset(prev => ({ ...prev, [psyId]: 'done' }));
      setToast && setToast('Availability cleared for psyId=' + psyId + '. The psychologist can now re-save from their dashboard.');
      setTimeout(() => setAvailReset(prev => ({ ...prev, [psyId]: 'idle' })), 4000);
    } catch (e) {
      setAvailReset(prev => ({ ...prev, [psyId]: 'error' }));
      setToast && setToast('Error: ' + e.message);
    }
  }

  function reject(userId, name) {
    setRejectModal({
      title: 'Reject application?',
      body: name + "'s application will be rejected. This cannot be undone.",
      confirmLabel: 'Yes, reject application',
      onConfirm: async function() {
        await fetch('/api/admin/users/' + userId + '/reject', { method: 'POST', headers: authHeaders() });
        setPending(p => p.filter(u => u.id !== userId));
        setToast && setToast(name.split(' ')[0] + "'s application rejected.");
      },
    });
  }

  return (
    <div className="page wide">
      {selectedApp && (
        <ApplicationDetailModal
          app={selectedApp}
          onApprove={approve}
          onReject={reject}
          onClose={() => setSelectedApp(null)}
        />
      )}
      {rejectModal && (
        <RejectConfirmModal
          title={rejectModal.title}
          body={rejectModal.body}
          confirmLabel={rejectModal.confirmLabel}
          onConfirm={rejectModal.onConfirm}
          onClose={() => setRejectModal(null)}
        />
      )}

      <div style={{ marginBottom: 24, display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end', gap: 16 }}>
        <div>
          <span className="eyebrow muted">{t('admin_eyebrow')}</span>
          <h1 className="display" style={{ fontSize: 36, marginTop: 6 }}>{t('admin_h1')}</h1>
          <p style={{ color: 'var(--fg2)', marginTop: 6 }}>
            {loading ? '…' : (
              pending.length > 0
                ? pending.length + ' ' + (pending.length !== 1 ? t('admin_sub_pending_pl') : t('admin_sub_pending_one'))
                : t('admin_sub_empty')
            )}
          </p>
        </div>
        <button className="btn primary" onClick={() => openEditProfile && openEditProfile(null)}>
          <Icon name="add" className="sm" /> {t('admin_add_psy')}
        </button>
      </div>

      <div className="dash">
        <div className="stat">
          <span className="num">{verifiedCount}</span>
          <div className="label">{t('admin_stat_verified')}</div>
        </div>
        <div className="stat">
          <span className="num">{pending.length}</span>
          <div className="label">{t('admin_stat_pending')}</div>
        </div>
        <div className="stat">
          <span className="num">{pendingReviews.length}</span>
          <div className="label">{t('admin_stat_reviews')}</div>
        </div>
      </div>

      {/* Tab switcher */}
      <div style={{ display: 'flex', gap: 4, marginTop: 32, borderBottom: '2px solid var(--psy-rule)' }}>
        {[
          { id: 'verification', label: t('admin_tab_queue'), icon: 'verified_user' },
          { id: 'audit',        label: t('admin_tab_audit'), icon: 'history' },
        ].map(tab => (
          <button key={tab.id} onClick={() => setAdminTab(tab.id)} style={{
            border: 'none', background: 'none', cursor: 'pointer', padding: '10px 18px',
            fontWeight: adminTab === tab.id ? 700 : 500,
            fontSize: 14, color: adminTab === tab.id ? 'var(--psy-accent)' : 'var(--fg2)',
            borderBottom: adminTab === tab.id ? '2px solid var(--psy-accent)' : '2px solid transparent',
            marginBottom: -2, display: 'flex', alignItems: 'center', gap: 6,
          }}>
            <Icon name={tab.icon} style={{ fontSize: 16 }} /> {tab.label}
          </button>
        ))}
      </div>

      {/* ── AUDIT TAB ── */}
      {adminTab === 'audit' && (
        <div style={{ marginTop: 24 }}>
          {/* Filters */}
          <div style={{ display: 'flex', gap: 8, marginBottom: 16, flexWrap: 'wrap' }}>
            {[
              { label: t('audit_filter_all'),            value: '' },
              { label: t('audit_filter_logins'),         value: 'user.login' },
              { label: t('audit_filter_signups'),        value: 'user.signup' },
              { label: t('audit_filter_profiles'),       value: 'profile.view' },
              { label: t('audit_filter_profile_update'), value: 'profile.update' },
              { label: t('audit_filter_bookings'),       value: 'booking.request' },
              { label: t('audit_filter_accepted'),       value: 'booking.accepted' },
              { label: t('audit_filter_declined'),       value: 'booking.declined' },
              { label: t('audit_filter_admin'),          value: 'admin.' },
              { label: t('audit_filter_plan'),           value: 'plan.' },
            ].map(f => (
              <button key={f.value} onClick={() => { setAuditFilter(f.value); loadAudit(f.value); }}
                className={auditFilter === f.value ? 'btn accent sm' : 'btn ghost sm'}
                style={{ fontSize: 12 }}>
                {f.label}
              </button>
            ))}
            <button className="btn ghost sm" style={{ marginLeft: 'auto', fontSize: 12 }}
              onClick={() => loadAudit(auditFilter)}>
              <Icon name="refresh" className="sm" /> {t('audit_refresh')}
            </button>
          </div>

          {/* Event type legend */}
          <div className="card" style={{ padding: 0 }}>
            <div style={{ padding: '12px 20px', borderBottom: '1px solid var(--psy-rule)', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
              <span style={{ fontWeight: 600, fontSize: 14 }}>
                <Icon name="history" style={{ verticalAlign: -3, marginRight: 6, color: 'var(--psy-accent)' }} />
                {auditLog.length} {t('audit_events')}
              </span>
            </div>
            {auditLoading ? (
              <div style={{ padding: 32, textAlign: 'center', color: 'var(--fg3)' }}>{t('audit_loading')}</div>
            ) : auditLog.length === 0 ? (
              <div style={{ padding: 32, textAlign: 'center', color: 'var(--fg3)' }}>
                <Icon name="history" style={{ fontSize: 36, display: 'block', margin: '0 auto 12px', opacity: 0.3 }} />
                {t('audit_empty')}
              </div>
            ) : (
              <div style={{ overflowX: 'auto' }}>
                <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13 }}>
                  <thead>
                    <tr style={{ background: 'var(--psy-surface)' }}>
                      {[t('audit_col_time'), t('audit_col_event'), t('audit_col_user'), t('audit_col_details')].map(h => (
                        <th key={h} style={{ padding: '10px 16px', textAlign: 'left', fontWeight: 600, fontSize: 11, color: 'var(--fg2)', letterSpacing: '0.05em', whiteSpace: 'nowrap' }}>{h.toUpperCase()}</th>
                      ))}
                    </tr>
                  </thead>
                  <tbody>
                    {auditLog.map((e, i) => {
                      const meta = e.meta || {};
                      const eventColors = {
                        'user.login':    '#6366F1', 'user.signup':  '#10B981',
                        'profile.view':  '#F59E0B', 'profile.update': '#A855F7',
                        'booking.request': '#3B82F6',
                        'booking.accepted': '#22C55E', 'booking.declined': '#EF4444',
                        'booking.calendar': '#8B5CF6', 'admin.approve_psychologist': '#10B981',
                        'admin.reject_psychologist': '#EF4444', 'plan.interest': '#F97316',
                      };
                      const color = eventColors[e.event_type] || '#6B7280';
                      const details = Object.entries(meta)
                        .filter(([k]) => !['user_id'].includes(k))
                        .map(([k, v]) => `${k}: ${v}`)
                        .join(' · ');
                      return (
                        <tr key={e.id} style={{ borderTop: '1px solid var(--psy-rule)', background: i % 2 === 0 ? 'white' : 'var(--psy-surface)' }}>
                          <td style={{ padding: '8px 16px', color: 'var(--fg3)', whiteSpace: 'nowrap', fontSize: 12 }}>
                            {new Date(e.created_at).toLocaleString('el-GR', { day: '2-digit', month: '2-digit', hour: '2-digit', minute: '2-digit' })}
                          </td>
                          <td style={{ padding: '8px 16px', whiteSpace: 'nowrap' }}>
                            <span style={{ fontSize: 11, fontWeight: 700, padding: '2px 8px', borderRadius: 99, background: color + '20', color }}>
                              {e.event_type}
                            </span>
                          </td>
                          <td style={{ padding: '8px 16px', whiteSpace: 'nowrap' }}>
                            {e.user_name ? (
                              <span style={{ fontWeight: 500 }}>{e.user_name}</span>
                            ) : (
                              <span style={{ color: 'var(--fg3)', fontSize: 12 }}>{t('audit_guest')}</span>
                            )}
                            {e.user_email && <div style={{ fontSize: 11, color: 'var(--fg3)' }}>{e.user_email}</div>}
                          </td>
                          <td style={{ padding: '8px 16px', color: 'var(--fg2)', maxWidth: 400 }}>
                            <span style={{ fontSize: 12 }}>{details || '—'}</span>
                          </td>
                        </tr>
                      );
                    })}
                  </tbody>
                </table>
              </div>
            )}
          </div>
        </div>
      )}

      {/* ── VERIFICATION TAB ── */}
      {adminTab === 'verification' && <>

      {/* Real verification queue */}
      <div className="card" style={{ padding: 0, marginTop: 24 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', padding: '18px 22px 14px', borderBottom: '1px solid var(--psy-rule)' }}>
          <h3 className="display" style={{ fontSize: 20, fontWeight: 600 }}>Verification queue</h3>
          <span style={{ fontSize: 12, color: 'var(--fg2)' }}>Applications from psychologists who signed up</span>
        </div>
        {loading && (
          <div style={{ padding: 32, textAlign: 'center', color: 'var(--fg3)' }}>Loading applications…</div>
        )}
        {!loading && pending.length === 0 && (
          <div style={{ padding: 40, textAlign: 'center' }}>
            <Icon name="check_circle" style={{ fontSize: 36, color: 'var(--psy-leaf)', display: 'block', margin: '0 auto 12px' }} />
            <div style={{ fontSize: 15, color: 'var(--fg2)' }}>All caught up — no pending applications.</div>
          </div>
        )}
        {pending.map(p => (
          <div key={p.id} className="queue-row" onClick={() => setSelectedApp(p)}
            style={{ cursor: 'pointer', transition: 'background 0.15s' }}
            onMouseEnter={function(e) { e.currentTarget.style.background = 'var(--psy-surface)'; }}
            onMouseLeave={function(e) { e.currentTarget.style.background = ''; }}>
            <div className="avatar-sm" style={{ background: avatarBg('b') }}>
              {p.name.split(' ').map(w => w[0]).join('').slice(0, 2).toUpperCase()}
            </div>
            <div>
              <div className="who">{p.name}</div>
              <div className="creds" style={{ marginTop: 2 }}>
                {p.email}
                {p.district && ` · ${p.district}`}
                {p.credentials && <span style={{ color: 'var(--fg2)' }}> · {p.credentials}</span>}
                {' · Applied '}{new Date(p.created_at).toLocaleDateString('en-GB', { day: 'numeric', month: 'short' })}
              </div>
              <div style={{ display: 'flex', gap: 6, marginTop: 6, flexWrap: 'wrap' }}>
                {!p.email_verified && (
                  <div style={{ display: 'inline-flex', alignItems: 'center', gap: 4, padding: '2px 8px', background: '#FEF3C7', color: '#92400E', borderRadius: 999, fontSize: 11, fontWeight: 600 }}>
                    <Icon name="warning" className="sm" /> Email not verified
                  </div>
                )}
                {p.documents && p.documents.length > 0 && (
                  <div style={{ display: 'inline-flex', alignItems: 'center', gap: 4, padding: '2px 8px', background: '#DCFCE7', color: '#166534', borderRadius: 999, fontSize: 11, fontWeight: 600 }}>
                    <Icon name="attach_file" className="sm" /> {p.documents.length} document{p.documents.length !== 1 ? 's' : ''}
                  </div>
                )}
                {p.license_number && (
                  <div style={{ display: 'inline-flex', alignItems: 'center', gap: 4, padding: '2px 8px', background: 'var(--psy-accent-soft)', color: 'var(--psy-accent)', borderRadius: 999, fontSize: 11, fontWeight: 600 }}>
                    <Icon name="badge" className="sm" /> {p.license_number}
                  </div>
                )}
              </div>
            </div>
            <span />
            <span className="when">{p.created_at ? new Date(p.created_at).toLocaleTimeString('en-GB', { hour: '2-digit', minute: '2-digit' }) : ''}</span>
            <div style={{ display: 'flex', gap: 6 }} onClick={function(e) { e.stopPropagation(); }}>
              <button className="btn ghost sm" style={{ color: 'var(--color-error)' }} onClick={() => reject(p.id, p.name)}>
                Reject
              </button>
              <button className="btn primary sm" onClick={() => approve(p.id, p.name)}>
                <Icon name="check" className="sm" /> Approve
              </button>
            </div>
          </div>
        ))}
      </div>

      {/* Psychologists management */}
      <div className="card" style={{ padding: 0, marginTop: 24 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', padding: '18px 22px 14px', borderBottom: '1px solid var(--psy-rule)', flexWrap: 'wrap', gap: 8 }}>
          <div>
            <h3 className="display" style={{ fontSize: 20, fontWeight: 600 }}>All psychologist profiles</h3>
            <p style={{ fontSize: 13, color: 'var(--fg2)', marginTop: 4 }}>
              Manage visibility. Legacy mock profiles (non-numeric IDs like p1–p6) are automatically hidden on startup.
            </p>
          </div>
        </div>
        {profilesLoading && (
          <div style={{ padding: 28, textAlign: 'center', color: 'var(--fg3)', fontSize: 14 }}>Loading profiles…</div>
        )}
        {!profilesLoading && allProfiles.length === 0 && (
          <div style={{ padding: 28, textAlign: 'center', color: 'var(--fg3)', fontSize: 14 }}>No profiles found.</div>
        )}
        {allProfiles.map(p => (
          <React.Fragment key={p.id}>
          <div style={{
            display: 'flex', alignItems: 'center', gap: 14, padding: '12px 22px',
            borderTop: '1px solid var(--psy-rule)', flexWrap: 'wrap',
            opacity: p.visible ? 1 : 0.6,
          }}>
            <div className="avatar-sm" style={{ background: avatarBg(p.name ? p.name[0].toLowerCase() : 'a'), flexShrink: 0 }}>
              {p.name ? p.name.split(' ').map(w => w[0]).join('').slice(0, 2).toUpperCase() : '?'}
            </div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontWeight: 600, fontSize: 14 }}>{p.name || '—'}</div>
              <div style={{ fontSize: 12, color: 'var(--fg2)', marginTop: 2 }}>
                ID: <code style={{ fontFamily: 'monospace', background: 'var(--psy-surface)', padding: '1px 5px', borderRadius: 4 }}>{p.id}</code>
                {p.email && <span> · <a href={`mailto:${p.email}`} style={{ color: 'var(--fg2)', textDecoration: 'none' }}>{p.email}</a></span>}
                {p.district && <span> · {p.district}</span>}
                {p.credentials && <span> · {p.credentials}</span>}
                {p.visible ? (
                  <span style={{ marginLeft: 8, color: 'var(--psy-leaf)', fontWeight: 600 }}>● Visible</span>
                ) : (
                  <span style={{ marginLeft: 8, color: 'var(--fg3)', fontWeight: 600 }}>○ Hidden</span>
                )}
              </div>
            </div>
            <div style={{ display: 'flex', gap: 6, flexShrink: 0, flexWrap: 'wrap' }}>
              {p.visible && setRoute && (
                <button className="btn ghost sm" onClick={() => setRoute('book', p.id)} title="Preview booking calendar for this profile">
                  <Icon name="preview" className="sm" /> Preview
                </button>
              )}
              <button className="btn ghost sm" onClick={() => openEditProfile && openEditProfile(p.id)}>
                <Icon name="edit" className="sm" /> Edit
              </button>
              <button className="btn ghost sm" onClick={() => checkAvailability(p.id)} title="Inspect what availability days are stored in the database for this profile">
                <Icon name="event_available" className="sm" /> Avail DB
              </button>
              <button
                className="btn ghost sm"
                style={{ color: p.visible ? 'var(--color-error)' : 'var(--psy-leaf)' }}
                onClick={() => toggleVisibility(p.id, p.visible)}
              >
                <Icon name={p.visible ? 'visibility_off' : 'visibility'} className="sm" />
                {p.visible ? 'Hide' : 'Show'}
              </button>
            </div>
          </div>
          {/* Availability inspector panel (shown after clicking "Avail DB") */}
          {availInfo[p.id] && (() => {
            const info = availInfo[p.id];
            const SHORT = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'];
            const resetState = availReset[p.id] || 'idle';
            return (
              <div style={{ margin: '0 16px 12px', padding: '12px 16px', borderRadius: 10, background: 'var(--psy-surface)', border: '1px solid var(--psy-rule)', fontSize: 13 }}>
                {info.loading && <span style={{ color: 'var(--fg3)' }}>Loading availability from DB…</span>}
                {info.error  && <span style={{ color: 'var(--color-error)' }}>Error: {info.error}</span>}
                {!info.loading && !info.error && (
                  <div>
                    <div style={{ fontWeight: 700, marginBottom: 6 }}>
                      DB availability for psyId=<code style={{ background: 'var(--psy-rule)', padding: '1px 5px', borderRadius: 4 }}>{p.id}</code>:
                      {' '}
                      {info.rows.length === 0
                        ? <span style={{ color: 'var(--fg3)' }}>No rows — booking calendar will show all days greyed out</span>
                        : <span style={{ color: 'var(--psy-ink)', fontFamily: 'monospace' }}>
                            [{[...new Set(info.rows.map(r => r.day_of_week))].sort((a,b)=>a-b).map(d => SHORT[d]).join(', ')}]
                            {' — raw: '}[{[...new Set(info.rows.map(r => r.day_of_week))].sort((a,b)=>a-b).join(', ')}]
                          </span>
                      }
                    </div>
                    {info.rows.length > 0 && (
                      <table style={{ borderCollapse: 'collapse', width: '100%', marginBottom: 10, fontSize: 12 }}>
                        <thead>
                          <tr style={{ background: 'var(--psy-rule)' }}>
                            <th style={{ padding: '3px 8px', textAlign: 'left' }}>day_of_week</th>
                            <th style={{ padding: '3px 8px', textAlign: 'left' }}>day</th>
                            <th style={{ padding: '3px 8px', textAlign: 'left' }}>start</th>
                            <th style={{ padding: '3px 8px', textAlign: 'left' }}>end</th>
                          </tr>
                        </thead>
                        <tbody>
                          {info.rows.map((r, ri) => (
                            <tr key={ri} style={{ borderBottom: '1px solid var(--psy-rule)' }}>
                              <td style={{ padding: '3px 8px', fontFamily: 'monospace' }}>{r.day_of_week}</td>
                              <td style={{ padding: '3px 8px', fontWeight: 600 }}>{SHORT[r.day_of_week]}</td>
                              <td style={{ padding: '3px 8px', fontFamily: 'monospace' }}>{r.start_time}</td>
                              <td style={{ padding: '3px 8px', fontFamily: 'monospace' }}>{r.end_time}</td>
                            </tr>
                          ))}
                        </tbody>
                      </table>
                    )}
                    <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
                      <button className="btn ghost sm" onClick={() => checkAvailability(p.id)}>
                        <Icon name="refresh" className="sm" /> Refresh
                      </button>
                      <button
                        className="btn ghost sm"
                        style={{ color: 'var(--color-error)', borderColor: 'var(--color-error)' }}
                        disabled={resetState === 'saving' || info.rows.length === 0}
                        onClick={() => {
                          if (window.confirm('Clear ALL availability rows for psyId=' + p.id + '?\n\nThe psychologist will need to re-save from their dashboard.\n\nThis cannot be undone.')) {
                            clearAvailability(p.id);
                          }
                        }}
                      >
                        <Icon name="delete_sweep" className="sm" />
                        {resetState === 'saving' ? 'Clearing…' : resetState === 'done' ? 'Cleared!' : 'Clear all rows'}
                      </button>
                      {resetState === 'done' && <span style={{ color: 'var(--psy-leaf)', fontSize: 12, fontWeight: 600 }}>✓ Cleared — psychologist must re-save</span>}
                    </div>
                  </div>
                )}
              </div>
            );
          })()}
          </React.Fragment>
        ))}
      </div>

      {/* Pending reviews */}
      <div className="card" style={{ padding: 0, marginTop: 24 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', padding: '18px 22px 14px', borderBottom: '1px solid var(--psy-rule)' }}>
          <h3 className="display" style={{ fontSize: 20, fontWeight: 600 }}>{t('admin_reviews_pending_h')}</h3>
          <span style={{ fontSize: 12, color: 'var(--fg2)' }}>{t('admin_reviews_pending_sub')}</span>
        </div>

        {reviewsLoading && (
          <div style={{ padding: 28, textAlign: 'center', color: 'var(--fg3)', fontSize: 14 }}>{t('audit_loading')}</div>
        )}
        {!reviewsLoading && pendingReviews.length === 0 && (
          <div style={{ padding: '32px 22px', textAlign: 'center' }}>
            <Icon name="rate_review" style={{ fontSize: 32, color: 'var(--psy-leaf)', display: 'block', margin: '0 auto 10px' }} />
            <div style={{ fontSize: 14, fontWeight: 600, color: 'var(--psy-ink)', marginBottom: 6 }}>{t('admin_no_pending_reviews')}</div>
            <div style={{ fontSize: 13, color: 'var(--fg2)', maxWidth: 360, margin: '0 auto', lineHeight: 1.55 }}>
              {t('admin_reviews_pending_sub')}
            </div>
          </div>
        )}

        {pendingReviews.map(r => (
          <div key={r.id} style={{ padding: '16px 22px', borderTop: '1px solid var(--psy-rule)' }}>
            <div style={{ display: 'flex', alignItems: 'flex-start', gap: 14 }}>
              <div className="avatar-sm" style={{ background: avatarBg('a'), flexShrink: 0 }}>{r.initials}</div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap', marginBottom: 4 }}>
                  <span style={{ fontWeight: 600, fontSize: 14 }}>{r.author}</span>
                  <span style={{ fontSize: 12, color: 'var(--fg3)' }}>→ {r.psy_name}</span>
                  <span style={{ fontSize: 11, color: 'var(--fg3)' }}>{r.created_at ? new Date(r.created_at).toLocaleDateString('en-GB', { day: 'numeric', month: 'short' }) : ''}</span>
                  {r.verified ? (
                    <span style={{ display: 'inline-flex', alignItems: 'center', gap: 3, padding: '1px 7px', background: '#DCFCE7', color: '#166534', borderRadius: 999, fontSize: 11, fontWeight: 600 }}>
                      <Icon name="verified" className="sm" /> Confirmed booking
                    </span>
                  ) : (
                    <span style={{ display: 'inline-flex', alignItems: 'center', gap: 3, padding: '1px 7px', background: '#FEF3C7', color: '#92400E', borderRadius: 999, fontSize: 11, fontWeight: 600 }}>
                      <Icon name="help" className="sm" /> No booking on record
                    </span>
                  )}
                  <span style={{ marginLeft: 'auto', display: 'flex', gap: 2 }}>
                    {[1,2,3,4,5].map(n => (
                      <Icon key={n} name="star" className="sm" style={{ color: n <= r.rating ? 'var(--psy-accent)' : 'var(--psy-rule)', fontSize: 14 }} />
                    ))}
                  </span>
                </div>
                <p style={{ fontSize: 13.5, color: 'var(--psy-ink)', lineHeight: 1.55, margin: '0 0 6px' }}>{r.body}</p>
                {r.sessions > 0 && (
                  <span style={{ fontSize: 12, color: 'var(--fg3)' }}>
                    <Icon name="event_repeat" className="sm" style={{ verticalAlign: -3, marginRight: 3 }} />
                    {r.sessions} session{r.sessions !== 1 ? 's' : ''} reported by reviewer
                  </span>
                )}
              </div>
            </div>
            <div style={{ display: 'flex', gap: 8, marginTop: 12, justifyContent: 'flex-end', flexWrap: 'wrap' }}>
              <button className="btn ghost sm" style={{ color: 'var(--color-error)' }}
                onClick={() => rejectReview(r.id, r.author)}>
                Reject
              </button>
              {r.verified ? (
                // Has confirmed booking — single clear approve
                <button className="btn primary sm" style={{ background: 'var(--psy-leaf)', borderColor: 'var(--psy-leaf)' }}
                  onClick={() => approveReview(r.id, r.author, false)}>
                  <Icon name="verified" className="sm" /> Approve (Verified)
                </button>
              ) : (
                // No booking on record — offer two options
                <>
                  <button className="btn ghost sm"
                    onClick={() => approveReview(r.id, r.author, false)}
                    title="Publish with 'External session' label — session not booked via Psyche">
                    <Icon name="check" className="sm" /> Approve as external
                  </button>
                  <button className="btn primary sm"
                    onClick={() => approveReview(r.id, r.author, true)}
                    title="Manually confirm — use only if you verified the session by other means">
                    <Icon name="verified" className="sm" /> Approve (Verified)
                  </button>
                </>
              )}
            </div>
          </div>
        ))}

      {/* Plan Interest / Waitlist */}
      <div className="card" style={{ padding: 0, marginTop: 32 }}>

        <div style={{ padding: '18px 24px 14px', borderBottom: '1px solid var(--psy-rule)', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <div>
            <h3 className="display" style={{ fontSize: 20, fontWeight: 600 }}>{t('admin_plan_interest_h')}</h3>
            <p style={{ fontSize: 13, color: 'var(--fg2)', margin: '4px 0 0' }}>{t('admin_plan_interest_sub')}</p>
          </div>
          <span style={{ fontSize: 13, color: 'var(--fg2)' }}>{planInterest.length} {t('audit_events')}</span>
        </div>
        {planInterestLoading ? (
          <div style={{ padding: 24, color: 'var(--fg3)', fontSize: 14 }}>{t('audit_loading')}</div>
        ) : planInterest.length === 0 ? (
          <div style={{ padding: 24, textAlign: 'center', color: 'var(--fg3)', fontSize: 14 }}>
            <Icon name="notifications_none" style={{ fontSize: 28, display: 'block', margin: '0 auto 10px' }} />
            {t('admin_plan_empty')}
          </div>
        ) : (
          <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 14 }}>
            <thead>
              <tr style={{ background: 'var(--psy-surface)' }}>
                {['#', t('admin_plan_col_user'), 'Email', t('admin_plan_col_plan'), t('admin_plan_col_date')].map(h => (
                  <th key={h} style={{ padding: '10px 20px', textAlign: 'left', fontWeight: 600, fontSize: 12, color: 'var(--fg2)', letterSpacing: '0.05em' }}>{h.toUpperCase()}</th>
                ))}
              </tr>
            </thead>
            <tbody>
              {planInterest.map((r, i) => (
                <tr key={r.id} style={{ borderTop: '1px solid var(--psy-rule)' }}>
                  <td style={{ padding: '10px 20px', color: 'var(--fg3)' }}>{i + 1}</td>
                  <td style={{ padding: '10px 20px' }}>
                    {r.psy_profile_id ? (
                      <button className="btn ghost sm" style={{ padding: '2px 8px', fontSize: 13 }}
                        onClick={() => setRoute('detail', r.psy_profile_id)}>
                        {r.name || '—'}
                      </button>
                    ) : (
                      <span style={{ color: 'var(--fg2)' }}>{r.name || '—'}</span>
                    )}
                  </td>
                  <td style={{ padding: '10px 20px' }}>
                    <a href={'mailto:' + r.email} style={{ color: 'var(--psy-accent)', textDecoration: 'none' }}>{r.email}</a>
                  </td>
                  <td style={{ padding: '10px 20px' }}>
                    <span style={{ fontSize: 11, fontWeight: 700, padding: '2px 8px', borderRadius: 99, background: 'var(--psy-accent-soft)', color: 'var(--psy-accent)' }}>
                      {r.plan === 'premium' ? 'Premium' : 'Professional'}
                    </span>
                  </td>
                  <td style={{ padding: '10px 20px', color: 'var(--fg2)' }}>
                    {r.created_at ? new Date(r.created_at).toLocaleDateString('en-GB', { day: 'numeric', month: 'short', year: 'numeric' }) : '—'}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
      </div>
      </div>
      </>}
    </div>
  );
}

Object.assign(window, { ProviderScreen, AdminScreen, PendingApprovalScreen });
