// ============================================================
// ADMIN PANEL — /admin route
// ------------------------------------------------------------
// Sections: Dashboard · Users · Elite Applications · Notifications · Settings
// All data fetched from Supabase. RLS enforces admin-only access on the DB.
// The frontend route guard in app.jsx is just a UX layer.
// ============================================================

const ROLE_OPTIONS         = ['free', 'elite', 'admin'];
const ELITE_STATUS_OPTIONS = ['active', 'inactive', 'expired'];
const APP_STATUS_OPTIONS   = ['new', 'contacted', 'accepted', 'rejected'];

const fmtDate = (iso) => {
  if (!iso) return '—';
  const d = new Date(iso);
  if (isNaN(d.getTime())) return iso;
  return d.toLocaleString('ro-RO', { dateStyle: 'medium', timeStyle: 'short' });
};
const fmtDateShort = (iso) => {
  if (!iso) return '—';
  const d = new Date(iso);
  if (isNaN(d.getTime())) return iso;
  return d.toLocaleDateString('ro-RO', { dateStyle: 'medium' });
};

// ============================================================
// ROOT
// ============================================================
const AdminPage = ({ user, onNav }) => {
  const [tab, setTab] = React.useState('dashboard');

  if (!window.sb) {
    return (
      <section style={{paddingTop: 80, paddingBottom: 80}}>
        <div className="container">
          <div className="card card-pad-lg" style={{textAlign:'center'}}>
            <h2>Backend not configured</h2>
            <p style={{marginTop: 12, color: 'var(--text-mute)'}}>
              Fill in <code>config.js</code> with your Supabase URL and anon key, then reload.
            </p>
          </div>
        </div>
      </section>
    );
  }

  const tabs = [
    { id: 'dashboard',     icon: 'layout',   label: 'Dashboard' },
    { id: 'users',         icon: 'users',    label: 'Users' },
    { id: 'applications',  icon: 'mail',     label: 'Elite Applications' },
    { id: 'recordings',    icon: 'bolt',     label: 'Elite Recordings' },
    { id: 'tradingplans',  icon: 'book',     label: 'Trading Plans' },
    { id: 'consultations', icon: 'phone',    label: '1:1 Consultations' },
    { id: 'rsvps',         icon: 'check',    label: 'Live Call RSVPs' },
    { id: 'notifications', icon: 'bolt',     label: 'Notifications' },
    { id: 'settings',      icon: 'settings', label: 'Settings' },
  ];

  return (
    <section style={{paddingTop: 40, paddingBottom: 80}}>
      <div className="container">
        <div className="ap-shell">
          <aside className="ap-side">
            <div className="eyebrow"><span className="dot"/>ADMIN PANEL</div>
            <div className="ap-side-user">
              <div className="ap-side-avatar"><Icon name="user" size={16}/></div>
              <div style={{minWidth: 0}}>
                <div className="ap-side-name">{user.name || user.email}</div>
                <div className="ap-side-mail">{user.email}</div>
              </div>
            </div>
            <nav className="ap-side-nav">
              {tabs.map(t => (
                <button key={t.id}
                  className={`ap-side-btn ${tab === t.id ? 'active' : ''}`}
                  onClick={() => setTab(t.id)}>
                  <Icon name={t.icon} size={15}/>
                  <span>{t.label}</span>
                </button>
              ))}
            </nav>
            <button className="ap-side-btn ap-side-back" onClick={() => onNav('home')}>
              <Icon name="chevLeft" size={15}/><span>Back to site</span>
            </button>
          </aside>

          <div className="ap-main">
            {tab === 'dashboard'     && <AdminDashboard onJump={setTab}/>}
            {tab === 'users'         && <AdminUsers currentUser={user}/>}
            {tab === 'applications'  && <AdminApplications/>}
            {tab === 'recordings'    && <AdminRecordings/>}
            {tab === 'tradingplans'  && <AdminTradingPlans/>}
            {tab === 'consultations' && <AdminConsultations/>}
            {tab === 'rsvps'         && <AdminRsvps/>}
            {tab === 'notifications' && <AdminNotifications/>}
            {tab === 'settings'      && <AdminSettings/>}
          </div>
        </div>
      </div>
    </section>
  );
};

// ============================================================
// DASHBOARD
// ============================================================
const AdminDashboard = ({ onJump }) => {
  const [stats, setStats] = React.useState({ total: 0, free: 0, elite: 0, admin: 0, newApps: 0, unreadNotif: 0 });
  const [recentSignups, setRecentSignups] = React.useState([]);
  const [recentApps, setRecentApps] = React.useState([]);
  const [recentNotif, setRecentNotif] = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const [err, setErr] = React.useState('');

  React.useEffect(() => {
    let cancelled = false;
    (async () => {
      try {
        const sb = window.sb;
        const [profiles, apps, notifs] = await Promise.all([
          sb.from('profiles').select('id, name, email, role, elite_status, created_at').order('created_at', { ascending: false }),
          sb.from('elite_applications').select('id, name, status, created_at').order('created_at', { ascending: false }),
          sb.from('admin_notifications').select('id, type, message, status, created_at').order('created_at', { ascending: false }).limit(5),
        ]);
        if (cancelled) return;
        if (profiles.error) throw profiles.error;
        if (apps.error) throw apps.error;
        if (notifs.error) throw notifs.error;

        const all = profiles.data || [];
        const allApps = apps.data || [];
        setStats({
          total: all.length,
          free: all.filter(p => p.role === 'free').length,
          elite: all.filter(p => p.role === 'elite').length,
          admin: all.filter(p => p.role === 'admin').length,
          newApps: allApps.filter(a => a.status === 'new').length,
          unreadNotif: (notifs.data || []).filter(n => n.status === 'unread').length,
        });
        setRecentSignups(all.slice(0, 5));
        setRecentApps(allApps.slice(0, 5));
        setRecentNotif(notifs.data || []);
      } catch (e) {
        if (!cancelled) setErr(e.message || String(e));
      } finally {
        if (!cancelled) setLoading(false);
      }
    })();
    return () => { cancelled = true; };
  }, []);

  if (loading) return <div className="ap-loading">Loading dashboard…</div>;
  if (err)     return <div className="ap-error">Error: {err}</div>;

  const cards = [
    { label: 'Total Users',           value: stats.total,       color: 'acid' },
    { label: 'Free Members',          value: stats.free,        color: 'cyan' },
    { label: 'Elite Members',         value: stats.elite,       color: 'gold' },
    { label: 'New Applications',      value: stats.newApps,     color: 'blue', onClick: () => onJump('applications') },
  ];

  return (
    <>
      <div className="ap-stats">
        {cards.map(c => (
          <div key={c.label}
               className={`ap-stat card eborder ${c.color}`}
               style={{ cursor: c.onClick ? 'pointer' : 'default' }}
               onClick={c.onClick}>
            <div className="ap-stat-label">{c.label}</div>
            <div className="ap-stat-value" style={{color: `var(--${c.color})`}}>{c.value}</div>
          </div>
        ))}
      </div>

      <div className="ap-row-2">
        <div className="card card-pad-lg">
          <div className="ap-section-head">
            <h4>Recent signups</h4>
            <button className="ap-link" onClick={() => onJump('users')}>View all →</button>
          </div>
          {recentSignups.length === 0 ? (
            <div className="ap-empty">Niciun user încă.</div>
          ) : (
            <div className="col" style={{gap: 8, marginTop: 14}}>
              {recentSignups.map(u => (
                <div key={u.id} className="ap-mini-row">
                  <div style={{flex:1, minWidth: 0}}>
                    <div className="ap-mini-title">{u.name || u.email}</div>
                    <div className="ap-mini-sub">{u.email}</div>
                  </div>
                  <RoleBadge role={u.role}/>
                  <span className="ap-mini-time">{fmtDateShort(u.created_at)}</span>
                </div>
              ))}
            </div>
          )}
        </div>

        <div className="card card-pad-lg">
          <div className="ap-section-head">
            <h4>Recent Elite applications</h4>
            <button className="ap-link" onClick={() => onJump('applications')}>View all →</button>
          </div>
          {recentApps.length === 0 ? (
            <div className="ap-empty">Nicio aplicație încă.</div>
          ) : (
            <div className="col" style={{gap: 8, marginTop: 14}}>
              {recentApps.map(a => (
                <div key={a.id} className="ap-mini-row">
                  <div style={{flex:1, minWidth: 0}}>
                    <div className="ap-mini-title">{a.name}</div>
                    <div className="ap-mini-sub">{fmtDate(a.created_at)}</div>
                  </div>
                  <AppStatusBadge status={a.status}/>
                </div>
              ))}
            </div>
          )}
        </div>
      </div>

      <div className="card card-pad-lg" style={{marginTop: 20}}>
        <div className="ap-section-head">
          <h4>Recent notifications</h4>
          <button className="ap-link" onClick={() => onJump('notifications')}>View all →</button>
        </div>
        {recentNotif.length === 0 ? (
          <div className="ap-empty">Nicio notificare.</div>
        ) : (
          <div className="col" style={{gap: 8, marginTop: 14}}>
            {recentNotif.map(n => (
              <div key={n.id} className={`ap-mini-row ${n.status === 'unread' ? 'ap-mini-unread' : ''}`}>
                <NotifTypeChip type={n.type}/>
                <div style={{flex:1, minWidth: 0}}>
                  <div className="ap-mini-title">{n.message}</div>
                  <div className="ap-mini-sub">{fmtDate(n.created_at)}</div>
                </div>
              </div>
            ))}
          </div>
        )}
      </div>
    </>
  );
};

// ============================================================
// USERS
// ============================================================
const AdminUsers = ({ currentUser }) => {
  const [users, setUsers] = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const [err, setErr] = React.useState('');
  const [search, setSearch] = React.useState('');
  const [roleFilter, setRoleFilter] = React.useState('all');
  const [statusFilter, setStatusFilter] = React.useState('all');
  const [openUser, setOpenUser] = React.useState(null);
  const myId = currentUser?.id;

  const load = React.useCallback(async () => {
    setLoading(true);
    const [profilesRes, appsRes] = await Promise.all([
      window.sb
        .from('profiles')
        .select('id, name, email, role, elite_status, elite_expires_at, marketing_consent, marketing_consent_date, last_login_at, created_at')
        .order('created_at', { ascending: false }),
      window.sb
        .from('elite_applications')
        .select('user_id, phone, created_at')
        .not('user_id', 'is', null)
        .order('created_at', { ascending: false }),
    ]);
    if (profilesRes.error) { setErr(profilesRes.error.message); setLoading(false); return; }
    // Latest phone per user from elite_applications
    const phoneByUser = {};
    for (const a of (appsRes.data || [])) {
      if (!phoneByUser[a.user_id]) phoneByUser[a.user_id] = a.phone;
    }
    const merged = (profilesRes.data || []).map(u => ({ ...u, phone: phoneByUser[u.id] || null }));
    setUsers(merged);
    setLoading(false);
  }, []);

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

  const updateUserRole = async (userId, newRole) => {
    // Guard: prevent self-demotion. Losing admin via the UI permanently locks
    // you out (only a SQL update via service_role can recover).
    if (userId === myId && newRole !== 'admin') {
      const ok = window.confirm(
        'AVERTISMENT: Îți schimbi propriul rol de la "admin" la "' + newRole + '".\n\n' +
        'După confirmare nu mai ai acces la panoul Admin și nu mai poți reveni decât rulând SQL direct în Supabase Studio.\n\n' +
        'Sigur vrei să continui?'
      );
      if (!ok) return;
    }
    // When promoting to Elite, auto-activate elite_status so the user gets
    // benefits IMMEDIATELY without needing to "apply" — same for admin (treat
    // admins as having full access). Setting to 'free' resets elite_status.
    const patch = { role: newRole };
    if (newRole === 'elite') {
      patch.elite_status = 'active';
    } else if (newRole === 'free') {
      patch.elite_status = 'inactive';
      patch.elite_expires_at = null;
    }
    const { error } = await window.sb.from('profiles').update(patch).eq('id', userId);
    if (error) { setErr(error.message); return; }
    setUsers(prev => prev.map(u => u.id === userId ? { ...u, ...patch } : u));
  };

  const filtered = users.filter(u => {
    if (roleFilter !== 'all' && u.role !== roleFilter) return false;
    if (statusFilter !== 'all' && u.elite_status !== statusFilter) return false;
    if (search) {
      const q = search.toLowerCase();
      if (!(u.email || '').toLowerCase().includes(q) && !(u.name || '').toLowerCase().includes(q) && !(u.phone || '').toLowerCase().includes(q)) return false;
    }
    return true;
  });

  return (
    <>
      <div className="ap-toolbar">
        <div className="ap-search">
          <Icon name="search" size={14} style={{color: 'var(--text-mute)'}}/>
          <input className="ap-search-input" placeholder="Caută după nume, email sau telefon…"
                 value={search} onChange={e => setSearch(e.target.value)}/>
        </div>
        <div className="ap-filters">
          <label className="ap-filter-label">Rol</label>
          <select className="ap-select" value={roleFilter} onChange={e => setRoleFilter(e.target.value)}>
            <option value="all">Toate</option>
            <option value="free">Free</option>
            <option value="elite">Elite</option>
            <option value="admin">Admin</option>
          </select>
          <label className="ap-filter-label">Elite</label>
          <select className="ap-select" value={statusFilter} onChange={e => setStatusFilter(e.target.value)}>
            <option value="all">Toate</option>
            <option value="active">Active</option>
            <option value="inactive">Inactive</option>
            <option value="expired">Expired</option>
          </select>
          <button className="ap-link" onClick={load}><Icon name="refresh" size={13}/> Reload</button>
        </div>
      </div>

      {loading && <div className="ap-loading">Loading…</div>}
      {err && <div className="ap-error">{err}</div>}

      {!loading && !err && (
        <div className="ap-table-wrap">
          <table className="ap-table">
            <thead>
              <tr>
                <th>Nume</th>
                <th>Email</th>
                <th>Telefon</th>
                <th>Rol</th>
                <th>Elite status</th>
                <th>Expiră</th>
                <th>Marketing</th>
                <th>Înregistrat</th>
                <th>Last login</th>
                <th></th>
              </tr>
            </thead>
            <tbody>
              {filtered.map(u => (
                <tr key={u.id}>
                  <td>{u.name || '—'}</td>
                  <td><span className="mono ap-mono-cell">{u.email}</span></td>
                  <td>{u.phone ? <span className="mono ap-mono-cell">{u.phone}</span> : <span style={{color:'var(--text-mute)'}}>—</span>}</td>
                  <td><RoleEditor role={u.role} onChange={(r) => updateUserRole(u.id, r)}/></td>
                  <td><EliteBadge status={u.elite_status}/></td>
                  <td>{fmtDateShort(u.elite_expires_at)}</td>
                  <td>{u.marketing_consent ? 'Yes' : 'No'}</td>
                  <td>{fmtDateShort(u.created_at)}</td>
                  <td>{fmtDateShort(u.last_login_at)}</td>
                  <td>
                    <button className="ap-row-btn" onClick={() => setOpenUser(u)}>
                      <Icon name="settings" size={14}/>
                    </button>
                  </td>
                </tr>
              ))}
              {filtered.length === 0 && (
                <tr><td colSpan={10} className="ap-empty">Niciun user găsit.</td></tr>
              )}
            </tbody>
          </table>
        </div>
      )}

      {openUser && (
        <UserDetailModal user={openUser} currentUser={currentUser} onClose={() => setOpenUser(null)} onChange={() => { setOpenUser(null); load(); }}/>
      )}
    </>
  );
};

// ============================================================
// USER DETAIL MODAL
// ============================================================
const UserDetailModal = ({ user, currentUser, onClose, onChange }) => {
  const [busy, setBusy] = React.useState(false);
  const [err, setErr] = React.useState('');
  const [eliteDays, setEliteDays] = React.useState(30);
  const [noteText, setNoteText] = React.useState('');
  const [notes, setNotes] = React.useState([]);
  const [apps, setApps] = React.useState([]);
  const [confirmDelete, setConfirmDelete] = React.useState('');
  const [confirmAdmin, setConfirmAdmin] = React.useState('');
  const isSelf = currentUser?.id && user?.id === currentUser.id;

  React.useEffect(() => {
    (async () => {
      const [n, a] = await Promise.all([
        window.sb.from('admin_notes').select('*').eq('user_id', user.id).order('created_at', { ascending: false }),
        window.sb.from('elite_applications').select('*').eq('user_id', user.id).order('created_at', { ascending: false }),
      ]);
      setNotes(n.data || []);
      setApps(a.data || []);
    })();
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', onKey);
    document.body.style.overflow = 'hidden';
    return () => {
      window.removeEventListener('keydown', onKey);
      document.body.style.overflow = '';
    };
  }, [user.id, onClose]);

  const updateProfile = async (patch, notif) => {
    setBusy(true); setErr('');
    const { error } = await window.sb.from('profiles').update(patch).eq('id', user.id);
    if (!error && notif) {
      await window.sb.from('admin_notifications').insert({
        type: notif.type, message: notif.message,
        payload: { user_id: user.id, email: user.email, ...(notif.payload || {}) },
      });
    }
    setBusy(false);
    if (error) { setErr(error.message); return false; }
    onChange?.();
    return true;
  };

  const upgradeToElite = async () => {
    const expires = new Date(Date.now() + (eliteDays * 86400000)).toISOString();
    await updateProfile(
      { role: 'elite', elite_status: 'active', elite_expires_at: expires },
      { type: 'user_upgraded', message: `Upgraded to Elite: ${user.email}`, payload: { elite_expires_at: expires } }
    );
  };

  const extendElite = async () => {
    const base = user.elite_expires_at ? new Date(user.elite_expires_at) : new Date();
    const next = new Date(Math.max(base.getTime(), Date.now()) + eliteDays * 86400000).toISOString();
    await updateProfile({ elite_status: 'active', elite_expires_at: next });
  };

  const removeElite = async () => {
    if (isSelf && user.role === 'admin') {
      const ok = window.confirm(
        'AVERTISMENT: Această acțiune îți schimbă propriul rol din "admin" în "free".\n\n' +
        'După confirmare nu mai ai acces la panoul Admin și nu mai poți reveni decât rulând SQL în Supabase Studio.\n\n' +
        'Sigur vrei să continui?'
      );
      if (!ok) return;
    }
    await updateProfile({ role: 'free', elite_status: 'inactive', elite_expires_at: null });
  };

  const setRole = async (role) => {
    if (isSelf && user.role === 'admin' && role !== 'admin') {
      const ok = window.confirm(
        'AVERTISMENT: Îți schimbi propriul rol de la "admin" la "' + role + '".\n\n' +
        'După confirmare nu mai ai acces la panoul Admin și nu mai poți reveni decât rulând SQL în Supabase Studio.\n\n' +
        'Sigur vrei să continui?'
      );
      if (!ok) return;
    }
    await updateProfile({ role });
  };

  const makeAdmin = async () => {
    if (confirmAdmin !== user.email) { setErr('Confirmă tastând email-ul utilizatorului.'); return; }
    await updateProfile({ role: 'admin' });
  };

  const deleteUser = async () => {
    if (isSelf) { setErr('Nu îți poți șterge propriul cont din panoul Admin.'); return; }
    if (confirmDelete !== user.email) { setErr('Confirmă tastând email-ul utilizatorului.'); return; }
    setBusy(true); setErr('');
    // Deleting from auth.users requires the service role; from the browser we can
    // only delete the public.profiles row. The auth row would remain orphaned —
    // for a small-scale workflow this is acceptable; document the limitation.
    const { error } = await window.sb.from('profiles').delete().eq('id', user.id);
    setBusy(false);
    if (error) { setErr(error.message); return; }
    onChange?.();
  };

  const addNote = async () => {
    if (!noteText.trim()) return;
    setBusy(true); setErr('');
    const { data, error } = await window.sb
      .from('admin_notes')
      .insert({ user_id: user.id, note: noteText.trim() })
      .select()
      .single();
    setBusy(false);
    if (error) { setErr(error.message); return; }
    setNotes([data, ...notes]);
    setNoteText('');
  };

  return (
    <div className="auth-overlay" onClick={onClose}>
      <div className="ap-modal" onClick={(e) => e.stopPropagation()}>
        <button className="auth-close" onClick={onClose} aria-label="Close"><Icon name="x" size={18}/></button>

        <div className="ap-modal-head">
          <div className="ap-side-avatar" style={{width: 44, height: 44}}><Icon name="user" size={18}/></div>
          <div style={{flex: 1, minWidth: 0}}>
            <h3 style={{margin: 0}}>{user.name || user.email}{isSelf && <span style={{ marginLeft: 10, fontSize: 11, padding: '3px 8px', borderRadius: 999, background: 'rgba(183,255,26,0.10)', border: '1px solid rgba(183,255,26,0.30)', color: 'var(--acid)', letterSpacing: '0.12em', textTransform: 'uppercase', fontFamily: "'JetBrains Mono', monospace" }}>You</span>}</h3>
            <div style={{fontSize: 13, color: 'var(--text-mute)'}} className="mono">{user.email}</div>
          </div>
          <RoleBadge role={user.role}/>
        </div>
        {isSelf && (
          <div style={{
            margin: '0 0 18px',
            padding: '10px 14px',
            borderRadius: 10,
            background: 'rgba(255, 203, 82, 0.08)',
            border: '1px solid rgba(255, 203, 82, 0.28)',
            color: 'var(--gold, #FFCB52)',
            fontSize: 13,
            display: 'flex',
            alignItems: 'center',
            gap: 10,
          }}>
            <Icon name="bolt" size={14} />
            <span>Editezi propriul cont. Schimbările de rol care îți pierd accesul admin sunt blocate cu confirmare.</span>
          </div>
        )}

        <div className="ap-modal-grid">
          <div className="ap-modal-col">
            <div className="card card-pad-lg">
              <h4>Detalii</h4>
              <div className="ap-kv">
                <div><span>Înregistrat</span><b>{fmtDate(user.created_at)}</b></div>
                <div><span>Last login</span><b>{fmtDate(user.last_login_at)}</b></div>
                <div><span>Elite status</span><b><EliteBadge status={user.elite_status}/></b></div>
                <div><span>Elite expiră</span><b>{fmtDateShort(user.elite_expires_at)}</b></div>
                <div><span>Marketing consent</span><b>{user.marketing_consent ? 'Yes' : 'No'}</b></div>
              </div>
            </div>

            <div className="card card-pad-lg" style={{marginTop: 14}}>
              <h4>Aplicație Elite</h4>
              {apps.length === 0 ? (
                <div className="ap-empty">Nicio aplicație.</div>
              ) : (
                apps.map(a => (
                  <div key={a.id} className="ap-kv" style={{marginTop: 10}}>
                    <div><span>Telefon</span><b className="mono">{a.phone}</b></div>
                    <div><span>Experiență</span><b style={{whiteSpace: 'pre-wrap'}}>{a.trading_experience}</b></div>
                    <div><span>Status</span><b><AppStatusBadge status={a.status}/></b></div>
                    <div><span>Trimisă</span><b>{fmtDate(a.created_at)}</b></div>
                  </div>
                ))
              )}
            </div>

            <div className="card card-pad-lg" style={{marginTop: 14}}>
              <h4>Note interne</h4>
              <div style={{marginTop: 10}}>
                <textarea className="textarea" value={noteText}
                          onChange={e => setNoteText(e.target.value)}
                          placeholder="Notează ceva pentru viitorul tine…"
                          style={{minHeight: 70}}/>
                <Button variant="acid" size="sm" onClick={addNote}
                        className="mt-2"
                        style={{opacity: noteText.trim() && !busy ? 1 : 0.5}}
                        disabled={!noteText.trim() || busy}>
                  Add note
                </Button>
              </div>
              <div className="col" style={{gap: 8, marginTop: 14}}>
                {notes.map(n => (
                  <div key={n.id} className="ap-note">
                    <div className="ap-note-text">{n.note}</div>
                    <div className="ap-note-date">{fmtDate(n.created_at)}</div>
                  </div>
                ))}
                {notes.length === 0 && <div className="ap-empty">Nicio notiță.</div>}
              </div>
            </div>
          </div>

          <div className="ap-modal-col">
            <div className="card card-pad-lg">
              <h4>Acțiuni rapide</h4>
              <div className="col" style={{gap: 10, marginTop: 14}}>
                <div className="ap-action-row">
                  <div className="label" style={{margin: 0}}>Schimbă rol</div>
                  <div className="row" style={{gap: 6}}>
                    {ROLE_OPTIONS.filter(r => r !== 'admin').map(r => (
                      <button key={r}
                              className={`ap-pill ${user.role === r ? 'active' : ''}`}
                              onClick={() => setRole(r)} disabled={busy || user.role === r}>
                        {r}
                      </button>
                    ))}
                  </div>
                </div>
              </div>
            </div>

            <div className="card card-pad-lg eborder gold" style={{marginTop: 14}}>
              <h4>Elite</h4>
              <div className="label mt-3">Durată acces (zile)</div>
              <div className="row" style={{gap: 8}}>
                {[30, 60, 90, 180, 365].map(d => (
                  <button key={d}
                          className={`ap-pill ${eliteDays === d ? 'active' : ''}`}
                          onClick={() => setEliteDays(d)}>{d}d</button>
                ))}
                <input className="input ap-days-input" type="number" min="1"
                       value={eliteDays}
                       onChange={e => setEliteDays(parseInt(e.target.value || '0', 10) || 1)}/>
              </div>
              <div className="row" style={{gap: 8, marginTop: 14, flexWrap: 'wrap'}}>
                <Button variant="acid" size="sm" onClick={upgradeToElite} disabled={busy}>
                  Upgrade to Elite
                </Button>
                <Button variant="ghost" size="sm" onClick={extendElite}
                        disabled={busy || user.role !== 'elite'}>
                  Extend access
                </Button>
                <Button variant="ghost" size="sm" onClick={removeElite}
                        disabled={busy || user.role !== 'elite'}>
                  Remove Elite
                </Button>
              </div>
            </div>

            <div className="card card-pad-lg" style={{marginTop: 14}}>
              <h4>Make admin</h4>
              <p className="ap-help">Confirmă tastând email-ul utilizatorului.</p>
              <input className="input mt-2" placeholder={user.email}
                     value={confirmAdmin} onChange={e => setConfirmAdmin(e.target.value)}/>
              <Button variant="ghost" size="sm" className="mt-2"
                      onClick={makeAdmin} disabled={busy || confirmAdmin !== user.email}>
                Make admin
              </Button>
            </div>

            <div className="card card-pad-lg eborder rose" style={{marginTop: 14}}>
              <h4 style={{color: '#FF8585'}}>Șterge profil</h4>
              <p className="ap-help">
                Șterge rândul din public.profiles. Notă: contul auth rămâne; folosește dashboard-ul Supabase pentru ștergere completă.
              </p>
              <input className="input mt-2" placeholder={user.email}
                     value={confirmDelete} onChange={e => setConfirmDelete(e.target.value)}/>
              <Button variant="ghost" size="sm" className="mt-2"
                      onClick={deleteUser} disabled={busy || confirmDelete !== user.email}>
                Șterge
              </Button>
            </div>

            {err && <div className="auth-error" style={{marginTop: 14}}>{err}</div>}
          </div>
        </div>
      </div>
    </div>
  );
};

// ============================================================
// APPLICATIONS
// ============================================================
const AdminApplications = () => {
  const [apps, setApps] = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const [err, setErr] = React.useState('');
  const [search, setSearch] = React.useState('');
  const [statusFilter, setStatusFilter] = React.useState('all');
  const [open, setOpen] = React.useState(null);

  const load = React.useCallback(async () => {
    setLoading(true);
    const { data, error } = await window.sb
      .from('elite_applications')
      .select('*')
      .order('created_at', { ascending: false });
    if (error) setErr(error.message);
    else setApps(data || []);
    setLoading(false);
  }, []);

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

  // Resolve linked emails for apps with user_id
  const [emails, setEmails] = React.useState({});
  React.useEffect(() => {
    const ids = [...new Set(apps.filter(a => a.user_id).map(a => a.user_id))];
    if (ids.length === 0) return;
    (async () => {
      const { data } = await window.sb.from('profiles').select('id, email').in('id', ids);
      const map = {};
      (data || []).forEach(p => { map[p.id] = p.email; });
      setEmails(map);
    })();
  }, [apps]);

  const filtered = apps.filter(a => {
    if (statusFilter !== 'all' && a.status !== statusFilter) return false;
    if (search) {
      const q = search.toLowerCase();
      if (!a.name.toLowerCase().includes(q) && !a.phone.includes(q)) return false;
    }
    return true;
  });

  return (
    <>
      <div className="ap-toolbar">
        <div className="ap-search">
          <Icon name="search" size={14} style={{color: 'var(--text-mute)'}}/>
          <input className="ap-search-input" placeholder="Caută după nume sau telefon…"
                 value={search} onChange={e => setSearch(e.target.value)}/>
        </div>
        <div className="ap-filters">
          <label className="ap-filter-label">Status</label>
          <select className="ap-select" value={statusFilter} onChange={e => setStatusFilter(e.target.value)}>
            <option value="all">Toate</option>
            {APP_STATUS_OPTIONS.map(s => <option key={s} value={s}>{s}</option>)}
          </select>
          <button className="ap-link" onClick={load}><Icon name="refresh" size={13}/> Reload</button>
        </div>
      </div>

      {loading && <div className="ap-loading">Loading…</div>}
      {err && <div className="ap-error">{err}</div>}

      {!loading && !err && (
        <div className="ap-table-wrap">
          <table className="ap-table">
            <thead>
              <tr>
                <th>Nume</th>
                <th>Telefon</th>
                <th>Email (account)</th>
                <th>Trimisă</th>
                <th>Status</th>
                <th></th>
              </tr>
            </thead>
            <tbody>
              {filtered.map(a => (
                <tr key={a.id}>
                  <td>{a.name}</td>
                  <td><span className="mono ap-mono-cell">{a.phone}</span></td>
                  <td><span className="mono ap-mono-cell">{a.user_id ? (emails[a.user_id] || '…') : '— anon'}</span></td>
                  <td>{fmtDate(a.created_at)}</td>
                  <td><AppStatusBadge status={a.status}/></td>
                  <td>
                    <button className="ap-row-btn" onClick={() => setOpen(a)}>
                      <Icon name="chevRight" size={14}/>
                    </button>
                  </td>
                </tr>
              ))}
              {filtered.length === 0 && (
                <tr><td colSpan={6} className="ap-empty">Nicio aplicație.</td></tr>
              )}
            </tbody>
          </table>
        </div>
      )}

      {open && (
        <ApplicationDetailModal app={open} linkedEmail={open.user_id ? emails[open.user_id] : null}
                                onClose={() => setOpen(null)}
                                onChange={() => { setOpen(null); load(); }}/>
      )}
    </>
  );
};

// ============================================================
// APPLICATION DETAIL
// ============================================================
const ApplicationDetailModal = ({ app, linkedEmail, onClose, onChange }) => {
  const [busy, setBusy] = React.useState(false);
  const [err, setErr] = React.useState('');
  const [note, setNote] = React.useState(app.internal_note || '');
  const [eliteDays, setEliteDays] = React.useState(30);

  React.useEffect(() => {
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', onKey);
    document.body.style.overflow = 'hidden';
    return () => {
      window.removeEventListener('keydown', onKey);
      document.body.style.overflow = '';
    };
  }, [onClose]);

  const updateStatus = async (status) => {
    setBusy(true); setErr('');
    const { error } = await window.sb.from('elite_applications').update({ status }).eq('id', app.id);
    setBusy(false);
    if (error) { setErr(error.message); return; }
    onChange?.();
  };

  const saveNote = async () => {
    setBusy(true); setErr('');
    const { error } = await window.sb.from('elite_applications').update({ internal_note: note }).eq('id', app.id);
    setBusy(false);
    if (error) { setErr(error.message); return; }
  };

  const upgradeLinkedToElite = async () => {
    if (!app.user_id) return;
    setBusy(true); setErr('');
    const expires = new Date(Date.now() + eliteDays * 86400000).toISOString();
    const { error: e1 } = await window.sb.from('profiles').update({
      role: 'elite', elite_status: 'active', elite_expires_at: expires,
    }).eq('id', app.user_id);
    if (e1) { setBusy(false); setErr(e1.message); return; }
    const { error: e2 } = await window.sb.from('elite_applications').update({ status: 'accepted' }).eq('id', app.id);
    await window.sb.from('admin_notifications').insert({
      type: 'user_upgraded',
      message: `Upgraded to Elite: ${linkedEmail || app.name}`,
      payload: { user_id: app.user_id, application_id: app.id, elite_expires_at: expires },
    });
    setBusy(false);
    if (e2) { setErr(e2.message); return; }
    onChange?.();
  };

  return (
    <div className="auth-overlay" onClick={onClose}>
      <div className="ap-modal ap-modal-md" onClick={(e) => e.stopPropagation()}>
        <button className="auth-close" onClick={onClose} aria-label="Close"><Icon name="x" size={18}/></button>

        <div className="ap-modal-head">
          <IconChip icon="mail" color="gold"/>
          <div style={{flex: 1, minWidth: 0}}>
            <h3 style={{margin: 0}}>{app.name}</h3>
            <div style={{fontSize: 13, color: 'var(--text-mute)'}}>{fmtDate(app.created_at)}</div>
          </div>
          <AppStatusBadge status={app.status}/>
        </div>

        <div style={{padding: '0 28px 28px'}}>
          <div className="ap-kv">
            <div><span>Telefon</span><b className="mono">{app.phone}</b></div>
            <div><span>Experiență</span><b style={{whiteSpace: 'pre-wrap'}}>{app.trading_experience}</b></div>
            <div><span>Account email</span><b className="mono">{linkedEmail || '— anonymous —'}</b></div>
          </div>

          <h4 style={{marginTop: 22}}>Schimbă status</h4>
          <div className="row" style={{gap: 8, marginTop: 10, flexWrap: 'wrap'}}>
            {APP_STATUS_OPTIONS.map(s => (
              <button key={s} className={`ap-pill ${app.status === s ? 'active' : ''}`}
                      onClick={() => updateStatus(s)} disabled={busy || app.status === s}>
                {s}
              </button>
            ))}
          </div>

          {app.user_id && (
            <>
              <h4 style={{marginTop: 22}}>Upgrade contul la Elite</h4>
              <div className="row" style={{gap: 8, marginTop: 10}}>
                {[30, 60, 90, 180, 365].map(d => (
                  <button key={d} className={`ap-pill ${eliteDays === d ? 'active' : ''}`}
                          onClick={() => setEliteDays(d)}>{d}d</button>
                ))}
              </div>
              <Button variant="acid" size="sm" className="mt-2" onClick={upgradeLinkedToElite} disabled={busy}>
                Upgrade to Elite ({eliteDays} zile)
              </Button>
            </>
          )}

          <h4 style={{marginTop: 22}}>Notă internă</h4>
          <textarea className="textarea mt-2" value={note}
                    onChange={e => setNote(e.target.value)}
                    placeholder="Notează pentru viitorul tine…" style={{minHeight: 80}}/>
          <Button variant="ghost" size="sm" className="mt-2" onClick={saveNote} disabled={busy}>
            Salvează nota
          </Button>

          {err && <div className="auth-error" style={{marginTop: 14}}>{err}</div>}
        </div>
      </div>
    </div>
  );
};

// ============================================================
// NOTIFICATIONS
// ============================================================
// ============================================================
// ADMIN: TRADING PLANS — review, give corrections, approve.
// ============================================================
const ATP_STATUS = {
  draft:          { label: 'CIORNĂ',    color: 'cyan'  },
  pending_review: { label: 'IN REVIEW', color: 'gold'  },
  corrections:    { label: 'CORECTĂRI', color: 'rose'  },
  approved:       { label: 'APROBAT',   color: 'acid'  },
};

const AdminTradingPlans = () => {
  const [plans, setPlans] = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const [err, setErr]   = React.useState('');
  const [msg, setMsg]   = React.useState('');
  const [openPlanId, setOpenPlanId] = React.useState(null);
  const [filter, setFilter] = React.useState('all');

  const load = React.useCallback(async () => {
    setLoading(true);
    const { data: tp, error } = await window.sb
      .from('trading_plans')
      .select('*')
      .order('updated_at', { ascending: false });
    if (error) { setErr(error.message); setLoading(false); return; }
    // Hydrate with user info via a single profiles query
    const userIds = (tp || []).map(p => p.user_id);
    if (userIds.length > 0) {
      const { data: profs } = await window.sb
        .from('profiles')
        .select('id, name, email, role, elite_status')
        .in('id', userIds);
      const byId = Object.fromEntries((profs || []).map(p => [p.id, p]));
      setPlans((tp || []).map(p => ({ ...p, profile: byId[p.user_id] || null })));
    } else {
      setPlans([]);
    }
    setLoading(false);
  }, []);

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

  const filtered = plans.filter(p => filter === 'all' || p.status === filter);

  const flash = (m) => { setMsg(m); setTimeout(() => setMsg(''), 2400); };

  return (
    <div>
      <div className="ap-head">
        <h2>Trading Plans</h2>
        <p>Revizuiește planurile membrilor Elite. Lasă feedback la "Corecturi" sau aprobă-le direct.</p>
      </div>

      <div className="atp-toolbar">
        <div className="ap-filters">
          <label className="ap-filter-label">Status</label>
          <select className="ap-select" value={filter} onChange={(e) => setFilter(e.target.value)}>
            <option value="all">Toate ({plans.length})</option>
            <option value="draft">Ciornă ({plans.filter(p => p.status === 'draft').length})</option>
            <option value="pending_review">In review ({plans.filter(p => p.status === 'pending_review').length})</option>
            <option value="corrections">Corecturi ({plans.filter(p => p.status === 'corrections').length})</option>
            <option value="approved">Aprobat ({plans.filter(p => p.status === 'approved').length})</option>
          </select>
          <button className="ap-link" onClick={load}><Icon name="refresh" size={13}/> Reload</button>
        </div>
        {msg && <div className="atp-ok">{msg}</div>}
      </div>

      {loading && <div className="ap-loading">Loading…</div>}
      {err && <div className="ap-error">{err}</div>}

      {!loading && !err && (
        <div className="atp-list">
          {filtered.length === 0 ? (
            <div className="atp-empty">Niciun plan în această categorie.</div>
          ) : filtered.map(p => {
            const s = ATP_STATUS[p.status] || ATP_STATUS.draft;
            return (
              <div key={p.id} className="atp-row">
                <div className="atp-row-head">
                  <div className="atp-row-user">
                    <div className="atp-row-avatar"><Icon name="user" size={14}/></div>
                    <div style={{minWidth:0}}>
                      <div className="atp-row-name">{p.profile?.name || p.profile?.email?.split('@')[0] || '—'}</div>
                      <div className="atp-row-email mono">{p.profile?.email || p.user_id}</div>
                    </div>
                  </div>
                  <div className="atp-row-meta">
                    <span className={`tag ${s.color}`}>{s.label}</span>
                    <span className="atp-row-date mono">{new Date(p.updated_at).toLocaleString('ro-RO')}</span>
                    <button className="ap-row-btn" onClick={() => setOpenPlanId(p.id)} title="Open">
                      <Icon name="settings" size={14}/>
                    </button>
                  </div>
                </div>
              </div>
            );
          })}
        </div>
      )}

      {openPlanId && (
        <AdminTradingPlanModal
          plan={plans.find(x => x.id === openPlanId)}
          onClose={() => setOpenPlanId(null)}
          onSaved={() => { load(); flash('Salvat.'); }}
        />
      )}

      <style>{`
        .atp-toolbar {
          display: flex; justify-content: space-between; align-items: center;
          gap: 12px; flex-wrap: wrap;
          margin-bottom: 14px;
        }
        .atp-ok {
          padding: 8px 14px;
          border-radius: 10px;
          background: rgba(183,255,26,0.08);
          border: 1px solid rgba(183,255,26,0.32);
          color: var(--acid);
          font-size: 13px;
        }
        .atp-list { display: grid; gap: 8px; }
        .atp-empty {
          padding: 24px;
          text-align: center;
          color: var(--text-mute);
          border: 1px dashed rgba(255,255,255,0.10);
          border-radius: 12px;
          background: rgba(255,255,255,0.02);
        }
        .atp-row {
          padding: 14px 16px;
          border-radius: 12px;
          background: rgba(255,255,255,0.025);
          border: 1px solid rgba(255,255,255,0.08);
          transition: background 0.2s, border-color 0.2s;
        }
        .atp-row:hover { background: rgba(255,255,255,0.04); border-color: rgba(255,255,255,0.14); }
        .atp-row-head {
          display: flex; justify-content: space-between; align-items: center;
          gap: 14px; flex-wrap: wrap;
        }
        .atp-row-user { display: flex; align-items: center; gap: 12px; min-width: 0; }
        .atp-row-avatar {
          width: 34px; height: 34px; border-radius: 50%;
          background: rgba(183,255,26,0.10);
          color: var(--acid);
          display: grid; place-items: center; flex-shrink: 0;
        }
        .atp-row-name { font-weight: 600; font-size: 14px; }
        .atp-row-email { font-size: 11.5px; color: var(--text-mute); }
        .atp-row-meta { display: flex; align-items: center; gap: 12px; }
        .atp-row-date { font-size: 11px; color: var(--text-mute); }
      `}</style>
    </div>
  );
};

// Modal for reviewing & editing a single plan
const AdminTradingPlanModal = ({ plan, onClose, onSaved }) => {
  const [feedback, setFeedback] = React.useState(plan?.tyrone_feedback || '');
  const [busy, setBusy] = React.useState(false);
  const [err, setErr]   = React.useState('');

  React.useEffect(() => {
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', onKey);
    document.body.style.overflow = 'hidden';
    return () => {
      window.removeEventListener('keydown', onKey);
      document.body.style.overflow = '';
    };
  }, [onClose]);

  if (!plan) return null;

  const updatePlan = async (patch) => {
    setBusy(true); setErr('');
    const { error } = await window.sb
      .from('trading_plans')
      .update(patch)
      .eq('id', plan.id);
    setBusy(false);
    if (error) { setErr(error.message); return false; }
    onSaved?.();
    return true;
  };

  const saveCorrections = async () => {
    const ok = await updatePlan({
      tyrone_feedback: feedback.trim() || null,
      feedback_at: new Date().toISOString(),
      status: 'corrections',
    });
    if (ok) onClose();
  };

  const markPendingReview = async () => {
    const ok = await updatePlan({ status: 'pending_review' });
    if (ok) onClose();
  };

  const approve = async () => {
    const ok = await updatePlan({
      status: 'approved',
      approved_at: new Date().toISOString(),
      tyrone_feedback: feedback.trim() || plan.tyrone_feedback || null,
      feedback_at: feedback.trim() ? new Date().toISOString() : plan.feedback_at,
    });
    if (ok) onClose();
  };

  const currentStatus = ATP_STATUS[plan.status] || ATP_STATUS.draft;

  return (
    <div className="auth-overlay" onClick={onClose}>
      <div className="ap-modal atp-modal" onClick={(e) => e.stopPropagation()}>
        <button className="auth-close" onClick={onClose} aria-label="Close"><Icon name="x" size={18}/></button>

        <div className="ap-modal-head">
          <div className="ap-side-avatar" style={{width: 44, height: 44}}><Icon name="user" size={18}/></div>
          <div style={{flex: 1, minWidth: 0}}>
            <h3 style={{margin: 0}}>{plan.profile?.name || '—'}</h3>
            <div style={{fontSize: 13, color: 'var(--text-mute)'}} className="mono">{plan.profile?.email}</div>
          </div>
          <span className={`tag ${currentStatus.color}`}>{currentStatus.label}</span>
        </div>

        <div className="atp-modal-grid">
          <div className="atp-modal-col">
            <h4>Planul scris de membru</h4>
            <div className="atp-plan-text">{plan.plan_text || <em style={{color:'var(--text-mute)'}}>(gol)</em>}</div>
            <div className="atp-meta-row">
              <span>Creat: {new Date(plan.created_at).toLocaleString('ro-RO')}</span>
              <span>Ultima salvare: {new Date(plan.updated_at).toLocaleString('ro-RO')}</span>
            </div>
          </div>

          <div className="atp-modal-col">
            <h4>Corecturile tale</h4>
            <textarea
              className="atp-feedback-input"
              rows={12}
              placeholder="Ex: 1) Riscul de 1% e prea mare pentru un cont 50K — coboară la 0.5%.&#10;2) Sesiunea aleasă e bună, dar adaugă o regulă de daily loss.&#10;3) Lipsește planul de payout — adaugă-l."
              value={feedback}
              onChange={(e) => setFeedback(e.target.value)}
            />
            {err && <div className="ap-error" style={{marginTop:10}}>{err}</div>}

            <div className="atp-modal-actions">
              <Button variant="ghost" onClick={saveCorrections} disabled={busy || !feedback.trim()}>
                {busy ? 'Salvează…' : 'Salvează corecturi'}
              </Button>
              <Button variant="acid" onClick={approve} disabled={busy}>
                Aprobă plan ✓
              </Button>
            </div>
            <button
              type="button"
              className="atp-status-btn"
              onClick={markPendingReview}
              disabled={busy || plan.status === 'pending_review'}>
              Marchează „In Review"
            </button>
          </div>
        </div>

        <style>{`
          .atp-modal {
            max-width: 1100px;
          }
          .atp-modal-grid {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 24px;
            margin-top: 12px;
          }
          @media (max-width: 880px) {
            .atp-modal-grid { grid-template-columns: 1fr; }
          }
          .atp-modal-col h4 {
            margin: 0 0 12px;
            font-size: 14px;
            color: var(--text-dim);
          }
          .atp-plan-text {
            padding: 16px 18px;
            background: rgba(0,0,0,0.35);
            border: 1px solid rgba(255,255,255,0.08);
            border-radius: 12px;
            font-size: 13.5px;
            line-height: 1.65;
            white-space: pre-wrap;
            max-height: 360px;
            overflow-y: auto;
            color: var(--text);
          }
          .atp-meta-row {
            margin-top: 10px;
            display: flex; flex-direction: column; gap: 4px;
            font-family: 'JetBrains Mono', monospace;
            font-size: 11px;
            color: var(--text-mute);
          }
          .atp-feedback-input {
            width: 100%;
            padding: 14px 16px;
            background: rgba(0,0,0,0.35);
            border: 1px solid rgba(255,255,255,0.08);
            border-radius: 12px;
            color: var(--text);
            font: inherit; font-size: 13.5px;
            line-height: 1.6;
            resize: vertical;
            outline: none;
            transition: border-color 0.2s, background 0.2s;
          }
          .atp-feedback-input:focus {
            border-color: rgba(244,63,94,0.40);
            background: rgba(0,0,0,0.45);
          }
          .atp-modal-actions {
            margin-top: 14px;
            display: flex; gap: 10px; flex-wrap: wrap;
          }
          .atp-status-btn {
            margin-top: 10px;
            padding: 8px 14px;
            background: transparent;
            border: 1px dashed rgba(255,255,255,0.16);
            color: var(--text-mute);
            font: inherit; font-size: 12px;
            border-radius: 10px;
            cursor: pointer;
            transition: border-color 0.2s, color 0.2s;
          }
          .atp-status-btn:hover:not(:disabled) {
            border-color: rgba(255,203,82,0.45);
            color: var(--gold, #FFCB52);
          }
          .atp-status-btn:disabled { opacity: 0.4; cursor: not-allowed; }
        `}</style>
      </div>
    </div>
  );
};

// ============================================================
// ADMIN: 1:1 CONSULTATIONS — phone requests from Elite members.
// ============================================================
const AC_STATUS = {
  requested: { label: 'NEW',       color: 'gold'  },
  confirmed: { label: 'CONFIRMED', color: 'cyan'  },
  done:      { label: 'DONE',      color: 'acid'  },
  cancelled: { label: 'CANCELLED', color: 'rose'  },
};

const AdminConsultations = () => {
  const [items, setItems]   = React.useState([]);
  const [loading, setLoad]  = React.useState(true);
  const [err, setErr]       = React.useState('');
  const [filter, setFilter] = React.useState('all');
  const [openId, setOpenId] = React.useState(null);

  const load = React.useCallback(async () => {
    setLoad(true);
    const { data: reqs, error } = await window.sb
      .from('consultation_requests')
      .select('*')
      .order('created_at', { ascending: false });
    if (error) { setErr(error.message); setLoad(false); return; }
    const ids = [...new Set((reqs || []).map(r => r.user_id))];
    let profMap = {};
    if (ids.length) {
      const { data: profs } = await window.sb
        .from('profiles').select('id, name, email, role').in('id', ids);
      profMap = Object.fromEntries((profs || []).map(p => [p.id, p]));
    }
    setItems((reqs || []).map(r => ({ ...r, profile: profMap[r.user_id] || null })));
    setLoad(false);
  }, []);

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

  const setStatus = async (id, status) => {
    const { error } = await window.sb.from('consultation_requests').update({ status }).eq('id', id);
    if (error) { setErr(error.message); return; }
    load();
  };

  const filtered = items.filter(r => filter === 'all' || r.status === filter);

  return (
    <div>
      <div className="ap-head">
        <h2>1:1 Consultations</h2>
        <p>Cereri de call privat de la membrii Elite. Marchează confirmed când stabilești ora, done după call.</p>
      </div>

      <div className="atp-toolbar">
        <div className="ap-filters">
          <label className="ap-filter-label">Status</label>
          <select className="ap-select" value={filter} onChange={(e) => setFilter(e.target.value)}>
            <option value="all">Toate ({items.length})</option>
            <option value="requested">New ({items.filter(r => r.status === 'requested').length})</option>
            <option value="confirmed">Confirmed ({items.filter(r => r.status === 'confirmed').length})</option>
            <option value="done">Done ({items.filter(r => r.status === 'done').length})</option>
            <option value="cancelled">Cancelled ({items.filter(r => r.status === 'cancelled').length})</option>
          </select>
          <button className="ap-link" onClick={load}><Icon name="refresh" size={13}/> Reload</button>
        </div>
      </div>

      {loading && <div className="ap-loading">Loading…</div>}
      {err && <div className="ap-error">{err}</div>}

      {!loading && !err && (
        <div className="atp-list">
          {filtered.length === 0 ? (
            <div className="atp-empty">Nicio cerere în această categorie.</div>
          ) : filtered.map(r => {
            const s = AC_STATUS[r.status] || AC_STATUS.requested;
            const isOpen = openId === r.id;
            return (
              <div key={r.id} className="atp-row">
                <div className="atp-row-head" style={{cursor:'pointer'}} onClick={() => setOpenId(isOpen ? null : r.id)}>
                  <div className="atp-row-user">
                    <div className="atp-row-avatar"><Icon name="phone" size={14}/></div>
                    <div style={{minWidth:0}}>
                      <div className="atp-row-name">{r.profile?.name || r.profile?.email?.split('@')[0] || '—'}</div>
                      <div className="atp-row-email mono">
                        <a href={`tel:${r.phone}`} onClick={(e) => e.stopPropagation()} style={{color:'var(--acid)'}}>{r.phone}</a>
                        {' · '}{r.profile?.email}
                      </div>
                    </div>
                  </div>
                  <div className="atp-row-meta">
                    <span className={`tag ${s.color}`}>{s.label}</span>
                    <span className="atp-row-date mono">{new Date(r.created_at).toLocaleString('ro-RO')}</span>
                    <Icon name={isOpen ? 'chevDown' : 'chevRight'} size={14}/>
                  </div>
                </div>
                {isOpen && (
                  <div style={{marginTop:14, paddingTop:14, borderTop:'1px dashed rgba(255,255,255,0.08)'}}>
                    <div style={{fontFamily:"'JetBrains Mono', monospace", fontSize:10.5, letterSpacing:'0.14em', color:'var(--text-mute)', textTransform:'uppercase', marginBottom:8}}>
                      Întrebări (snapshot la momentul cererii)
                    </div>
                    <div style={{
                      padding: '14px 16px',
                      background: 'rgba(0,0,0,0.35)',
                      border: '1px solid rgba(255,255,255,0.08)',
                      borderRadius: 10,
                      fontSize: 13,
                      lineHeight: 1.6,
                      whiteSpace: 'pre-wrap',
                      maxHeight: 280,
                      overflowY: 'auto',
                    }}>{r.questions_snapshot || <em style={{color:'var(--text-mute)'}}>(gol)</em>}</div>

                    <div style={{marginTop:14, display:'flex', gap:8, flexWrap:'wrap'}}>
                      {r.status === 'requested' && (
                        <Button variant="acid" size="sm" onClick={() => setStatus(r.id, 'confirmed')}>Confirm</Button>
                      )}
                      {r.status === 'confirmed' && (
                        <Button variant="acid" size="sm" onClick={() => setStatus(r.id, 'done')}>Mark done</Button>
                      )}
                      {r.status !== 'cancelled' && r.status !== 'done' && (
                        <Button variant="ghost" size="sm" onClick={() => setStatus(r.id, 'cancelled')}>Cancel</Button>
                      )}
                      {r.status === 'done' && (
                        <span style={{padding:'8px 14px', fontSize:12, color:'var(--text-mute)'}}>Call complet.</span>
                      )}
                    </div>
                  </div>
                )}
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
};

// ============================================================
// ADMIN: LIVE CALL RSVPs — see who responded for each Friday call.
// ============================================================
const AdminRsvps = () => {
  const [items, setItems] = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const [err, setErr] = React.useState('');
  const [eventFilter, setEventFilter] = React.useState('');

  const load = React.useCallback(async () => {
    setLoading(true);
    const { data: rsvps, error } = await window.sb
      .from('live_rsvp')
      .select('*')
      .order('responded_at', { ascending: false });
    if (error) { setErr(error.message); setLoading(false); return; }
    const ids = [...new Set((rsvps || []).map(r => r.user_id))];
    let profMap = {};
    if (ids.length) {
      const { data: profs } = await window.sb
        .from('profiles').select('id, name, email, role').in('id', ids);
      profMap = Object.fromEntries((profs || []).map(p => [p.id, p]));
    }
    setItems((rsvps || []).map(r => ({ ...r, profile: profMap[r.user_id] || null })));
    setLoading(false);
  }, []);

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

  // Build list of unique events with counts
  const events = React.useMemo(() => {
    const map = new Map();
    for (const r of items) {
      if (!map.has(r.event_key)) map.set(r.event_key, { key: r.event_key, present: 0, absent: 0 });
      const e = map.get(r.event_key);
      if (r.status === 'present') e.present++;
      else if (r.status === 'absent') e.absent++;
    }
    return Array.from(map.values()).sort((a, b) => b.key.localeCompare(a.key));
  }, [items]);

  // Auto-select most recent event if nothing selected
  React.useEffect(() => {
    if (!eventFilter && events.length > 0) setEventFilter(events[0].key);
  }, [events, eventFilter]);

  const filtered = items.filter(r => !eventFilter || r.event_key === eventFilter);
  const presentCount = filtered.filter(r => r.status === 'present').length;
  const absentCount  = filtered.filter(r => r.status === 'absent').length;
  const formatDate = (key) => {
    try {
      const d = new Date(key);
      return d.toLocaleDateString('ro-RO', { weekday: 'long', day: '2-digit', month: 'short', year: 'numeric' });
    } catch { return key; }
  };

  return (
    <div>
      <div className="ap-head">
        <h2>Live Call RSVPs</h2>
        <p>Vezi cine a confirmat prezența sau a marcat că nu ajunge la fiecare live call.</p>
      </div>

      <div className="atp-toolbar">
        <div className="ap-filters">
          <label className="ap-filter-label">Eveniment</label>
          <select
            className="ap-select"
            value={eventFilter}
            onChange={(e) => setEventFilter(e.target.value)}
            style={{minWidth: 240}}>
            {events.length === 0 && <option value="">— niciun eveniment —</option>}
            {events.map(e => (
              <option key={e.key} value={e.key}>
                {formatDate(e.key)} · {e.present + e.absent} răspunsuri
              </option>
            ))}
          </select>
          <button className="ap-link" onClick={load}><Icon name="refresh" size={13}/> Reload</button>
        </div>
      </div>

      {!loading && eventFilter && (
        <div className="rsvp-counts">
          <div className="rsvp-count rsvp-count-yes">
            <Icon name="check" size={14} stroke={3}/>
            <div>
              <div className="rsvp-count-num">{presentCount}</div>
              <div className="rsvp-count-label">Prezenți</div>
            </div>
          </div>
          <div className="rsvp-count rsvp-count-no">
            <Icon name="x" size={14} stroke={3}/>
            <div>
              <div className="rsvp-count-num">{absentCount}</div>
              <div className="rsvp-count-label">Nu ajung</div>
            </div>
          </div>
          <div className="rsvp-count rsvp-count-total">
            <Icon name="users" size={14}/>
            <div>
              <div className="rsvp-count-num">{presentCount + absentCount}</div>
              <div className="rsvp-count-label">Total răspunsuri</div>
            </div>
          </div>
        </div>
      )}

      {loading && <div className="ap-loading">Loading…</div>}
      {err && <div className="ap-error">{err}</div>}

      {!loading && !err && (
        <div className="atp-list" style={{marginTop: 18}}>
          {filtered.length === 0 ? (
            <div className="atp-empty">Niciun răspuns încă pentru acest eveniment.</div>
          ) : filtered.map(r => (
            <div key={r.id} className="atp-row">
              <div className="atp-row-head">
                <div className="atp-row-user">
                  <div className={`atp-row-avatar ${r.status === 'present' ? 'is-yes' : 'is-no'}`}>
                    <Icon name={r.status === 'present' ? 'check' : 'x'} size={14} stroke={3}/>
                  </div>
                  <div style={{minWidth:0}}>
                    <div className="atp-row-name">{r.profile?.name || r.profile?.email?.split('@')[0] || '—'}</div>
                    <div className="atp-row-email mono">{r.profile?.email}</div>
                  </div>
                </div>
                <div className="atp-row-meta">
                  <span className={`tag ${r.status === 'present' ? 'acid' : 'rose'}`}>
                    {r.status === 'present' ? 'PREZENT' : 'NU AJUNGE'}
                  </span>
                  <span className="atp-row-date mono">{new Date(r.responded_at).toLocaleString('ro-RO')}</span>
                </div>
              </div>
            </div>
          ))}
        </div>
      )}

      <style>{`
        .rsvp-counts {
          display: grid;
          grid-template-columns: repeat(3, 1fr);
          gap: 12px;
          margin: 14px 0 18px;
        }
        @media (max-width: 540px) { .rsvp-counts { grid-template-columns: 1fr; } }
        .rsvp-count {
          display: flex; align-items: center; gap: 14px;
          padding: 14px 18px;
          border-radius: 14px;
          background: rgba(255,255,255,0.02);
          border: 1px solid rgba(255,255,255,0.08);
        }
        .rsvp-count > svg { flex-shrink: 0; }
        .rsvp-count-num { font-size: 22px; font-weight: 800; letter-spacing: -0.02em; line-height: 1; }
        .rsvp-count-label {
          font-family: 'JetBrains Mono', monospace;
          font-size: 10.5px; letter-spacing: 0.14em; text-transform: uppercase;
          color: var(--text-mute); margin-top: 4px;
        }
        .rsvp-count-yes   { border-color: rgba(183,255,26,0.30); background: rgba(183,255,26,0.04); }
        .rsvp-count-yes   svg { color: var(--acid); }
        .rsvp-count-yes   .rsvp-count-num { color: var(--acid); }
        .rsvp-count-no    { border-color: rgba(244,63,94,0.30);  background: rgba(244,63,94,0.04); }
        .rsvp-count-no    svg { color: #FB7185; }
        .rsvp-count-no    .rsvp-count-num { color: #FB7185; }
        .rsvp-count-total svg { color: var(--text-mute); }
        .atp-row-avatar.is-yes {
          background: rgba(183,255,26,0.14); color: var(--acid);
          border: 1px solid rgba(183,255,26,0.35);
        }
        .atp-row-avatar.is-no {
          background: rgba(244,63,94,0.12); color: #FB7185;
          border: 1px solid rgba(244,63,94,0.32);
        }
      `}</style>
    </div>
  );
};

const AdminNotifications = () => {
  const [items, setItems] = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const [err, setErr] = React.useState('');
  const [filter, setFilter] = React.useState('all');

  const load = React.useCallback(async () => {
    setLoading(true);
    const { data, error } = await window.sb
      .from('admin_notifications')
      .select('*')
      .order('created_at', { ascending: false });
    if (error) setErr(error.message);
    else setItems(data || []);
    setLoading(false);
  }, []);

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

  const markRead = async (id) => {
    await window.sb.from('admin_notifications').update({ status: 'read' }).eq('id', id);
    setItems(items.map(n => n.id === id ? { ...n, status: 'read' } : n));
  };
  const markAllRead = async () => {
    await window.sb.from('admin_notifications').update({ status: 'read' }).eq('status', 'unread');
    setItems(items.map(n => ({ ...n, status: 'read' })));
  };

  const visible = items.filter(n => filter === 'all' || n.status === filter);
  const unreadCount = items.filter(n => n.status === 'unread').length;

  return (
    <>
      <div className="ap-toolbar">
        <div className="ap-filters">
          <button className={`ap-pill ${filter === 'all' ? 'active' : ''}`} onClick={() => setFilter('all')}>All ({items.length})</button>
          <button className={`ap-pill ${filter === 'unread' ? 'active' : ''}`} onClick={() => setFilter('unread')}>Unread ({unreadCount})</button>
          <button className={`ap-pill ${filter === 'read' ? 'active' : ''}`} onClick={() => setFilter('read')}>Read</button>
        </div>
        <div className="ap-filters">
          <button className="ap-link" onClick={load}><Icon name="refresh" size={13}/> Reload</button>
          {unreadCount > 0 && (
            <Button variant="ghost" size="sm" onClick={markAllRead}>Mark all as read</Button>
          )}
        </div>
      </div>

      {loading && <div className="ap-loading">Loading…</div>}
      {err && <div className="ap-error">{err}</div>}

      {!loading && !err && (
        <div className="col" style={{gap: 8}}>
          {visible.length === 0 && <div className="ap-empty card card-pad-lg" style={{textAlign: 'center'}}>Nicio notificare.</div>}
          {visible.map(n => (
            <div key={n.id} className={`ap-notif ${n.status === 'unread' ? 'unread' : ''}`}>
              <NotifTypeChip type={n.type}/>
              <div style={{flex: 1, minWidth: 0}}>
                <div className="ap-notif-msg">{n.message}</div>
                <div className="ap-notif-time">{fmtDate(n.created_at)}</div>
              </div>
              {n.status === 'unread' ? (
                <button className="ap-link" onClick={() => markRead(n.id)}>Mark as read</button>
              ) : (
                <span className="ap-notif-read">read</span>
              )}
            </div>
          ))}
        </div>
      )}
    </>
  );
};

// ============================================================
// SETTINGS (stub)
// ============================================================
const AdminSettings = () => (
  <div className="card card-pad-lg" style={{textAlign: 'center'}}>
    <IconChip icon="settings" color="cyan"/>
    <h3 style={{marginTop: 16}}>Settings</h3>
    <p style={{marginTop: 10, color: 'var(--text-mute)'}}>Coming soon. Pentru moment, gestionează din Supabase Studio.</p>
  </div>
);

// ============================================================
// BADGES
// ============================================================
const RoleBadge = ({ role }) => {
  const c = role === 'admin' ? 'acid' : role === 'elite' ? 'gold' : 'cyan';
  return <span className={`tag ${c}`} style={{textTransform: 'uppercase', fontSize: 10, padding: '3px 8px'}}>{role}</span>;
};

const RoleEditor = ({ role, onChange }) => {
  const [open, setOpen] = React.useState(false);
  const [busy, setBusy] = React.useState(false);
  const ref = React.useRef(null);
  React.useEffect(() => {
    if (!open) return;
    const onDoc = (e) => { if (!ref.current?.contains(e.target)) setOpen(false); };
    document.addEventListener('mousedown', onDoc);
    return () => document.removeEventListener('mousedown', onDoc);
  }, [open]);
  const pick = async (r) => {
    if (r === role) { setOpen(false); return; }
    setBusy(true);
    await onChange(r);
    setBusy(false);
    setOpen(false);
  };
  return (
    <span ref={ref} className="ap-role-editor" style={{position:'relative', display:'inline-block'}}>
      <button type="button" onClick={() => setOpen(o => !o)} disabled={busy}
              className="ap-role-trigger"
              style={{background:'transparent', border:'none', padding:0, cursor: busy ? 'wait' : 'pointer'}}>
        <RoleBadge role={role}/>
      </button>
      {open && (
        <div className="ap-role-menu" style={{
          position:'absolute', top:'calc(100% + 4px)', left:0, zIndex:50,
          background:'#0E0E12', border:'1px solid rgba(255,255,255,0.12)', borderRadius:8,
          padding:4, minWidth:96, boxShadow:'0 8px 24px rgba(0,0,0,0.45)'
        }}>
          {['free','elite','admin'].map(r => (
            <button key={r} type="button" onClick={() => pick(r)}
                    className="ap-role-menu-item"
                    style={{
                      display:'flex', alignItems:'center', gap:8, width:'100%',
                      background: r === role ? 'rgba(255,255,255,0.06)' : 'transparent',
                      border:'none', padding:'6px 8px', borderRadius:6, cursor:'pointer',
                      textAlign:'left'
                    }}>
              <RoleBadge role={r}/>
            </button>
          ))}
        </div>
      )}
    </span>
  );
};
const EliteBadge = ({ status }) => {
  if (!status || status === 'inactive') return <span className="ap-pill-static">inactive</span>;
  if (status === 'expired') return <span className="tag rose" style={{padding: '3px 8px', fontSize: 10, background: 'rgba(244,63,94,0.12)', color: '#F87171', border: '1px solid rgba(244,63,94,0.35)'}}>expired</span>;
  return <span className="tag acid" style={{padding: '3px 8px', fontSize: 10}}>active</span>;
};
const AppStatusBadge = ({ status }) => {
  const map = {
    new:       { c: 'cyan',  label: 'NEW' },
    contacted: { c: 'blue',  label: 'CONTACTED' },
    accepted:  { c: 'acid',  label: 'ACCEPTED' },
    rejected:  { c: 'rose',  label: 'REJECTED' },
  };
  const m = map[status] || { c: 'cyan', label: status };
  if (m.c === 'rose') {
    return <span className="tag" style={{padding:'3px 8px', fontSize:10, background:'rgba(244,63,94,0.12)', color:'#F87171', border:'1px solid rgba(244,63,94,0.35)'}}>{m.label}</span>;
  }
  return <span className={`tag ${m.c}`} style={{padding: '3px 8px', fontSize: 10}}>{m.label}</span>;
};
const NotifTypeChip = ({ type }) => {
  const map = {
    elite_application: { icon: 'mail',  color: 'gold' },
    new_user:          { icon: 'user',  color: 'cyan' },
    user_upgraded:     { icon: 'crown', color: 'acid' },
    elite_expired:     { icon: 'warn',  color: 'rose' },
  };
  const m = map[type] || { icon: 'bolt', color: 'blue' };
  return <IconChip icon={m.icon} color={m.color}/>;
};

Object.assign(window, { AdminPage });
