'use client';

import { useState, useRef, useEffect, useCallback } from 'react';
import { AppToast } from '@/app/components/AppToast';
import type { Toast } from 'primereact/toast';
import { Dropdown } from 'primereact/dropdown';
import { Dialog } from 'primereact/dialog';
import { ProgressSpinner } from 'primereact/progressspinner';
import DashboardShell from '../components/DashboardShell';
import { useApi } from '@/hooks/useApi';
import { useSettingsApi } from '@/hooks/useSettingsApi';
import { useAuthStore } from '@/store/authStore';

/** يُرسل لـ API في الحقل country_code (ثابت للسعودية) */
const CAPTAIN_COUNTRY_CODE = '966';

/** قيم حقل type في POST captains — القيمة المُرسلة للباك: individual | company */
const CAPTAIN_TYPE_OPTIONS: { label: string; value: 'individual' | 'company' }[] = [
  { label: 'أفراد', value: 'individual' },
  { label: 'شركات', value: 'company' },
];

const DEFAULT_AVATAR =
  'https://readdy.ai/api/search-image?query=Saudi%20male%20bus%20driver%20professional%20portrait%20smiling%20white%20background%20realistic%20photo%20high%20quality%20close%20up%20face%20natural%20lighting&width=80&height=80&seq=drv-api&orientation=squarish';

interface SettingsBannerResponse {
  key?: string;
  data?: string;
}

function LegalHtmlBlock({ content }: { content: string }) {
  const trimmed = content.trim();
  if (!trimmed) {
    return <p className="text-sm text-slate-500">لا يوجد محتوى متاح حالياً.</p>;
  }
  const looksHtml = /<\/?[a-z][\s\S]*>/i.test(trimmed);
  if (looksHtml) {
    return (
      <div
        className="legal-html prose prose-sm max-w-none text-slate-700 text-sm leading-relaxed [&_a]:text-blue-700 [&_img]:max-w-full"
        dir="rtl"
        dangerouslySetInnerHTML={{ __html: trimmed }}
      />
    );
  }
  return <p className="whitespace-pre-wrap text-sm text-slate-700 leading-relaxed">{trimmed}</p>;
}

/* ─────────────── Types ─────────────── */

interface DriverRow {
  id: string;          // display_code e.g. "D-013"
  rawId: number;       // numeric id for API calls
  name: string;
  phone: string;
  fullPhone: string;
  email: string;
  bus: string;
  route: string;
  status: string;
  statusColor: string;
  statusBg: string;
  rating: number;
  trips: number;
  joinDate: string;
  avatar: string;
  type: string;
}

interface ApiCaptain {
  id: number;
  display_code?: string;
  name?: string;
  phone?: string;
  country_code?: string;
  full_phone?: string;
  image?: string | null;
  bus?: { title?: string | null; plate_number?: string; display_code?: string; model?: string } | null;
  assigned_bus?: { title?: string | null; plate_number?: string; display_code?: string } | null;
  path?: { name?: string | null; description?: string | null } | null;
  trips_count?: number;
  trip_count?: number;
  num_of_trips?: number;
  rating?: { average?: number; count?: number } | number;
  status?: string;
  is_active?: boolean;
  is_approved?: boolean;
  joined_at?: string;
  created_at?: string;
  type?: string;
}

interface ApiCaptainDetail {
  id: number;
  display_code?: string;
  name?: string;
  phone?: string;
  country_code?: string;
  full_phone?: string;
  email?: string;
  image?: string | null;
  driving_license_image?: string | null;
  identifier_image?: string | null;
  identifier_number?: string;
  type?: string;
  nationality?: string;
  status?: string;
  rating?: { average?: number; count?: number };
  joined_at?: string;
  bus?: unknown;
  paths?: unknown[];
  has_medical_insurance?: boolean;
}

interface CaptainsListResponse {
  key?: string;
  msg?: string;
  data?: {
    data?: ApiCaptain[];
    pagination?: {
      total_items?: number;
      count_items?: number;
      per_page?: number;
      total_pages?: number;
      current_page?: number;
      next_page_url?: string;
      perv_page_url?: string;
    };
  };
}

interface CaptainDetailResponse {
  key?: string;
  msg?: string;
  data?: ApiCaptainDetail;
}

interface CaptainCreateResponse {
  key?: string;
  msg?: string;
  message?: string;
  error?: string;
  errors?: Record<string, string[] | string>;
}

/* ─────────────── Helpers ─────────────── */

function isSuccessKey(key: unknown): boolean {
  return String(key ?? '').toLowerCase() === 'success';
}

function backendMessage(res: CaptainCreateResponse): string {
  const r = res as Record<string, unknown>;
  for (const k of ['msg', 'message', 'error'] as const) {
    const v = r[k];
    if (typeof v === 'string' && v.trim()) return v.trim();
  }
  const errors = r.errors;
  if (errors && typeof errors === 'object') {
    for (const v of Object.values(errors as Record<string, unknown>)) {
      if (Array.isArray(v) && v.length > 0 && typeof v[0] === 'string') return v[0];
      if (typeof v === 'string' && v.trim()) return v.trim();
    }
  }
  return 'لم يُرجع الخادم رسالة توضيحية.';
}

function resolveStatus(c: ApiCaptain): { label: string; color: string; bg: string } {
  const s = c.status ?? '';
  if (s === 'active' || c.is_active === true) return { label: 'نشط', color: '#059669', bg: '#DCFCE7' };
  if (s === 'pending_approval') return { label: 'معلق', color: '#D97706', bg: '#FEF3C7' };
  if (s === 'on_leave') return { label: 'إجازة', color: '#2563EB', bg: '#DBEAFE' };
  if (s === 'blocked') return { label: 'محظور', color: '#EF4444', bg: '#FEE2E2' };
  if (c.is_approved === false) return { label: 'معلق', color: '#D97706', bg: '#FEF3C7' };
  if (c.is_active === false) return { label: 'غير نشط', color: '#64748B', bg: '#F1F5F9' };
  return { label: s || 'نشط', color: '#059669', bg: '#DCFCE7' };
}

function getRating(r: ApiCaptain['rating']): number {
  if (typeof r === 'number') return r;
  if (r && typeof r === 'object' && 'average' in r) return r.average ?? 0;
  return 0;
}

function mapApiCaptain(c: ApiCaptain): DriverRow {
  const { label, color, bg } = resolveStatus(c);

  const busObj = c.bus ?? c.assigned_bus;
  let busLabel = 'غير مسند';
  if (busObj && typeof busObj === 'object') {
    const title = 'title' in busObj && busObj.title ? String(busObj.title).trim() : '';
    const code = 'display_code' in busObj && busObj.display_code ? String(busObj.display_code) : '';
    const plate = 'plate_number' in busObj && busObj.plate_number ? String(busObj.plate_number) : '';
    const model = 'model' in busObj && busObj.model ? String(busObj.model) : '';
    if (title || code || plate) busLabel = [title, code, plate, model].filter(Boolean).join(' — ');
  }

  const routeName = c.path?.description?.trim() || c.path?.name?.trim();
  const route = routeName || 'غير مسند';
  const trips = c.trips_count ?? c.trip_count ?? c.num_of_trips ?? 0;
  const rating = getRating(c.rating);

  const joinDate = c.joined_at
    ? new Date(c.joined_at).toLocaleDateString('ar-SA', { year: 'numeric', month: 'long', day: 'numeric' })
    : c.created_at
    ? new Date(c.created_at).toLocaleDateString('ar-SA', { year: 'numeric', month: 'long', day: 'numeric' })
    : '—';

  return {
    id: c.display_code ?? `D-${c.id}`,
    rawId: c.id,
    name: c.name ?? '—',
    phone: c.phone ?? '—',
    fullPhone: c.full_phone ?? c.phone ?? '—',
    email: '—',
    bus: busLabel,
    route,
    status: label,
    statusColor: color,
    statusBg: bg,
    rating,
    trips,
    joinDate,
    avatar: c.image || DEFAULT_AVATAR,
    type: c.type ?? '',
  };
}

/** يزيل 966/0 من البداية */
function normalizePhoneLocal(raw: string): string {
  let d = raw.replace(/\D/g, '');
  if (d.startsWith('966')) d = d.slice(3);
  if (d.startsWith('0')) d = d.slice(1);
  return d;
}

function Stars({ count }: { count: number }) {
  return (
    <div className="flex items-center gap-0.5">
      {[1, 2, 3, 4, 5].map((i) => (
        <i
          key={i}
          className={`ri-star-${i <= Math.round(count) ? 'fill' : 'line'} text-xs`}
          style={{ color: i <= Math.round(count) ? '#F59E0B' : '#E2E8F0' }}
        ></i>
      ))}
    </div>
  );
}

/* ─────────────── Form defaults ─────────────── */

const emptyForm = {
  name: '',
  phone: '',
  email: '',
  type: '' as '' | 'individual' | 'company',
  nationality: '',
  identifier_number: '',
  password: '',
  password_confirmation: '',
  agreeTerms: false,
  has_medical_insurance: false,
  imageFile: null as File | null,
  imagePreview: '',
  driving_license_imageFile: null as File | null,
  driving_license_preview: '',
  driving_license_name: '',
  identifier_imageFile: null as File | null,
  identifier_image_preview: '',
  identifier_image_name: '',
  showPassword: false,
  showConfirm: false,
};

/* ─────────────── Status filter options ─────────────── */
const STATUS_FILTER_OPTIONS = [
  { label: 'الكل', value: '' },
  { label: 'نشط', value: 'active' },
  { label: 'إجازة', value: 'on_leave' },
  { label: 'معلق', value: 'pending_approval' },
];

/* ═══════════════════════════════════════════════════════ */
/*                      Component                         */
/* ═══════════════════════════════════════════════════════ */

export default function DriversPage() {
  const toastRef = useRef<Toast>(null);
  const hasHydrated = useAuthStore((s) => s._hasHydrated);
  const token = useAuthStore((s) => s.token);

  const listApi = useApi<CaptainsListResponse>();
  const detailApi = useApi<CaptainDetailResponse>();
  const createApi = useApi<CaptainCreateResponse>();
  const updateApi = useApi<CaptainCreateResponse>();
  const deleteApi = useApi<CaptainCreateResponse>();
  const { request: settingsRequest } = useSettingsApi();

  const [termsDialogVisible, setTermsDialogVisible] = useState(false);
  const [privacyDialogVisible, setPrivacyDialogVisible] = useState(false);
  const [termsBody, setTermsBody] = useState('');
  const [privacyBody, setPrivacyBody] = useState('');
  const [termsLoading, setTermsLoading] = useState(false);
  const [privacyLoading, setPrivacyLoading] = useState(false);

  async function loadTermsContent() {
    setTermsLoading(true);
    const json = (await settingsRequest('/terms', { skipAuth: true })) as SettingsBannerResponse | null;
    setTermsLoading(false);
    const raw = json?.data;
    setTermsBody(typeof raw === 'string' ? raw : '');
  }

  async function loadPrivacyContent() {
    setPrivacyLoading(true);
    const json = (await settingsRequest('/privacy', { skipAuth: true })) as SettingsBannerResponse | null;
    setPrivacyLoading(false);
    const raw = json?.data;
    setPrivacyBody(typeof raw === 'string' ? raw : '');
  }

  /* ── List state ── */
  const [drivers, setDrivers] = useState<DriverRow[]>([]);
  const [pagination, setPagination] = useState({
    total_items: 0,
    total_pages: 1,
    current_page: 1,
    per_page: 15,
  });

  /* ── Filters ── */
  const [search, setSearch] = useState('');
  const [searchDebounced, setSearchDebounced] = useState('');
  const [statusFilter, setStatusFilter] = useState('');   // API value
  const [page, setPage] = useState(1);

  /* ── Modals ── */
  const [showAdd, setShowAdd] = useState(false);
  const [selected, setSelected] = useState<ApiCaptainDetail | null>(null);
  const [selectedLoading, setSelectedLoading] = useState(false);
  const [deleteTarget, setDeleteTarget] = useState<DriverRow | null>(null);

  /* ── Edit modal ── */
  const [editTarget, setEditTarget] = useState<DriverRow | null>(null);
  const [editDetail, setEditDetail] = useState<ApiCaptainDetail | null>(null);
  const [editDetailLoading, setEditDetailLoading] = useState(false);
  const [editForm, setEditForm] = useState({
    name: '',
    phone: '',
    country_code: CAPTAIN_COUNTRY_CODE,
    email: '',
    imageFile: null as File | null,
    imagePreview: '',
    accept_terms: false,
    showPassword: false,
  });
  const [editErrors, setEditErrors] = useState<Record<string, string>>({});
  const [editSubmitLoading, setEditSubmitLoading] = useState(false);
  const [editSubmitted, setEditSubmitted] = useState(false);

  /* ── Add form ── */
  const [form, setForm] = useState({ ...emptyForm });
  const [errors, setErrors] = useState<Record<string, string>>({});
  const [submitLoading, setSubmitLoading] = useState(false);

  /* ── Refs ── */
  const imageRef = useRef<HTMLInputElement>(null);
  const drivingLicenseRef = useRef<HTMLInputElement>(null);
  const identifierImageRef = useRef<HTMLInputElement>(null);
  const editPhotoRef = useRef<HTMLInputElement>(null);

  /* ─────────────── Debounce search ─────────────── */
  useEffect(() => {
    const t = setTimeout(() => {
      setSearchDebounced(search);
      setPage(1);
    }, 400);
    return () => clearTimeout(t);
  }, [search]);

  /* ─────────────── Fetch list ─────────────── */
  const fetchCaptains = useCallback(async () => {
    if (!hasHydrated || !token) return;
    const qs = new URLSearchParams();
    qs.set('paginate', '15');
    qs.set('page', String(page));
    if (searchDebounced) qs.set('search', searchDebounced);
    if (statusFilter) qs.set('status', statusFilter);

    const res = await listApi.request(`captains?${qs.toString()}`);
    const raw = res?.data;
    const list: ApiCaptain[] = Array.isArray(raw) ? raw : (raw?.data ?? []);
    const rows = list.map(mapApiCaptain);
    setDrivers(rows);

    if (raw && !Array.isArray(raw) && raw.pagination) {
      const p = raw.pagination;
      setPagination({
        total_items: p.total_items ?? rows.length,
        total_pages: p.total_pages ?? 1,
        current_page: p.current_page ?? 1,
        per_page: p.per_page ?? 15,
      });
    } else {
      setPagination((prev) => ({ ...prev, total_items: rows.length, total_pages: 1, current_page: 1 }));
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [hasHydrated, token, searchDebounced, statusFilter, page]);

  useEffect(() => {
    fetchCaptains();
  }, [fetchCaptains]);

  /* ─────────────── Open detail modal ─────────────── */
  async function openDetail(row: DriverRow) {
    setSelectedLoading(true);
    setSelected(null);
    const res = await detailApi.request(`captains/${row.rawId}`);
    setSelectedLoading(false);
    if (res?.data) setSelected(res.data);
  }

  /* ─────────────── Open edit modal ─────────────── */
  async function openEdit(row: DriverRow) {
    setEditTarget(row);
    setEditErrors({});
    setEditSubmitted(false);
    setEditDetailLoading(true);
    setEditDetail(null);
    setEditForm({
      name: row.name,
      phone: row.phone,
      country_code: CAPTAIN_COUNTRY_CODE,
      email: row.email,
      imageFile: null,
      imagePreview: row.avatar,
      accept_terms: false,
      showPassword: false,
    });
    const res = await detailApi.request(`captains/${row.rawId}`);
    setEditDetailLoading(false);
    if (res?.data) {
      const d = res.data;
      setEditDetail(d);
      setEditForm({
        name: d.name ?? row.name,
        phone: d.phone ?? row.phone,
        country_code: d.country_code ?? CAPTAIN_COUNTRY_CODE,
        email: d.email ?? '',
        imageFile: null,
        imagePreview: d.image || row.avatar,
        accept_terms: false,
        showPassword: false,
      });
    }
  }

  function closeEdit() {
    setEditTarget(null);
    setEditDetail(null);
    setEditErrors({});
    setEditSubmitted(false);
    setEditSubmitLoading(false);
  }

  function handleEditPhotoChange(e: React.ChangeEvent<HTMLInputElement>) {
    const file = e.target.files?.[0];
    if (!file) return;
    setEditForm((f) => ({ ...f, imageFile: file, imagePreview: URL.createObjectURL(file) }));
  }

  function validateEdit() {
    const e: Record<string, string> = {};
    if (!editForm.name.trim()) e.name = 'الاسم الكامل مطلوب';
    const local = normalizePhoneLocal(editForm.phone);
    if (!local) e.phone = 'رقم الجوال مطلوب';
    else if (!/^5\d{8}$/.test(local)) e.phone = 'أدخل رقم جوال سعودي صحيح (9 أرقام تبدأ بـ 5)';
    if (!editForm.email.trim()) e.email = 'البريد الإلكتروني مطلوب';
    else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(editForm.email.trim())) e.email = 'البريد غير صالح';
    return e;
  }

  async function handleEditSubmit() {
    const e = validateEdit();
    setEditErrors(e);
    if (Object.keys(e).length > 0) return;
    if (!editTarget) return;
    setEditSubmitLoading(true);

    const fd = new FormData();
    fd.append('name', editForm.name.trim());
    fd.append('phone', normalizePhoneLocal(editForm.phone));
    fd.append('country_code', editForm.country_code || CAPTAIN_COUNTRY_CODE);
    fd.append('email', editForm.email.trim());
    fd.append('accept_terms', editForm.accept_terms ? '1' : '0');
    if (editForm.imageFile) fd.append('image', editForm.imageFile);

    const res = await updateApi.request(`captains/${editTarget.rawId}/update`, {
      method: 'POST',
      body: fd,
    });

    setEditSubmitLoading(false);

    if (res !== null && isSuccessKey(res.key)) {
      toastRef.current?.show({ severity: 'success', summary: 'تم', detail: 'تم تحديث بيانات السائق', life: 3500 });
      setEditSubmitted(true);
      setTimeout(() => {
        closeEdit();
        fetchCaptains();
      }, 1800);
      return;
    }

    const msg = res !== null ? backendMessage(res) : (updateApi.lastError.current || '');
    toastRef.current?.show({ severity: 'error', summary: 'حدث خطأ', detail: msg, life: 9000 });
  }

  /* ─────────────── Add form handlers ─────────────── */

  function handleImageChange(e: React.ChangeEvent<HTMLInputElement>) {
    const file = e.target.files?.[0];
    if (!file) return;
    setForm((f) => ({ ...f, imageFile: file, imagePreview: URL.createObjectURL(file) }));
    setErrors((er) => ({ ...er, image: '' }));
  }

  function handleDrivingLicenseChange(e: React.ChangeEvent<HTMLInputElement>) {
    const file = e.target.files?.[0];
    if (!file) return;
    setForm((f) => ({ ...f, driving_license_imageFile: file, driving_license_preview: URL.createObjectURL(file), driving_license_name: file.name }));
    setErrors((er) => ({ ...er, driving_license_image: '' }));
  }

  function handleIdentifierImageChange(e: React.ChangeEvent<HTMLInputElement>) {
    const file = e.target.files?.[0];
    if (!file) return;
    setForm((f) => ({ ...f, identifier_imageFile: file, identifier_image_preview: URL.createObjectURL(file), identifier_image_name: file.name }));
    setErrors((er) => ({ ...er, identifier_image: '' }));
  }

  function validateAdd() {
    const e: Record<string, string> = {};
    if (!form.name.trim()) e.name = 'الاسم الكامل مطلوب';
    if (!form.imageFile) e.image = 'صورة السائق مطلوبة';
    const local = normalizePhoneLocal(form.phone);
    if (!local) e.phone = 'رقم الجوال مطلوب';
    else if (!/^5\d{8}$/.test(local)) e.phone = 'أدخل رقم جوال سعودي صحيح (9 أرقام تبدأ بـ 5)';
    if (!form.email.trim()) e.email = 'البريد الإلكتروني مطلوب';
    else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.email.trim())) e.email = 'البريد غير صالح';
    if (form.type !== 'individual' && form.type !== 'company') e.type = 'النوع مطلوب';
    if (!form.nationality.trim()) e.nationality = 'الجنسية مطلوبة';
    if (!form.identifier_number.trim()) e.identifier_number = 'رقم الهوية مطلوب';
    if (!form.driving_license_imageFile) e.driving_license_image = 'صورة رخصة القيادة مطلوبة';
    if (!form.identifier_imageFile) e.identifier_image = 'صورة الهوية مطلوبة';
    if (!form.password) e.password = 'كلمة المرور مطلوبة';
    else if (form.password.length < 8) e.password = 'كلمة المرور 8 أحرف على الأقل';
    if (form.password_confirmation !== form.password) e.password_confirmation = 'كلمتا المرور غير متطابقتين';
    if (!form.agreeTerms) e.agreeTerms = 'يجب الموافقة على الشروط والأحكام';
    return e;
  }

  async function handleSubmit() {
    const e = validateAdd();
    setErrors(e);
    if (Object.keys(e).length > 0) return;
    if (!hasHydrated || !token) {
      toastRef.current?.show({ severity: 'error', summary: 'خطأ', detail: 'يجب تسجيل الدخول أولاً', life: 4000 });
      return;
    }
    setSubmitLoading(true);
    const fd = new FormData();
    fd.append('country_code', CAPTAIN_COUNTRY_CODE);
    fd.append('name', form.name.trim());
    fd.append('phone', normalizePhoneLocal(form.phone));
    fd.append('password', form.password);
    fd.append('password_confirmation', form.password_confirmation);
    fd.append('accept_terms', form.agreeTerms ? '1' : '0');
    if (form.imageFile) fd.append('image', form.imageFile);
    if (form.driving_license_imageFile) fd.append('driving_license_image', form.driving_license_imageFile);
    fd.append('identifier_number', form.identifier_number.trim());
    if (form.identifier_imageFile) fd.append('identifier_image', form.identifier_imageFile);
    fd.append('email', form.email.trim());
    fd.append('type', form.type);
    fd.append('nationality', form.nationality.trim());
    fd.append('has_medical_insurance', form.has_medical_insurance ? '1' : '0');

    const res = await createApi.request('captains', { method: 'POST', body: fd });
    setSubmitLoading(false);

    if (res !== null && isSuccessKey(res.key)) {
      toastRef.current?.show({ severity: 'success', summary: 'تم', detail: 'تم إضافة السائق', life: 3500 });
      setShowAdd(false);
      setForm({ ...emptyForm });
      setErrors({});
      await fetchCaptains();
      return;
    }

    const msg = res !== null ? backendMessage(res) : (createApi.lastError.current || '');
    toastRef.current?.show({ severity: 'error', summary: 'حدث خطأ', detail: msg || 'لم تُستلم رسالة من الخادم.', life: 9000 });
  }

  function closeAdd() {
    setShowAdd(false);
    setForm({ ...emptyForm });
    setErrors({});
    setSubmitLoading(false);
  }

  async function handleDeleteCaptainConfirm() {
    if (!deleteTarget) return;
    if (!hasHydrated || !token) {
      toastRef.current?.show({ severity: 'error', summary: 'خطأ', detail: 'يجب تسجيل الدخول أولاً', life: 4000 });
      return;
    }

    const res = await deleteApi.request(`captains/${deleteTarget.rawId}`, { method: 'DELETE' });

    if (res !== null && isSuccessKey(res.key)) {
      const fromApi =
        (typeof res.msg === 'string' && res.msg.trim()) ||
        (typeof res.message === 'string' && res.message.trim()) ||
        '';
      toastRef.current?.show({
        severity: 'success',
        summary: 'تم',
        detail: fromApi || 'تم حذف السائق',
        life: 4000,
      });
      setDeleteTarget(null);
      await fetchCaptains();
      return;
    }

    const msg = res !== null ? backendMessage(res) : (deleteApi.lastError.current || '');
    toastRef.current?.show({ severity: 'error', summary: 'حدث خطأ', detail: msg, life: 9000 });
  }

  /* ─────────────── Helpers ─────────────── */
  const typeLabel = (t?: string) =>
    t === 'individual' ? 'أفراد' : t === 'company' ? 'شركات' : t ?? '—';

  /* ═══════════════════════════════════════════════════════ */
  /*                        Render                          */
  /* ═══════════════════════════════════════════════════════ */

  return (
    <>
      <AppToast ref={toastRef} />
      <DashboardShell title="إدارة السائقين" subtitle={`${pagination.total_items} سائق مسجل`}>

        {/* ─── Toolbar ─── */}
        <div className="flex items-center justify-between mb-6">
          <div className="flex items-center gap-3 flex-wrap">
            <div className="relative">
              <input
                type="text"
                placeholder="بحث بالاسم أو الجوال..."
                value={search}
                onChange={(e) => setSearch(e.target.value)}
                className="h-10 bg-white border border-slate-200 rounded-xl pr-10 pl-4 text-sm outline-none text-slate-700"
                style={{ width: '260px', fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}
              />
              <div className="absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 flex items-center justify-center">
                <i className="ri-search-line text-slate-400 text-sm"></i>
              </div>
            </div>
            {STATUS_FILTER_OPTIONS.map((opt) => (
              <button
                key={opt.value}
                onClick={() => { setStatusFilter(opt.value); setPage(1); }}
                className="px-4 py-2 rounded-xl text-sm font-bold cursor-pointer transition-all whitespace-nowrap"
                style={{
                  background: statusFilter === opt.value ? '#1E3A8A' : 'white',
                  color: statusFilter === opt.value ? 'white' : '#64748b',
                  border: `1px solid ${statusFilter === opt.value ? '#1E3A8A' : '#E2E8F0'}`,
                  fontFamily: '"IBM Plex Sans Arabic", sans-serif',
                }}
              >
                {opt.label}
              </button>
            ))}
          </div>
          <button
            onClick={() => setShowAdd(true)}
            className="flex items-center gap-2 px-5 py-2.5 rounded-xl font-bold text-sm cursor-pointer whitespace-nowrap"
            style={{ background: '#1E3A8A', color: 'white', fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}
          >
            <i className="ri-user-add-line text-base"></i>
            إضافة سائق
          </button>
        </div>

        {/* ─── Table ─── */}
        <div className="bg-white rounded-2xl overflow-hidden" style={{ border: '1px solid #F1F5F9', boxShadow: '0 1px 4px rgba(0,0,0,0.04)' }}>
          <table className="w-full">
            <thead>
              <tr style={{ background: '#F8FAFC' }}>
                {['السائق', 'الجوال', 'الباص المسند', 'المسار', 'الرحلات', 'التقييم', 'الحالة', 'تاريخ الانضمام', 'الإجراءات'].map((h) => (
                  <th key={h} className="text-right px-5 py-3 text-xs font-bold text-slate-500 whitespace-nowrap" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{h}</th>
                ))}
              </tr>
            </thead>
            <tbody>
              {listApi.loading && (
                <tr>
                  <td colSpan={9} className="px-5 py-12 text-center text-sm text-slate-500" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>
                    جاري تحميل السائقين...
                  </td>
                </tr>
              )}
              {!listApi.loading && drivers.length === 0 && (
                <tr>
                  <td colSpan={9} className="px-5 py-12 text-center text-sm text-slate-500" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>
                    لا يوجد سائقون مطابقون للبحث أو التصفية.
                  </td>
                </tr>
              )}
              {!listApi.loading && drivers.map((d) => (
                <tr
                  key={d.rawId}
                  className="border-t hover:bg-slate-50 transition-colors cursor-pointer"
                  style={{ borderColor: '#F8FAFC' }}
                  onClick={() => openDetail(d)}
                >
                  <td className="px-5 py-3.5">
                    <div className="flex items-center gap-3">
                      <div className="w-9 h-9 rounded-xl overflow-hidden flex-shrink-0">
                        <img src={d.avatar} alt={d.name} className="w-full h-full object-cover object-top" />
                      </div>
                      <div>
                        <p className="text-sm font-bold text-slate-800 whitespace-nowrap" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{d.name}</p>
                        <p className="text-xs text-slate-400" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{d.id}</p>
                      </div>
                    </div>
                  </td>
                  <td className="px-5 py-3.5"><span className="text-xs font-mono text-slate-600">{d.fullPhone}</span></td>
                  <td className="px-5 py-3.5"><span className="text-xs text-slate-600 whitespace-nowrap" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{d.bus}</span></td>
                  <td className="px-5 py-3.5">
                    <span className="text-xs text-slate-500 whitespace-nowrap" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif', maxWidth: '180px', display: 'block', overflow: 'hidden', textOverflow: 'ellipsis' }}>
                      {d.route}
                    </span>
                  </td>
                  <td className="px-5 py-3.5"><span className="text-xs font-bold text-slate-700" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{d.trips}</span></td>
                  <td className="px-5 py-3.5">
                    <div className="flex items-center gap-1.5">
                      <Stars count={d.rating} />
                      <span className="text-xs font-bold text-slate-600" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{d.rating > 0 ? d.rating : '-'}</span>
                    </div>
                  </td>
                  <td className="px-5 py-3.5">
                    <span className="inline-block px-2.5 py-0.5 rounded-full text-xs font-bold whitespace-nowrap" style={{ background: d.statusBg, color: d.statusColor, fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>
                      {d.status}
                    </span>
                  </td>
                  <td className="px-5 py-3.5"><span className="text-xs text-slate-500 whitespace-nowrap" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{d.joinDate}</span></td>
                  <td className="px-5 py-3.5" onClick={(e) => e.stopPropagation()}>
                    <div className="flex items-center gap-1.5">
                      <button
                        onClick={() => openEdit(d)}
                        className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-bold cursor-pointer whitespace-nowrap transition-all hover:opacity-80"
                        style={{ background: '#EEF2FF', color: '#1E3A8A', fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}
                      >
                        <i className="ri-edit-line text-xs"></i>
                        تعديل
                      </button>
                      <button
                        onClick={() => setDeleteTarget(d)}
                        className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-bold cursor-pointer whitespace-nowrap transition-all hover:opacity-80"
                        style={{ background: '#FEE2E2', color: '#EF4444', fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}
                      >
                        <i className="ri-delete-bin-line text-xs"></i>
                        حذف
                      </button>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>

          {/* ─── Pagination ─── */}
          {pagination.total_pages > 1 && (
            <div className="flex items-center justify-between px-5 py-3 border-t border-slate-100">
              <p className="text-xs text-slate-500" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>
                صفحة {pagination.current_page} من {pagination.total_pages} — إجمالي {pagination.total_items} سائق
              </p>
              <div className="flex items-center gap-2">
                <button
                  disabled={pagination.current_page <= 1 || listApi.loading}
                  onClick={() => setPage((p) => Math.max(1, p - 1))}
                  className="w-8 h-8 rounded-lg flex items-center justify-center text-sm font-bold transition-all disabled:opacity-40 disabled:cursor-not-allowed"
                  style={{ background: '#EEF2FF', color: '#1E3A8A' }}
                >
                  <i className="ri-arrow-right-s-line"></i>
                </button>
                {Array.from({ length: pagination.total_pages }, (_, i) => i + 1).map((p) => (
                  <button
                    key={p}
                    onClick={() => setPage(p)}
                    className="w-8 h-8 rounded-lg text-xs font-bold transition-all"
                    style={{
                      background: p === pagination.current_page ? '#1E3A8A' : '#F8FAFC',
                      color: p === pagination.current_page ? 'white' : '#64748B',
                      fontFamily: '"IBM Plex Sans Arabic", sans-serif',
                    }}
                  >
                    {p}
                  </button>
                ))}
                <button
                  disabled={pagination.current_page >= pagination.total_pages || listApi.loading}
                  onClick={() => setPage((p) => Math.min(pagination.total_pages, p + 1))}
                  className="w-8 h-8 rounded-lg flex items-center justify-center text-sm font-bold transition-all disabled:opacity-40 disabled:cursor-not-allowed"
                  style={{ background: '#EEF2FF', color: '#1E3A8A' }}
                >
                  <i className="ri-arrow-left-s-line"></i>
                </button>
              </div>
            </div>
          )}
        </div>

        {/* ═══════════════════════════════════════════════════════ */}
        {/*              Driver Detail Modal (captains/:id)        */}
        {/* ═══════════════════════════════════════════════════════ */}
        {(selectedLoading || selected) && (
          <div className="fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-6" onClick={() => { setSelected(null); setSelectedLoading(false); }}>
            <div className="bg-white rounded-3xl p-7 w-full max-w-lg shadow-2xl" onClick={(e) => e.stopPropagation()}>

              {selectedLoading ? (
                <div className="flex flex-col items-center justify-center gap-4 py-16">
                  <i className="ri-loader-4-line text-3xl animate-spin" style={{ color: '#1E3A8A' }}></i>
                  <p className="text-sm text-slate-500" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>جاري تحميل البيانات...</p>
                </div>
              ) : selected && (
                <>
                  {/* Header */}
                  <div className="flex items-center justify-between mb-5">
                    <h2 className="text-lg font-black text-slate-900" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>بيانات السائق</h2>
                    <button onClick={() => setSelected(null)} className="w-9 h-9 bg-slate-100 rounded-xl flex items-center justify-center cursor-pointer">
                      <i className="ri-close-line text-slate-500 text-lg"></i>
                    </button>
                  </div>

                  {/* Avatar + name */}
                  <div className="flex items-center gap-4 mb-5 p-4 rounded-2xl" style={{ background: '#F8FAFC' }}>
                    <div className="w-16 h-16 rounded-2xl overflow-hidden flex-shrink-0">
                      <img src={selected.image || DEFAULT_AVATAR} alt={selected.name} className="w-full h-full object-cover object-top" />
                    </div>
                    <div>
                      <p className="text-lg font-black text-slate-900" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{selected.name ?? '—'}</p>
                      <p className="text-sm text-slate-400" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{selected.display_code ?? `D-${selected.id}`}</p>
                    </div>
                  </div>

                  {/* Info rows */}
                  <div className="space-y-3 mb-5">
                    {[
                      { icon: 'ri-phone-line', label: 'رقم الجوال', val: selected.full_phone ?? selected.phone ?? '—' },
                      { icon: 'ri-mail-line', label: 'البريد الإلكتروني', val: selected.email ?? '—' },
                      { icon: 'ri-user-line', label: 'النوع', val: typeLabel(selected.type) },
                      { icon: 'ri-flag-line', label: 'الجنسية', val: selected.nationality ?? '—' },
                      { icon: 'ri-id-card-line', label: 'رقم الهوية', val: selected.identifier_number ?? '—' },
                    ].map((row, i) => (
                      <div key={i} className="flex items-center gap-3">
                        <div className="w-8 h-8 rounded-xl flex items-center justify-center flex-shrink-0" style={{ background: '#EEF2FF' }}>
                          <i className={`${row.icon} text-sm`} style={{ color: '#1E3A8A' }}></i>
                        </div>
                        <div>
                          <p className="text-[10px] text-slate-400" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{row.label}</p>
                          <p className="text-sm text-slate-700 font-semibold" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{row.val}</p>
                        </div>
                      </div>
                    ))}
                  </div>

                  {/* Documents: driving license + identifier image */}
                  {(selected.driving_license_image || selected.identifier_image) && (
                    <div className="grid grid-cols-2 gap-3 mb-5">
                      {selected.driving_license_image && (
                        <div>
                          <p className="text-xs text-slate-500 font-bold mb-1.5" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>صورة رخصة القيادة</p>
                          <a href={selected.driving_license_image} target="_blank" rel="noreferrer">
                            <img src={selected.driving_license_image} alt="رخصة القيادة" className="w-full h-28 object-cover rounded-xl border border-slate-200 hover:opacity-90 transition-all" />
                          </a>
                        </div>
                      )}
                      {selected.identifier_image && (
                        <div>
                          <p className="text-xs text-slate-500 font-bold mb-1.5" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>صورة الهوية</p>
                          <a href={selected.identifier_image} target="_blank" rel="noreferrer">
                            <img src={selected.identifier_image} alt="الهوية" className="w-full h-28 object-cover rounded-xl border border-slate-200 hover:opacity-90 transition-all" />
                          </a>
                        </div>
                      )}
                    </div>
                  )}

                  <div className="flex gap-3">
                    <button
                      className="flex-1 h-10 bg-slate-100 rounded-xl font-bold text-sm text-slate-600 cursor-pointer"
                      style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}
                      onClick={() => setSelected(null)}
                    >
                      إغلاق
                    </button>
                    <button
                      className="flex-1 h-10 rounded-xl font-bold text-sm text-white cursor-pointer"
                      style={{ background: '#1E3A8A', fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}
                      onClick={() => {
                        const row = drivers.find((d) => d.rawId === selected.id);
                        setSelected(null);
                        if (row) openEdit(row);
                      }}
                    >
                      تعديل البيانات
                    </button>
                  </div>
                </>
              )}
            </div>
          </div>
        )}

        {/* ═══════════════════════════════════════════════════════ */}
        {/*          Edit Driver Modal (captains/:id/update)       */}
        {/* ═══════════════════════════════════════════════════════ */}
        {editTarget && (
          <div className="fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-6" onClick={() => !editSubmitLoading && closeEdit()}>
            <div className="bg-white rounded-3xl w-full max-w-xl shadow-2xl flex flex-col" style={{ maxHeight: '90vh' }} onClick={(e) => e.stopPropagation()}>

              {/* Modal Header */}
              <div className="flex items-center justify-between px-7 pt-6 pb-4 border-b border-slate-100 flex-shrink-0">
                <div className="flex items-center gap-3">
                  <div className="w-10 h-10 rounded-xl overflow-hidden flex-shrink-0">
                    <img src={editForm.imagePreview || editTarget.avatar} alt={editTarget.name} className="w-full h-full object-cover object-top" />
                  </div>
                  <div>
                    <h2 className="text-lg font-black text-slate-900" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>تعديل بيانات السائق</h2>
                    <p className="text-xs text-slate-400" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{editTarget.id}</p>
                  </div>
                </div>
                <button disabled={editSubmitLoading} onClick={closeEdit} className="w-9 h-9 bg-slate-100 rounded-xl flex items-center justify-center cursor-pointer disabled:opacity-50">
                  <i className="ri-close-line text-slate-500 text-lg"></i>
                </button>
              </div>

              {editDetailLoading ? (
                <div className="flex flex-col items-center justify-center gap-4 py-16">
                  <i className="ri-loader-4-line text-3xl animate-spin" style={{ color: '#1E3A8A' }}></i>
                  <p className="text-sm text-slate-500" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>جاري تحميل البيانات...</p>
                </div>
              ) : editSubmitted ? (
                <div className="flex flex-col items-center justify-center gap-4 py-16">
                  <div className="w-16 h-16 rounded-full flex items-center justify-center" style={{ background: '#DCFCE7' }}>
                    <i className="ri-check-line text-3xl" style={{ color: '#059669' }}></i>
                  </div>
                  <p className="text-base font-black text-slate-800" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>تم تحديث البيانات بنجاح</p>
                </div>
              ) : (
                <>
                  <div className="overflow-y-auto px-7 py-5 flex-1 space-y-5">

                    {/* Photo */}
                    <div>
                      <label className="block text-sm font-bold text-slate-700 mb-2" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>صورة السائق</label>
                      <div className="flex items-center gap-4">
                        <div
                          className="w-20 h-20 rounded-2xl overflow-hidden flex-shrink-0 flex items-center justify-center cursor-pointer border-2 border-dashed transition-all"
                          style={{ borderColor: editForm.imagePreview ? '#1E3A8A' : '#CBD5E1', background: '#F8FAFC' }}
                          onClick={() => editPhotoRef.current?.click()}
                        >
                          {editForm.imagePreview
                            ? <img src={editForm.imagePreview} alt="preview" className="w-full h-full object-cover object-top" />
                            : <i className="ri-user-3-line text-2xl text-slate-300"></i>
                          }
                        </div>
                        <div>
                          <button type="button" onClick={() => editPhotoRef.current?.click()}
                            className="flex items-center gap-2 px-4 py-2 rounded-xl text-sm font-bold cursor-pointer whitespace-nowrap border transition-all"
                            style={{ borderColor: '#1E3A8A', color: '#1E3A8A', background: '#EEF2FF', fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>
                            <i className="ri-upload-2-line text-sm"></i>
                            تغيير الصورة
                          </button>
                          <p className="text-xs text-slate-400 mt-1.5" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>JPG أو PNG، حجم أقصى 5MB</p>
                        </div>
                      </div>
                      <input ref={editPhotoRef} type="file" accept="image/*" className="hidden" onChange={handleEditPhotoChange} />
                    </div>

                    {/* Name */}
                    <div>
                      <label className="block text-sm font-bold text-slate-700 mb-1.5" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>
                        الاسم الكامل <span className="text-red-500">*</span>
                      </label>
                      <input
                        type="text"
                        value={editForm.name}
                        onChange={(e) => { setEditForm((f) => ({ ...f, name: e.target.value })); setEditErrors((er) => ({ ...er, name: '' })); }}
                        className="w-full h-11 bg-slate-50 rounded-xl px-4 text-sm outline-none text-slate-700 border transition-all"
                        style={{ borderColor: editErrors.name ? '#EF4444' : '#E2E8F0', fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}
                      />
                      {editErrors.name && <p className="text-xs text-red-500 mt-1" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{editErrors.name}</p>}
                    </div>

                    {/* Phone + country_code */}
                    <div>
                      <label className="block text-sm font-bold text-slate-700 mb-1.5" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>
                        رقم الجوال <span className="text-red-500">*</span>
                      </label>
                      <div
                        className="flex h-11 rounded-xl border transition-all overflow-hidden bg-slate-50"
                        style={{ borderColor: editErrors.phone ? '#EF4444' : '#E2E8F0' }}
                        dir="ltr"
                      >
                        <span className="flex items-center flex-shrink-0 px-3 text-sm font-bold text-slate-600 bg-slate-100 border-r border-slate-200">
                          {editForm.country_code || CAPTAIN_COUNTRY_CODE}
                        </span>
                        <input
                          type="tel"
                          inputMode="numeric"
                          placeholder="5XXXXXXXX"
                          value={editForm.phone}
                          onChange={(e) => { setEditForm((f) => ({ ...f, phone: e.target.value })); setEditErrors((er) => ({ ...er, phone: '' })); }}
                          className="flex-1 min-w-0 h-full px-3 text-sm outline-none bg-transparent text-slate-800"
                        />
                      </div>
                      {editErrors.phone && <p className="text-xs text-red-500 mt-1" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{editErrors.phone}</p>}
                    </div>

                    {/* Email */}
                    <div>
                      <label className="block text-sm font-bold text-slate-700 mb-1.5" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>
                        البريد الإلكتروني <span className="text-red-500">*</span>
                      </label>
                      <input
                        type="email"
                        placeholder="name@example.com"
                        value={editForm.email}
                        onChange={(e) => { setEditForm((f) => ({ ...f, email: e.target.value })); setEditErrors((er) => ({ ...er, email: '' })); }}
                        className="w-full h-11 bg-slate-50 rounded-xl px-4 text-sm outline-none text-slate-700 border transition-all"
                        style={{ borderColor: editErrors.email ? '#EF4444' : '#E2E8F0', fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}
                        dir="ltr"
                      />
                      {editErrors.email && <p className="text-xs text-red-500 mt-1" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{editErrors.email}</p>}
                    </div>

                    {/* accept_terms — روابط الشروط والخصوصية كما في صفحة التسجيل */}
                    <label
                      className="flex items-start gap-3 cursor-pointer p-4 rounded-xl transition-all"
                      style={{
                        background: editForm.accept_terms ? '#EEF2FF' : '#F8FAFC',
                        border: `1px solid ${editForm.accept_terms ? '#1E3A8A' : '#E2E8F0'}`,
                      }}
                    >
                      <input
                        type="checkbox"
                        checked={editForm.accept_terms}
                        onChange={(e) => setEditForm((f) => ({ ...f, accept_terms: e.target.checked }))}
                        className="w-5 h-5 mt-0.5 accent-blue-600 flex-shrink-0"
                      />
                      <span className="text-sm text-slate-600 leading-relaxed" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>
                        أوافق على{' '}
                        <button
                          type="button"
                          className="font-semibold bg-transparent border-0 p-0 cursor-pointer underline-offset-2 hover:underline"
                          style={{ color: '#1D4ED8' }}
                          onClick={(e) => {
                            e.preventDefault();
                            e.stopPropagation();
                            setTermsDialogVisible(true);
                            void loadTermsContent();
                          }}
                        >
                          الشروط والأحكام
                        </button>{' '}
                        و{' '}
                        <button
                          type="button"
                          className="font-semibold bg-transparent border-0 p-0 cursor-pointer underline-offset-2 hover:underline"
                          style={{ color: '#1D4ED8' }}
                          onClick={(e) => {
                            e.preventDefault();
                            e.stopPropagation();
                            setPrivacyDialogVisible(true);
                            void loadPrivacyContent();
                          }}
                        >
                          سياسة الخصوصية
                        </button>
                      </span>
                    </label>

                  </div>

                  {/* Footer */}
                  <div className="px-7 py-4 border-t border-slate-100 flex gap-3 flex-shrink-0">
                    <button
                      disabled={editSubmitLoading}
                      onClick={closeEdit}
                      className="flex-1 h-11 bg-slate-100 rounded-xl font-bold text-sm text-slate-600 cursor-pointer whitespace-nowrap disabled:opacity-50"
                      style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}
                    >
                      إلغاء
                    </button>
                    <button
                      disabled={editSubmitLoading}
                      onClick={handleEditSubmit}
                      className="flex-1 h-11 rounded-xl font-bold text-sm text-white cursor-pointer whitespace-nowrap flex items-center justify-center gap-2 transition-all disabled:opacity-70"
                      style={{ background: '#1E3A8A', fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}
                    >
                      {editSubmitLoading
                        ? <><i className="ri-loader-4-line text-base animate-spin"></i> جاري الحفظ...</>
                        : <><i className="ri-save-line text-base"></i> حفظ التعديلات</>
                      }
                    </button>
                  </div>
                </>
              )}
            </div>
          </div>
        )}

        {/* ═══════════════════════════════════════════════════════ */}
        {/*                  Delete Confirm Modal                  */}
        {/* ═══════════════════════════════════════════════════════ */}
        {deleteTarget && (
          <div
            className="fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-6"
            onClick={() => !deleteApi.loading && setDeleteTarget(null)}
          >
            <div className="bg-white rounded-3xl p-7 w-full max-w-sm shadow-2xl" onClick={(e) => e.stopPropagation()}>
              <div className="flex flex-col items-center gap-4 mb-6">
                <div className="w-16 h-16 rounded-full flex items-center justify-center" style={{ background: '#FEE2E2' }}>
                  <i className="ri-delete-bin-line text-3xl" style={{ color: '#EF4444' }}></i>
                </div>
                <div className="text-center">
                  <p className="text-base font-black text-slate-800 mb-1" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>حذف السائق</p>
                  <p className="text-sm text-slate-500" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>
                    هل أنت متأكد من حذف <span className="font-bold text-slate-700">{deleteTarget.name}</span>؟ لا يمكن التراجع عن هذا الإجراء.
                  </p>
                </div>
              </div>
              <div className="flex gap-3">
                <button
                  type="button"
                  disabled={deleteApi.loading}
                  onClick={() => setDeleteTarget(null)}
                  className="flex-1 h-11 bg-slate-100 rounded-xl font-bold text-sm text-slate-600 cursor-pointer whitespace-nowrap disabled:opacity-50 disabled:cursor-not-allowed"
                  style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}
                >
                  إلغاء
                </button>
                <button
                  type="button"
                  disabled={deleteApi.loading}
                  onClick={() => void handleDeleteCaptainConfirm()}
                  className="flex-1 h-11 rounded-xl font-bold text-sm text-white cursor-pointer whitespace-nowrap disabled:opacity-70 disabled:cursor-not-allowed flex items-center justify-center gap-2"
                  style={{ background: '#EF4444', fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}
                >
                  {deleteApi.loading ? (
                    <>
                      <i className="ri-loader-4-line text-base animate-spin"></i>
                      جاري الحذف...
                    </>
                  ) : (
                    'نعم، احذف'
                  )}
                </button>
              </div>
            </div>
          </div>
        )}

        {/* ═══════════════════════════════════════════════════════ */}
        {/*                   Add Driver Modal                     */}
        {/* ═══════════════════════════════════════════════════════ */}
        {showAdd && (
          <div className="fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-6" onClick={() => !submitLoading && closeAdd()}>
            <div className="bg-white rounded-3xl w-full max-w-3xl shadow-2xl flex flex-col" style={{ maxHeight: '90vh' }} onClick={(e) => e.stopPropagation()}>
              <div className="flex items-center justify-between px-7 pt-6 pb-4 border-b border-slate-100 flex-shrink-0">
                <div>
                  <h2 className="text-lg font-black text-slate-900" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>إضافة سائق جديد</h2>
                  <p className="text-xs text-slate-400 mt-0.5" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>الحقول المميزة بـ * مطلوبة</p>
                </div>
                <button type="button" disabled={submitLoading} onClick={closeAdd} className="w-9 h-9 bg-slate-100 rounded-xl flex items-center justify-center cursor-pointer disabled:opacity-50">
                  <i className="ri-close-line text-slate-500 text-lg"></i>
                </button>
              </div>

              <div className="overflow-y-auto px-7 py-5 flex-1 space-y-5">
                {/* Image */}
                <div>
                  <label className="block text-sm font-bold text-slate-700 mb-2" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>صورة السائق <span className="text-red-500">*</span></label>
                  <div className="flex items-center gap-4">
                    <div
                      className="w-20 h-20 rounded-2xl overflow-hidden flex-shrink-0 flex items-center justify-center cursor-pointer border-2 border-dashed transition-all"
                      style={{ borderColor: errors.image ? '#EF4444' : form.imagePreview ? '#1E3A8A' : '#CBD5E1', background: '#F8FAFC' }}
                      onClick={() => imageRef.current?.click()}
                    >
                      {form.imagePreview
                        ? <img src={form.imagePreview} alt="" className="w-full h-full object-cover object-top" />
                        : <div className="flex flex-col items-center gap-1">
                            <i className="ri-user-3-line text-2xl text-slate-300"></i>
                            <span className="text-[10px] text-slate-400" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>رفع صورة</span>
                          </div>
                      }
                    </div>
                    <div>
                      <button type="button" onClick={() => imageRef.current?.click()}
                        className="flex items-center gap-2 px-4 py-2 rounded-xl text-sm font-bold cursor-pointer whitespace-nowrap border transition-all"
                        style={{ borderColor: '#1E3A8A', color: '#1E3A8A', background: '#EEF2FF', fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>
                        <i className="ri-upload-2-line text-sm"></i>
                        {form.imageFile ? 'تغيير الصورة' : 'اختر صورة'}
                      </button>
                      <p className="text-xs text-slate-400 mt-1.5" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>صورة (JPG أو PNG)</p>
                      {errors.image && <p className="text-xs text-red-500 mt-1" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{errors.image}</p>}
                    </div>
                  </div>
                  <input ref={imageRef} type="file" accept="image/*" className="hidden" onChange={handleImageChange} />
                </div>

                {/* Name + Email */}
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <label className="block text-sm font-bold text-slate-700 mb-1.5" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>الاسم الكامل <span className="text-red-500">*</span></label>
                    <input type="text" placeholder="الاسم الكامل" value={form.name}
                      onChange={(e) => { setForm((f) => ({ ...f, name: e.target.value })); setErrors((er) => ({ ...er, name: '' })); }}
                      className="w-full h-11 bg-slate-50 rounded-xl px-4 text-sm outline-none text-slate-700 border transition-all"
                      style={{ borderColor: errors.name ? '#EF4444' : '#E2E8F0', fontFamily: '"IBM Plex Sans Arabic", sans-serif' }} />
                    {errors.name && <p className="text-xs text-red-500 mt-1" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{errors.name}</p>}
                  </div>
                  <div>
                    <label className="block text-sm font-bold text-slate-700 mb-1.5" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>البريد الإلكتروني <span className="text-red-500">*</span></label>
                    <input type="email" placeholder="name@example.com" value={form.email}
                      onChange={(e) => { setForm((f) => ({ ...f, email: e.target.value })); setErrors((er) => ({ ...er, email: '' })); }}
                      className="w-full h-11 bg-slate-50 rounded-xl px-4 text-sm outline-none text-slate-700 border transition-all"
                      style={{ borderColor: errors.email ? '#EF4444' : '#E2E8F0', fontFamily: '"IBM Plex Sans Arabic", sans-serif' }} dir="ltr" />
                    {errors.email && <p className="text-xs text-red-500 mt-1" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{errors.email}</p>}
                  </div>
                </div>

                {/* Phone */}
                <div>
                  <label className="block text-sm font-bold text-slate-700 mb-1.5" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>رقم الجوال <span className="text-red-500">*</span></label>
                  <div
                    className="flex h-11 rounded-xl border transition-all overflow-hidden bg-slate-50"
                    style={{ borderColor: errors.phone ? '#EF4444' : '#E2E8F0' }}
                    dir="ltr"
                  >
                    <span className="flex items-center flex-shrink-0 px-3 text-sm font-bold text-slate-600 bg-slate-100 border-r border-slate-200">966</span>
                    <input
                      type="tel"
                      inputMode="numeric"
                      autoComplete="tel-national"
                      placeholder="5XXXXXXXX"
                      value={form.phone}
                      onChange={(e) => { setForm((f) => ({ ...f, phone: e.target.value })); setErrors((er) => ({ ...er, phone: '' })); }}
                      className="flex-1 min-w-0 h-full px-3 text-sm outline-none bg-transparent text-slate-800"
                    />
                  </div>
                  {errors.phone && <p className="text-xs text-red-500 mt-1" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{errors.phone}</p>}
                </div>

                {/* Type + Nationality */}
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <label htmlFor="captain-type" className="block text-sm font-bold text-slate-700 mb-1.5" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>النوع <span className="text-red-500">*</span></label>
                    <Dropdown
                      inputId="captain-type"
                      value={form.type || null}
                      options={CAPTAIN_TYPE_OPTIONS}
                      optionLabel="label"
                      optionValue="value"
                      placeholder="اختر النوع"
                      onChange={(e) => { setForm((f) => ({ ...f, type: e.value ?? '' })); setErrors((er) => ({ ...er, type: '' })); }}
                      className="w-full"
                      style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}
                      panelStyle={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}
                      invalid={!!errors.type}
                      pt={{ root: { className: 'min-h-[2.75rem] rounded-xl border bg-slate-50' }, input: { className: 'text-sm text-slate-700' } }}
                    />
                    {errors.type && <p className="text-xs text-red-500 mt-1" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{errors.type}</p>}
                  </div>
                  <div>
                    <label className="block text-sm font-bold text-slate-700 mb-1.5" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>الجنسية <span className="text-red-500">*</span></label>
                    <input type="text" placeholder="مثال: سعودي" value={form.nationality}
                      onChange={(e) => { setForm((f) => ({ ...f, nationality: e.target.value })); setErrors((er) => ({ ...er, nationality: '' })); }}
                      className="w-full h-11 bg-slate-50 rounded-xl px-4 text-sm outline-none text-slate-700 border transition-all"
                      style={{ borderColor: errors.nationality ? '#EF4444' : '#E2E8F0', fontFamily: '"IBM Plex Sans Arabic", sans-serif' }} />
                    {errors.nationality && <p className="text-xs text-red-500 mt-1" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{errors.nationality}</p>}
                  </div>
                </div>

                {/* Identifier number */}
                <div>
                  <label className="block text-sm font-bold text-slate-700 mb-1.5" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>رقم الهوية / الإقامة <span className="text-red-500">*</span></label>
                  <input type="text" placeholder="رقم الهوية / الإقامة" value={form.identifier_number}
                    onChange={(e) => { setForm((f) => ({ ...f, identifier_number: e.target.value })); setErrors((er) => ({ ...er, identifier_number: '' })); }}
                    className="w-full h-11 bg-slate-50 rounded-xl px-4 text-sm outline-none text-slate-700 border transition-all"
                    style={{ borderColor: errors.identifier_number ? '#EF4444' : '#E2E8F0', fontFamily: '"IBM Plex Sans Arabic", sans-serif' }} dir="ltr" />
                  {errors.identifier_number && <p className="text-xs text-red-500 mt-1" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{errors.identifier_number}</p>}
                </div>

                {/* Driving license image */}
                <div>
                  <label className="block text-sm font-bold text-slate-700 mb-1.5" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>صورة رخصة القيادة <span className="text-red-500">*</span></label>
                  <div onClick={() => drivingLicenseRef.current?.click()}
                    className="flex items-center gap-3 h-12 rounded-xl px-4 border-2 border-dashed cursor-pointer transition-all"
                    style={{ borderColor: errors.driving_license_image ? '#EF4444' : form.driving_license_imageFile ? '#1E3A8A' : '#CBD5E1', background: form.driving_license_imageFile ? '#EEF2FF' : '#F8FAFC' }}>
                    <i className={`${form.driving_license_imageFile ? 'ri-file-check-line' : 'ri-upload-cloud-2-line'} text-lg`} style={{ color: form.driving_license_imageFile ? '#1E3A8A' : '#94a3b8' }}></i>
                    <span className="text-sm flex-1 truncate" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif', color: form.driving_license_imageFile ? '#1E3A8A' : '#94a3b8' }}>
                      {form.driving_license_name || 'رفع صورة رخصة القيادة'}
                    </span>
                    {form.driving_license_imageFile && (
                      <button type="button" onClick={(e) => { e.stopPropagation(); setForm((f) => ({ ...f, driving_license_imageFile: null, driving_license_name: '', driving_license_preview: '' })); }}
                        className="w-5 h-5 flex items-center justify-center rounded-full hover:bg-red-100 cursor-pointer">
                        <i className="ri-close-line text-xs text-red-400"></i>
                      </button>
                    )}
                  </div>
                  <input ref={drivingLicenseRef} type="file" accept="image/*" className="hidden" onChange={handleDrivingLicenseChange} />
                  {errors.driving_license_image && <p className="text-xs text-red-500 mt-1" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{errors.driving_license_image}</p>}
                </div>

                {/* Identifier image */}
                <div>
                  <label className="block text-sm font-bold text-slate-700 mb-1.5" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>صورة الهوية <span className="text-red-500">*</span></label>
                  <div onClick={() => identifierImageRef.current?.click()}
                    className="flex items-center gap-3 h-12 rounded-xl px-4 border-2 border-dashed cursor-pointer transition-all"
                    style={{ borderColor: errors.identifier_image ? '#EF4444' : form.identifier_imageFile ? '#1E3A8A' : '#CBD5E1', background: form.identifier_imageFile ? '#EEF2FF' : '#F8FAFC' }}>
                    <i className={`${form.identifier_imageFile ? 'ri-file-check-line' : 'ri-upload-cloud-2-line'} text-lg`} style={{ color: form.identifier_imageFile ? '#1E3A8A' : '#94a3b8' }}></i>
                    <span className="text-sm flex-1 truncate" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif', color: form.identifier_imageFile ? '#1E3A8A' : '#94a3b8' }}>
                      {form.identifier_image_name || 'رفع صورة الهوية'}
                    </span>
                    {form.identifier_imageFile && (
                      <button type="button" onClick={(e) => { e.stopPropagation(); setForm((f) => ({ ...f, identifier_imageFile: null, identifier_image_name: '', identifier_image_preview: '' })); }}
                        className="w-5 h-5 flex items-center justify-center rounded-full hover:bg-red-100 cursor-pointer">
                        <i className="ri-close-line text-xs text-red-400"></i>
                      </button>
                    )}
                  </div>
                  <input ref={identifierImageRef} type="file" accept="image/*" className="hidden" onChange={handleIdentifierImageChange} />
                  {errors.identifier_image && <p className="text-xs text-red-500 mt-1" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{errors.identifier_image}</p>}
                </div>

                {/* Password */}
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <label className="block text-sm font-bold text-slate-700 mb-1.5" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>كلمة المرور <span className="text-red-500">*</span></label>
                    <div className="relative">
                      <input type={form.showPassword ? 'text' : 'password'} placeholder="أدخل كلمة مرور مكونه من 8 حروف وأرقام" value={form.password}
                        onChange={(e) => { setForm((f) => ({ ...f, password: e.target.value })); setErrors((er) => ({ ...er, password: '' })); }}
                        className="w-full h-11 bg-slate-50 rounded-xl pr-4 pl-10 text-sm outline-none text-slate-700 border transition-all"
                        style={{ borderColor: errors.password ? '#EF4444' : '#E2E8F0' }} dir="ltr" />
                      <button type="button" onClick={() => setForm((f) => ({ ...f, showPassword: !f.showPassword }))}
                        className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 flex items-center justify-center cursor-pointer">
                        <i className={`${form.showPassword ? 'ri-eye-off-line' : 'ri-eye-line'} text-slate-400 text-sm`}></i>
                      </button>
                    </div>
                    {errors.password && <p className="text-xs text-red-500 mt-1" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{errors.password}</p>}
                  </div>
                  <div>
                    <label className="block text-sm font-bold text-slate-700 mb-1.5" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>تأكيد كلمة المرور <span className="text-red-500">*</span></label>
                    <div className="relative">
                      <input type={form.showConfirm ? 'text' : 'password'} placeholder="أعد كتابة كلمة المرور" value={form.password_confirmation}
                        onChange={(e) => { setForm((f) => ({ ...f, password_confirmation: e.target.value })); setErrors((er) => ({ ...er, password_confirmation: '' })); }}
                        className="w-full h-11 bg-slate-50 rounded-xl pr-4 pl-10 text-sm outline-none text-slate-700 border transition-all"
                        style={{ borderColor: errors.password_confirmation ? '#EF4444' : '#E2E8F0' }} dir="ltr" />
                      <button type="button" onClick={() => setForm((f) => ({ ...f, showConfirm: !f.showConfirm }))}
                        className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 flex items-center justify-center cursor-pointer">
                        <i className={`${form.showConfirm ? 'ri-eye-off-line' : 'ri-eye-line'} text-slate-400 text-sm`}></i>
                      </button>
                    </div>
                    {errors.password_confirmation && <p className="text-xs text-red-500 mt-1" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{errors.password_confirmation}</p>}
                  </div>
                </div>

                {/* Medical insurance */}
                <div
                  className="flex items-start gap-3 p-4 rounded-xl cursor-pointer transition-all"
                  style={{ background: form.has_medical_insurance ? '#EEF2FF' : '#F8FAFC', border: '1px solid #E2E8F0' }}
                  onClick={() => setForm((f) => ({ ...f, has_medical_insurance: !f.has_medical_insurance }))}
                >
                  <div className="w-5 h-5 rounded-md flex items-center justify-center flex-shrink-0 mt-0.5 transition-all"
                    style={{ background: form.has_medical_insurance ? '#1E3A8A' : 'white', border: `2px solid ${form.has_medical_insurance ? '#1E3A8A' : '#CBD5E1'}` }}>
                    {form.has_medical_insurance && <i className="ri-check-line text-white text-xs"></i>}
                  </div>
                  <p className="text-sm text-slate-600 leading-relaxed" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>لديه تأمين طبي</p>
                </div>

                {/* Agree terms — روابط الشروط والخصوصية كما في التسجيل */}
                <div>
                  <label
                    className="flex items-start gap-3 cursor-pointer p-4 rounded-xl transition-all"
                    style={{
                      background: form.agreeTerms ? '#EEF2FF' : '#F8FAFC',
                      border: `1px solid ${errors.agreeTerms ? '#EF4444' : form.agreeTerms ? '#1E3A8A' : '#E2E8F0'}`,
                    }}
                  >
                    <input
                      type="checkbox"
                      checked={form.agreeTerms}
                      onChange={(e) => {
                        setForm((f) => ({ ...f, agreeTerms: e.target.checked }));
                        setErrors((er) => ({ ...er, agreeTerms: '' }));
                      }}
                      className="w-5 h-5 mt-0.5 accent-blue-600 flex-shrink-0"
                    />
                    <span className="text-sm text-slate-600 leading-relaxed" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>
                      أوافق على{' '}
                      <button
                        type="button"
                        className="font-semibold bg-transparent border-0 p-0 cursor-pointer underline-offset-2 hover:underline"
                        style={{ color: '#1D4ED8' }}
                        onClick={(e) => {
                          e.preventDefault();
                          e.stopPropagation();
                          setTermsDialogVisible(true);
                          void loadTermsContent();
                        }}
                      >
                        الشروط والأحكام
                      </button>{' '}
                      و{' '}
                      <button
                        type="button"
                        className="font-semibold bg-transparent border-0 p-0 cursor-pointer underline-offset-2 hover:underline"
                        style={{ color: '#1D4ED8' }}
                        onClick={(e) => {
                          e.preventDefault();
                          e.stopPropagation();
                          setPrivacyDialogVisible(true);
                          void loadPrivacyContent();
                        }}
                      >
                        سياسة الخصوصية
                      </button>
                    </span>
                  </label>
                  {errors.agreeTerms && <p className="text-xs text-red-500 mt-1" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{errors.agreeTerms}</p>}
                </div>
              </div>

              <div className="px-7 py-4 border-t border-slate-100 flex gap-3 flex-shrink-0">
                <button type="button" disabled={submitLoading} onClick={closeAdd}
                  className="flex-1 h-11 bg-slate-100 rounded-xl font-bold text-sm text-slate-600 cursor-pointer whitespace-nowrap disabled:opacity-50"
                  style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>
                  إلغاء
                </button>
                <button type="button" disabled={submitLoading} onClick={handleSubmit}
                  className="flex-1 h-11 rounded-xl font-bold text-sm text-white cursor-pointer whitespace-nowrap flex items-center justify-center gap-2 transition-all disabled:opacity-70"
                  style={{ background: '#1E3A8A', fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>
                  {submitLoading
                    ? <><i className="ri-loader-4-line text-base animate-spin"></i> جاري الإرسال...</>
                    : <><i className="ri-user-add-line text-base"></i> إضافة السائق</>
                  }
                </button>
              </div>
            </div>
          </div>
        )}

      {/* الشروط والأحكام / سياسة الخصوصية — نفس أسلوب التسجيل */}
      <Dialog
        visible={termsDialogVisible}
        onHide={() => setTermsDialogVisible(false)}
        header="الشروط والأحكام"
        modal
        draggable={false}
        resizable={false}
        style={{ width: 'min(92vw, 560px)' }}
        contentStyle={{ padding: '1rem 1.25rem', direction: 'rtl', maxHeight: '70vh', overflow: 'auto' }}
      >
        {termsLoading ? (
          <div className="flex justify-center py-12">
            <ProgressSpinner style={{ width: '48px', height: '48px' }} strokeWidth="4" />
          </div>
        ) : (
          <LegalHtmlBlock content={termsBody} />
        )}
      </Dialog>

      <Dialog
        visible={privacyDialogVisible}
        onHide={() => setPrivacyDialogVisible(false)}
        header="سياسة الخصوصية"
        modal
        draggable={false}
        resizable={false}
        style={{ width: 'min(92vw, 560px)' }}
        contentStyle={{ padding: '1rem 1.25rem', direction: 'rtl', maxHeight: '70vh', overflow: 'auto' }}
      >
        {privacyLoading ? (
          <div className="flex justify-center py-12">
            <ProgressSpinner style={{ width: '48px', height: '48px' }} strokeWidth="4" />
          </div>
        ) : (
          <LegalHtmlBlock content={privacyBody} />
        )}
      </Dialog>

      </DashboardShell>
    </>
  );
}