// apps/verify/src/pages/Dashboard.jsx
// Production-grade SkillNexus B2B Dashboard
// Features: Job posting, candidate management, plan-gated access, mobile-first, real-time AI insights, API key management

import React, {
  useState, useEffect, useCallback, useRef, useMemo,
  createContext, useContext, lazy, Suspense,
} from 'react';
import { useNavigate, Link, useSearchParams } from 'react-router-dom';
import {
  LayoutDashboard, Users, TrendingUp, DollarSign, LogOut,
  Settings, Menu, X, Bell, Search, CheckCircle2, Briefcase,
  ChevronRight, BarChart3, FileText, CreditCard,
  Mail, Wifi, WifiOff, RefreshCw, ShieldCheck,
  ArrowUpRight, ArrowDownRight, Download, Star,
  Activity, PieChart, HelpCircle, BookOpen,
  Sparkles, Check, Lock, Zap, AlertCircle,
  ChevronDown, ExternalLink, Clock, Filter,
  Building2, Target, Award, XCircle, Loader2,
  Key, Copy, Globe, Server, Database, Terminal,
  Plus, Edit, Trash2, Eye, EyeOff, Calendar,
  MapPin, DollarSign as DollarIcon, Briefcase as BriefcaseIcon,
  Building, UserCircle, Clock as ClockIcon, Tag,
  Search as SearchIcon, Filter as FilterIcon,
  Users as UsersIcon, MessageSquare, Share2, Bookmark,
  Heart, TrendingUp as TrendingUpIcon, Award as AwardIcon,
  Sparkles as SparklesIcon, Zap as ZapIcon, Shield as ShieldIcon,
  ChevronLeft, ChevronRight as ChevronRightIcon, MoreVertical,
  Send, Linkedin, Youtube, Twitter, Facebook, Instagram
} from 'lucide-react';
import { api, tokenStore } from '../../../../services/api/client';
import logo from '../../../../services/api/src/components/logo.png';

// ─── Constants ────────────────────────────────────────────────────────────────

const REFRESH_INTERVAL = 90_000;
const POLL_INTERVAL = 3_000;
const POLL_MAX = 40;

const TIER_CONFIG = {
  critical: { bg: 'bg-red-100', text: 'text-red-700', border: 'border-red-200', dot: 'bg-red-500' },
  high:     { bg: 'bg-orange-50', text: 'text-orange-700', border: 'border-orange-200', dot: 'bg-orange-400' },
  medium:   { bg: 'bg-amber-50', text: 'text-amber-700', border: 'border-amber-200', dot: 'bg-amber-400' },
  low:      { bg: 'bg-sky-50', text: 'text-sky-700', border: 'border-sky-200', dot: 'bg-sky-400' },
};

const JOB_STATUS_COLORS = {
  active: { bg: 'bg-emerald-100', text: 'text-emerald-700', dot: 'bg-emerald-500' },
  paused: { bg: 'bg-amber-100', text: 'text-amber-700', dot: 'bg-amber-500' },
  closed: { bg: 'bg-gray-100', text: 'text-gray-700', dot: 'bg-gray-400' },
  draft: { bg: 'bg-blue-100', text: 'text-blue-700', dot: 'bg-blue-500' },
};

const NAV = [
  { id: 'overview',       label: 'Overview',       icon: LayoutDashboard },
  { id: 'jobs',           label: 'Jobs',           icon: BriefcaseIcon },
  { id: 'candidates',     label: 'Candidates',     icon: Users           },
  { id: 'audits',         label: 'Audits',         icon: FileText        },
  { id: 'notifications',  label: 'Notifications',  icon: Bell            },
  { id: 'analytics',      label: 'Analytics',      icon: BarChart3       },
  { id: 'payments',       label: 'Plan & Billing', icon: CreditCard      },
  { id: 'api-keys',       label: 'API Keys',       icon: Key             },
  { id: 'settings',       label: 'Settings',       icon: Settings        },
];

// ─── Formatters ───────────────────────────────────────────────────────────────

const fmt = {
  currency: (n, currency = 'USD') =>
    n == null ? '—' : new Intl.NumberFormat('en-US', { style: 'currency', currency, maximumFractionDigits: 0 }).format(n),
  number: (n) => n == null ? '—' : new Intl.NumberFormat('en-US').format(n),
  percent: (n) => n == null ? '—' : `${Number(n).toFixed(1)}%`,
  date: (d) => d ? new Date(d).toLocaleDateString('en-GB', { day: 'numeric', month: 'short', year: 'numeric' }) : '—',
  datetime: (d) => d ? new Date(d).toLocaleString('en-GB', { day: 'numeric', month: 'short', year: 'numeric', hour: '2-digit', minute: '2-digit' }) : '—',
  reltime: (d) => {
    if (!d) return '—';
    const diff = Date.now() - new Date(d).getTime();
    if (diff < 60_000) return 'just now';
    if (diff < 3_600_000) return `${Math.floor(diff / 60_000)}m ago`;
    if (diff < 86_400_000) return `${Math.floor(diff / 3_600_000)}h ago`;
    if (diff < 604_800_000) return `${Math.floor(diff / 86_400_000)}d ago`;
    return fmt.date(d);
  },
  initials: (s) => s
    ? s.split(/[\s@]/).filter(Boolean).slice(0, 2).map(p => p[0]).join('').toUpperCase()
    : 'SN',
  truncate: (s, n = 40) => s?.length > n ? s.slice(0, n) + '...' : s,
  jobType: (type) => {
    const types = {
      full_time: 'Full Time',
      part_time: 'Part Time',
      contract: 'Contract',
      freelance: 'Freelance',
      internship: 'Internship',
      remote: 'Remote',
      hybrid: 'Hybrid',
    };
    return types[type] || type;
  },
  experienceLevel: (level) => {
    const levels = {
      entry: 'Entry Level',
      junior: 'Junior',
      mid: 'Mid Level',
      senior: 'Senior',
      lead: 'Lead',
      manager: 'Manager',
      director: 'Director',
      executive: 'Executive',
    };
    return levels[level] || level;
  },
};

// ─── Entitlement Context ──────────────────────────────────────────────────────

const EntitlementCtx = createContext({
  plan: null, features: {}, hasAccess: false, evaluationsUsed: 0,
  evaluationsLimit: null, status: 'free',
  can: () => false,
  reload: () => {},
});

function EntitlementProvider({ children }) {
  const [entitlements, setEntitlements] = useState({
    plan: null, features: {}, hasAccess: false,
    evaluationsUsed: 0, evaluationsLimit: null, status: 'free',
  });

  const reload = useCallback(async () => {
    try {
      const res = await api.subscriptions.me();
      if (res?.success && res.data) {
        setEntitlements(res.data);
      }
    } catch {}
  }, []);

  useEffect(() => { reload(); }, [reload]);

  const can = useCallback((feature) => {
    if (!entitlements.hasAccess) return false;
    const val = entitlements.features?.[feature];
    if (val === undefined) return false;
    if (typeof val === 'boolean') return val;
    if (typeof val === 'number') return val > 0;
    return !!val;
  }, [entitlements]);

  return (
    <EntitlementCtx.Provider value={{ ...entitlements, can, reload }}>
      {children}
    </EntitlementCtx.Provider>
  );
}

const useEntitlements = () => useContext(EntitlementCtx);

// ─── Base Components ──────────────────────────────────────────────────────────

function Skeleton({ className = '' }) {
  return <div className={`animate-pulse bg-gray-200 rounded-lg ${className}`} aria-hidden="true" />;
}

function Badge({ children, variant = 'default', size = 'sm' }) {
  const styles = {
    default:  'bg-gray-100 text-gray-600',
    success:  'bg-emerald-50 text-emerald-700 ring-1 ring-emerald-200',
    warning:  'bg-amber-50 text-amber-700 ring-1 ring-amber-200',
    danger:   'bg-red-50 text-red-700 ring-1 ring-red-200',
    critical: 'bg-red-100 text-red-800 ring-1 ring-red-300',
    info:     'bg-sky-50 text-sky-700 ring-1 ring-sky-200',
    purple:   'bg-violet-50 text-violet-700 ring-1 ring-violet-200',
    premium:  'bg-gradient-to-r from-amber-400 to-yellow-500 text-white',
  };
  const sizes = { sm: 'text-[10px] px-2 py-0.5', md: 'text-xs px-2.5 py-1' };
  return (
    <span className={`inline-flex items-center font-bold rounded-full ${styles[variant] ?? styles.default} ${sizes[size]}`}>
      {children}
    </span>
  );
}

function JobStatusBadge({ status }) {
  const color = JOB_STATUS_COLORS[status] || JOB_STATUS_COLORS.draft;
  return (
    <span className={`inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-bold ${color.bg} ${color.text}`}>
      <span className={`w-1.5 h-1.5 rounded-full ${color.dot}`} />
      {status}
    </span>
  );
}

function StatCard({ label, value, delta, positive, icon, loading, sub }) {
  return (
    <div className="bg-white rounded-2xl border border-gray-100 p-4 md:p-5 shadow-sm hover:shadow-md transition-shadow">
      <div className="flex items-start justify-between gap-2">
        <div className="min-w-0 flex-1">
          <p className="text-[10px] font-semibold text-gray-400 uppercase tracking-widest truncate">{label}</p>
          {loading
            ? <Skeleton className="h-7 w-24 mt-2" />
            : <p className="text-2xl font-black text-gray-900 mt-1 tracking-tight tabular-nums">{value ?? '—'}</p>
          }
        </div>
        <div className="p-2.5 rounded-xl bg-gray-50 text-gray-400 flex-shrink-0">
          {icon}
        </div>
      </div>
      {!loading && (delta != null || sub) && (
        <div className="flex items-center gap-1.5 mt-3 flex-wrap">
          {delta != null && (
            <span className={`flex items-center gap-0.5 text-xs font-bold ${positive ? 'text-emerald-600' : 'text-red-500'}`}>
              {positive ? <ArrowUpRight className="w-3.5 h-3.5" /> : <ArrowDownRight className="w-3.5 h-3.5" />}
              {delta}
            </span>
          )}
          {sub && <span className="text-xs text-gray-400">{sub}</span>}
        </div>
      )}
    </div>
  );
}

function Toast({ message, type = 'info', onDismiss }) {
  useEffect(() => {
    const t = setTimeout(onDismiss, 4000);
    return () => clearTimeout(t);
  }, [onDismiss]);

  const styles = {
    info:    'bg-sky-600',
    success: 'bg-emerald-600',
    error:   'bg-red-600',
    warning: 'bg-amber-500',
  };

  return (
    <div className={`fixed bottom-4 right-4 z-[9999] flex items-center gap-3 px-4 py-3 rounded-xl text-white text-sm font-semibold shadow-xl max-w-sm ${styles[type]}`}
         role="alert">
      <span className="flex-1">{message}</span>
      <button onClick={onDismiss} className="opacity-70 hover:opacity-100"><X className="w-4 h-4" /></button>
    </div>
  );
}

function FeatureGate({ feature, fallback, children }) {
  const { can, plan, hasAccess } = useEntitlements();
  if (can(feature)) return children;
  return fallback || (
    <div className="flex flex-col items-center justify-center p-8 bg-gray-50 rounded-xl border border-dashed border-gray-200 text-center">
      <Lock className="w-8 h-8 text-gray-300 mb-3" />
      <p className="text-sm font-semibold text-gray-500">
        {hasAccess ? 'Upgrade your plan to unlock this feature' : 'Subscribe to access this feature'}
      </p>
      <p className="text-xs text-gray-400 mt-1 capitalize">
        {plan ? `Current plan: ${plan}` : 'No active plan'}
      </p>
    </div>
  );
}

// ─── Job Management Components ────────────────────────────────────────────────

function JobFormModal({ isOpen, onClose, job, onSave, loading }) {
  const [formData, setFormData] = useState({
    title: '',
    department: '',
    location: '',
    type: 'full_time',
    experienceLevel: 'mid',
    salaryMin: '',
    salaryMax: '',
    currency: 'USD',
    description: '',
    requirements: '',
    benefits: '',
    status: 'draft',
    remote: false,
    expiresAt: '',
  });

  useEffect(() => {
    if (job) {
      setFormData({
        title: job.title || '',
        department: job.department || '',
        location: job.location || '',
        type: job.type || 'full_time',
        experienceLevel: job.experienceLevel || 'mid',
        salaryMin: job.salaryMin || '',
        salaryMax: job.salaryMax || '',
        currency: job.currency || 'USD',
        description: job.description || '',
        requirements: job.requirements || '',
        benefits: job.benefits || '',
        status: job.status || 'draft',
        remote: job.remote || false,
        expiresAt: job.expiresAt || '',
      });
    } else {
      setFormData(prev => ({ ...prev, title: '', description: '', requirements: '', benefits: '' }));
    }
  }, [job]);

  if (!isOpen) return null;

  const handleSubmit = (e) => {
    e.preventDefault();
    onSave(formData);
  };

  return (
    <div className="fixed inset-0 bg-gray-900/60 backdrop-blur-sm z-50 flex items-center justify-center p-4" onClick={onClose}>
      <div className="bg-white rounded-2xl shadow-2xl max-w-3xl w-full max-h-[90vh] overflow-y-auto" onClick={e => e.stopPropagation()}>
        <div className="sticky top-0 bg-white border-b border-gray-200 px-6 py-4 flex items-center justify-between">
          <h3 className="text-lg font-bold text-gray-900">
            {job ? 'Edit Job' : 'Post New Job'}
          </h3>
          <button onClick={onClose} className="p-1.5 rounded-lg hover:bg-gray-100">
            <X className="w-5 h-5 text-gray-500" />
          </button>
        </div>

        <form onSubmit={handleSubmit} className="p-6 space-y-5">
          {/* Basic Info */}
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <label className="block text-xs font-semibold text-gray-700 mb-1.5">Job Title *</label>
              <input
                type="text"
                value={formData.title}
                onChange={(e) => setFormData({ ...formData, title: e.target.value })}
                required
                className="w-full px-3 py-2 border border-gray-200 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                placeholder="Senior Software Engineer"
              />
            </div>
            <div>
              <label className="block text-xs font-semibold text-gray-700 mb-1.5">Department</label>
              <input
                type="text"
                value={formData.department}
                onChange={(e) => setFormData({ ...formData, department: e.target.value })}
                className="w-full px-3 py-2 border border-gray-200 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                placeholder="Engineering"
              />
            </div>
          </div>

          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <label className="block text-xs font-semibold text-gray-700 mb-1.5">Location</label>
              <input
                type="text"
                value={formData.location}
                onChange={(e) => setFormData({ ...formData, location: e.target.value })}
                className="w-full px-3 py-2 border border-gray-200 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                placeholder="London, UK or Remote"
              />
            </div>
            <div>
              <label className="block text-xs font-semibold text-gray-700 mb-1.5">Job Type</label>
              <select
                value={formData.type}
                onChange={(e) => setFormData({ ...formData, type: e.target.value })}
                className="w-full px-3 py-2 border border-gray-200 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:border-transparent"
              >
                <option value="full_time">Full Time</option>
                <option value="part_time">Part Time</option>
                <option value="contract">Contract</option>
                <option value="freelance">Freelance</option>
                <option value="internship">Internship</option>
              </select>
            </div>
          </div>

          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <label className="block text-xs font-semibold text-gray-700 mb-1.5">Experience Level</label>
              <select
                value={formData.experienceLevel}
                onChange={(e) => setFormData({ ...formData, experienceLevel: e.target.value })}
                className="w-full px-3 py-2 border border-gray-200 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:border-transparent"
              >
                <option value="entry">Entry Level</option>
                <option value="junior">Junior</option>
                <option value="mid">Mid Level</option>
                <option value="senior">Senior</option>
                <option value="lead">Lead</option>
                <option value="manager">Manager</option>
                <option value="director">Director</option>
                <option value="executive">Executive</option>
              </select>
            </div>
            <div className="flex items-center gap-2 pt-1">
              <label className="flex items-center gap-2 cursor-pointer">
                <input
                  type="checkbox"
                  checked={formData.remote}
                  onChange={(e) => setFormData({ ...formData, remote: e.target.checked })}
                  className="w-4 h-4 rounded border-gray-300 text-blue-600 focus:ring-blue-500"
                />
                <span className="text-sm font-medium text-gray-700">Remote</span>
              </label>
            </div>
          </div>

          {/* Salary */}
          <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
            <div>
              <label className="block text-xs font-semibold text-gray-700 mb-1.5">Min Salary</label>
              <input
                type="number"
                value={formData.salaryMin}
                onChange={(e) => setFormData({ ...formData, salaryMin: e.target.value })}
                className="w-full px-3 py-2 border border-gray-200 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                placeholder="50000"
              />
            </div>
            <div>
              <label className="block text-xs font-semibold text-gray-700 mb-1.5">Max Salary</label>
              <input
                type="number"
                value={formData.salaryMax}
                onChange={(e) => setFormData({ ...formData, salaryMax: e.target.value })}
                className="w-full px-3 py-2 border border-gray-200 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                placeholder="80000"
              />
            </div>
            <div>
              <label className="block text-xs font-semibold text-gray-700 mb-1.5">Currency</label>
              <select
                value={formData.currency}
                onChange={(e) => setFormData({ ...formData, currency: e.target.value })}
                className="w-full px-3 py-2 border border-gray-200 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:border-transparent"
              >
                <option value="USD">USD</option>
                <option value="EUR">EUR</option>
                <option value="GBP">GBP</option>
                <option value="NGN">NGN</option>
              </select>
            </div>
          </div>

          {/* Description */}
          <div>
            <label className="block text-xs font-semibold text-gray-700 mb-1.5">Job Description *</label>
            <textarea
              value={formData.description}
              onChange={(e) => setFormData({ ...formData, description: e.target.value })}
              required
              rows={4}
              className="w-full px-3 py-2 border border-gray-200 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:border-transparent resize-none"
              placeholder="Describe the role, responsibilities, and what makes this position unique..."
            />
          </div>

          {/* Requirements */}
          <div>
            <label className="block text-xs font-semibold text-gray-700 mb-1.5">Requirements</label>
            <textarea
              value={formData.requirements}
              onChange={(e) => setFormData({ ...formData, requirements: e.target.value })}
              rows={3}
              className="w-full px-3 py-2 border border-gray-200 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:border-transparent resize-none"
              placeholder="List the key requirements, skills, and qualifications..."
            />
          </div>

          {/* Benefits */}
          <div>
            <label className="block text-xs font-semibold text-gray-700 mb-1.5">Benefits</label>
            <textarea
              value={formData.benefits}
              onChange={(e) => setFormData({ ...formData, benefits: e.target.value })}
              rows={2}
              className="w-full px-3 py-2 border border-gray-200 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:border-transparent resize-none"
              placeholder="List the benefits, perks, and what you offer..."
            />
          </div>

          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <label className="block text-xs font-semibold text-gray-700 mb-1.5">Status</label>
              <select
                value={formData.status}
                onChange={(e) => setFormData({ ...formData, status: e.target.value })}
                className="w-full px-3 py-2 border border-gray-200 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:border-transparent"
              >
                <option value="draft">Draft</option>
                <option value="active">Active</option>
                <option value="paused">Paused</option>
                <option value="closed">Closed</option>
              </select>
            </div>
            <div>
              <label className="block text-xs font-semibold text-gray-700 mb-1.5">Expiry Date</label>
              <input
                type="date"
                value={formData.expiresAt}
                onChange={(e) => setFormData({ ...formData, expiresAt: e.target.value })}
                className="w-full px-3 py-2 border border-gray-200 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:border-transparent"
              />
            </div>
          </div>

          <div className="flex gap-3 pt-4 border-t border-gray-200">
            <button
              type="button"
              onClick={onClose}
              className="flex-1 px-4 py-2.5 bg-gray-100 hover:bg-gray-200 text-gray-700 font-semibold rounded-xl text-sm transition-colors"
            >
              Cancel
            </button>
            <button
              type="submit"
              disabled={loading}
              className="flex-1 px-4 py-2.5 bg-gradient-to-r from-blue-600 to-indigo-600 hover:from-blue-700 hover:to-indigo-700 text-white font-semibold rounded-xl text-sm transition-all shadow-lg shadow-blue-500/20 flex items-center justify-center gap-2"
            >
              {loading ? <Loader2 className="w-4 h-4 animate-spin" /> : <Plus className="w-4 h-4" />}
              {loading ? 'Saving...' : job ? 'Update Job' : 'Post Job'}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}

// ─── Jobs Tab ─────────────────────────────────────────────────────────────────

function JobsTab({ jobs, loading, onRefresh, onToast, navigate }) {
  const [showJobModal, setShowJobModal] = useState(false);
  const [editingJob, setEditingJob] = useState(null);
  const [savingJob, setSavingJob] = useState(false);
  const [filter, setFilter] = useState('all');
  const [searchTerm, setSearchTerm] = useState('');

  const filteredJobs = useMemo(() => {
    let list = Array.isArray(jobs) ? jobs : [];
    
    if (filter !== 'all') {
      list = list.filter(j => j.status === filter);
    }
    
    if (searchTerm) {
      const term = searchTerm.toLowerCase();
      list = list.filter(j => 
        j.title.toLowerCase().includes(term) ||
        j.department?.toLowerCase().includes(term) ||
        j.location?.toLowerCase().includes(term)
      );
    }
    
    return list;
  }, [jobs, filter, searchTerm]);

  const handleSaveJob = useCallback(async (jobData) => {
    setSavingJob(true);
    try {
      const url = editingJob 
        ? `/api/jobs/${editingJob.id}` 
        : '/api/jobs';
      const method = editingJob ? 'PUT' : 'POST';
      
      const response = await fetch(url, {
        method,
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${tokenStore.get()}`
        },
        body: JSON.stringify(jobData),
      });
      
      const data = await response.json();
      
      if (data.success) {
        onToast(editingJob ? 'Job updated successfully!' : 'Job posted successfully!', 'success');
        setShowJobModal(false);
        setEditingJob(null);
        onRefresh();
      } else {
        onToast(data.error || 'Failed to save job', 'error');
      }
    } catch (err) {
      onToast('Failed to save job', 'error');
    } finally {
      setSavingJob(false);
    }
  }, [editingJob, onRefresh, onToast]);

  const handleDeleteJob = useCallback(async (jobId) => {
    if (!confirm('Are you sure you want to delete this job?')) return;
    
    try {
      const response = await fetch(`/api/jobs/${jobId}`, {
        method: 'DELETE',
        headers: {
          'Authorization': `Bearer ${tokenStore.get()}`
        }
      });
      const data = await response.json();
      
      if (data.success) {
        onToast('Job deleted successfully', 'success');
        onRefresh();
      } else {
        onToast(data.error || 'Failed to delete job', 'error');
      }
    } catch (err) {
      onToast('Failed to delete job', 'error');
    }
  }, [onRefresh, onToast]);

  const stats = useMemo(() => ({
    total: jobs.length,
    active: jobs.filter(j => j.status === 'active').length,
    paused: jobs.filter(j => j.status === 'paused').length,
    closed: jobs.filter(j => j.status === 'closed').length,
  }), [jobs]);

  return (
    <div className="max-w-7xl mx-auto space-y-4">
      {/* Header */}
      <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3">
        <div>
          <h2 className="text-base font-bold text-gray-900">Jobs</h2>
          <p className="text-xs text-gray-500 mt-0.5">Manage your job postings</p>
        </div>
        <button
          onClick={() => {
            setEditingJob(null);
            setShowJobModal(true);
          }}
          className="px-4 py-2 bg-gradient-to-r from-blue-600 to-indigo-600 hover:from-blue-700 hover:to-indigo-700 text-white text-xs font-bold rounded-xl inline-flex items-center gap-1.5 transition-all shadow-sm"
        >
          <Plus className="w-3.5 h-3.5" /> Post New Job
        </button>
      </div>

      {/* Stats */}
      <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
        <div className="bg-white rounded-xl border border-gray-100 p-3 shadow-sm">
          <p className="text-[10px] text-gray-400 font-medium">Total Jobs</p>
          <p className="text-xl font-black text-gray-900 mt-1">{stats.total}</p>
        </div>
        <div className="bg-white rounded-xl border border-gray-100 p-3 shadow-sm">
          <p className="text-[10px] text-gray-400 font-medium">Active</p>
          <p className="text-xl font-black text-emerald-600 mt-1">{stats.active}</p>
        </div>
        <div className="bg-white rounded-xl border border-gray-100 p-3 shadow-sm">
          <p className="text-[10px] text-gray-400 font-medium">Paused</p>
          <p className="text-xl font-black text-amber-600 mt-1">{stats.paused}</p>
        </div>
        <div className="bg-white rounded-xl border border-gray-100 p-3 shadow-sm">
          <p className="text-[10px] text-gray-400 font-medium">Closed</p>
          <p className="text-xl font-black text-gray-600 mt-1">{stats.closed}</p>
        </div>
      </div>

      {/* Filters */}
      <div className="flex flex-col sm:flex-row gap-3 items-start sm:items-center justify-between">
        <div className="flex flex-wrap gap-1.5">
          {['all', 'active', 'paused', 'closed', 'draft'].map(f => (
            <button
              key={f}
              onClick={() => setFilter(f)}
              className={`px-3 py-1.5 rounded-lg text-[11px] font-semibold transition-colors capitalize ${
                filter === f ? 'bg-blue-600 text-white' : 'text-gray-500 hover:bg-gray-100'
              }`}
            >
              {f}
            </button>
          ))}
        </div>
        <div className="relative w-full sm:w-48">
          <SearchIcon className="absolute left-3 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-gray-400" />
          <input
            type="text"
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
            placeholder="Search jobs..."
            className="w-full pl-9 pr-3 py-1.5 text-xs bg-gray-50 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500/20 focus:border-blue-400 transition-all"
          />
        </div>
      </div>

      {/* Jobs List */}
      <div className="bg-white rounded-2xl border border-gray-100 shadow-sm overflow-hidden">
        {loading ? (
          <div className="p-8 text-center">
            <Loader2 className="w-6 h-6 text-blue-500 animate-spin mx-auto" />
            <p className="text-xs text-gray-400 mt-2">Loading jobs...</p>
          </div>
        ) : filteredJobs.length === 0 ? (
          <div className="p-12 text-center">
            <BriefcaseIcon className="w-12 h-12 text-gray-200 mx-auto mb-3" />
            <p className="text-sm font-semibold text-gray-400">No jobs found</p>
            <p className="text-xs text-gray-400 mt-1">
              {searchTerm ? 'Try adjusting your search' : 'Post your first job to get started'}
            </p>
            {!searchTerm && (
              <button
                onClick={() => {
                  setEditingJob(null);
                  setShowJobModal(true);
                }}
                className="mt-4 px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white text-xs font-bold rounded-xl transition-colors"
              >
                Post New Job
              </button>
            )}
          </div>
        ) : (
          <div className="divide-y divide-gray-100">
            {filteredJobs.map((job) => (
              <div key={job.id} className="p-4 hover:bg-gray-50 transition-colors">
                <div className="flex flex-col sm:flex-row sm:items-start justify-between gap-3">
                  <div className="flex-1 min-w-0">
                    <div className="flex items-start gap-3">
                      <div className="p-2 bg-blue-50 rounded-lg flex-shrink-0">
                        <BriefcaseIcon className="w-4 h-4 text-blue-600" />
                      </div>
                      <div className="min-w-0">
                        <div className="flex flex-wrap items-center gap-2">
                          <h3 className="text-sm font-bold text-gray-900 truncate">{job.title}</h3>
                          <JobStatusBadge status={job.status} />
                        </div>
                        <div className="flex flex-wrap items-center gap-3 mt-1 text-xs text-gray-500">
                          {job.department && <span>{job.department}</span>}
                          {job.location && <span className="flex items-center gap-1"><MapPin className="w-3 h-3" /> {job.location}</span>}
                          {job.remote && <Badge variant="info" size="sm">Remote</Badge>}
                          {job.type && <span>{fmt.jobType(job.type)}</span>}
                          {job.experienceLevel && <span>• {fmt.experienceLevel(job.experienceLevel)}</span>}
                        </div>
                        {job.salaryMin && job.salaryMax && (
                          <p className="text-xs font-semibold text-emerald-600 mt-1">
                            {fmt.currency(job.salaryMin)} - {fmt.currency(job.salaryMax)}
                          </p>
                        )}
                        <p className="text-xs text-gray-400 mt-1">
                          Posted {fmt.reltime(job.createdAt)}
                          {job.expiresAt && ` • Expires ${fmt.date(job.expiresAt)}`}
                        </p>
                      </div>
                    </div>
                  </div>
                  <div className="flex items-center gap-1.5 flex-shrink-0 self-start sm:self-auto">
                    <button
                      onClick={() => {
                        setEditingJob(job);
                        setShowJobModal(true);
                      }}
                      className="p-1.5 rounded-lg hover:bg-blue-50 text-blue-600 transition-colors"
                      title="Edit"
                    >
                      <Edit className="w-3.5 h-3.5" />
                    </button>
                    <button
                      onClick={() => handleDeleteJob(job.id)}
                      className="p-1.5 rounded-lg hover:bg-red-50 text-red-500 transition-colors"
                      title="Delete"
                    >
                      <Trash2 className="w-3.5 h-3.5" />
                    </button>
                    <button
                      onClick={() => navigate(`/jobs/${job.id}`)}
                      className="p-1.5 rounded-lg hover:bg-gray-100 text-gray-500 transition-colors"
                      title="View"
                    >
                      <Eye className="w-3.5 h-3.5" />
                    </button>
                  </div>
                </div>
              </div>
            ))}
          </div>
        )}
      </div>

      {/* Job Form Modal */}
      <JobFormModal
        isOpen={showJobModal}
        onClose={() => {
          setShowJobModal(false);
          setEditingJob(null);
        }}
        job={editingJob}
        onSave={handleSaveJob}
        loading={savingJob}
      />
    </div>
  );
}

// ─── Plan Picker & Payment Flow ───────────────────────────────────────────────

const PLAN_DISPLAY = {
  starter: {
    name: 'Starter',
    price: 1500,
    period: '/month',
    badge: null,
    color: 'border-gray-200',
    highlight: false,
    features: [
      '50 candidate evaluations/month',
      'Standard test library',
      'Email & chat support',
      'Standard reporting',
      'Basic proctoring',
      'Basic anti-cheat AI',
      '5 active jobs',
    ],
    locked: ['Custom tests', 'ATS / Webhook API', 'AI insights', 'AI code review', 'Dedicated CSM', 'Unlimited jobs'],
  },
  growth: {
    name: 'Growth',
    price: 3000,
    period: '/month',
    badge: 'Most Popular',
    color: 'border-blue-500',
    highlight: true,
    features: [
      '150 candidate evaluations/month',
      'Advanced test library',
      'Custom test creation',
      'Priority 24/7 support',
      'Custom branded reporting',
      'Advanced proctoring',
      'ATS & Webhook API access',
      'Advanced anti-cheat AI',
      'Custom candidate branding',
      'AI dashboard insights',
      'AI code review feedback',
      '25 active jobs',
      'Job posting & management',
    ],
    locked: ['Dedicated CSM', 'On-premise / single-tenant', 'Custom SLA', 'Unlimited jobs'],
  },
  enterprise: {
    name: 'Enterprise',
    price: null,
    period: 'Custom pricing',
    badge: null,
    color: 'border-gray-200',
    highlight: false,
    features: [
      'Unlimited evaluations',
      'Everything in Growth',
      'Dedicated CSM',
      'On-premise / single-tenant',
      'Custom SLA & uptime guarantee',
      'Custom integrations',
      'Unlimited jobs',
      'White-label job portal',
    ],
    locked: [],
    cta: 'Contact Sales',
    ctaLink: 'mailto:enterprise@skillnexus.uk',
  },
};

function PlanCard({ planId, current, onSelect, loading }) {
  const plan = PLAN_DISPLAY[planId];
  if (!plan) return null;
  const isCurrent = current === planId;

  return (
    <div className={`relative flex flex-col bg-white rounded-2xl border-2 ${plan.highlight ? 'border-blue-500 shadow-lg shadow-blue-100' : 'border-gray-200'} overflow-hidden transition-all hover:shadow-md`}>
      {plan.badge && (
        <div className="absolute top-0 right-0 bg-blue-500 text-white text-[10px] font-black px-3 py-1 rounded-bl-xl">
          {plan.badge}
        </div>
      )}
      <div className={`p-6 ${plan.highlight ? 'bg-blue-600' : 'bg-gray-50'}`}>
        <h3 className={`text-lg font-black ${plan.highlight ? 'text-white' : 'text-gray-900'}`}>{plan.name}</h3>
        {plan.price != null ? (
          <div className="mt-2 flex items-end gap-1">
            <span className={`text-4xl font-black tracking-tight ${plan.highlight ? 'text-white' : 'text-gray-900'}`}>
            ${plan.price.toLocaleString()}
            </span>
            <span className={`text-sm mb-1 ${plan.highlight ? 'text-blue-100' : 'text-gray-500'}`}>/mo</span>
          </div>
        ) : (
          <p className={`text-2xl font-black mt-2 ${plan.highlight ? 'text-white' : 'text-gray-900'}`}>Custom</p>
        )}
      </div>

      <div className="p-6 flex-1 flex flex-col gap-4">
        <ul className="space-y-2.5 flex-1">
          {plan.features.map((f, i) => (
            <li key={i} className="flex items-start gap-2.5 text-sm text-gray-700">
              <Check className="w-4 h-4 text-emerald-500 mt-0.5 flex-shrink-0" />
              <span>{f}</span>
            </li>
          ))}
          {plan.locked.map((f, i) => (
            <li key={i} className="flex items-start gap-2.5 text-sm text-gray-400">
              <Lock className="w-4 h-4 mt-0.5 flex-shrink-0" />
              <span>{f}</span>
            </li>
          ))}
        </ul>

        {plan.ctaLink ? (
          <a
            href={plan.ctaLink}
            className="mt-4 block w-full text-center py-3 rounded-xl text-sm font-bold bg-gray-100 hover:bg-gray-200 text-gray-800 transition-colors"
          >
            {plan.cta || 'Contact Sales'}
          </a>
        ) : isCurrent ? (
          <div className="mt-4 w-full py-3 rounded-xl text-sm font-bold text-center bg-emerald-50 text-emerald-700 ring-1 ring-emerald-200 flex items-center justify-center gap-2">
            <CheckCircle2 className="w-4 h-4" /> Current plan
          </div>
        ) : (
          <button
            onClick={() => onSelect(planId)}
            disabled={loading}
            className={`mt-4 w-full py-3 rounded-xl text-sm font-bold transition-all ${
              plan.highlight
                ? 'bg-blue-600 hover:bg-blue-700 text-white shadow-sm hover:shadow-md'
                : 'bg-gray-900 hover:bg-gray-800 text-white'
            } disabled:opacity-50 disabled:cursor-not-allowed`}
          >
            {loading ? <Loader2 className="w-4 h-4 animate-spin mx-auto" /> : `Upgrade to ${plan.name}`}
          </button>
        )}
      </div>
    </div>
  );
}

function PaymentStatusPoller({ reference, onSuccess, onFailure }) {
  const pollCount = useRef(0);

  useEffect(() => {
    if (!reference) return;

    const interval = setInterval(async () => {
      pollCount.current += 1;
      if (pollCount.current > POLL_MAX) {
        clearInterval(interval);
        onFailure('Payment verification timed out. Contact support if charged.');
        return;
      }

      try {
        const res = await api.subscriptions.status(reference);
        if (res?.data?.status === 'success') {
          clearInterval(interval);
          onSuccess(res.data);
        } else if (res?.data?.status === 'failed') {
          clearInterval(interval);
          onFailure('Payment was not completed. Please try again.');
        }
      } catch {}
    }, POLL_INTERVAL);

    return () => clearInterval(interval);
  }, [reference, onSuccess, onFailure]);

  return (
    <div className="flex flex-col items-center justify-center gap-4 p-8">
      <Loader2 className="w-10 h-10 text-blue-500 animate-spin" />
      <p className="text-sm font-semibold text-gray-700">Verifying your payment…</p>
      <p className="text-xs text-gray-400">This usually takes a few seconds. Do not close this tab.</p>
    </div>
  );
}

// ─── Payments Tab ─────────────────────────────────────────────────────────────

function PaymentsTab({ onToast }) {
  const { plan, status, hasAccess, evaluationsUsed, evaluationsLimit, currentPeriodEnd, reload } = useEntitlements();
  const [checkoutLoading, setCheckoutLoading] = useState(false);
  const [pendingPlan, setPendingPlan] = useState(null);
  const [pollingRef, setPollingRef] = useState(null);
  const [cancelConfirm, setCancelConfirm] = useState(false);
  const [cancelLoading, setCancelLoading] = useState(false);
  const [searchParams] = useSearchParams();

  useEffect(() => {
    const ref = searchParams.get('reference') || searchParams.get('trxref');
    if (ref) {
      setPollingRef(ref);
    }
  }, [searchParams]);

  const handleSelect = useCallback(async (planId) => {
    setCheckoutLoading(true);
    setPendingPlan(planId);
    try {
      const res = await api.subscriptions.checkout({
        planId,
        email: '',
        callbackUrl: `${window.location.origin}/dashboard?tab=payments`,
      });

      if (res?.authorizationUrl) {
        window.location.href = res.authorizationUrl;
      } else if (res?.redirectUrl) {
        window.location.href = res.redirectUrl;
      } else {
        onToast('Unable to initiate checkout. Please try again.', 'error');
      }
    } catch (err) {
      onToast(err.message || 'Checkout failed.', 'error');
    } finally {
      setCheckoutLoading(false);
      setPendingPlan(null);
    }
  }, [onToast]);

  const handlePaymentSuccess = useCallback(async (data) => {
    setPollingRef(null);
    await reload();
    onToast(`🎉 ${PLAN_DISPLAY[data.planId]?.name || 'Plan'} activated! Welcome.`, 'success');
    window.history.replaceState({}, '', window.location.pathname);
  }, [reload, onToast]);

  const handlePaymentFailure = useCallback((msg) => {
    setPollingRef(null);
    onToast(msg, 'error');
    window.history.replaceState({}, '', window.location.pathname);
  }, [onToast]);

  const handleCancel = useCallback(async () => {
    setCancelLoading(true);
    try {
      await api.subscriptions.cancel();
      await reload();
      onToast('Subscription cancelled. Access continues until period end.', 'info');
      setCancelConfirm(false);
    } catch (err) {
      onToast(err.message || 'Cancellation failed.', 'error');
    } finally {
      setCancelLoading(false);
    }
  }, [reload, onToast]);

  const usagePct = evaluationsLimit
    ? Math.min(Math.round((evaluationsUsed / evaluationsLimit) * 100), 100)
    : 0;

  if (pollingRef) {
    return (
      <div className="max-w-md mx-auto mt-16">
        <div className="bg-white rounded-2xl border border-gray-100 shadow-sm overflow-hidden">
          <div className="bg-blue-600 px-6 py-4">
            <h2 className="text-white font-bold">Completing your payment</h2>
          </div>
          <PaymentStatusPoller
            reference={pollingRef}
            onSuccess={handlePaymentSuccess}
            onFailure={handlePaymentFailure}
          />
        </div>
      </div>
    );
  }

  return (
    <div className="max-w-6xl mx-auto space-y-8">

      {hasAccess && (
        <div className="bg-white rounded-2xl border border-gray-100 shadow-sm p-6">
          <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
            <div>
              <p className="text-xs text-gray-400 font-semibold uppercase tracking-wider">Active plan</p>
              <div className="flex items-center gap-3 mt-1.5">
                <h2 className="text-2xl font-black text-gray-900 capitalize">{plan}</h2>
                <Badge variant="success" size="md">{status}</Badge>
              </div>
              {currentPeriodEnd && (
                <p className="text-xs text-gray-500 mt-1">
                  Renews {fmt.date(currentPeriodEnd)}
                </p>
              )}
            </div>
            <button
              onClick={() => setCancelConfirm(true)}
              className="self-start sm:self-auto text-xs font-semibold text-gray-400 hover:text-red-500 transition-colors underline underline-offset-2"
            >
              Cancel subscription
            </button>
          </div>

          {evaluationsLimit != null && (
            <div className="mt-5 pt-5 border-t border-gray-100">
              <div className="flex items-center justify-between mb-2">
                <span className="text-xs font-semibold text-gray-600">Evaluations this month</span>
                <span className="text-xs font-bold text-gray-800 tabular-nums">
                  {evaluationsUsed} / {evaluationsLimit}
                </span>
              </div>
              <div className="h-2 bg-gray-100 rounded-full overflow-hidden">
                <div
                  className={`h-full rounded-full transition-all duration-700 ${usagePct > 90 ? 'bg-red-500' : usagePct > 70 ? 'bg-amber-500' : 'bg-blue-500'}`}
                  style={{ width: `${usagePct}%` }}
                />
              </div>
              {usagePct > 80 && (
                <p className="text-xs text-amber-600 font-semibold mt-1.5 flex items-center gap-1">
                  <AlertCircle className="w-3.5 h-3.5" />
                  Approaching monthly limit — consider upgrading
                </p>
              )}
            </div>
          )}
        </div>
      )}

      {cancelConfirm && (
        <div className="fixed inset-0 bg-gray-900/50 z-50 flex items-center justify-center p-4 backdrop-blur-sm" onClick={() => setCancelConfirm(false)}>
          <div className="bg-white rounded-2xl shadow-2xl p-6 max-w-sm w-full" onClick={e => e.stopPropagation()}>
            <h3 className="text-base font-bold text-gray-900">Cancel subscription?</h3>
            <p className="text-sm text-gray-500 mt-2">
              You'll keep access until {fmt.date(currentPeriodEnd)}. No refunds for remaining days.
            </p>
            <div className="flex gap-3 mt-6">
              <button onClick={() => setCancelConfirm(false)}
                className="flex-1 py-2.5 rounded-xl text-sm font-bold bg-gray-100 hover:bg-gray-200 text-gray-700 transition-colors">
                Keep plan
              </button>
              <button onClick={handleCancel} disabled={cancelLoading}
                className="flex-1 py-2.5 rounded-xl text-sm font-bold bg-red-600 hover:bg-red-700 text-white transition-colors disabled:opacity-50">
                {cancelLoading ? <Loader2 className="w-4 h-4 animate-spin mx-auto" /> : 'Yes, cancel'}
              </button>
            </div>
          </div>
        </div>
      )}

      <div>
        <h2 className="text-lg font-black text-gray-900 mb-1">
          {hasAccess ? 'Change plan' : 'Choose your plan'}
        </h2>
        <p className="text-sm text-gray-500 mb-6">All plans are billed monthly. Cancel any time.</p>

        <div className="grid grid-cols-1 md:grid-cols-3 gap-5">
          {['starter', 'growth', 'enterprise'].map(id => (
            <PlanCard
              key={id}
              planId={id}
              current={plan}
              onSelect={handleSelect}
              loading={checkoutLoading && pendingPlan === id}
            />
          ))}
        </div>

        <p className="text-xs text-gray-400 text-center mt-6">
          Payments processed via Paystack or Flutterwave. Secure & encrypted.
          <a href="mailto:billing@skillnexus.uk" className="text-blue-500 hover:underline ml-1">
            Billing questions?
          </a>
        </p>
      </div>
    </div>
  );
}

// ─── Analytics Tab ────────────────────────────────────────────────────────────

function AnalyticsTab({ data, loading }) {
  const { can } = useEntitlements();

  return (
    <FeatureGate feature="aiInsights">
      <div className="max-w-6xl mx-auto space-y-5">
        <h2 className="text-base font-bold text-gray-900">Analytics</h2>

        {data.verifyStats?.scoreDistribution && (
          <div className="bg-white rounded-2xl border border-gray-100 shadow-sm p-5">
            <h3 className="text-sm font-bold text-gray-900 mb-4 flex items-center gap-2">
              <PieChart className="w-4 h-4 text-indigo-500" />
              Score Distribution
            </h3>
            <div className="space-y-3">
              {Object.entries(data.verifyStats.scoreDistribution).map(([range, count]) => {
                const total = Object.values(data.verifyStats.scoreDistribution).reduce((a, b) => a + b, 0);
                const pct = total ? Math.round((count / total) * 100) : 0;
                const color = range === '85-100' ? 'bg-emerald-500' : range === '70-84' ? 'bg-blue-500' : range === '50-69' ? 'bg-amber-500' : 'bg-red-400';
                return (
                  <div key={range} className="flex items-center gap-3">
                    <span className="text-xs font-mono text-gray-500 w-14 flex-shrink-0 text-right">{range}</span>
                    <div className="flex-1 bg-gray-100 rounded-full h-2.5 overflow-hidden">
                      <div className={`h-full rounded-full ${color} transition-all duration-700`} style={{ width: `${pct}%` }} />
                    </div>
                    <span className="text-xs font-bold text-gray-700 w-10 text-right tabular-nums">{count}</span>
                    <span className="text-[11px] text-gray-400 w-8 tabular-nums">{pct}%</span>
                  </div>
                );
              })}
            </div>
          </div>
        )}

        {data.verifyStats && (
          <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
            {[
              { label: 'Verification Rate', value: fmt.percent(data.verifyStats.verificationRate), icon: <Activity className="w-4 h-4" /> },
              { label: 'Avg Score', value: data.verifyStats.avgScore ?? '—', icon: <Star className="w-4 h-4" /> },
              { label: 'Top Score', value: data.verifyStats.maxScore ?? '—', icon: <TrendingUp className="w-4 h-4" /> },
              { label: 'Pass Threshold', value: data.verifyStats.threshold ?? 70, icon: <ShieldCheck className="w-4 h-4" /> },
            ].map((s, i) => (
              <div key={i} className="bg-white rounded-xl border border-gray-100 p-4 shadow-sm flex items-center gap-3">
                <div className="p-2 bg-indigo-50 text-indigo-600 rounded-lg flex-shrink-0">{s.icon}</div>
                <div className="min-w-0">
                  <p className="text-[10px] text-gray-400 font-medium truncate">{s.label}</p>
                  <p className="text-lg font-black text-gray-900 tabular-nums">{s.value}</p>
                </div>
              </div>
            ))}
          </div>
        )}

        {loading.verifyStats && (
          <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
            {Array(4).fill(0).map((_, i) => <Skeleton key={i} className="h-20 rounded-xl" />)}
          </div>
        )}
      </div>
    </FeatureGate>
  );
}

// ─── Candidates Tab ───────────────────────────────────────────────────────────

function CandidatesTab({ data, loading, navigate }) {
  const [filter, setFilter] = useState('all');

  const filtered = useMemo(() => {
    const list = Array.isArray(data.candidates) ? data.candidates : [];
    if (filter === 'verified') return list.filter(c => c.verified);
    if (filter === 'failed') return list.filter(c => !c.verified);
    return list;
  }, [data.candidates, filter]);

  return (
    <div className="max-w-6xl mx-auto space-y-4">
      <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3">
        <h2 className="text-base font-bold text-gray-900">Candidate Verifications</h2>
        <button
          onClick={() => navigate('/results')}
          className="self-start sm:self-auto px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white text-xs font-bold rounded-xl inline-flex items-center gap-1.5 transition-all"
        >
          <ShieldCheck className="w-3.5 h-3.5" /> Verify Candidate
        </button>
      </div>

      {data.verifyStats && (
        <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
          <StatCard label="Total" value={fmt.number(data.verifyStats.totalCandidates)} icon={<Users className="w-4 h-4" />} />
          <StatCard label="Verified" value={fmt.number(data.verifyStats.verifiedCandidates)} icon={<CheckCircle2 className="w-4 h-4" />} positive />
          <StatCard label="Pass Rate" value={fmt.percent(data.verifyStats.verificationRate)} icon={<TrendingUp className="w-4 h-4" />} positive={(data.verifyStats.verificationRate || 0) >= 30} />
          <StatCard label="Avg Score" value={data.verifyStats.avgScore} icon={<Star className="w-4 h-4" />} positive={(data.verifyStats.avgScore || 0) >= 70} />
        </div>
      )}

      <div className="bg-white rounded-2xl border border-gray-100 shadow-sm overflow-hidden">
        <div className="px-5 py-3.5 border-b border-gray-100 flex items-center justify-between gap-3">
          <span className="text-xs font-bold text-gray-500 uppercase tracking-wider">Candidates</span>
          <div className="flex gap-1">
            {['all', 'verified', 'failed'].map(f => (
              <button key={f} onClick={() => setFilter(f)}
                className={`px-2.5 py-1 rounded-lg text-[11px] font-semibold transition-colors capitalize ${filter === f ? 'bg-blue-600 text-white' : 'text-gray-500 hover:bg-gray-100'}`}>
                {f}
              </button>
            ))}
          </div>
        </div>

        <div className="overflow-x-auto">
          <table className="w-full text-sm min-w-[500px]">
            <thead>
              <tr className="border-b border-gray-100 bg-gray-50/60">
                <th className="px-5 py-3 text-left text-[11px] font-semibold text-gray-400 uppercase tracking-wider">ID</th>
                <th className="px-5 py-3 text-left text-[11px] font-semibold text-gray-400 uppercase tracking-wider">Score</th>
                <th className="px-5 py-3 text-left text-[11px] font-semibold text-gray-400 uppercase tracking-wider">Status</th>
                <th className="px-5 py-3 text-left text-[11px] font-semibold text-gray-400 uppercase tracking-wider hidden sm:table-cell">Verified</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-gray-50">
              {loading.candidates
                ? Array(5).fill(0).map((_, i) => (
                    <tr key={i}><td colSpan={4} className="px-5 py-3"><Skeleton className="h-4 w-full" /></td></tr>
                  ))
                : filtered.length === 0
                  ? (
                      <tr><td colSpan={4} className="px-5 py-10 text-center">
                        <Users className="w-8 h-8 text-gray-200 mx-auto mb-2" />
                        <p className="text-sm text-gray-400 font-medium">No candidates found</p>
                      </td></tr>
                    )
                  : filtered.map(c => (
                      <tr key={c.id} className="hover:bg-gray-50 transition-colors">
                        <td className="px-5 py-3.5 text-xs font-mono font-semibold text-gray-700 truncate max-w-[120px]">{c.candidate_id || c.id}</td>
                        <td className="px-5 py-3.5">
                          <div className="flex items-center gap-2">
                            <div className="w-14 bg-gray-100 rounded-full h-1.5 hidden sm:block">
                              <div
                                className={`h-full rounded-full ${c.score >= 70 ? 'bg-emerald-500' : c.score >= 50 ? 'bg-amber-500' : 'bg-red-400'}`}
                                style={{ width: `${c.score || 0}%` }}
                              />
                            </div>
                            <span className="text-xs font-bold text-gray-800 tabular-nums">{c.score}%</span>
                          </div>
                        </td>
                        <td className="px-5 py-3.5">
                          <Badge variant={c.verified ? 'success' : 'danger'}>
                            {c.verified ? 'Verified' : 'Not verified'}
                          </Badge>
                        </td>
                        <td className="px-5 py-3.5 text-xs text-gray-400 hidden sm:table-cell">{fmt.date(c.verified_at)}</td>
                      </tr>
                    ))
              }
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}

// ─── Audits Tab ───────────────────────────────────────────────────────────────

function AuditsTab({ data, loading, setData, onToast, navigate }) {
  const audits = Array.isArray(data.audits) ? data.audits : [];

  const auditStats = useMemo(() => ({
    total: audits.length,
    avgScore: audits.length ? Math.round(audits.reduce((a, b) => a + (b.severity_score || 0), 0) / audits.length) : 0,
    converted: audits.filter(a => a.status === 'converted').length,
    newLeads: audits.filter(a => a.status === 'new').length,
  }), [audits]);

  const handleStatusChange = useCallback(async (auditId, status) => {
    setData(prev => ({
      ...prev,
      audits: prev.audits.map(a => a.id === auditId ? { ...a, status } : a),
    }));
    try {
      await api.audit.updateStatus(auditId, status);
    } catch (err) {
      onToast('Status update failed.', 'error');
    }
  }, [setData, onToast]);

  return (
    <div className="max-w-6xl mx-auto space-y-4">
      <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3">
        <h2 className="text-base font-bold text-gray-900">Hiring Audits</h2>
        <button className="self-start sm:self-auto px-4 py-2 bg-white border border-gray-200 text-gray-700 text-xs font-bold rounded-xl inline-flex items-center gap-1.5 hover:bg-gray-50 transition-all">
          <Download className="w-3.5 h-3.5" /> Export CSV
        </button>
      </div>

      <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
        {[
          { label: 'Total Audits', value: auditStats.total },
          { label: 'Avg Severity', value: auditStats.avgScore || '—' },
          { label: 'Converted', value: auditStats.converted },
          { label: 'New Leads', value: auditStats.newLeads },
        ].map((s, i) => (
          <div key={i} className="bg-white rounded-xl border border-gray-100 p-4 shadow-sm">
            <p className="text-[10px] text-gray-400 font-medium uppercase tracking-wider">{s.label}</p>
            <p className="text-xl font-black text-gray-900 mt-1 tabular-nums">{s.value}</p>
          </div>
        ))}
      </div>

      <div className="bg-white rounded-2xl border border-gray-100 shadow-sm overflow-hidden">
        <div className="overflow-x-auto">
          <table className="w-full text-sm min-w-[600px]">
            <thead>
              <tr className="border-b border-gray-100 bg-gray-50/60">
                {['Company', 'Industry', 'Size', 'Score', 'Tier', 'Status', 'Submitted'].map(h => (
                  <th key={h} className="px-4 py-3 text-left text-[11px] font-semibold text-gray-400 uppercase tracking-wider">{h}</th>
                ))}
              </tr>
            </thead>
            <tbody className="divide-y divide-gray-50">
              {loading.audits
                ? Array(5).fill(0).map((_, i) => (
                    <tr key={i}><td colSpan={7} className="px-4 py-3"><Skeleton className="h-4 w-full" /></td></tr>
                  ))
                : audits.length === 0
                  ? (
                      <tr><td colSpan={7} className="px-4 py-10 text-center">
                        <FileText className="w-8 h-8 text-gray-200 mx-auto mb-2" />
                        <p className="text-sm text-gray-400 font-medium">No audits yet</p>
                      </td></tr>
                    )
                  : audits.map(a => {
                      const tierCfg = TIER_CONFIG[a.score_tier] || TIER_CONFIG.low;
                      return (
                        <tr key={a.id}
                          className="hover:bg-gray-50/80 transition-colors cursor-pointer"
                          onClick={() => navigate(`/results?id=${a.id}`)}>
                          <td className="px-4 py-3 text-xs font-semibold text-gray-900 max-w-[140px] truncate">{a.company_name}</td>
                          <td className="px-4 py-3 text-xs text-gray-500">{a.industry}</td>
                          <td className="px-4 py-3 text-xs text-gray-500">{a.company_size}</td>
                          <td className="px-4 py-3">
                            <span className="text-sm font-black text-gray-800 tabular-nums">{a.severity_score}</span>
                            <span className="text-gray-400 text-xs">/100</span>
                          </td>
                          <td className="px-4 py-3">
                            <span className={`inline-flex items-center gap-1 text-[10px] font-bold px-2 py-0.5 rounded-full ${tierCfg.bg} ${tierCfg.text}`}>
                              <span className={`w-1.5 h-1.5 rounded-full ${tierCfg.dot}`} />
                              {a.score_tier}
                            </span>
                          </td>
                          <td className="px-4 py-3" onClick={e => e.stopPropagation()}>
                            <select
                              value={a.status || 'new'}
                              onChange={e => handleStatusChange(a.id, e.target.value)}
                              className="text-[11px] font-semibold border border-gray-200 rounded-lg px-2 py-1 bg-white text-gray-700 focus:outline-none focus:ring-2 focus:ring-blue-500/20 cursor-pointer"
                            >
                              <option value="new">New</option>
                              <option value="contacted">Contacted</option>
                              <option value="converted">Converted</option>
                            </select>
                          </td>
                          <td className="px-4 py-3 text-[11px] text-gray-400">{fmt.reltime(a.created_at)}</td>
                        </tr>
                      );
                    })
              }
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}

// ─── Notifications Tab ────────────────────────────────────────────────────────

function NotificationsTab({ notifications, loading, unreadCount, onMarkRead, onMarkAll }) {
  return (
    <div className="max-w-3xl mx-auto space-y-3">
      <div className="flex items-center justify-between">
        <h2 className="text-base font-bold text-gray-900">
          Notifications
          {unreadCount > 0 && (
            <span className="text-gray-400 font-normal text-sm ml-1">({unreadCount} unread)</span>
          )}
        </h2>
        {unreadCount > 0 && (
          <button onClick={onMarkAll} className="text-xs text-blue-600 font-semibold hover:underline">
            Mark all read
          </button>
        )}
      </div>

      {loading
        ? Array(5).fill(0).map((_, i) => (
            <div key={i} className="bg-white rounded-xl border border-gray-100 p-4 flex gap-3">
              <Skeleton className="w-10 h-10 rounded-xl flex-shrink-0" />
              <div className="flex-1 space-y-2"><Skeleton className="h-3.5 w-40" /><Skeleton className="h-3 w-56" /></div>
            </div>
          ))
        : notifications.length === 0
          ? (
              <div className="bg-white rounded-2xl border border-gray-100 p-16 text-center">
                <Bell className="w-10 h-10 text-gray-200 mx-auto mb-3" />
                <p className="text-sm font-semibold text-gray-400">No notifications yet</p>
              </div>
            )
          : notifications.map(n => (
              <div
                key={n.id}
                className={`bg-white rounded-xl border shadow-sm p-4 flex items-start gap-3 cursor-pointer hover:shadow-md transition-all ${n.status === 'pending' ? 'border-blue-200 bg-blue-50/30' : 'border-gray-100'}`}
                onClick={() => onMarkRead(n.id)}
              >
                <div className={`p-2 rounded-xl flex-shrink-0 ${n.status === 'pending' ? 'bg-blue-100 text-blue-600' : 'bg-gray-100 text-gray-400'}`}>
                  {n.type === 'contact' ? <Mail className="w-4 h-4" /> :
                   n.type === 'audit' ? <FileText className="w-4 h-4" /> :
                   n.type === 'reminder' ? <Clock className="w-4 h-4" /> : <Bell className="w-4 h-4" />}
                </div>
                <div className="flex-1 min-w-0">
                  <div className="flex items-start justify-between gap-2">
                    <p className="text-sm font-semibold text-gray-900 truncate">{n.title}</p>
                    <Badge variant={n.priority === 'urgent' ? 'critical' : n.priority === 'high' ? 'danger' : n.priority === 'medium' ? 'warning' : 'info'}>
                      {n.priority}
                    </Badge>
                  </div>
                  <p className="text-xs text-gray-500 mt-0.5 line-clamp-2">{n.message}</p>
                  <p className="text-[11px] text-gray-400 mt-1.5">{fmt.reltime(n.created_at)}</p>
                </div>
                {n.status === 'pending' && <div className="w-2 h-2 rounded-full bg-blue-500 mt-2 flex-shrink-0" />}
              </div>
            ))
      }
    </div>
  );
}

// ─── API Keys Tab ─────────────────────────────────────────────────────────────

function ApiKeysTab({ onToast, user }) {
  const [apiKeys, setApiKeys] = useState([]);
  const [loading, setLoading] = useState(false);
  const [generating, setGenerating] = useState(false);
  const [newKey, setNewKey] = useState(null);
  const [showNewKey, setShowNewKey] = useState(false);
  const [copied, setCopied] = useState(false);
  const [keyName, setKeyName] = useState('');

  const fetchApiKeys = useCallback(async () => {
    setLoading(true);
    try {
      const res = await fetch('/api/public/auth/list', {
        headers: {
          'Authorization': `Bearer ${tokenStore.get()}`
        }
      });
      const data = await res.json();
      if (data.success) {
        setApiKeys(data.data || []);
      }
    } catch (err) {
      // Silent fail
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    fetchApiKeys();
  }, [fetchApiKeys]);

  const generateApiKey = useCallback(async () => {
    if (!keyName.trim()) {
      onToast('Please enter a name for your API key', 'warning');
      return;
    }

    setGenerating(true);
    try {
      const res = await fetch('/api/public/auth/register', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${tokenStore.get()}`
        },
        body: JSON.stringify({
          name: keyName.trim(),
          company: user?.company || 'Your Company',
          email: user?.email || 'dev@company.com'
        })
      });
      const data = await res.json();
      
      if (data.success) {
        setNewKey(data.data.apiKey);
        setShowNewKey(true);
        setKeyName('');
        onToast('API key generated successfully!', 'success');
        fetchApiKeys();
      } else {
        onToast(data.error || 'Failed to generate API key', 'error');
      }
    } catch (err) {
      onToast('Failed to generate API key', 'error');
    } finally {
      setGenerating(false);
    }
  }, [keyName, user, onToast, fetchApiKeys]);

  const revokeApiKey = useCallback(async (keyId) => {
    if (!confirm('Are you sure you want to revoke this API key? This action cannot be undone.')) return;

    try {
      const res = await fetch(`/api/public/auth/revoke/${keyId}`, {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${tokenStore.get()}`
        }
      });
      const data = await res.json();
      
      if (data.success) {
        onToast('API key revoked successfully', 'success');
        fetchApiKeys();
      } else {
        onToast(data.error || 'Failed to revoke API key', 'error');
      }
    } catch (err) {
      onToast('Failed to revoke API key', 'error');
    }
  }, [fetchApiKeys, onToast]);

  const copyToClipboard = (text) => {
    navigator.clipboard.writeText(text);
    setCopied(true);
    setTimeout(() => setCopied(false), 3000);
  };

  return (
    <div className="max-w-4xl mx-auto space-y-6">
      <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3">
        <div>
          <h2 className="text-base font-bold text-gray-900">API Keys</h2>
          <p className="text-xs text-gray-500 mt-0.5">Manage your API keys for programmatic access</p>
        </div>
      </div>

      <div className="bg-white rounded-2xl border border-gray-100 shadow-sm p-6">
        <h3 className="text-sm font-bold text-gray-900 mb-2">Generate New API Key</h3>
        <p className="text-xs text-gray-500 mb-4">
          Create a new API key for integration with your applications. Keys are rate-limited and can be revoked at any time.
        </p>
        
        <div className="flex flex-col sm:flex-row gap-3">
          <input
            type="text"
            value={keyName}
            onChange={(e) => setKeyName(e.target.value)}
            placeholder="e.g., Production API, Staging, etc."
            className="flex-1 px-3 py-2 border border-gray-200 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:border-transparent"
          />
          <button
            onClick={generateApiKey}
            disabled={generating}
            className="px-6 py-2 bg-blue-600 hover:bg-blue-700 text-white text-sm font-semibold rounded-lg transition-colors disabled:opacity-50 flex items-center gap-2"
          >
            {generating ? <Loader2 className="w-4 h-4 animate-spin" /> : <Key className="w-4 h-4" />}
            {generating ? 'Generating...' : 'Generate Key'}
          </button>
        </div>
      </div>

      {showNewKey && newKey && (
        <div className="bg-emerald-50 border-2 border-emerald-500 rounded-2xl p-6">
          <div className="flex items-start gap-3">
            <CheckCircle2 className="w-5 h-5 text-emerald-600 mt-0.5 flex-shrink-0" />
            <div className="flex-1 min-w-0">
              <h4 className="text-sm font-bold text-emerald-900">Your New API Key</h4>
              <p className="text-xs text-emerald-700 mt-0.5">
                Copy this key now. It will not be shown again for security reasons.
              </p>
              <div className="mt-3 flex flex-col sm:flex-row gap-2">
                <code className="flex-1 bg-white px-3 py-2 rounded-lg text-xs font-mono text-gray-800 border border-emerald-200 break-all">
                  {newKey}
                </code>
                <button
                  onClick={() => copyToClipboard(newKey)}
                  className="px-4 py-2 bg-emerald-600 hover:bg-emerald-700 text-white text-xs font-semibold rounded-lg transition-colors flex items-center gap-2 whitespace-nowrap"
                >
                  {copied ? <Check className="w-3.5 h-3.5" /> : <Copy className="w-3.5 h-3.5" />}
                  {copied ? 'Copied!' : 'Copy Key'}
                </button>
              </div>
            </div>
            <button
              onClick={() => setShowNewKey(false)}
              className="text-emerald-600 hover:text-emerald-800 transition-colors"
            >
              <X className="w-4 h-4" />
            </button>
          </div>
        </div>
      )}

      <div className="bg-white rounded-2xl border border-gray-100 shadow-sm overflow-hidden">
        <div className="px-5 py-4 border-b border-gray-100 flex items-center justify-between">
          <h3 className="text-xs font-bold text-gray-500 uppercase tracking-wider">Your API Keys</h3>
          <span className="text-[10px] text-gray-400">{apiKeys.length} key{apiKeys.length !== 1 ? 's' : ''}</span>
        </div>

        {loading ? (
          <div className="p-8 text-center">
            <Loader2 className="w-6 h-6 text-blue-500 animate-spin mx-auto" />
            <p className="text-xs text-gray-400 mt-2">Loading your API keys...</p>
          </div>
        ) : apiKeys.length === 0 ? (
          <div className="p-12 text-center">
            <Key className="w-10 h-10 text-gray-200 mx-auto mb-3" />
            <p className="text-sm text-gray-400 font-medium">No API keys yet</p>
            <p className="text-xs text-gray-400 mt-1">Generate your first API key above</p>
          </div>
        ) : (
          <div className="divide-y divide-gray-50">
            {apiKeys.map((key) => (
              <div key={key.id} className="px-5 py-4 flex flex-col sm:flex-row sm:items-center justify-between gap-3">
                <div className="min-w-0">
                  <p className="text-sm font-semibold text-gray-900">{key.name || 'Unnamed'}</p>
                  <div className="flex flex-wrap items-center gap-2 mt-0.5">
                    <code className="text-xs font-mono text-gray-500 bg-gray-50 px-2 py-0.5 rounded">
                      {fmt.truncate(key.key_hash ? `pk_skillnexus_...${key.key_hash.slice(-8)}` : '••••••••')}
                    </code>
                    <span className="w-1 h-1 rounded-full bg-gray-300" />
                    <span className="text-[10px] text-gray-400">
                      Created {fmt.reltime(key.created_at)}
                    </span>
                    {key.active === 1 ? (
                      <Badge variant="success" size="sm">Active</Badge>
                    ) : (
                      <Badge variant="danger" size="sm">Revoked</Badge>
                    )}
                  </div>
                  <div className="flex flex-wrap items-center gap-3 mt-1.5 text-[10px] text-gray-400">
                    <span className="flex items-center gap-1">
                      <Clock className="w-3 h-3" />
                      {key.minute_limit || 60}/min
                    </span>
                    <span className="flex items-center gap-1">
                      <Database className="w-3 h-3" />
                      {key.daily_limit || 1000}/day
                    </span>
                    {key.usage_count !== undefined && (
                      <span className="flex items-center gap-1">
                        <Activity className="w-3 h-3" />
                        {key.usage_count} requests
                      </span>
                    )}
                  </div>
                </div>
                {key.active === 1 && (
                  <button
                    onClick={() => revokeApiKey(key.id)}
                    className="self-start sm:self-auto px-3 py-1.5 text-xs font-semibold text-red-600 hover:bg-red-50 rounded-lg transition-colors"
                  >
                    Revoke
                  </button>
                )}
              </div>
            ))}
          </div>
        )}
      </div>

      <div className="bg-gray-50 rounded-2xl border border-gray-200 p-5">
        <div className="flex items-start gap-3">
          <ShieldCheck className="w-5 h-5 text-gray-400 mt-0.5 flex-shrink-0" />
          <div>
            <h4 className="text-xs font-bold text-gray-700">Rate Limits</h4>
            <ul className="text-xs text-gray-500 mt-1 space-y-1">
              <li>• <span className="font-semibold">60</span> requests per minute</li>
              <li>• <span className="font-semibold">1,000</span> requests per day</li>
              <li>• Rate limits reset at midnight UTC</li>
              <li className="mt-2 text-[10px] text-gray-400">
                💡 Monitor your usage in the dashboard or via the <code className="bg-gray-200 px-1.5 py-0.5 rounded text-[10px]">/api/public/auth/verify</code> endpoint
              </li>
            </ul>
          </div>
        </div>
      </div>
    </div>
  );
}

// ─── Settings Tab ─────────────────────────────────────────────────────────────

function SettingsTab({ user, refreshing, onRefresh, onLogout, onSwitchTab }) {
  return (
    <div className="max-w-xl mx-auto space-y-4">
      <h2 className="text-base font-bold text-gray-900">Settings</h2>

      <div className="bg-white rounded-2xl border border-gray-100 shadow-sm divide-y divide-gray-100">
        <div className="p-5">
          <h3 className="text-xs font-bold text-gray-500 uppercase tracking-wider mb-3">Account</h3>
          {[
            ['Name', user?.name || '—'],
            ['Email', user?.email || '—'],
            ['Role', user?.role || 'Admin'],
            ['Company', user?.company || '—'],
          ].map(([label, value]) => (
            <div key={label} className="flex items-center justify-between py-2">
              <span className="text-xs text-gray-500">{label}</span>
              <span className="text-xs font-semibold text-gray-800 truncate max-w-[200px]">{value}</span>
            </div>
          ))}
        </div>

        <div className="p-5">
          <h3 className="text-xs font-bold text-gray-500 uppercase tracking-wider mb-1">Data</h3>
          <p className="text-xs text-gray-400 mb-3">Dashboard auto-refreshes every 90 seconds.</p>
          <button
            onClick={onRefresh}
            disabled={refreshing}
            className="px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white text-xs font-bold rounded-xl inline-flex items-center gap-1.5 disabled:opacity-50 transition-all"
          >
            <RefreshCw className={`w-3.5 h-3.5 ${refreshing ? 'animate-spin' : ''}`} />
            {refreshing ? 'Refreshing…' : 'Refresh now'}
          </button>
        </div>

        <div className="p-5">
          <h3 className="text-xs font-bold text-gray-500 uppercase tracking-wider mb-3">API Access</h3>
          <p className="text-xs text-gray-400 mb-3">Generate API keys for programmatic access.</p>
          <button
            onClick={() => onSwitchTab('api-keys')}
            className="px-4 py-2 bg-violet-600 hover:bg-violet-700 text-white text-xs font-bold rounded-xl inline-flex items-center gap-1.5 transition-all"
          >
            <Key className="w-3.5 h-3.5" /> Manage API Keys
          </button>
        </div>

        <div className="p-5">
          <h3 className="text-xs font-bold text-gray-500 uppercase tracking-wider mb-3">Support</h3>
          <div className="flex flex-wrap gap-2">
            <a href="mailto:support@skillnexus.uk"
              className="px-3 py-1.5 bg-gray-100 hover:bg-gray-200 text-gray-700 text-xs font-semibold rounded-lg inline-flex items-center gap-1.5 transition-colors">
              <Mail className="w-3.5 h-3.5" /> Email support
            </a>
            <a href="https://app.skillnexus.uk/api-docs" target="_blank" rel="noopener noreferrer"
              className="px-3 py-1.5 bg-gray-100 hover:bg-gray-200 text-gray-700 text-xs font-semibold rounded-lg inline-flex items-center gap-1.5 transition-colors">
              <BookOpen className="w-3.5 h-3.5" /> Documentation
            </a>
            <a href="https://app.skillnexus.uk/PublicApiDocs" target="_blank" rel="noopener noreferrer"
              className="px-3 py-1.5 bg-gray-100 hover:bg-gray-200 text-gray-700 text-xs font-semibold rounded-lg inline-flex items-center gap-1.5 transition-colors">
              <Terminal className="w-3.5 h-3.5" /> API Reference
            </a>
          </div>
        </div>

        <div className="p-5">
          <button onClick={onLogout}
            className="px-4 py-2 bg-red-50 hover:bg-red-100 text-red-600 text-xs font-bold rounded-xl inline-flex items-center gap-1.5 transition-all">
            <LogOut className="w-3.5 h-3.5" /> Sign out
          </button>
        </div>
      </div>
    </div>
  );
}

// ─── Overview Tab ─────────────────────────────────────────────────────────────

function OverviewTab({ data, loading, aiInsight, aiLoading, user, navigate, setActiveTab }) {
  const { hasAccess, plan } = useEntitlements();
  const { verifyStats, dashStats, overview, audits, candidates, jobs } = data;
  const auditList = Array.isArray(audits) ? audits : [];
  const candidateList = Array.isArray(candidates) ? candidates : [];
  const jobList = Array.isArray(jobs) ? jobs : [];

  const stats = [
    {
      label: 'Total Candidates',
      value: fmt.number(verifyStats?.totalCandidates ?? dashStats?.totalCandidates),
      delta: `${verifyStats?.verificationRate ?? 0}% verified`,
      positive: (verifyStats?.verificationRate ?? 0) >= 30,
      icon: <Users className="w-5 h-5" />,
    },
    {
      label: 'Verified This Month',
      value: fmt.number(verifyStats?.verifiedCandidates ?? dashStats?.verifiedCandidates),
      delta: `Avg ${verifyStats?.avgScore ?? 0}/100`,
      positive: (verifyStats?.avgScore ?? 0) >= 70,
      icon: <ShieldCheck className="w-5 h-5" />,
    },
    {
      label: 'Active Jobs',
      value: fmt.number(jobList.filter(j => j.status === 'active').length),
      delta: `${jobList.length} total jobs`,
      positive: jobList.length > 0,
      icon: <BriefcaseIcon className="w-5 h-5" />,
    },
    {
      label: 'Total Placements',
      value: fmt.number(overview?.metrics?.totalPlacements ?? dashStats?.totalPlacements),
      delta: `${overview?.metrics?.activeSubscriptions ?? 0} active co.`,
      positive: true,
      icon: <Briefcase className="w-5 h-5" />,
    },
  ];

  return (
    <div className="space-y-5 max-w-7xl mx-auto">
      <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3">
        <div>
          <h2 className="text-xl font-black text-gray-900 tracking-tight">
            Good {new Date().getHours() < 12 ? 'morning' : new Date().getHours() < 17 ? 'afternoon' : 'evening'}, {user?.name?.split(' ')[0] || 'there'} 👋
          </h2>
          <p className="text-xs text-gray-500 mt-0.5">Here's what's happening across your hiring pipelines.</p>
        </div>
        <div className="flex items-center gap-2 flex-wrap">
          <button
            onClick={() => navigate('/results')}
            className="px-3.5 py-2 bg-blue-600 hover:bg-blue-700 text-white text-xs font-bold rounded-xl inline-flex items-center gap-1.5 transition-all shadow-sm hover:shadow-md"
          >
            <ShieldCheck className="w-3.5 h-3.5" /> Verify candidate
          </button>
          {!hasAccess && (
            <button
              onClick={() => setActiveTab('payments')}
              className="px-3.5 py-2 bg-gradient-to-r from-amber-400 to-amber-500 text-white text-xs font-bold rounded-xl inline-flex items-center gap-1.5 transition-all shadow-sm hover:shadow-md"
            >
              <Zap className="w-3.5 h-3.5" /> Unlock all features
            </button>
          )}
        </div>
      </div>

      {!hasAccess && (
        <div className="bg-gradient-to-r from-amber-50 to-orange-50 border border-amber-200 rounded-2xl p-4 flex flex-col sm:flex-row sm:items-center justify-between gap-4">
          <div className="flex items-start gap-3">
            <AlertCircle className="w-5 h-5 text-amber-600 mt-0.5 flex-shrink-0" />
            <div>
              <p className="text-sm font-bold text-amber-900">You're on the free tier</p>
              <p className="text-xs text-amber-700 mt-0.5">Upgrade to unlock candidate verifications, AI insights, ATS integrations, and more.</p>
            </div>
          </div>
          <button
            onClick={() => setActiveTab('payments')}
            className="self-start sm:self-auto flex-shrink-0 px-4 py-2 bg-amber-500 hover:bg-amber-600 text-white text-xs font-bold rounded-xl transition-colors"
          >
            See plans
          </button>
        </div>
      )}

      <div className="grid grid-cols-2 lg:grid-cols-4 gap-3">
        {stats.map((s, i) => (
          <StatCard key={i} {...s} loading={loading.verifyStats || loading.overview || loading.dashStats} sub="vs last month" />
        ))}
      </div>

      {(aiInsight || aiLoading) && (
        <div className="bg-gradient-to-br from-slate-800 to-indigo-900 rounded-2xl p-4 text-white shadow-lg">
          <div className="flex items-start gap-3">
            <div className="p-1.5 bg-white/15 rounded-lg flex-shrink-0 mt-0.5">
              <Sparkles className="w-4 h-4" />
            </div>
            <div className="flex-1 min-w-0">
              <div className="flex items-center gap-2 mb-1.5">
                <p className="text-[10px] font-bold text-white/60 uppercase tracking-widest">AI Insight</p>
                <Badge variant="premium">Cloudflare AI</Badge>
              </div>
              {aiLoading
                ? <div className="space-y-1.5"><div className="h-3.5 bg-white/15 rounded animate-pulse w-3/4" /><div className="h-3.5 bg-white/15 rounded animate-pulse w-1/2" /></div>
                : <p className="text-sm leading-relaxed text-white/90">{aiInsight}</p>
              }
            </div>
          </div>
        </div>
      )}

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-4">
        {/* Recent Audits */}
        <div className="bg-white rounded-2xl border border-gray-100 shadow-sm overflow-hidden">
          <div className="px-5 py-4 border-b border-gray-100 flex items-center justify-between">
            <div>
              <h3 className="text-sm font-bold text-gray-900">Recent Audits</h3>
              <p className="text-[11px] text-gray-400 mt-0.5">Latest hiring pain-point submissions</p>
            </div>
            <button onClick={() => setActiveTab('audits')}
              className="text-xs font-semibold text-blue-600 hover:text-blue-700 inline-flex items-center gap-1">
              View all <ChevronRight className="w-3.5 h-3.5" />
            </button>
          </div>
          <div className="divide-y divide-gray-50 max-h-64 overflow-y-auto overscroll-contain">
            {loading.audits
              ? Array(4).fill(0).map((_, i) => (
                  <div key={i} className="px-5 py-3 flex items-center gap-3">
                    <Skeleton className="w-8 h-8 rounded-xl" />
                    <div className="flex-1 space-y-1.5"><Skeleton className="h-3 w-32" /><Skeleton className="h-2.5 w-20" /></div>
                  </div>
                ))
              : auditList.length === 0
                ? <div className="px-5 py-8 text-center text-xs text-gray-400">No audits yet</div>
                : auditList.slice(0, 5).map(a => {
                    const tierCfg = TIER_CONFIG[a.score_tier] || TIER_CONFIG.low;
                    return (
                      <div key={a.id} className="px-5 py-3 flex items-center gap-3 hover:bg-gray-50 transition-colors cursor-pointer"
                        onClick={() => navigate(`/results?id=${a.id}`)}>
                        <div className="w-8 h-8 rounded-xl bg-gray-100 text-gray-500 flex items-center justify-center flex-shrink-0">
                          <FileText className="w-3.5 h-3.5" />
                        </div>
                        <div className="flex-1 min-w-0">
                          <p className="text-xs font-semibold text-gray-900 truncate">{a.company_name}</p>
                          <p className="text-[11px] text-gray-400">{a.industry} · {fmt.reltime(a.created_at)}</p>
                        </div>
                        <div className="flex items-center gap-2 flex-shrink-0">
                          <span className="text-xs font-black text-gray-700 tabular-nums">{a.severity_score}</span>
                          <span className={`text-[10px] font-bold px-1.5 py-0.5 rounded-full ${tierCfg.bg} ${tierCfg.text}`}>
                            {a.score_tier}
                          </span>
                        </div>
                      </div>
                    );
                  })
            }
          </div>
        </div>

        {/* Recent Candidates */}
        <div className="bg-white rounded-2xl border border-gray-100 shadow-sm overflow-hidden">
          <div className="px-5 py-4 border-b border-gray-100 flex items-center justify-between">
            <div>
              <h3 className="text-sm font-bold text-gray-900">Candidates</h3>
              <p className="text-[11px] text-gray-400 mt-0.5">Latest verifications</p>
            </div>
            <button onClick={() => setActiveTab('candidates')}
              className="text-xs font-semibold text-blue-600 hover:text-blue-700 inline-flex items-center gap-1">
              View all <ChevronRight className="w-3.5 h-3.5" />
            </button>
          </div>
          <div className="divide-y divide-gray-50 max-h-64 overflow-y-auto overscroll-contain">
            {loading.candidates
              ? Array(4).fill(0).map((_, i) => (
                  <div key={i} className="px-5 py-3 flex items-center gap-3">
                    <Skeleton className="w-7 h-7 rounded-full" />
                    <div className="flex-1 space-y-1.5"><Skeleton className="h-3 w-28" /><Skeleton className="h-2.5 w-16" /></div>
                  </div>
                ))
              : candidateList.length === 0
                ? <div className="px-5 py-8 text-center text-xs text-gray-400">No candidates yet</div>
                : candidateList.slice(0, 5).map(c => (
                    <div key={c.id} className="px-5 py-3 flex items-center gap-3 hover:bg-gray-50 transition-colors">
                      <div className="w-7 h-7 rounded-full bg-indigo-100 text-indigo-600 flex items-center justify-center text-[10px] font-black flex-shrink-0">
                        {(c.candidate_id || 'C').slice(-2).toUpperCase()}
                      </div>
                      <div className="flex-1 min-w-0">
                        <p className="text-xs font-semibold text-gray-900 truncate">{c.candidate_id}</p>
                        <p className="text-[11px] text-gray-400">{fmt.reltime(c.verified_at)}</p>
                      </div>
                      <div className="flex items-center gap-2 flex-shrink-0">
                        <span className="text-xs font-black text-gray-800 tabular-nums">{c.score}%</span>
                        <Badge variant={c.verified ? 'success' : 'danger'}>
                          {c.verified ? 'Verified' : 'Failed'}
                        </Badge>
                      </div>
                    </div>
                  ))
            }
          </div>
        </div>

        {/* Recent Jobs */}
        <div className="bg-white rounded-2xl border border-gray-100 shadow-sm overflow-hidden">
          <div className="px-5 py-4 border-b border-gray-100 flex items-center justify-between">
            <div>
              <h3 className="text-sm font-bold text-gray-900">Recent Jobs</h3>
              <p className="text-[11px] text-gray-400 mt-0.5">Latest job postings</p>
            </div>
            <button onClick={() => setActiveTab('jobs')}
              className="text-xs font-semibold text-blue-600 hover:text-blue-700 inline-flex items-center gap-1">
              View all <ChevronRight className="w-3.5 h-3.5" />
            </button>
          </div>
          <div className="divide-y divide-gray-50 max-h-64 overflow-y-auto overscroll-contain">
            {loading.jobs
              ? Array(4).fill(0).map((_, i) => (
                  <div key={i} className="px-5 py-3 flex items-center gap-3">
                    <Skeleton className="w-8 h-8 rounded-xl" />
                    <div className="flex-1 space-y-1.5"><Skeleton className="h-3 w-32" /><Skeleton className="h-2.5 w-20" /></div>
                  </div>
                ))
              : jobList.length === 0
                ? <div className="px-5 py-8 text-center text-xs text-gray-400">No jobs posted yet</div>
                : jobList.slice(0, 5).map(j => (
                    <div key={j.id} className="px-5 py-3 flex items-center gap-3 hover:bg-gray-50 transition-colors cursor-pointer"
                      onClick={() => setActiveTab('jobs')}>
                      <div className="w-8 h-8 rounded-xl bg-blue-100 text-blue-600 flex items-center justify-center flex-shrink-0">
                        <BriefcaseIcon className="w-3.5 h-3.5" />
                      </div>
                      <div className="flex-1 min-w-0">
                        <p className="text-xs font-semibold text-gray-900 truncate">{j.title}</p>
                        <p className="text-[11px] text-gray-400">{j.location || 'Remote'} · {fmt.reltime(j.createdAt)}</p>
                      </div>
                      <JobStatusBadge status={j.status} />
                    </div>
                  ))
            }
          </div>
        </div>
      </div>
    </div>
  );
}

// ─── Main Dashboard ───────────────────────────────────────────────────────────

export function Dashboard() {
  const navigate = useNavigate();
  const [searchParams] = useSearchParams();

  const tabFromUrl = searchParams.get('tab');

  const [activeTab, setActiveTab] = useState(tabFromUrl || 'overview');
  const [isMobileMenuOpen, setIsMobileMenuOpen] = useState(false);
  const [searchQuery, setSearchQuery] = useState('');
  const [online, setOnline] = useState(navigator.onLine);
  const [refreshing, setRefreshing] = useState(false);
  const [lastUpdated, setLastUpdated] = useState(null);
  const [notifDropdown, setNotifDropdown] = useState(false);
  const [toast, setToast] = useState(null);
  const notifRef = useRef(null);
  const user = useRef(null);

  const [data, setData] = useState({
    overview: null, verifyStats: null, dashStats: null,
    audits: [], candidates: [], contacts: [], notifications: [], jobs: [],
  });

  const [loading, setLoading] = useState({
    overview: false, verifyStats: false, dashStats: false,
    audits: false, candidates: false, contacts: false, notifications: false, jobs: false,
  });

  const [unreadCount, setUnreadCount] = useState(0);
  const [aiInsight, setAiInsight] = useState('');
  const [aiLoading, setAiLoading] = useState(false);

  // ── Auth user ────────────────────────────────────────────────────────────
  useEffect(() => {
    api.auth.me().then(res => {
      if (res?.data || res?.user) {
        user.current = res.data || res.user;
      }
    }).catch(() => {});
  }, []);

  // ── Online/offline ───────────────────────────────────────────────────────
  useEffect(() => {
    const on = () => setOnline(true);
    const off = () => setOnline(false);
    window.addEventListener('online', on);
    window.addEventListener('offline', off);
    return () => { window.removeEventListener('online', on); window.removeEventListener('offline', off); };
  }, []);

  // ── Session expiry ───────────────────────────────────────────────────────
  useEffect(() => {
    const handler = () => {
      showToast('Your session expired. Please log in again.', 'warning');
      tokenStore.clear();
      setTimeout(() => navigate('/login', { replace: true }), 2000);
    };
    window.addEventListener('sknx:session-expired', handler);
    return () => window.removeEventListener('sknx:session-expired', handler);
  }, [navigate]);

  // ── Close notification dropdown on outside click ─────────────────────────
  useEffect(() => {
    const handler = e => { if (notifRef.current && !notifRef.current.contains(e.target)) setNotifDropdown(false); };
    document.addEventListener('mousedown', handler);
    return () => document.removeEventListener('mousedown', handler);
  }, []);

  // ── Mobile menu close on resize ──────────────────────────────────────────
  useEffect(() => {
    const handler = () => { if (window.innerWidth >= 768) setIsMobileMenuOpen(false); };
    window.addEventListener('resize', handler);
    return () => window.removeEventListener('resize', handler);
  }, []);

  // ── Toast helper ─────────────────────────────────────────────────────────
  const showToast = useCallback((message, type = 'info') => {
    setToast({ message, type, id: Date.now() });
  }, []);

  // ── Data fetching ────────────────────────────────────────────────────────
  const mark = useCallback((key, val) => setLoading(prev => ({ ...prev, [key]: val })), []);

  const settle = useCallback(async (key, fn, onSuccess) => {
    mark(key, true);
    try {
      const res = await fn();
      if (res?.success !== false) onSuccess(res?.data || res);
    } catch (e) {
      // Silent fail — mock data will show
    } finally {
      mark(key, false);
    }
  }, [mark]);

  const fetchData = useCallback(async () => {
    await Promise.allSettled([
      settle('overview', () => api.dashboard.overview(), d => setData(p => ({ ...p, overview: d }))),
      settle('verifyStats', () => api.verify.stats(), d => setData(p => ({ ...p, verifyStats: d }))),
      settle('dashStats', () => api.dashboard.stats(), d => setData(p => ({ ...p, dashStats: d }))),
      settle('audits', () => api.audit.list({ limit: 20 }), d => setData(p => ({ ...p, audits: d || [] }))),
      settle('candidates', () => api.verify.candidates({ limit: 20 }), d => setData(p => ({ ...p, candidates: d || [] }))),
      settle('notifications', () => api.notifications.list({ limit: 30 }), d => {
        setData(p => ({ ...p, notifications: d || [] }));
        setUnreadCount((d || []).filter(n => n.status === 'pending').length);
      }),
      settle('jobs', () => api.jobs.list({ limit: 20 }), d => setData(p => ({ ...p, jobs: d || [] }))),
    ]);
    setLastUpdated(new Date());
  }, [settle]);

  const refresh = useCallback(async () => {
    setRefreshing(true);
    await fetchData();
    setRefreshing(false);
  }, [fetchData]);

  // ── AI insight ───────────────────────────────────────────────────────────
  const fetchAiInsight = useCallback(async () => {
    const { verifyStats, dashStats, audits, jobs } = data;
    if (!verifyStats && !dashStats) return;
    setAiLoading(true);
    try {
      const res = await api.ai.insights({
        verifyStats,
        dashStats,
        auditCount: Array.isArray(audits) ? audits.length : 0,
        candidateCount: verifyStats?.totalCandidates,
        verificationRate: verifyStats?.verificationRate,
        jobCount: Array.isArray(jobs) ? jobs.length : 0,
        activeJobCount: Array.isArray(jobs) ? jobs.filter(j => j.status === 'active').length : 0,
      });
      setAiInsight(res?.insight || res?.data?.insight || '');
    } catch {
      const rate = data.verifyStats?.verificationRate ?? 0;
      const avg = data.verifyStats?.avgScore ?? 0;
      const jobCount = Array.isArray(data.jobs) ? data.jobs.length : 0;
      setAiInsight(
        rate < 40
          ? `Verification rate is ${rate}% — below the 40% benchmark. Refine pre-screening criteria or adjust assessment difficulty. ${jobCount > 0 ? `You have ${jobCount} active job postings.` : ''}`
          : `Verification rate of ${rate}% with avg score ${avg} is healthy. ${jobCount > 0 ? `Focus on filling your ${jobCount} open positions.` : 'Focus on reducing time-to-hire and scaling audit submissions.'}`
      );
    } finally {
      setAiLoading(false);
    }
  }, [data.verifyStats, data.dashStats, data.audits, data.jobs]);

  // ── Auto-refresh ─────────────────────────────────────────────────────────
  useEffect(() => {
    fetchData();
  }, []);

  useEffect(() => {
    const id = setInterval(() => { if (online) fetchData(); }, REFRESH_INTERVAL);
    return () => clearInterval(id);
  }, [online, fetchData]);

  useEffect(() => {
    if (data.verifyStats || data.dashStats) fetchAiInsight();
  }, [data.verifyStats?.verificationRate, data.dashStats?.totalAudits, data.jobs?.length]);

  // ── Notification actions ─────────────────────────────────────────────────
  const handleMarkRead = useCallback(async (id) => {
    setData(p => ({
      ...p,
      notifications: p.notifications.map(n => n.id === id ? { ...n, status: 'read' } : n),
    }));
    setUnreadCount(c => Math.max(0, c - 1));
    try { await api.notifications.markRead(id); } catch {}
  }, []);

  const handleMarkAllRead = useCallback(async () => {
    setData(p => ({
      ...p,
      notifications: p.notifications.map(n => ({ ...n, status: 'read' })),
    }));
    setUnreadCount(0);
    try { await api.notifications.markAllRead(user.current?.id); } catch {}
  }, []);

  // ── Logout ────────────────────────────────────────────────────────────────
  const handleLogout = useCallback(async () => {
    try {
      tokenStore.clear();
      await api.auth.logout();
    } catch {
      // Ignore errors - we're logging out anyway
    }
    navigate('/', { replace: true });
  }, [navigate]);

  // ── Tab change with URL sync ──────────────────────────────────────────────
  const handleTabChange = useCallback((tab) => {
    setActiveTab(tab);
    setIsMobileMenuOpen(false);
    if (tab !== 'overview') {
      window.history.replaceState({}, '', `${window.location.pathname}?tab=${tab}`);
    } else {
      window.history.replaceState({}, '', window.location.pathname);
    }
  }, []);

  const currentUser = user.current;

  // ─── Render ───────────────────────────────────────────────────────────────

  return (
    <EntitlementProvider>
      <div className="min-h-screen bg-[#F7F8FC] flex flex-col md:flex-row font-sans antialiased text-gray-900">

        {toast && (
          <Toast
            key={toast.id}
            message={toast.message}
            type={toast.type}
            onDismiss={() => setToast(null)}
          />
        )}

        {isMobileMenuOpen && (
          <div
            onClick={() => setIsMobileMenuOpen(false)}
            className="fixed inset-0 bg-gray-900/50 z-40 md:hidden backdrop-blur-sm"
            aria-hidden="true"
          />
        )}

        {/* ── Sidebar ───────────────────────────────────────────────────────── */}
        <aside
          className={`fixed md:static inset-y-0 left-0 z-50 w-60 bg-white border-r border-gray-100 flex flex-col justify-between transform transition-transform duration-300 ease-in-out ${isMobileMenuOpen ? 'translate-x-0' : '-translate-x-full md:translate-x-0'}`}
          aria-label="Main navigation"
        >
          <div className="flex flex-col h-full">
            {/* Logo */}
            <div className="px-4 py-4 border-b border-gray-100 flex items-center justify-between flex-shrink-0">
              <Link to="/" className="flex items-center gap-2.5 group">
                <img 
                  src={logo} 
                  alt="SkillNexus" 
                  className="w-8 h-8 rounded-xl shadow-md shadow-blue-500/20 object-cover"
                />
                <div>
                  <span className="text-sm font-extrabold text-gray-900 tracking-tight block leading-none">SkillNexus</span>
                  <span className="text-[9px] text-gray-400 font-medium">B2B Portal</span>
                </div>
              </Link>
              <button onClick={() => setIsMobileMenuOpen(false)}
                className="md:hidden p-1.5 rounded-lg text-gray-400 hover:bg-gray-100 transition-colors" aria-label="Close menu">
                <X className="w-4 h-4" />
              </button>
            </div>

            {/* Nav */}
            <nav className="flex-1 overflow-y-auto p-2 space-y-0.5 mt-1">
              {NAV.map(({ id, label, icon: Icon }) => {
                const active = activeTab === id;
                return (
                  <button
                    key={id}
                    onClick={() => handleTabChange(id)}
                    className={`w-full flex items-center gap-2.5 px-3 py-2.5 rounded-xl text-sm font-semibold transition-all group ${
                      active ? 'bg-blue-600 text-white shadow-sm' : 'text-gray-500 hover:bg-gray-50 hover:text-gray-900'
                    }`}
                    aria-current={active ? 'page' : undefined}
                  >
                    <Icon className={`w-4 h-4 flex-shrink-0 ${active ? 'text-white' : 'text-gray-400 group-hover:text-gray-600'}`} />
                    <span className="truncate">{label}</span>
                    {id === 'notifications' && unreadCount > 0 && (
                      <span className={`ml-auto text-[9px] font-black px-1.5 py-0.5 rounded-full ${active ? 'bg-white/20 text-white' : 'bg-blue-600 text-white'}`}>
                        {unreadCount > 99 ? '99+' : unreadCount}
                      </span>
                    )}
                  </button>
                );
              })}
            </nav>

            {/* Sidebar footer */}
            <div className="p-3 border-t border-gray-100 flex-shrink-0">
              <div className="px-3 py-1.5 mb-1">
                <p className="text-[10px] font-semibold text-gray-400 truncate">{currentUser?.email || '—'}</p>
                <div className="flex items-center gap-1.5 mt-0.5">
                  <span className="w-1.5 h-1.5 rounded-full bg-emerald-400" />
                  <span className="text-[9px] text-gray-400 capitalize">{currentUser?.role || 'Admin'}</span>
                </div>
              </div>
              <button
                onClick={handleLogout}
                className="w-full flex items-center gap-2 px-3 py-2 text-xs font-semibold text-red-500 hover:bg-red-50 rounded-xl transition-colors"
              >
                <LogOut className="w-3.5 h-3.5" /> Sign out
              </button>
            </div>
          </div>
        </aside>

        {/* ── Main content ──────────────────────────────────────────────────── */}
        <div className="flex-1 flex flex-col min-w-0 overflow-hidden">

          {/* Top bar */}
          <header className="bg-white border-b border-gray-100 px-4 py-3 flex items-center justify-between gap-3 sticky top-0 z-30 flex-shrink-0">
            <div className="flex items-center gap-2.5 min-w-0">
              <button onClick={() => setIsMobileMenuOpen(true)}
                className="md:hidden p-2 rounded-lg text-gray-500 hover:bg-gray-100 transition-colors" aria-label="Open menu">
                <Menu className="w-5 h-5" />
              </button>
              <div className="min-w-0">
                <h1 className="text-sm font-extrabold text-gray-900 capitalize truncate">
                  {NAV.find(n => n.id === activeTab)?.label || activeTab}
                </h1>
                {lastUpdated && (
                  <p className="text-[10px] text-gray-400 leading-none mt-0.5">
                    Updated {fmt.reltime(lastUpdated)}
                  </p>
                )}
              </div>
            </div>

            <div className="flex items-center gap-1.5 flex-shrink-0">
              {/* Search — desktop only */}
              <div className="relative hidden sm:block w-40 lg:w-48">
                <Search className="w-3.5 h-3.5 absolute left-2.5 top-1/2 -translate-y-1/2 text-gray-400" />
                <input
                  type="text"
                  placeholder="Search…"
                  value={searchQuery}
                  onChange={e => setSearchQuery(e.target.value)}
                  className="w-full pl-8 pr-3 py-1.5 text-xs bg-gray-50 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500/20 focus:border-blue-400 transition-all"
                  aria-label="Search"
                />
              </div>

              {/* Connection status */}
              <div className={`flex items-center gap-1 text-xs font-semibold px-2 py-1 rounded-lg ${online ? 'text-emerald-600 bg-emerald-50' : 'text-red-500 bg-red-50'}`}>
                {online ? <Wifi className="w-3.5 h-3.5" /> : <WifiOff className="w-3.5 h-3.5" />}
                <span className="hidden sm:inline">{online ? 'Live' : 'Offline'}</span>
              </div>

              {/* Refresh */}
              <button
                onClick={refresh}
                disabled={refreshing}
                className="p-2 rounded-lg text-gray-400 hover:text-gray-700 hover:bg-gray-100 transition-colors disabled:opacity-50"
                aria-label="Refresh"
              >
                <RefreshCw className={`w-4 h-4 ${refreshing ? 'animate-spin' : ''}`} />
              </button>

              {/* Notification bell */}
              <div className="relative" ref={notifRef}>
                <button
                  onClick={() => setNotifDropdown(!notifDropdown)}
                  className="p-2 rounded-lg text-gray-400 hover:text-gray-700 hover:bg-gray-100 relative transition-colors"
                  aria-label={`Notifications (${unreadCount} unread)`}
                >
                  <Bell className="w-4 h-4" />
                  {unreadCount > 0 && (
                    <span className="absolute -top-0.5 -right-0.5 w-4 h-4 rounded-full bg-blue-600 text-white text-[9px] font-black flex items-center justify-center">
                      {unreadCount > 9 ? '9+' : unreadCount}
                    </span>
                  )}
                </button>

                {notifDropdown && (
                  <div className="absolute right-0 top-full mt-2 w-80 bg-white border border-gray-200 rounded-2xl shadow-2xl z-50 overflow-hidden">
                    <div className="px-4 py-3 border-b border-gray-100 flex items-center justify-between">
                      <span className="text-sm font-bold text-gray-900">Notifications</span>
                      {unreadCount > 0 && (
                        <button onClick={() => { handleMarkAllRead(); setNotifDropdown(false); }}
                          className="text-xs text-blue-600 font-semibold hover:underline">
                          Mark all read
                        </button>
                      )}
                    </div>
                    <div className="max-h-72 overflow-y-auto divide-y divide-gray-50">
                      {data.notifications.length === 0 ? (
                        <div className="p-6 text-center text-xs text-gray-400">
                          <Bell className="w-6 h-6 mx-auto mb-2 text-gray-200" />
                          No notifications
                        </div>
                      ) : (
                        data.notifications.slice(0, 6).map(n => (
                          <div key={n.id}
                            onClick={() => { handleMarkRead(n.id); setNotifDropdown(false); }}
                            className={`px-4 py-3 hover:bg-gray-50 transition-colors cursor-pointer ${n.status === 'pending' ? 'bg-blue-50/30' : ''}`}>
                            <div className="flex items-start gap-2">
                              <div className={`w-1.5 h-1.5 rounded-full mt-1.5 flex-shrink-0 ${n.status === 'pending' ? 'bg-blue-500' : 'bg-gray-300'}`} />
                              <div className="min-w-0 flex-1">
                                <p className="text-xs font-semibold text-gray-800 truncate">{n.title}</p>
                                <p className="text-[11px] text-gray-500 mt-0.5 line-clamp-2">{n.message}</p>
                                <p className="text-[10px] text-gray-400 mt-1">{fmt.reltime(n.created_at)}</p>
                              </div>
                            </div>
                          </div>
                        ))
                      )}
                    </div>
                    <div className="px-4 py-2.5 border-t border-gray-100">
                      <button
                        onClick={() => { handleTabChange('notifications'); setNotifDropdown(false); }}
                        className="w-full text-xs text-blue-600 font-semibold text-center hover:underline">
                        View all
                      </button>
                    </div>
                  </div>
                )}
              </div>

              {/* Avatar */}
              <button
                onClick={() => handleTabChange('settings')}
                className="w-7 h-7 rounded-full bg-gradient-to-br from-blue-600 to-indigo-700 text-white font-black text-[10px] flex items-center justify-center flex-shrink-0 hover:shadow-md transition-all"
                aria-label="Settings"
              >
                {fmt.initials(currentUser?.name || currentUser?.email || 'SN')}
              </button>
            </div>
          </header>

          {/* Content */}
          <main className="flex-1 overflow-y-auto overscroll-contain p-4 md:p-6">
            <Suspense fallback={
              <div className="flex items-center justify-center h-48">
                <Loader2 className="w-8 h-8 text-blue-500 animate-spin" />
              </div>
            }>
              {activeTab === 'overview' && (
                <OverviewTab
                  data={data} loading={loading}
                  aiInsight={aiInsight} aiLoading={aiLoading}
                  user={currentUser} navigate={navigate}
                  setActiveTab={handleTabChange}
                />
              )}
              {activeTab === 'jobs' && (
                <JobsTab
                  jobs={data.jobs}
                  loading={loading.jobs}
                  onRefresh={refresh}
                  onToast={showToast}
                  navigate={navigate}
                />
              )}
              {activeTab === 'candidates' && (
                <CandidatesTab data={data} loading={loading} navigate={navigate} />
              )}
              {activeTab === 'audits' && (
                <AuditsTab data={data} loading={loading} setData={setData} onToast={showToast} navigate={navigate} />
              )}
              {activeTab === 'notifications' && (
                <NotificationsTab
                  notifications={data.notifications}
                  loading={loading.notifications}
                  unreadCount={unreadCount}
                  onMarkRead={handleMarkRead}
                  onMarkAll={handleMarkAllRead}
                />
              )}
              {activeTab === 'analytics' && (
                <AnalyticsTab data={data} loading={loading} />
              )}
              {activeTab === 'payments' && (
                <PaymentsTab onToast={showToast} />
              )}
              {activeTab === 'api-keys' && (
                <ApiKeysTab onToast={showToast} user={currentUser} />
              )}
              {activeTab === 'settings' && (
                <SettingsTab
                  user={currentUser}
                  refreshing={refreshing}
                  onRefresh={refresh}
                  onLogout={handleLogout}
                  onSwitchTab={handleTabChange}
                />
              )}
            </Suspense>
          </main>
        </div>
      </div>
    </EntitlementProvider>
  );
}

export default Dashboard;