'use client';

import { useCallback, useEffect, useMemo, useState } from 'react';
import { toast } from 'react-toastify';
import { api } from '@/lib/api';
import { activityWsUrl, safeWebSocket } from '@/lib/ws';
import type { User } from '@/types';
import { motion, AnimatePresence } from 'framer-motion';
import ClientFilterSelect from '@/components/dashboard/ClientFilterSelect';
import { DataTable } from '@/components/data-table/DataTable';
import { PageLoader } from '@/components/DotLoader';

function getToday() {
  return new Date().toLocaleDateString('en-IN', { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' });
}

interface KPIStats {
  total_users: number;
  total_recruiters: number;
  open_jds: number;
  total_candidates: number;
  total_ai_calls: number;
  total_offers: number;
}

interface UserActivity {
  email: string;
  name: string;
  role: string;
  actions_count: number;
  last_action: string;
  last_action_time: string;
}

interface JdProgress {
  id: number;
  title: string;
  client: string;
  priority: string;
  assigned_recruiters: string[];
  progress: {
    total: number;
    in_progress: number;
    placed: number;
    rejected: number;
  };
  created_at: string;
}

interface RecruiterPerf {
  id: number;
  name: string;
  email: string;
  candidates_added: number;
  calls_completed: number;
  assigned_active_jds: number;
}

interface ClientOverview {
  id: number;
  name: string;
  email?: string;
  phone?: string;
  website?: string;
  created_at: string;
}

interface AuditLogEntry {
  id: number;
  user_email: string;
  user_name: string;
  action: string;
  description: string;
  ip_address: string;
  created_at: string;
}

interface DashData {
  kpis: KPIStats | null;
  todayActivities: UserActivity[];
  openJdsProgress: JdProgress[];
  recruiterPerformance: RecruiterPerf[];
  recentActivity: AuditLogEntry[];
  clientName: string | null;
}

// Module-scope cache keyed by client scope ('global' or the client id) —
// survives navigation remounts, so returning to the dashboard paints
// instantly with the last data while a fresh fetch runs silently in the
// background.
const dashCache: Record<string, DashData> = {};

// When clientId is set the dashboard runs in client mode: every KPI is scoped
// to that client and the global-only sections (Today's Activity, Recruiter
// Performance, Live Feed) are hidden.
export default function AdminDashboard({ user, clientId }: { user: User; clientId?: string }) {
  const cacheKey = clientId || 'global';
  const cached = dashCache[cacheKey];
  const clientMode = !!clientId;

  const [kpis, setKpis] = useState<KPIStats | null>(cached?.kpis ?? null);
  const [todayActivities, setTodayActivities] = useState<UserActivity[]>(cached?.todayActivities ?? []);
  const [openJdsProgress, setOpenJdsProgress] = useState<JdProgress[]>(cached?.openJdsProgress ?? []);
  const [recruiterPerformance, setRecruiterPerformance] = useState<RecruiterPerf[]>(cached?.recruiterPerformance ?? []);
  const [recentActivity, setRecentActivity] = useState<AuditLogEntry[]>(cached?.recentActivity ?? []);
  const [clientName, setClientName] = useState<string | null>(cached?.clientName ?? null);

  const [loading, setLoading] = useState(!cached);
  const [wsConnected, setWsConnected] = useState(false);
  const [clients, setClients] = useState<ClientOverview[]>([]);
  const [clientsLoading, setClientsLoading] = useState(true);

  const hasClientsViewPermission = user.role === 'ADMIN' || user.permissions?.includes('clients.view_client');

  // Collapsible big tables (collapsed = body hidden). Default expanded.
  const [collapsed, setCollapsed] = useState<Record<string, boolean>>({});
  const toggleCollapse = (key: string) => setCollapsed((c) => ({ ...c, [key]: !c[key] }));
  const CollapseBtn = ({ section }: { section: string }) => (
    <button
      onClick={() => toggleCollapse(section)}
      title={collapsed[section] ? 'Expand' : 'Collapse'}
      className="w-6 h-6 flex items-center justify-center rounded-none text-slate-400 hover:text-[#405189] hover:bg-slate-100 dark:hover:bg-slate-800 transition cursor-pointer shrink-0"
    >
      <i className={`fa-solid fa-chevron-down text-xs transition-transform ${collapsed[section] ? '-rotate-90' : ''}`} />
    </button>
  );

  // Auto-refresh interval (seconds). 0 = off. Default 60s, persisted per browser.
  const [refreshSec, setRefreshSec] = useState<number>(() => {
    if (typeof window === 'undefined') return 60;
    const v = Number(localStorage.getItem('dashRefreshSec'));
    return Number.isFinite(v) && v >= 0 ? v : 60;
  });
  const [lastUpdated, setLastUpdated] = useState<Date | null>(null);
  const [refreshing, setRefreshing] = useState(false);

  const setRefreshInterval = (sec: number) => {
    setRefreshSec(sec);
    try { localStorage.setItem('dashRefreshSec', String(sec)); } catch { /* ignore */ }
  };

  // Fetch dashboard data. `manual` shows the button spinner + error toast.
  const loadDashboard = useCallback(async (manual = false) => {
    const key = clientId || 'global';
    if (manual) setRefreshing(true);
    try {
      const res: any = await api.get(`/dashboard/command-center/${clientId ? `?client=${encodeURIComponent(clientId)}` : ''}`);
      const data = res.data || {};
      const fresh: DashData = {
        kpis: data.kpis || null,
        todayActivities: data.today_activities || [],
        openJdsProgress: data.open_jds_progress || [],
        recruiterPerformance: data.recruiter_performance || [],
        recentActivity: data.recent_activity || [],
        clientName: data.client?.name ?? null,
      };
      dashCache[key] = fresh;
      setKpis(fresh.kpis);
      setTodayActivities(fresh.todayActivities);
      setOpenJdsProgress(fresh.openJdsProgress);
      setRecruiterPerformance(fresh.recruiterPerformance);
      setRecentActivity(fresh.recentActivity);
      setClientName(fresh.clientName);
      setLastUpdated(new Date());
    } catch (err: any) {
      console.error('Failed to load dashboard data:', err);
      if (manual) toast.error('Failed to refresh dashboard');
    } finally {
      setLoading(false);
    }
  }, [clientId]);

  // Paint cached data for this scope instantly, then load fresh. Re-runs when
  // the client scope changes — no page reload needed.
  useEffect(() => {
    const hit = dashCache[clientId || 'global'];
    setKpis(hit?.kpis ?? null);
    setTodayActivities(hit?.todayActivities ?? []);
    setOpenJdsProgress(hit?.openJdsProgress ?? []);
    setRecruiterPerformance(hit?.recruiterPerformance ?? []);
    setRecentActivity(hit?.recentActivity ?? []);
    setClientName(hit?.clientName ?? null);
    setLoading(!hit);
    loadDashboard();
  }, [clientId, loadDashboard]);

  // Configurable auto-refresh (default 60s; off when refreshSec is 0).
  useEffect(() => {
    if (!refreshSec) return;
    const t = setInterval(() => loadDashboard(), refreshSec * 1000);
    return () => clearInterval(t);
  }, [refreshSec, loadDashboard]);

  useEffect(() => {
    if (!hasClientsViewPermission) {
      setClients([]);
      setClientsLoading(false);
      return;
    }

    let mounted = true;
    setClientsLoading(true);
    api.get('/clients/?page_size=50')
      .then((res: any) => {
        if (!mounted) return;
        const payload = res?.data ?? res;
        const list = Array.isArray(payload)
          ? payload
          : Array.isArray(payload.results)
            ? payload.results
            : [];
        setClients(list.map((client: any) => ({
          id: client.id,
          name: client.name,
          email: client.email,
          phone: client.phone,
          website: client.website,
          created_at: client.created_at,
        })));
      })
      .catch((err: any) => {
        if (!mounted) return;
        console.error('Failed to load clients for admin dashboard:', err);
        setClients([]);
      })
      .finally(() => {
        if (!mounted) setClientsLoading(false);
      });

    return () => {
      mounted = false;
    };
  }, [hasClientsViewPermission]);

  const clientColumns = useMemo(
    () => [
      {
        id: 'name',
        header: 'Client',
        accessorKey: 'name',
        cell: ({ row }: any) => (
          <div className="text-sm font-semibold text-[#495057] dark:text-white">
            {row.original.name}
          </div>
        ),
      },
      {
        accessorKey: 'email',
        header: 'Email',
        cell: ({ row }: any) => row.original.email || <span className="text-slate-400">—</span>,
      },
      {
        accessorKey: 'phone',
        header: 'Phone',
        cell: ({ row }: any) => row.original.phone || <span className="text-slate-400">—</span>,
      },
      {
        accessorKey: 'website',
        header: 'Website',
        cell: ({ row }: any) => {
          const website = row.original.website;
          if (!website) return <span className="text-slate-400">—</span>;
          const label = website.replace(/^https?:\/\//, '').replace(/\/$/, '');
          return (
            <a
              href={website}
              target="_blank"
              rel="noopener noreferrer"
              className="text-indigo-600 dark:text-indigo-400 hover:underline"
              onClick={(e) => e.stopPropagation()}
            >
              {label}
            </a>
          );
        },
      },
      {
        accessorKey: 'created_at',
        header: 'Created',
        cell: ({ row }: any) => new Date(row.original.created_at).toLocaleDateString('en-IN'),
      },
    ],
    [],
  );

  // Connect to Activity WebSockets on the gateway.
  // Skipped in client mode — the live feed is hidden there and its KPI
  // increments are global, which would corrupt client-scoped numbers.
  useEffect(() => {
    if (clientMode) return;
    // wss:// on https (via reverse proxy), ws://host:8000 on local http.
    const ws = safeWebSocket(activityWsUrl());
    // No WebSocket (disabled, or host can't proxy WS)? The configurable
    // auto-refresh above keeps the feed + KPIs current, so just skip live mode.
    if (!ws) return;

    ws.onopen = () => {
      console.log('Connected to activity WebSocket');
      setWsConnected(true);
    };

    ws.onmessage = (event) => {
      try {
        const data: AuditLogEntry = JSON.parse(event.data);
        
        // Add to live feed list
        setRecentActivity((prev) => [data, ...prev.slice(0, 29)]);

        // Update Today's User Activity list
        setTodayActivities((prev) => {
          const exists = prev.find((act) => act.email === data.user_email);
          if (exists) {
            return prev.map((act) =>
              act.email === data.user_email
                ? {
                    ...act,
                    actions_count: act.actions_count + 1,
                    last_action: data.action,
                    last_action_time: data.created_at,
                  }
                : act
            );
          } else {
            return [
              ...prev,
              {
                email: data.user_email,
                name: data.user_name,
                role: 'USER',
                actions_count: 1,
                last_action: data.action,
                last_action_time: data.created_at,
              },
            ];
          }
        });

        // Live-update specific KPI counter
        setKpis((prev) => {
          if (!prev) return prev;
          const copy = { ...prev };
          if (data.action === 'JD_CREATED') {
            copy.open_jds += 1;
          } else if (data.action === 'CANDIDATE_UPLOADED') {
            copy.total_candidates += 1;
          } else if (data.action === 'AI_CALL_STARTED') {
            copy.total_ai_calls += 1;
          } else if (data.action === 'STAGE_UPDATED' && data.description.toLowerCase().includes('offer')) {
            copy.total_offers += 1;
          }
          return copy;
        });

        // Trigger dynamic visual alert
        toast.info(`Activity Logged: ${data.description}`, {
          position: 'bottom-right',
          autoClose: 3000,
          hideProgressBar: false,
          closeOnClick: true,
          pauseOnHover: true,
          draggable: true,
        });
      } catch (err) {
        console.error('Error handling WebSocket message:', err);
      }
    };

    ws.onclose = () => {
      console.log('Activity WebSocket disconnected');
      setWsConnected(false);
    };

    return () => {
      ws.close();
    };
  }, [clientMode]);

  const getActionIcon = (action: string) => {
    switch (action) {
      case 'USER_LOGIN':
        return <i className="fa-solid fa-key text-emerald-500"></i>;
      case 'JD_CREATED':
        return <i className="fa-solid fa-briefcase text-blue-500"></i>;
      case 'JD_ASSIGNED':
        return <i className="fa-solid fa-user-tag text-purple-500"></i>;
      case 'CANDIDATE_UPLOADED':
        return <i className="fa-solid fa-user-plus text-sky-500"></i>;
      case 'AI_CALL_STARTED':
        return <i className="fa-solid fa-phone-volume text-amber-500 animate-pulse"></i>;
      case 'AI_CALL_COMPLETED':
        return <i className="fa-solid fa-phone-slash text-teal-500"></i>;
      case 'STAGE_UPDATED':
        return <i className="fa-solid fa-circle-right text-rose-500"></i>;
      default:
        return <i className="fa-solid fa-circle-info text-slate-500"></i>;
    }
  };

  const getActionBg = (action: string) => {
    switch (action) {
      case 'USER_LOGIN': return 'bg-emerald-50 dark:bg-emerald-950/20';
      case 'JD_CREATED': return 'bg-blue-50 dark:bg-blue-950/20';
      case 'JD_ASSIGNED': return 'bg-purple-50 dark:bg-purple-950/20';
      case 'CANDIDATE_UPLOADED': return 'bg-sky-50 dark:bg-sky-950/20';
      case 'AI_CALL_STARTED': return 'bg-amber-50 dark:bg-amber-950/20';
      case 'AI_CALL_COMPLETED': return 'bg-teal-50 dark:bg-teal-950/20';
      case 'STAGE_UPDATED': return 'bg-rose-50 dark:bg-rose-950/20';
      default: return 'bg-slate-50 dark:bg-slate-900/20';
    }
  };

  if (loading) {
    return <PageLoader />;
  }

  return (
    <div className="space-y-6">
      {/* Welcome & Live Status Banner */}
      <div className="bg-white dark:bg-slate-900 border border-vz-border dark:border-slate-800 rounded-none p-6 shadow-sm flex flex-col md:flex-row md:items-center md:justify-between gap-4 transition-colors duration-200">
        <div>
          <p className="text-xs uppercase tracking-wider text-vz-muted font-semibold">
            {clientMode ? 'Client Dashboard' : 'Dashboard'}
          </p>
          <h2 className="text-xl font-bold text-[#495057] dark:text-white mt-1">
            {clientMode ? (clientName || 'Client') : 'Admin Dashboard'}
          </h2>
          <p className="text-xs text-vz-muted mt-1">{getToday()}</p>
        </div>
        <div className="flex flex-wrap items-center gap-3">
          {/* Client filter — switches this dashboard to a client-scoped view */}
          <ClientFilterSelect clientId={clientId} />

          {/* Last-updated + on-demand refresh + auto-refresh setting */}
          {lastUpdated && (
            <span className="text-[11px] text-vz-muted whitespace-nowrap">
              Updated {lastUpdated.toLocaleTimeString('en-IN', { hour: '2-digit', minute: '2-digit', second: '2-digit' })}
            </span>
          )}
          <button
            type="button"
            onClick={() => loadDashboard(true)}
            disabled={refreshing}
            title="Refresh now"
            className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-none border border-slate-200 dark:border-slate-700 text-xs font-bold text-slate-600 dark:text-slate-300 hover:bg-slate-50 dark:hover:bg-slate-800 disabled:opacity-50 transition cursor-pointer"
          >
            <i className={`fa-solid fa-arrows-rotate ${refreshing ? 'fa-spin' : ''}`}></i>
            Refresh
          </button>
          <label className="inline-flex items-center gap-1.5 text-[11px] font-semibold text-vz-muted" title="Dashboard auto-refresh interval">
            <i className="fa-solid fa-gear text-slate-400"></i>
            Auto
            <select
              value={refreshSec}
              onChange={(e) => setRefreshInterval(Number(e.target.value))}
              className="border border-slate-200 dark:border-slate-700 bg-white dark:bg-slate-900 rounded-none px-2 py-1 text-xs font-semibold text-slate-700 dark:text-slate-200 focus:outline-none cursor-pointer"
            >
              <option value={0}>Off</option>
              <option value={30}>30s</option>
              <option value={60}>60s</option>
              <option value={120}>2m</option>
              <option value={300}>5m</option>
            </select>
          </label>

          {wsConnected && (
            <span className="inline-flex items-center gap-1.5 px-3 py-1 rounded-full text-xs font-semibold bg-emerald-50 text-emerald-700 dark:bg-emerald-950/30 dark:text-emerald-400">
              <span className="w-2 h-2 rounded-full bg-emerald-500 animate-ping"></span>
              Live Connected
            </span>
          )}
        </div>
      </div>

      {/* KPI Overview Cards */}
      {kpis && (
        <div className="grid grid-cols-2 lg:grid-cols-6 gap-4">
          {[
            { label: 'Total Users', value: kpis.total_users, icon: 'fa-solid fa-users', color: 'bg-blue-500/10 text-blue-500', path: '/admins/users' },
            { label: 'Recruiters', value: kpis.total_recruiters, icon: 'fa-solid fa-user-tie', color: 'bg-purple-500/10 text-purple-500', path: '/admins/recruiters' },
            // `?status=Published` matches the exact same filter open_jds counts
            // (apps.dashboard.views: status="Published") — jobs/page.tsx seeds
            // its status dropdown from this param on first load.
            { label: 'Open JDs', value: kpis.open_jds, icon: 'fa-solid fa-briefcase', color: 'bg-amber-500/10 text-amber-500', path: '/jobs?status=Published' },
            { label: 'Candidates', value: kpis.total_candidates, icon: 'fa-solid fa-user-graduate', color: 'bg-info-subtle text-info', path: '/candidates' },
            { label: 'AI Calls', value: kpis.total_ai_calls, icon: 'fa-solid fa-phone-volume', color: 'bg-rose-500/10 text-rose-500', path: '/reports' },
            // `stage_codes=offered,placed` matches the exact stages total_offers
            // counts (apps.dashboard.views: code__in=["offered","placed"]).
            { label: 'Offers Made', value: kpis.total_offers, icon: 'fa-solid fa-file-signature', color: 'bg-success-subtle text-success', path: `/candidates?stage_codes=offered,placed&label=${encodeURIComponent('Offers Made')}` },
          ].map((card, i) => (
            <div
              key={card.label}
              onClick={() => window.open(card.path, '_blank', 'noopener,noreferrer')}
              className="bg-white dark:bg-slate-900 border border-vz-border dark:border-slate-800 rounded-none p-4 shadow-sm flex items-center justify-between hover:translate-y-[-2px] hover:border-[#405189] cursor-pointer transition duration-200"
            >
              <div>
                <p className="text-[10px] uppercase tracking-wider text-vz-muted font-bold">{card.label}</p>
                <p className="text-xl font-bold text-[#495057] dark:text-white mt-1">{card.value}</p>
              </div>
              <span className={`w-9 h-9 rounded-full flex items-center justify-center text-sm shrink-0 ${card.color}`}>
                <i className={card.icon}></i>
              </span>
            </div>
          ))}
        </div>
      )}

      {/* Main Grid: Data Tables and Live Feed */}
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {/* Left Side: Summary Tables */}
        <div className={`space-y-6 ${clientMode ? 'lg:col-span-3' : 'lg:col-span-2'}`}>
          {/* Today's User Activity Table — global view only */}
          {!clientMode && (
          <div className="bg-white dark:bg-slate-900 border border-vz-border dark:border-slate-800 shadow-sm rounded-none p-5 transition-colors">
            <div className="flex items-center justify-between mb-4">
              <h3 className="text-sm font-bold text-[#495057] dark:text-white flex items-center gap-1.5">
                <CollapseBtn section="activity" />
                <i className="fa-solid fa-chart-line text-[#405189]"></i> Today's User Activity
              </h3>
              <span className="text-[10px] text-vz-muted">Updated in real-time</span>
            </div>
            {!collapsed.activity && (
            <div className="overflow-x-auto max-h-[340px] overflow-y-auto custom-scrollbar">
              <table className="w-full text-left text-xs border-collapse">
                <thead className="sticky top-0 z-10">
                  <tr className="border-b border-vz-border dark:border-slate-850 text-vz-muted bg-slate-50 dark:bg-slate-950 font-semibold">
                    <th className="p-2.5">User</th>
                    <th className="p-2.5">Role</th>
                    <th className="p-2.5 text-center">Actions Today</th>
                    <th className="p-2.5">Last Activity</th>
                    <th className="p-2.5">Time</th>
                  </tr>
                </thead>
                <tbody>
                  {todayActivities.length === 0 ? (
                    <tr>
                      <td colSpan={5} className="p-4 text-center text-vz-muted">No actions recorded today yet.</td>
                    </tr>
                  ) : (
                    todayActivities.map((act) => (
                      <tr key={act.email} className="border-b border-vz-border dark:border-slate-850 hover:bg-slate-50/50 dark:hover:bg-slate-800/10">
                        <td className="p-2.5 font-medium text-[#495057] dark:text-white">
                          <div>{act.name}</div>
                          <div className="text-[10px] text-vz-muted">{act.email}</div>
                        </td>
                        <td className="p-2.5">
                          <span className="px-1.5 py-0.5 rounded-none text-[9px] font-semibold bg-slate-100 text-slate-700 border border-slate-200 uppercase">
                            {act.role}
                          </span>
                        </td>
                        <td className="p-2.5 text-center font-bold text-vz-primary">{act.actions_count}</td>
                        <td className="p-2.5 font-mono text-[10px] text-[#495057] dark:text-slate-300">{act.last_action}</td>
                        <td className="p-2.5 text-vz-muted text-[10px]">
                          {new Date(act.last_action_time).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', second: '2-digit' })}
                        </td>
                      </tr>
                    ))
                  )}
                </tbody>
              </table>
            </div>
            )}
          </div>
          )}

          {/* Open JDs Progress Table */}
          <div className="bg-white dark:bg-slate-900 border border-vz-border dark:border-slate-800 shadow-sm rounded-none p-5 transition-colors">
            <h3 className="text-sm font-bold text-[#495057] dark:text-white mb-4 flex items-center gap-1.5">
              <CollapseBtn section="openjds" />
              <i className="fa-solid fa-folder-open text-[#405189]"></i> Open JDs & Pipeline Progress
            </h3>
            {!collapsed.openjds && (
            <div className="overflow-x-auto max-h-[340px] overflow-y-auto custom-scrollbar">
              <table className="w-full text-left text-xs border-collapse">
                <thead className="sticky top-0 z-10">
                  <tr className="border-b border-vz-border dark:border-slate-850 text-vz-muted bg-slate-50 dark:bg-slate-950 font-semibold">
                    <th className="p-2.5">Job Details</th>
                    <th className="p-2.5">Assigned Recruiters</th>
                    <th className="p-2.5">Priority</th>
                    <th className="p-2.5">Pipeline Progress</th>
                  </tr>
                </thead>
                <tbody>
                  {openJdsProgress.length === 0 ? (
                    <tr>
                      <td colSpan={4} className="p-4 text-center text-vz-muted">No open job descriptions available.</td>
                    </tr>
                  ) : (
                    openJdsProgress.map((jd) => {
                      const pct = jd.progress.total > 0 ? Math.round((jd.progress.placed / jd.progress.total) * 100) : 0;
                      return (
                        <tr key={jd.id} className="border-b border-vz-border dark:border-slate-850 hover:bg-slate-50/50 dark:hover:bg-slate-800/10">
                          <td className="p-2.5 font-medium text-[#495057] dark:text-white">
                            <div>{jd.title}</div>
                            <div className="text-[10px] text-vz-muted">{jd.client}</div>
                          </td>
                          <td className="p-2.5 text-vz-muted">
                            {jd.assigned_recruiters.length > 0 ? jd.assigned_recruiters.join(', ') : 'Unassigned'}
                          </td>
                          <td className="p-2.5">
                            <span className={`px-1.5 py-0.5 rounded-none text-[9px] font-semibold uppercase ${
                              jd.priority === 'HIGH' ? 'bg-rose-50 text-rose-700 border border-rose-200' :
                              jd.priority === 'MEDIUM' ? 'bg-amber-50 text-amber-700 border border-amber-200' :
                              'bg-slate-50 text-slate-750 border border-slate-200'
                            }`}>
                              {jd.priority}
                            </span>
                          </td>
                          <td className="p-2.5">
                            <div className="flex items-center gap-2">
                              <div className="w-20 bg-slate-100 dark:bg-slate-850 h-1.5 rounded-none overflow-hidden border border-vz-border dark:border-slate-800">
                                <div className="bg-success h-full" style={{ width: `${pct}%` }}></div>
                              </div>
                              <span className="text-[10px] font-semibold text-[#495057] dark:text-slate-300">
                                {pct}% ({jd.progress.placed} Placed / {jd.progress.total} Total)
                              </span>
                            </div>
                          </td>
                        </tr>
                      );
                    })
                  )}
                </tbody>
              </table>
            </div>
            )}
          </div>

          {/* Recruiter Performance Table — global view only */}
          {!clientMode && hasClientsViewPermission && (
          <div className="bg-white dark:bg-slate-900 border border-vz-border dark:border-slate-800 shadow-sm rounded-none p-5 transition-colors">
            <div className="flex items-center justify-between mb-4">
              <h3 className="text-sm font-bold text-[#495057] dark:text-white flex items-center gap-1.5">
                <i className="fa-solid fa-building text-[#405189]"></i> All Clients
              </h3>
              <span className="text-[10px] text-vz-muted">Showing last 50 clients</span>
            </div>
            <DataTable
              columns={clientColumns}
              data={clients}
              loading={clientsLoading}
              searchPlaceholder="Search clients by name, website, phone or email..."
              emptyStateTitle="No Clients Found"
              emptyStateDescription="The client registry is empty or you do not have permission to view clients."
            />
          </div>
          )}

          {!clientMode && (
          <div className="bg-white dark:bg-slate-900 border border-vz-border dark:border-slate-800 shadow-sm rounded-none p-5 transition-colors">
            <h3 className="text-sm font-bold text-[#495057] dark:text-white mb-4 flex items-center gap-1.5">
              <CollapseBtn section="recruiters" />
              <i className="fa-solid fa-headset text-[#405189]"></i> Recruiter Performance Metrics
            </h3>
            {!collapsed.recruiters && (
            <div className="overflow-x-auto max-h-[340px] overflow-y-auto custom-scrollbar">
              <table className="w-full text-left text-xs border-collapse">
                <thead className="sticky top-0 z-10">
                  <tr className="border-b border-vz-border dark:border-slate-850 text-vz-muted bg-slate-50 dark:bg-slate-950 font-semibold">
                    <th className="p-2.5">Recruiter</th>
                    <th className="p-2.5 text-center">Candidates Added</th>
                    <th className="p-2.5 text-center">AI Calls Completed</th>
                    <th className="p-2.5 text-center">Assigned Open JDs</th>
                  </tr>
                </thead>
                <tbody>
                  {recruiterPerformance.length === 0 ? (
                    <tr>
                      <td colSpan={4} className="p-4 text-center text-vz-muted">No recruiters found.</td>
                    </tr>
                  ) : (
                    recruiterPerformance.map((rec) => (
                      <tr key={rec.id} className="border-b border-vz-border dark:border-slate-850 hover:bg-slate-50/50 dark:hover:bg-slate-800/10">
                        <td className="p-2.5 font-medium text-[#495057] dark:text-white">
                          <div>{rec.name}</div>
                          <div className="text-[10px] text-vz-muted">{rec.email}</div>
                        </td>
                        <td className="p-2.5 text-center font-semibold text-[#495057] dark:text-white">{rec.candidates_added}</td>
                        <td className="p-2.5 text-center font-semibold text-[#495057] dark:text-white">{rec.calls_completed}</td>
                        <td className="p-2.5 text-center font-bold text-vz-primary">{rec.assigned_active_jds}</td>
                      </tr>
                    ))
                  )}
                </tbody>
              </table>
            </div>
            )}
          </div>
          )}
        </div>

        {/* Right Side: Real-time Activity Feed — global view only */}
        {!clientMode && (
        <div className="bg-white dark:bg-slate-900 border border-vz-border dark:border-slate-800 shadow-sm rounded-none p-5 flex flex-col h-[480px] transition-colors">
          <div className="flex items-center justify-between mb-4 border-b border-vz-border dark:border-slate-850 pb-3">
            <h3 className="text-sm font-bold text-[#495057] dark:text-white flex items-center gap-1.5">
              <i className="fa-solid fa-list-check text-[#405189]"></i> Live Activity Feed
            </h3>
            <span className="w-2.5 h-2.5 bg-emerald-500 rounded-full animate-ping"></span>
          </div>

          <div className="flex-1 overflow-y-auto pr-1 space-y-4 scrollbar-thin">
            <AnimatePresence initial={false}>
              {recentActivity.map((log) => (
                <motion.div
                  key={log.id}
                  initial={{ opacity: 0, x: 20 }}
                  animate={{ opacity: 1, x: 0 }}
                  exit={{ opacity: 0, scale: 0.95 }}
                  className={`p-3 border border-vz-border/60 dark:border-slate-800/60 rounded-none flex items-start gap-3 transition-colors ${getActionBg(log.action)}`}
                >
                  <span className="w-7 h-7 rounded-full bg-white dark:bg-slate-900 flex items-center justify-center shadow-sm shrink-0 border border-vz-border/20">
                    {getActionIcon(log.action)}
                  </span>
                  <div className="space-y-1 min-w-0 flex-1">
                    <div className="flex items-center justify-between gap-2">
                      <span className="text-[10px] uppercase font-bold tracking-wider text-vz-muted">
                        {log.action}
                      </span>
                      <span className="text-[9px] text-vz-muted shrink-0">
                        {new Date(log.created_at).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', second: '2-digit' })}
                      </span>
                    </div>
                    <p className="text-xs font-semibold text-[#495057] dark:text-white break-words">
                      {log.description}
                    </p>
                    <div className="flex items-center justify-between text-[9px] text-vz-muted pt-0.5">
                      <span className="truncate max-w-[120px]">
                        By: <strong className="text-slate-700 dark:text-slate-350">{log.user_name}</strong>
                      </span>
                      <span>IP: {log.ip_address}</span>
                    </div>
                  </div>
                </motion.div>
              ))}
              {recentActivity.length === 0 && (
                <div className="py-20 text-center text-vz-muted text-xs">No activity logs recorded.</div>
              )}
            </AnimatePresence>
          </div>
        </div>
        )}
      </div>
    </div>
  );
}