'use client';

import { useState, useRef, useEffect, useCallback } from 'react';
import { AppToast } from '@/app/components/AppToast';
import type { Toast as ToastType } from 'primereact/toast';
import { Skeleton } from 'primereact/skeleton';
import DashboardShell from '../components/DashboardShell';
import { useApi } from '@/hooks/useApi';
import { useAuthStore } from '@/store/authStore';

const DEFAULT_CAPTAIN_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';

const initialBuses = [
  {
    id: 'B-001', plate: 'ABC 1234', model: 'تويوتا كوستر 2022', capacity: 14,
    driver: 'أحمد السلمي', driverId: 'D-001',
    route: 'حي النزهة ← جامعة الملك سعود',
    status: 'نشط', statusColor: '#059669', statusBg: '#DCFCE7',
    km: '124,500', lastService: '15 فبراير 2026',
    year: '2022', color: 'أبيض', vin: 'JT3HP10V5X0123456', insurance: '31 ديسمبر 2026', license: '15 مارس 2027',
    img: 'https://readdy.ai/api/search-image?query=modern%20white%20Toyota%20Coaster%20minibus%20side%20view%20clean%20white%20background%20professional%20photo%20realistic%20high%20quality%20transportation%20vehicle%20Saudi%20Arabia&width=200&height=120&seq=bus-list-01&orientation=landscape',
    docs: [
      { name: 'رخصة السير', status: 'ساري', exp: '15 مارس 2027', icon: 'ri-file-text-line', color: '#059669', bg: '#DCFCE7' },
      { name: 'وثيقة التأمين', status: 'ساري', exp: '31 ديسمبر 2026', icon: 'ri-shield-check-line', color: '#059669', bg: '#DCFCE7' },
      { name: 'فحص دوري', status: 'قريب الانتهاء', exp: '20 أبريل 2026', icon: 'ri-tools-line', color: '#D97706', bg: '#FEF3C7' },
    ],
  },
  {
    id: 'B-002', plate: 'XYZ 5678', model: 'هيونداي H350 2023', capacity: 18,
    driver: 'خالد العتيبي', driverId: 'D-002',
    route: 'حي الروضة ← جامعة الأميرة نورة',
    status: 'نشط', statusColor: '#059669', statusBg: '#DCFCE7',
    km: '87,200', lastService: '1 مارس 2026',
    year: '2023', color: 'أبيض', vin: 'KMHEC41BP3A234567', insurance: '28 فبراير 2027', license: '10 يونيو 2027',
    img: 'https://readdy.ai/api/search-image?query=modern%20white%20Hyundai%20H350%20minibus%20side%20view%20clean%20white%20background%20professional%20photo%20realistic%20high%20quality%20transportation%20vehicle&width=200&height=120&seq=bus-list-02&orientation=landscape',
    docs: [
      { name: 'رخصة السير', status: 'ساري', exp: '10 يونيو 2027', icon: 'ri-file-text-line', color: '#059669', bg: '#DCFCE7' },
      { name: 'وثيقة التأمين', status: 'ساري', exp: '28 فبراير 2027', icon: 'ri-shield-check-line', color: '#059669', bg: '#DCFCE7' },
      { name: 'فحص دوري', status: 'ساري', exp: '15 يوليو 2026', icon: 'ri-tools-line', color: '#059669', bg: '#DCFCE7' },
    ],
  },
  {
    id: 'B-003', plate: 'DEF 9012', model: 'مرسيدس سبرينتر 2021', capacity: 22,
    driver: 'فهد الشمري', driverId: 'D-003',
    route: 'حي السلام ← كلية التقنية',
    status: 'نشط', statusColor: '#059669', statusBg: '#DCFCE7',
    km: '201,300', lastService: '20 يناير 2026',
    year: '2021', color: 'فضي', vin: 'WDB9066351S345678', insurance: '30 نوفمبر 2026', license: '5 يناير 2027',
    img: 'https://readdy.ai/api/search-image?query=modern%20white%20Mercedes%20Sprinter%20minibus%20side%20view%20clean%20white%20background%20professional%20photo%20realistic%20high%20quality%20transportation%20vehicle&width=200&height=120&seq=bus-list-03&orientation=landscape',
    docs: [
      { name: 'رخصة السير', status: 'ساري', exp: '5 يناير 2027', icon: 'ri-file-text-line', color: '#059669', bg: '#DCFCE7' },
      { name: 'وثيقة التأمين', status: 'قريب الانتهاء', exp: '30 نوفمبر 2026', icon: 'ri-shield-check-line', color: '#D97706', bg: '#FEF3C7' },
      { name: 'فحص دوري', status: 'منتهي', exp: '1 مارس 2026', icon: 'ri-tools-line', color: '#EF4444', bg: '#FEE2E2' },
    ],
  },
  {
    id: 'B-004', plate: 'GHI 3456', model: 'تويوتا كوستر 2020', capacity: 14,
    driver: 'سعد القحطاني', driverId: 'D-004',
    route: 'حي الملك فهد ← جامعة الملك عبدالعزيز',
    status: 'صيانة', statusColor: '#D97706', statusBg: '#FEF3C7',
    km: '178,900', lastService: 'اليوم',
    year: '2020', color: 'أبيض', vin: 'JT3HP10V5X0456789', insurance: '15 أكتوبر 2026', license: '22 أغسطس 2026',
    img: 'https://readdy.ai/api/search-image?query=modern%20white%20Toyota%20Coaster%20minibus%20side%20view%20clean%20white%20background%20professional%20photo%20realistic%20high%20quality%20transportation%20vehicle%202020&width=200&height=120&seq=bus-list-04&orientation=landscape',
    docs: [
      { name: 'رخصة السير', status: 'ساري', exp: '22 أغسطس 2026', icon: 'ri-file-text-line', color: '#059669', bg: '#DCFCE7' },
      { name: 'وثيقة التأمين', status: 'ساري', exp: '15 أكتوبر 2026', icon: 'ri-shield-check-line', color: '#059669', bg: '#DCFCE7' },
      { name: 'فحص دوري', status: 'ساري', exp: '10 سبتمبر 2026', icon: 'ri-tools-line', color: '#059669', bg: '#DCFCE7' },
    ],
  },
  {
    id: 'B-005', plate: 'JKL 7890', model: 'فورد ترانزيت 2023', capacity: 16,
    driver: 'عمر الزهراني', driverId: 'D-005',
    route: 'حي العزيزية ← المستشفى الجامعي',
    status: 'نشط', statusColor: '#059669', statusBg: '#DCFCE7',
    km: '54,100', lastService: '5 مارس 2026',
    year: '2023', color: 'أبيض', vin: 'WF0XXXTTGXKA56789', insurance: '20 مايو 2027', license: '30 أبريل 2027',
    img: 'https://readdy.ai/api/search-image?query=modern%20white%20Ford%20Transit%20minibus%20side%20view%20clean%20white%20background%20professional%20photo%20realistic%20high%20quality%20transportation%20vehicle&width=200&height=120&seq=bus-list-05&orientation=landscape',
    docs: [
      { name: 'رخصة السير', status: 'ساري', exp: '30 أبريل 2027', icon: 'ri-file-text-line', color: '#059669', bg: '#DCFCE7' },
      { name: 'وثيقة التأمين', status: 'ساري', exp: '20 مايو 2027', icon: 'ri-shield-check-line', color: '#059669', bg: '#DCFCE7' },
      { name: 'فحص دوري', status: 'ساري', exp: '1 ديسمبر 2026', icon: 'ri-tools-line', color: '#059669', bg: '#DCFCE7' },
    ],
  },
  {
    id: 'B-006', plate: 'MNO 2345', model: 'هيونداي H350 2022', capacity: 18,
    driver: 'غير مسند', driverId: '',
    route: 'غير مسندة',
    status: 'متوقف', statusColor: '#EF4444', statusBg: '#FEE2E2',
    km: '143,700', lastService: '10 فبراير 2026',
    year: '2022', color: 'أبيض', vin: 'KMHEC41BP3A678901', insurance: '5 سبتمبر 2026', license: '18 أكتوبر 2026',
    img: 'https://readdy.ai/api/search-image?query=modern%20white%20Hyundai%20H350%20minibus%20side%20view%20clean%20white%20background%20professional%20photo%20realistic%20high%20quality%20transportation%20vehicle%202022&width=200&height=120&seq=bus-list-06&orientation=landscape',
    docs: [
      { name: 'رخصة السير', status: 'ساري', exp: '18 أكتوبر 2026', icon: 'ri-file-text-line', color: '#059669', bg: '#DCFCE7' },
      { name: 'وثيقة التأمين', status: 'قريب الانتهاء', exp: '5 سبتمبر 2026', icon: 'ri-shield-check-line', color: '#D97706', bg: '#FEF3C7' },
      { name: 'فحص دوري', status: 'منتهي', exp: '20 فبراير 2026', icon: 'ri-tools-line', color: '#EF4444', bg: '#FEE2E2' },
    ],
  },
];

// ─── Types ────────────────────────────────────────────────────────────────────

interface ApiFeature {
  id: number;
  name: string;
  icon?: string;
}

interface FeaturesResponse {
  data: ApiFeature[];
}

interface ApiBus {
  id: number;
  display_code: string;
  image: string | null;
  plate_number: string;
  capacity: number;
  num_of_users: number;
  current_mileage_km: number;
  is_active: boolean;
  is_approved: boolean;
  status: string;
  type_id: string | null;
  brand_id: string | null;
  model: string | null;
  captain: { id: number; name: string; image?: string | null } | null;
  path: { id: number; name?: string; description?: string } | null;
}

interface BusesListPaginated {
  data: ApiBus[];
  pagination: {
    total_items: number;
    count_items: number;
    per_page: number;
    total_pages: number;
    current_page: number;
  };
}

/** Backend يقدّر يرجّع `data` كمصفوفة مباشرة، أو كائن فيه `data` + `pagination` */
interface BusesApiResponse {
  key: string;
  msg: string;
  data: ApiBus[] | BusesListPaginated;
}

interface ApiBusDetail {
  id: number;
  display_code: string;
  color: string;
  production_date: string;
  numbers: number;
  letters: string;
  plate_number: string;
  form_serial: string;
  vin: string;
  num_of_users: number;
  capacity: number;
  current_mileage_km: number;
  notes: string;
  is_active: boolean;
  is_approved: boolean;
  status: string;
  form_end_date: string;
  insurance_end_date: string;
  last_maintenance_date: string;
  periodic_inspection_end_date: string;
  captain: { id: number; name: string; image?: string | null } | null;
  type_id: string | null;
  brand_id: string | null;
  model: string | null;
  features: { id: number; name: string }[];
  path: { id: number; name: string } | null;
  front_side_image: string | null;
  back_side_image: string | null;
  right_side_image: string | null;
  left_side_image: string | null;
  front_seat_image: string | null;
  back_seat_image: string | null;
  license_image: string | null;
  check_image: string | null;
  insurance_image: string | null;
  form_image: string | null;
}

interface ApiBusDetailResponse {
  key: string;
  msg: string;
  data: ApiBusDetail;
}

interface CaptainsForAssignItem {
  id: number;
  name: string;
  image: string | null;
}

interface CaptainsForAssignApiResponse {
  key?: string;
  msg?: string;
  data?: CaptainsForAssignItem[] | { data?: CaptainsForAssignItem[] };
}

interface AssignCaptainApiResponse {
  key: string;
  msg?: string;
  message?: string;
}

interface DeleteBusApiResponse {
  key: string;
  msg?: string;
  message?: string;
}

interface UpdateBusApiResponse {
  key?: string;
  msg?: string;
  message?: string;
}

interface ApiPathOption {
  id: number;
  description?: string;
  display_code?: string;
}

interface PathsListResponse {
  key?: string;
  msg?: string;
  data?: {
    data?: ApiPathOption[];
  } | ApiPathOption[];
}

function parseCaptainsForAssignData(res: CaptainsForAssignApiResponse | null): CaptainsForAssignItem[] {
  if (!res?.data) return [];
  const raw = res.data;
  if (Array.isArray(raw)) {
    return raw.filter((x): x is CaptainsForAssignItem => typeof x?.id === 'number' && typeof x?.name === 'string');
  }
  const inner = (raw as { data?: CaptainsForAssignItem[] }).data;
  if (!Array.isArray(inner)) return [];
  return inner.filter((x): x is CaptainsForAssignItem => typeof x?.id === 'number' && typeof x?.name === 'string');
}

function toastMetaFromApiKey(key?: string): { severity: 'success' | 'info' | 'warn' | 'error'; summary: string } {
  const normalized = String(key ?? '').toLowerCase();
  if (normalized === 'success') return { severity: 'success', summary: 'تم' };
  if (normalized === 'warning' || normalized === 'warn') return { severity: 'warn', summary: 'تنبيه' };
  if (normalized === 'info') return { severity: 'info', summary: 'معلومة' };
  return { severity: 'error', summary: 'خطأ' };
}

// Fallback static icon map (used when API doesn't return icon)
const featureIconMap: Record<string, string> = {
  'واي فاي': 'ri-wifi-line',
  'wifi': 'ri-wifi-line',
  'تكييف': 'ri-temp-cold-line',
  'ac': 'ri-temp-cold-line',
  'شحن': 'ri-plug-line',
  'usb': 'ri-plug-line',
  'كاميرا': 'ri-camera-line',
  'camera': 'ri-camera-line',
  'gps': 'ri-map-pin-line',
  'تتبع': 'ri-map-pin-line',
  'إسعاف': 'ri-heart-pulse-line',
  'firstaid': 'ri-heart-pulse-line',
  'ذوي': 'ri-wheelchair-line',
  'wheelchair': 'ri-wheelchair-line',
  'ستائر': 'ri-layout-column-line',
  'شاشة': 'ri-tv-2-line',
  'tv': 'ri-tv-2-line',
  'أمتعة': 'ri-briefcase-line',
  'luggage': 'ri-briefcase-line',
};

function getFeatureIcon(name: string): string {
  const lower = name.toLowerCase();
  for (const [key, icon] of Object.entries(featureIconMap)) {
    if (lower.includes(key.toLowerCase())) return icon;
  }
  return 'ri-checkbox-circle-line';
}

// ─── Image upload slots ────────────────────────────────────────────────────────

const imageSlots = [
  { key: 'front_side_image', label: 'صورة الباص الأمامية' },
  { key: 'back_side_image', label: 'صورة الباص الخلفية' },
  { key: 'right_side_image', label: 'الجانب الأيمن' },
  { key: 'left_side_image', label: 'الجانب الأيسر' },
  { key: 'front_seat_image', label: 'المقاعد الأمامية' },
  { key: 'back_seat_image', label: 'المقاعد الخلفية' },
  { key: 'license_image', label: 'صورة رخصة السير' },
  { key: 'check_image', label: 'صورة الفحص الدوري' },
  { key: 'insurance_image', label: 'صورة التأمين' },
  { key: 'form_image', label: 'صورة النموذج' },
] as const;

type ImageKey = typeof imageSlots[number]['key'];

// ─── Empty form ────────────────────────────────────────────────────────────────

const emptyForm = {
  // Step 1 – Basic Info
  color: '',
  production_date: '',
  type: '',
  brand: '',
  model: '',
  vin: '',
  numbers: '',
  letters: '',
  form_serial: '',
  current_mileage_km: '',
  num_of_users: '',
  notes: '',
  // Step 2 – Docs / Dates
  form_end_date: '',
  insurance_end_date: '',
  last_maintenance_date: '',
  periodic_inspection_end_date: '',
  // Step 3 – Assignment
  driverId: '',
  status: 'active' as 'active' | 'maintenance' | 'stopped',
  path_id: '',
  is_active: '1' as '0' | '1',
  // Features (populated from API)
  features: [] as number[],
  // Route (display-only, not sent to API)
  routeFrom: '',
  routeStops: [] as string[],
  routeTo: '',
};

// ─── Location options ──────────────────────────────────────────────────────────

const locationOptions = [
  'حي النزهة', 'حي الروضة', 'حي السلام', 'حي الملك فهد', 'حي العزيزية',
  'حي المروج', 'حي الربوة', 'حي الورود', 'حي الصفا', 'حي الزهراء',
  'حي الريان', 'حي الفيصلية', 'حي الشفاء', 'حي الحمراء', 'حي الخالدية',
  'جامعة الملك سعود', 'جامعة الأميرة نورة', 'جامعة الملك عبدالعزيز',
  'جامعة الملك فهد للبترول', 'جامعة الإمام محمد بن سعود', 'كلية التقنية',
  'المستشفى الجامعي', 'المطار الدولي', 'المركز التجاري', 'محطة القطار',
  'الحديقة المركزية', 'الملعب الرياضي', 'المجمع الحكومي',
];

// ─── LocationDropdown ──────────────────────────────────────────────────────────

function LocationDropdown({
  value,
  onChange,
  placeholder,
}: {
  value: string;
  onChange: (val: string) => void;
  placeholder: string;
}) {
  const [open, setOpen] = useState(false);
  const [search, setSearch] = useState('');
  const ref = useRef<HTMLDivElement>(null);

  useEffect(() => {
    function handleClick(e: MouseEvent) {
      if (ref.current && !ref.current.contains(e.target as Node)) setOpen(false);
    }
    document.addEventListener('mousedown', handleClick);
    return () => document.removeEventListener('mousedown', handleClick);
  }, []);

  const filtered = locationOptions.filter(l => l.includes(search));

  return (
    <div ref={ref} className="relative flex-1">
      <button
        type="button"
        onClick={() => { setOpen(o => !o); setSearch(''); }}
        className="w-full h-10 bg-slate-50 border border-slate-200 rounded-xl px-4 text-sm outline-none text-right flex items-center justify-between cursor-pointer hover:border-blue-300 transition-colors"
        style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif', color: value ? '#334155' : '#94a3b8' }}
      >
        <span className="truncate">{value || placeholder}</span>
        <i className={`ri-arrow-down-s-line text-slate-400 text-base transition-transform flex-shrink-0 mr-1 ${open ? 'rotate-180' : ''}`}></i>
      </button>
      {open && (
        <div className="absolute top-full mt-1 right-0 left-0 bg-white rounded-xl shadow-xl z-50 overflow-hidden" style={{ border: '1px solid #E2E8F0', maxHeight: '220px' }}>
          <div className="p-2 border-b" style={{ borderColor: '#F1F5F9' }}>
            <input
              autoFocus
              type="text"
              placeholder="بحث..."
              value={search}
              onChange={e => setSearch(e.target.value)}
              className="w-full h-8 bg-slate-50 rounded-lg px-3 text-xs outline-none"
              style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}
            />
          </div>
          <div className="overflow-y-auto" style={{ maxHeight: '160px' }}>
            <button
              type="button"
              onClick={() => { onChange(''); setOpen(false); }}
              className="w-full text-right px-4 py-2 text-xs text-slate-400 hover:bg-slate-50 cursor-pointer"
              style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}
            >— بدون تحديد —</button>
            {filtered.map(loc => (
              <button
                key={loc}
                type="button"
                onClick={() => { onChange(loc); setOpen(false); }}
                className="w-full text-right px-4 py-2 text-sm hover:bg-blue-50 cursor-pointer transition-colors flex items-center justify-between"
                style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif', color: value === loc ? '#1E3A8A' : '#334155', background: value === loc ? '#EEF2FF' : 'transparent' }}
              >
                {loc}
                {value === loc && <i className="ri-check-line text-xs" style={{ color: '#1E3A8A' }}></i>}
              </button>
            ))}
            {filtered.length === 0 && (
              <p className="text-center text-xs text-slate-400 py-4" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>لا توجد نتائج</p>
            )}
          </div>
        </div>
      )}
    </div>
  );
}

type Bus = typeof initialBuses[0];

// ─── Status helpers ────────────────────────────────────────────────────────────

const statusMap: Record<string, { arabic: string; color: string; bg: string }> = {
  active:      { arabic: 'نشط',    color: '#059669', bg: '#DCFCE7' },
  maintenance: { arabic: 'صيانة', color: '#D97706', bg: '#FEF3C7' },
  stopped:     { arabic: 'متوقف', color: '#EF4444', bg: '#FEE2E2' },
};

const statusApiMap: Record<string, string | undefined> = {
  'الكل':   undefined,
  'نشط':    'active',
  'صيانة':  'maintenance',
  'متوقف':  'stopped',
};

function getDocStatus(expDate: string | null): { status: string; color: string; bg: string } {
  if (!expDate || expDate === '-') return { status: 'غير محدد', color: '#94a3b8', bg: '#F1F5F9' };
  const diffDays = Math.floor((new Date(expDate).getTime() - Date.now()) / 86400000);
  if (diffDays < 0)   return { status: 'منتهي',          color: '#EF4444', bg: '#FEE2E2' };
  if (diffDays <= 30) return { status: 'قريب الانتهاء', color: '#D97706', bg: '#FEF3C7' };
  return                     { status: 'ساري',           color: '#059669', bg: '#DCFCE7' };
}

function mapApiBus(b: ApiBus): Bus {
  const info = statusMap[b.status] ?? statusMap.active;
  const routeLabel =
    b.path != null
      ? (b.path.description ?? b.path.name ?? 'غير مسندة')
      : 'غير مسندة';
  return {
    id: b.display_code,
    plate: b.plate_number,
    model: b.model || '-',
    capacity: b.capacity,
    driver: b.captain?.name || 'غير مسند',
    driverId: b.captain ? String(b.captain.id) : '',
    route: routeLabel,
    status: info.arabic,
    statusColor: info.color,
    statusBg: info.bg,
    km: b.current_mileage_km.toLocaleString('en-US'),
    lastService: '-',
    year: '-',
    color: '-',
    vin: '-',
    insurance: '-',
    license: '-',
    img: b.image ||
      'https://readdy.ai/api/search-image?query=modern%20white%20minibus%20side%20view%20clean%20white%20background%20professional%20photo%20realistic%20high%20quality%20transportation%20vehicle&width=200&height=120&seq=bus-api&orientation=landscape',
    docs: [
      { name: 'رخصة السير',   status: 'ساري', exp: '-', icon: 'ri-file-text-line',   color: '#059669', bg: '#DCFCE7' },
      { name: 'وثيقة التأمين', status: 'ساري', exp: '-', icon: 'ri-shield-check-line', color: '#059669', bg: '#DCFCE7' },
      { name: 'فحص دوري',     status: 'ساري', exp: '-', icon: 'ri-tools-line',         color: '#059669', bg: '#DCFCE7' },
    ],
  };
}

// ─── Main Page ─────────────────────────────────────────────────────────────────

export default function BusesPage() {
  const [buses, setBuses] = useState<Bus[]>([]);
  const [totalBuses, setTotalBuses] = useState(0);
  const [search, setSearch] = useState('');
  const [statusFilter, setStatusFilter] = useState('الكل');
  const [showAdd, setShowAdd] = useState(false);
  const [viewMode, setViewMode] = useState<'grid' | 'table'>('grid');
  const [selected, setSelected] = useState<Bus | null>(null);
  const [activeTab, setActiveTab] = useState('details');
  const [form, setForm] = useState(emptyForm);
  const [addStep, setAddStep] = useState(1);
  const [showAssign, setShowAssign] = useState(false);
  const [assignBus, setAssignBus] = useState<Bus | null>(null);
  const [assignDriver, setAssignDriver] = useState('');
  const [showDelete, setShowDelete] = useState(false);
  const [deleteBus, setDeleteBus] = useState<Bus | null>(null);

  // ── Edit modal state ─────────────────────────────────────────────────────────
  const [showEdit, setShowEdit] = useState(false);
  const [editBus, setEditBus] = useState<Bus | null>(null);
  const [editLoading, setEditLoading] = useState(false);
  const [editPrefillLoading, setEditPrefillLoading] = useState(false);
  const [editForm, setEditForm] = useState({
    color: '',
    production_date: '',
    type_id: '',
    brand_id: '',
    model_id: '',
    features: [] as number[],
    form_end_date: '',
    insurance_end_date: '',
    last_maintenance_date: '',
    periodic_inspection_end_date: '',
    numbers: '',
    letters: '',
    form_serial: '',
    vin: '',
    num_of_users: '',
    current_mileage_km: '',
    notes: '',
    status: 'active' as 'active' | 'maintenance' | 'stopped',
  });

  // ── Image files state ────────────────────────────────────────────────────────
  const [imageFiles, setImageFiles] = useState<Partial<Record<ImageKey, File>>>({});
  const [imagePreviews, setImagePreviews] = useState<Partial<Record<ImageKey, string>>>({});

  // ── API hooks ────────────────────────────────────────────────────────────────
  const hasHydrated  = useAuthStore((s) => s._hasHydrated);
  const token        = useAuthStore(s => s.token);
  const country_code = useAuthStore(s => s.country_code);
  const device_id    = useAuthStore(s => s.device_id);

  const featuresApi           = useApi<FeaturesResponse>();
  const busesApi              = useApi<BusesApiResponse>();
  const busDetailApi          = useApi<ApiBusDetailResponse>();
  const captainsForAssignApi  = useApi<CaptainsForAssignApiResponse>();
  const assignCaptainApi      = useApi<AssignCaptainApiResponse>();
  const deleteBusApi          = useApi<DeleteBusApiResponse>();
  const pathsApi              = useApi<PathsListResponse>();
  const editDetailApi         = useApi<ApiBusDetailResponse>();
  const updateBusApi          = useApi<UpdateBusApiResponse>();

  const toastRef = useRef<ToastType>(null);
  const busIdMapRef = useRef<Map<string, number>>(new Map());
  const [selectedDetail, setSelectedDetail] = useState<ApiBusDetail | null>(null);
  /** `null`: لم يُكتمل الطلب بعد، `[]`: لا يوجد سواق أو فشل / غير مصرّح */
  const [captainsForAssign, setCaptainsForAssign] = useState<CaptainsForAssignItem[] | null>(null);

  // ── API-loaded features ──────────────────────────────────────────────────────
  const [apiFeatures, setApiFeatures] = useState<ApiFeature[]>([]);
  const [pathOptions, setPathOptions] = useState<ApiPathOption[]>([]);

  // ── Fetch features on mount (wait for store hydration) ──────────────────────
  useEffect(() => {
    if (!hasHydrated || !token) return;
    featuresApi.request('buses/features').then(res => {
      if (res?.data) setApiFeatures(res.data);
    });
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [hasHydrated, token]);

  // ── Paths list for bus assignment (path_id select) ──────────────────────────
  useEffect(() => {
    if (!hasHydrated || !token) return;
    pathsApi.request('paths?paginate=100').then(res => {
      const payload = res?.data;
      if (!payload) {
        setPathOptions([]);
        return;
      }
      if (Array.isArray(payload)) {
        setPathOptions(payload);
        return;
      }
      setPathOptions(payload.data ?? []);
    });
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [hasHydrated, token]);

  // ── قائمة السواق المتاحين للإسناد (عند دخول الصفحة)
  useEffect(() => {
    if (!hasHydrated) return;
    if (!token) {
      setCaptainsForAssign([]);
      return;
    }
    setCaptainsForAssign(null);
    captainsForAssignApi.request('buses/captains-for-assign').then(res => {
      setCaptainsForAssign(parseCaptainsForAssignData(res));
    });
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [hasHydrated, token]);

  // ── Fetch buses ──────────────────────────────────────────────────────────────
  const fetchBuses = useCallback(async (status: string) => {
    if (!hasHydrated || !token) return;
    const apiStatus = statusApiMap[status];
    const query = apiStatus
      ? `buses?paginate=15&status=${apiStatus}`
      : 'buses?paginate=15';
    const res = await busesApi.request(query);
    if (!res?.data) return;
    const payload = res.data;
    const list: ApiBus[] = Array.isArray(payload) ? payload : payload.data ?? [];
    const pagination = Array.isArray(payload) ? undefined : payload.pagination;
    list.forEach(b => busIdMapRef.current.set(b.display_code, b.id));
    setBuses(list.map(mapApiBus));
    setTotalBuses(pagination?.total_items ?? list.length);
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [hasHydrated, token]);

  useEffect(() => {
    fetchBuses(statusFilter);
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [hasHydrated, token, statusFilter]);

  // ─── Submit loading state ───────────────────────────────────────────────────
  const [submitLoading, setSubmitLoading] = useState(false);
  const [submitError, setSubmitError] = useState<string | null>(null);

  // ── Helper: image input handler ──────────────────────────────────────────────
  function handleImageChange(key: ImageKey, file: File | null) {
    if (!file) return;
    setImageFiles(prev => ({ ...prev, [key]: file }));
    const url = URL.createObjectURL(file);
    setImagePreviews(prev => ({ ...prev, [key]: url }));
  }

  // ── Route string builder ─────────────────────────────────────────────────────
  function buildRouteString() {
    const parts = [form.routeFrom, ...form.routeStops.filter(s => s.trim()), form.routeTo].filter(Boolean);
    return parts.join(' ← ') || 'غير مسندة';
  }

  function addStop() {
    setForm(prev => ({ ...prev, routeStops: [...prev.routeStops, ''] }));
  }

  function updateStop(index: number, value: string) {
    setForm(prev => {
      const stops = [...prev.routeStops];
      stops[index] = value;
      return { ...prev, routeStops: stops };
    });
  }

  function removeStop(index: number) {
    setForm(prev => ({
      ...prev,
      routeStops: prev.routeStops.filter((_, i) => i !== index),
    }));
  }

  // ── Filtered buses (status already handled by API, client filters by search) ─
  const filtered = buses.filter(b =>
    !search.trim() ||
    b.plate.includes(search) ||
    b.model.includes(search) ||
    b.driver.includes(search)
  );

  // ── Open bus detail modal ────────────────────────────────────────────────────
  function handleBusClick(b: Bus) {
    setSelected(b);
    setSelectedDetail(null);
    setActiveTab('details');
    const numericId = busIdMapRef.current.get(b.id);
    if (!numericId) return;
    busDetailApi.request(`buses/${numericId}`).then(res => {
      if (res?.data) setSelectedDetail(res.data);
    });
  }

  function closeDetailModal() {
    setSelected(null);
    setSelectedDetail(null);
  }

  // ── Assign driver ────────────────────────────────────────────────────────────
  async function handleAssign() {
    if (!assignBus || !assignDriver) return;
    const busNumericId = busIdMapRef.current.get(assignBus.id);
    if (!busNumericId) {
      toastRef.current?.show({
        severity: 'error',
        summary: 'خطأ',
        detail: 'تعذّر تحديد معرّف الباص.',
        life: 5000,
      });
      return;
    }

    const captainId = Number(assignDriver);
    if (!Number.isFinite(captainId)) {
      toastRef.current?.show({
        severity: 'error',
        summary: 'خطأ',
        detail: 'معرّف السائق غير صالح.',
        life: 4000,
      });
      return;
    }

    const res = await assignCaptainApi.request(`buses/${busNumericId}/assign-captain`, {
      method: 'POST',
      body: { captain_id: captainId },
    });

    if (res !== null) {
      const ok = String(res.key).toLowerCase() === 'success';
      const detail =
        (typeof res.msg === 'string' && res.msg.trim()) ||
        (typeof res.message === 'string' && res.message.trim()) ||
        (ok ? 'تم إسناد السائق بنجاح.' : 'تعذّر إسناد السائق.');
      toastRef.current?.show({
        severity: ok ? 'success' : 'error',
        summary: ok ? 'تم' : 'خطأ',
        detail,
        life: ok ? 3500 : 6000,
      });
      if (ok) {
        const drv = captainsForAssign?.find(c => String(c.id) === assignDriver);
        const name = drv?.name ?? '';
        setBuses(prev => prev.map(b =>
          b.id === assignBus.id
            ? { ...b, driver: name || b.driver, driverId: assignDriver }
            : b
        ));
        if (selected && selected.id === assignBus.id) {
          setSelected(prev => prev ? { ...prev, driver: name || prev.driver, driverId: assignDriver } : null);
          busDetailApi.request(`buses/${busNumericId}`).then(detailRes => {
            if (detailRes?.data) setSelectedDetail(detailRes.data);
          });
        }
        setShowAssign(false);
        setAssignBus(null);
        setAssignDriver('');
        await fetchBuses(statusFilter);
      }
      return;
    }

    const errMsg = assignCaptainApi.lastError.current || 'تعذّر الاتصال بالخادم.';
    toastRef.current?.show({
      severity: 'error',
      summary: 'حدث خطأ',
      detail: errMsg,
      life: 8000,
    });
  }

  // ── Delete bus ───────────────────────────────────────────────────────────────
  async function handleDeleteBus() {
    if (!deleteBus) return;
    const busNumericId = busIdMapRef.current.get(deleteBus.id);
    if (!busNumericId) {
      toastRef.current?.show({
        severity: 'error',
        summary: 'خطأ',
        detail: 'تعذّر تحديد معرّف الباص.',
        life: 5000,
      });
      return;
    }
    try {
      const res = await deleteBusApi.request(`buses/${busNumericId}`, {
        method: 'DELETE',
      });

      if (res !== null) {
        const toastMeta = toastMetaFromApiKey(res.key);
        const isSuccess = toastMeta.severity === 'success';
        const detail =
          (typeof res.msg === 'string' && res.msg.trim()) ||
          (typeof res.message === 'string' && res.message.trim()) ||
          (isSuccess ? 'تم حذف الباص بنجاح.' : 'تعذّر حذف الباص.');
        toastRef.current?.show({
          severity: toastMeta.severity,
          summary: toastMeta.summary,
          detail,
          life: isSuccess ? 3500 : 6000,
        });
        if (isSuccess) {
          if (selected && selected.id === deleteBus.id) {
            closeDetailModal();
          }
          setShowDelete(false);
          setDeleteBus(null);
        }
        return;
      }

      const errMsg = deleteBusApi.lastError.current || 'تعذّر الاتصال بالخادم.';
      toastRef.current?.show({
        severity: 'error',
        summary: 'حدث خطأ',
        detail: errMsg,
        life: 8000,
      });
    } finally {
      await fetchBuses(statusFilter);
    }
  }

  // ── Edit bus: open modal and prefill form from detail API ───────────────────
  function openEditModal(b: Bus) {
    setEditBus(b);
    setShowEdit(true);
    setEditForm({
      color: '',
      production_date: '',
      type_id: '',
      brand_id: '',
      model_id: '',
      features: [],
      form_end_date: '',
      insurance_end_date: '',
      last_maintenance_date: '',
      periodic_inspection_end_date: '',
      numbers: '',
      letters: '',
      form_serial: '',
      vin: '',
      num_of_users: '',
      current_mileage_km: '',
      notes: '',
      status: 'active',
    });
    const numericId = busIdMapRef.current.get(b.id);
    if (!numericId) return;
    setEditPrefillLoading(true);
    editDetailApi.request(`buses/${numericId}`).then(res => {
      if (res?.data) {
        const d = res.data;
        const normalizedStatus =
          d.status === 'active' || d.status === 'maintenance' || d.status === 'stopped'
            ? d.status
            : 'active';
        setEditForm({
          color: d.color ?? '',
          production_date: d.production_date ?? '',
          type_id: d.type_id != null ? String(d.type_id) : '',
          brand_id: d.brand_id != null ? String(d.brand_id) : '',
          model_id: d.model != null ? String(d.model) : '',
          features: Array.isArray(d.features) ? d.features.map(f => f.id) : [],
          form_end_date: d.form_end_date ?? '',
          insurance_end_date: d.insurance_end_date ?? '',
          last_maintenance_date: d.last_maintenance_date ?? '',
          periodic_inspection_end_date: d.periodic_inspection_end_date ?? '',
          numbers: d.numbers != null ? String(d.numbers) : '',
          letters: d.letters ?? '',
          form_serial: d.form_serial ?? '',
          vin: d.vin ?? '',
          num_of_users: d.num_of_users != null ? String(d.num_of_users) : '',
          current_mileage_km: d.current_mileage_km != null ? String(d.current_mileage_km) : '',
          notes: d.notes ?? '',
          status: normalizedStatus,
        });
      }
    }).finally(() => {
      setEditPrefillLoading(false);
    });
  }

  function closeEditModal() {
    setShowEdit(false);
    setEditBus(null);
  }

  async function handleUpdateBus() {
    if (!editBus) return;
    const busNumericId = busIdMapRef.current.get(editBus.id);
    if (!busNumericId) {
      toastRef.current?.show({
        severity: 'error',
        summary: 'خطأ',
        detail: 'تعذّر تحديد معرّف الباص.',
        life: 5000,
      });
      return;
    }

    setEditLoading(true);
    try {
      const fd = new FormData();
      fd.append('color', editForm.color);
      fd.append('production_date', editForm.production_date);
      fd.append('type_id', editForm.type_id);
      fd.append('brand_id', editForm.brand_id);
      fd.append('model_id', editForm.model_id);
      editForm.features.forEach(id => fd.append('features[]', String(id)));
      fd.append('form_end_date', editForm.form_end_date);
      fd.append('insurance_end_date', editForm.insurance_end_date);
      fd.append('last_maintenance_date', editForm.last_maintenance_date);
      fd.append('periodic_inspection_end_date', editForm.periodic_inspection_end_date);
      fd.append('numbers', editForm.numbers);
      fd.append('letters', editForm.letters);
      fd.append('form_serial', editForm.form_serial);
      fd.append('vin', editForm.vin);
      fd.append('num_of_users', editForm.num_of_users);
      fd.append('current_mileage_km', editForm.current_mileage_km);
      fd.append('notes', editForm.notes);
      fd.append('status', editForm.status);

      const res = await updateBusApi.request(`buses/${busNumericId}/update`, {
        method: 'POST',
        body: fd,
      });

      if (res !== null) {
        const toastMeta = toastMetaFromApiKey(res.key);
        const isSuccess = toastMeta.severity === 'success';
        const detail =
          (typeof res.msg === 'string' && res.msg.trim()) ||
          (typeof res.message === 'string' && res.message.trim()) ||
          (isSuccess ? 'تم تعديل الباص بنجاح.' : 'تعذّر تعديل الباص.');
        toastRef.current?.show({
          severity: toastMeta.severity,
          summary: toastMeta.summary,
          detail,
          life: isSuccess ? 3500 : 6000,
        });
        if (isSuccess) {
          closeEditModal();
          await fetchBuses(statusFilter);
          if (selected && selected.id === editBus.id) {
            busDetailApi.request(`buses/${busNumericId}`).then(detailRes => {
              if (detailRes?.data) setSelectedDetail(detailRes.data);
            });
          }
        }
        return;
      }

      const errMsg = updateBusApi.lastError.current || 'تعذّر الاتصال بالخادم.';
      toastRef.current?.show({
        severity: 'error',
        summary: 'حدث خطأ',
        detail: errMsg,
        life: 8000,
      });
    } finally {
      setEditLoading(false);
    }
  }

  // ── Add bus via API ──────────────────────────────────────────────────────────
  async function handleAddBus() {
    setSubmitLoading(true);
    setSubmitError(null);

    try {
      const fd = new FormData();

      // Text fields
      fd.append('color', form.color);
      fd.append('production_date', form.production_date);
      fd.append('type', form.type);
      if (form.brand) fd.append('brand', form.brand);
      if (form.model) fd.append('model', form.model);
      fd.append('vin', form.vin);
      fd.append('numbers', form.numbers);
      fd.append('letters', form.letters);
      fd.append('form_serial', form.form_serial);
      if (form.current_mileage_km) fd.append('current_mileage_km', form.current_mileage_km);
      if (form.num_of_users) fd.append('num_of_users', form.num_of_users);
      fd.append('notes', form.notes);
      fd.append('status', form.status);
      fd.append('is_active', form.is_active);
      if (form.path_id) fd.append('path_id', form.path_id);
      const selectedCaptainId = form.driverId.trim();
      if (selectedCaptainId !== '') {
        const normalizedCaptainId = Number(selectedCaptainId);
        fd.append(
          'captain_id',
          Number.isFinite(normalizedCaptainId) ? String(normalizedCaptainId) : selectedCaptainId,
        );
      }

      // Date fields
      fd.append('form_end_date', form.form_end_date);
      fd.append('insurance_end_date', form.insurance_end_date);
      fd.append('last_maintenance_date', form.last_maintenance_date);
      fd.append('periodic_inspection_end_date', form.periodic_inspection_end_date);

      // Features array
      form.features.forEach(id => fd.append('features[]', String(id)));

      // Image files
      imageSlots.forEach(({ key }) => {
        const file = imageFiles[key];
        if (file) fd.append(key, file);
      });

      // بنبعت الـ FormData مباشرة عبر fetch عشان الـ hook مش بيدعم FormData صح
      const headers: Record<string, string> = {
        'Accept': 'application/json',
        'x-api-key': '5f43766dcd92b8c3e7639d2a8791063c',
        ...(token ? { 'Authorization': `Bearer ${token}` } : {}),
        ...(country_code ? { 'X-Country-Code': country_code } : {}),
        ...(device_id ? { 'X-Device-Id': device_id } : {}),
      };

      // country_code و device_id في الـ FormData كمان
      if (country_code && !fd.has('country_code')) fd.append('country_code', country_code);
      if (device_id && !fd.has('device_id')) fd.append('device_id', device_id);

      const response = await fetch('https://sast.4hoste.com/api/v1/company/buses', {
        method: 'POST',
        headers,
        body: fd,
      });

      const json = await response.json().catch(() => null);
      const result = response.ok ? json : null;
      if (!response.ok) {
        const errMsg = json?.msg || json?.message || json?.error || `HTTP ${response.status}`;
        setSubmitError(errMsg);
        toastRef.current?.show({
          severity: 'error',
          summary: 'تعذّر إضافة الباص',
          detail: errMsg,
          life: 8000,
        });
        return;
      }

      if (result !== null) {
        const toastMeta = toastMetaFromApiKey(result?.key);
        const detail =
          (typeof result?.msg === 'string' && result.msg.trim()) ||
          (typeof result?.message === 'string' && result.message.trim()) ||
          (toastMeta.severity === 'success' ? 'تمت إضافة الباص بنجاح.' : 'تعذّر إضافة الباص.');

        if (toastMeta.severity !== 'success') {
          setSubmitError(detail);
          toastRef.current?.show({
            severity: toastMeta.severity,
            summary: toastMeta.summary,
            detail,
            life: 8000,
          });
          return;
        }

        setShowAdd(false);
        setForm(emptyForm);
        setImageFiles({});
        setImagePreviews({});
        setAddStep(1);
        toastRef.current?.show({
          severity: 'success',
          summary: 'تم',
          detail,
          life: 3500,
        });
        fetchBuses(statusFilter);
      } else {
        const fallbackMsg = 'حدث خطأ أثناء الإضافة';
        setSubmitError(fallbackMsg);
        toastRef.current?.show({
          severity: 'error',
          summary: 'تعذّر إضافة الباص',
          detail: fallbackMsg,
          life: 8000,
        });
      }
    } catch (err) {
      const msg = err instanceof Error ? err.message : 'حدث خطأ أثناء الإضافة';
      setSubmitError(msg);
      toastRef.current?.show({
        severity: 'error',
        summary: 'تعذّر إضافة الباص',
        detail: msg,
        life: 8000,
      });
    } finally {
      setSubmitLoading(false);
    }
  }

  // ─── Reset modal state on close ────────────────────────────────────────────
  function closeAddModal() {
    setShowAdd(false);
    setForm(emptyForm);
    setImageFiles({});
    setImagePreviews({});
    setAddStep(1);
    setSubmitError(null);
  }

  return (
    <DashboardShell title="إدارة الباصات" subtitle={totalBuses > 0 ? `${totalBuses} باص مسجل` : busesApi.loading ? 'جاري التحميل...' : 'لا توجد باصات'}>
      <AppToast ref={toastRef} position="top-right" />

      {/* 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: '280px', 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>
          {['الكل', 'نشط', 'صيانة', 'متوقف'].map(s => (
            <button
              key={s}
              onClick={() => setStatusFilter(s)}
              className="px-4 py-2 rounded-xl text-sm font-bold cursor-pointer transition-all whitespace-nowrap"
              style={{
                background: statusFilter === s ? '#1E3A8A' : 'white',
                color: statusFilter === s ? 'white' : '#64748b',
                border: `1px solid ${statusFilter === s ? '#1E3A8A' : '#E2E8F0'}`,
                fontFamily: '"IBM Plex Sans Arabic", sans-serif',
              }}
            >{s}</button>
          ))}
        </div>
        <div className="flex items-center gap-2">
          <button onClick={() => setViewMode(viewMode === 'grid' ? 'table' : 'grid')} className="w-10 h-10 bg-white border border-slate-200 rounded-xl flex items-center justify-center cursor-pointer">
            <i className={`${viewMode === 'grid' ? 'ri-list-check' : 'ri-grid-fill'} text-slate-500 text-lg`}></i>
          </button>
          <button
            onClick={() => { setShowAdd(true); setAddStep(1); setForm(emptyForm); }}
            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-add-line text-base"></i>
            إضافة باص
          </button>
        </div>
      </div>

      {/* Loading State */}
      {busesApi.loading && (
        <div className="space-y-4 py-2">
          <div className="grid grid-cols-3 gap-5">
            {Array.from({ length: 6 }).map((_, idx) => (
              <div key={idx} className="bg-white rounded-2xl overflow-hidden p-4" style={{ border: '1px solid #F1F5F9' }}>
                <Skeleton height="9rem" borderRadius="0.75rem" />
                <div className="mt-3 space-y-2">
                  <Skeleton width="70%" height="1rem" />
                  <Skeleton width="45%" height="0.75rem" />
                  <Skeleton width="80%" height="0.75rem" />
                  <Skeleton width="65%" height="0.75rem" />
                </div>
              </div>
            ))}
          </div>
          <div className="flex items-center justify-center pt-2">
            <span className="text-xs text-slate-400" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>جاري تحميل الباصات...</span>
          </div>
        </div>
      )}

      {/* Error State */}
      {!busesApi.loading && busesApi.error && (
        <div className="flex flex-col items-center justify-center py-20 gap-3">
          <div className="w-14 h-14 rounded-2xl flex items-center justify-center" style={{ background: '#FEE2E2' }}>
            <i className="ri-error-warning-line text-2xl" style={{ color: '#EF4444' }}></i>
          </div>
          <p className="text-sm font-bold text-slate-500" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>فشل تحميل البيانات</p>
          <p className="text-xs text-slate-400" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{busesApi.error}</p>
          <button
            onClick={() => fetchBuses(statusFilter)}
            className="mt-2 px-5 py-2 rounded-xl text-sm font-bold text-white cursor-pointer"
            style={{ background: '#1E3A8A', fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}
          >إعادة المحاولة</button>
        </div>
      )}

      {/* Empty State */}
      {!busesApi.loading && !busesApi.error && filtered.length === 0 && (
        <div className="flex flex-col items-center justify-center py-20 gap-3">
          <div className="w-14 h-14 rounded-2xl flex items-center justify-center" style={{ background: '#F1F5F9' }}>
            <i className="ri-bus-2-line text-2xl text-slate-400"></i>
          </div>
          <p className="text-sm font-bold text-slate-500" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>لا توجد باصات</p>
        </div>
      )}

      {/* Grid / Table View */}
      {!busesApi.loading && !busesApi.error && filtered.length > 0 && viewMode === 'grid' ? (
        <div className="grid grid-cols-3 gap-5">
          {filtered.map((b, i) => (
            <div key={i} className="bg-white rounded-2xl overflow-hidden cursor-pointer hover:shadow-md transition-all" style={{ border: '1px solid #F1F5F9', boxShadow: '0 1px 4px rgba(0,0,0,0.04)' }} onClick={() => handleBusClick(b)}>
              <div className="relative h-36 overflow-hidden" style={{ background: '#F8FAFC' }}>
                <img src={b.img} alt={b.model} className="w-full h-full object-cover object-center" />
                <span className="absolute top-3 right-3 px-2.5 py-1 rounded-full text-xs font-bold" style={{ background: b.statusBg, color: b.statusColor, fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{b.status}</span>
                <span className="absolute top-3 left-3 px-2.5 py-1 rounded-full text-xs font-bold bg-white/90 text-slate-700" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{b.id}</span>
              </div>
              <div className="p-4">
                <h3 className="font-black text-slate-900 text-sm mb-0.5" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{b.model}</h3>
                <p className="text-xs text-slate-400 mb-3" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{b.plate}</p>
                <div className="space-y-1.5">
                  <div className="flex items-center gap-2">
                    <i className="ri-steering-2-line text-xs" style={{ color: '#94a3b8' }}></i>
                    <span className="text-xs text-slate-600" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{b.driver}</span>
                  </div>
                  <div className="flex items-center gap-2">
                    <i className="ri-group-line text-xs" style={{ color: '#94a3b8' }}></i>
                    <span className="text-xs text-slate-600" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{b.capacity} مقعد</span>
                  </div>
                  <div className="flex items-center gap-2">
                    <i className="ri-map-pin-2-line text-xs" style={{ color: '#94a3b8' }}></i>
                    <span className="text-xs text-slate-500 truncate" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{b.route}</span>
                  </div>
                </div>
                <div className="flex items-center justify-between mt-3 pt-3 border-t" style={{ borderColor: '#F1F5F9' }}>
                  <span className="text-xs text-slate-400" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{b.km} كم</span>
                  <div className="flex items-center gap-1" onClick={e => e.stopPropagation()}>
                    {(() => {
                      const hasAssignedDriver = String(b.driverId ?? '').trim() !== '';
                      return (
                    <button
                      onClick={() => {
                        if (hasAssignedDriver) return;
                        setAssignBus(b);
                        setAssignDriver(b.driverId);
                        setShowAssign(true);
                      }}
                      disabled={hasAssignedDriver}
                      className="flex items-center gap-1 px-2 py-1 rounded-lg text-xs font-bold cursor-pointer hover:bg-blue-50 transition-colors whitespace-nowrap disabled:opacity-60 disabled:cursor-not-allowed disabled:hover:bg-transparent"
                      style={{ color: '#1E3A8A', fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}
                    >
                      <i className="ri-user-shared-line text-xs"></i>
                      إسناد
                    </button>
                      );
                    })()}
                    <button
                      onClick={() => openEditModal(b)}
                      className="w-7 h-7 rounded-lg flex items-center justify-center cursor-pointer hover:bg-blue-50 transition-colors"
                      title="تعديل"
                    >
                      <i className="ri-pencil-line text-sm" style={{ color: '#1E3A8A' }}></i>
                    </button>
                    <button
                      onClick={() => { setDeleteBus(b); setShowDelete(true); }}
                      className="w-7 h-7 rounded-lg flex items-center justify-center cursor-pointer hover:bg-red-50 transition-colors"
                      title="حذف"
                    >
                      <i className="ri-delete-bin-line text-red-400 text-sm"></i>
                    </button>
                  </div>
                </div>
              </div>
            </div>
          ))}
        </div>
      ) : !busesApi.loading && !busesApi.error && filtered.length > 0 ? (
        <div className="bg-white rounded-2xl overflow-hidden" style={{ border: '1px solid #F1F5F9' }}>
          <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>
              {filtered.map((b, i) => (
                <tr key={i} className="border-t hover:bg-slate-50 transition-colors cursor-pointer" style={{ borderColor: '#F8FAFC' }} onClick={() => handleBusClick(b)}>
                  <td className="px-5 py-3.5"><span className="text-xs font-bold" style={{ color: '#1E3A8A', fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{b.id}</span></td>
                  <td className="px-5 py-3.5"><span className="text-xs text-slate-700 whitespace-nowrap" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{b.model}</span></td>
                  <td className="px-5 py-3.5"><span className="text-xs font-mono text-slate-600">{b.plate}</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' }}>{b.driver}</span></td>
                  <td className="px-5 py-3.5"><span className="text-xs text-slate-600" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{b.capacity}</span></td>
                  <td className="px-5 py-3.5"><span className="text-xs text-slate-600" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{b.km}</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' }}>{b.lastService}</span></td>
                  <td className="px-5 py-3.5"><span className="px-2.5 py-1 rounded-full text-xs font-bold whitespace-nowrap" style={{ background: b.statusBg, color: b.statusColor, fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{b.status}</span></td>
                  <td className="px-5 py-3.5" onClick={e => e.stopPropagation()}>
                    <div className="flex items-center gap-1">
                      {(() => {
                        const hasAssignedDriver = String(b.driverId ?? '').trim() !== '';
                        return (
                      <button
                        onClick={() => {
                          if (hasAssignedDriver) return;
                          setAssignBus(b);
                          setAssignDriver(b.driverId);
                          setShowAssign(true);
                        }}
                        disabled={hasAssignedDriver}
                        className="flex items-center gap-1 px-2 py-1 rounded-lg text-xs font-bold cursor-pointer hover:bg-blue-50 whitespace-nowrap disabled:opacity-60 disabled:cursor-not-allowed disabled:hover:bg-transparent"
                        style={{ color: '#1E3A8A', fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}
                      >
                        <i className="ri-user-shared-line text-xs"></i>
                        إسناد
                      </button>
                        );
                      })()}
                      <button
                        onClick={() => openEditModal(b)}
                        className="w-7 h-7 rounded-lg flex items-center justify-center cursor-pointer hover:bg-blue-50"
                        title="تعديل"
                      >
                        <i className="ri-pencil-line text-sm" style={{ color: '#1E3A8A' }}></i>
                      </button>
                      <button
                        onClick={() => { setDeleteBus(b); setShowDelete(true); }}
                        className="w-7 h-7 rounded-lg flex items-center justify-center cursor-pointer hover:bg-red-50"
                        title="حذف"
                      >
                        <i className="ri-delete-bin-line text-red-400 text-sm"></i>
                      </button>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      ) : null}

      {/* Bus Detail Modal */}
      {selected && (
        <div className="fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-6" onClick={closeDetailModal}>
          <div className="bg-white rounded-3xl w-full max-w-2xl shadow-2xl overflow-hidden" onClick={e => e.stopPropagation()} style={{ maxHeight: '90vh', overflowY: 'auto' }}>
            {/* Header Image */}
            <div className="relative h-44 overflow-hidden" style={{ background: '#F8FAFC' }}>
              <img
                src={selectedDetail?.front_side_image || selected.img}
                alt={selectedDetail?.model || selected.model}
                className="w-full h-full object-cover object-center"
              />
              <div className="absolute inset-0" style={{ background: 'linear-gradient(to top, rgba(0,0,0,0.5), transparent)' }}></div>
              <button onClick={closeDetailModal} className="absolute top-4 left-4 w-9 h-9 bg-white/90 rounded-xl flex items-center justify-center cursor-pointer">
                <i className="ri-close-line text-slate-700 text-lg"></i>
              </button>
              <div className="absolute bottom-4 right-4">
                <h2 className="text-xl font-black text-white" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>
                  {selectedDetail?.model || selected.model}
                </h2>
                <p className="text-sm text-white/80" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>
                  {selectedDetail?.plate_number || selected.plate} · {selected.id}
                </p>
              </div>
              <span className="absolute top-4 right-4 px-3 py-1 rounded-full text-xs font-bold" style={{ background: selected.statusBg, color: selected.statusColor, fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{selected.status}</span>
              {/* Loading indicator */}
              {busDetailApi.loading && (
                <div className="absolute bottom-4 left-4 flex items-center gap-1.5">
                  <div className="w-3.5 h-3.5 border-2 border-white/40 border-t-white rounded-full animate-spin"></div>
                  <span className="text-[11px] text-white/80" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>جاري التحميل...</span>
                </div>
              )}
            </div>

            {/* Tabs */}
            <div className="flex border-b" style={{ borderColor: '#F1F5F9' }}>
              {[
                { key: 'details', label: 'البيانات الأساسية', icon: 'ri-information-line' },
                { key: 'docs', label: 'المستندات', icon: 'ri-file-list-3-line' },
                { key: 'driver', label: 'السائق المسند', icon: 'ri-steering-2-line' },
              ].map(t => (
                <button
                  key={t.key}
                  onClick={() => setActiveTab(t.key)}
                  className="flex items-center gap-2 px-5 py-3.5 text-sm font-bold cursor-pointer transition-all whitespace-nowrap"
                  style={{
                    fontFamily: '"IBM Plex Sans Arabic", sans-serif',
                    color: activeTab === t.key ? '#1E3A8A' : '#94a3b8',
                    borderBottom: activeTab === t.key ? '2px solid #1E3A8A' : '2px solid transparent',
                  }}
                >
                  <i className={`${t.icon} text-sm`}></i>
                  {t.label}
                </button>
              ))}
            </div>

            <div className="p-6">
              {/* Details Tab */}
              {activeTab === 'details' && (
                <div className="space-y-4">
                  <div className="grid grid-cols-2 gap-4">
                    {[
                      { icon: 'ri-car-line',      label: 'الموديل',              val: selectedDetail?.model || selected.model },
                      { icon: 'ri-hashtag',        label: 'رقم اللوحة',           val: selectedDetail?.plate_number || selected.plate },
                      { icon: 'ri-calendar-line',  label: 'سنة الصنع',            val: selectedDetail?.production_date || selected.year },
                      { icon: 'ri-palette-line',   label: 'اللون',                val: selectedDetail?.color || selected.color },
                      { icon: 'ri-group-line',     label: 'السعة',                val: `${selectedDetail?.capacity ?? selected.capacity} مقعد` },
                      { icon: 'ri-barcode-line',   label: 'رقم الهيكل (VIN)',     val: selectedDetail?.vin || selected.vin },
                      { icon: 'ri-speed-line',     label: 'عداد الكيلومترات',     val: `${selectedDetail?.current_mileage_km?.toLocaleString('en-US') ?? selected.km} كم` },
                      { icon: 'ri-tools-line',     label: 'آخر صيانة',            val: selectedDetail?.last_maintenance_date || selected.lastService },
                      { icon: 'ri-route-line',     label: 'المسار',               val: selectedDetail?.path?.name || selected.route },
                      ...(selectedDetail?.form_serial ? [{ icon: 'ri-file-list-line', label: 'رقم النموذج', val: selectedDetail.form_serial }] : []),
                      ...(selectedDetail?.notes ? [{ icon: 'ri-sticky-note-line', label: 'ملاحظات', val: selectedDetail.notes }] : []),
                    ].map((row, i) => (
                      <div key={i} className="flex items-start gap-3 p-3 rounded-xl" style={{ background: '#F8FAFC' }}>
                        <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>

                  {/* Amenities from detail API */}
                  {selectedDetail && selectedDetail.features.length > 0 && (
                    <div className="p-4 rounded-xl" style={{ background: '#F8FAFC', border: '1px solid #F1F5F9' }}>
                      <p className="text-xs font-bold text-slate-500 mb-3" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>مميزات الباص</p>
                      <div className="flex flex-wrap gap-2">
                        {selectedDetail.features.map(f => (
                          <span key={f.id} className="flex items-center gap-1.5 px-3 py-1.5 rounded-full text-xs font-bold" style={{ background: '#EEF2FF', color: '#1E3A8A', fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>
                            <i className={`${getFeatureIcon(f.name)} text-xs`}></i>
                            {f.name}
                          </span>
                        ))}
                      </div>
                    </div>
                  )}
                </div>
              )}

              {/* Docs Tab */}
              {activeTab === 'docs' && (() => {
                const docs = selectedDetail ? [
                  { name: 'رخصة السير',    icon: 'ri-file-text-line',    exp: selectedDetail.form_end_date,                   imgUrl: selectedDetail.license_image,    ...getDocStatus(selectedDetail.form_end_date) },
                  { name: 'وثيقة التأمين', icon: 'ri-shield-check-line', exp: selectedDetail.insurance_end_date,              imgUrl: selectedDetail.insurance_image,  ...getDocStatus(selectedDetail.insurance_end_date) },
                  { name: 'فحص دوري',      icon: 'ri-tools-line',         exp: selectedDetail.periodic_inspection_end_date,   imgUrl: selectedDetail.check_image,      ...getDocStatus(selectedDetail.periodic_inspection_end_date) },
                ] : selected.docs.map(d => ({ ...d, imgUrl: null as string | null }));
                return (
                  <div className="space-y-3">
                    {docs.map((doc, i) => (
                      <div key={i} className="flex items-center justify-between p-4 rounded-2xl" style={{ background: '#F8FAFC', border: '1px solid #F1F5F9' }}>
                        <div className="flex items-center gap-3">
                          <div className="w-10 h-10 rounded-xl flex items-center justify-center" style={{ background: doc.bg }}>
                            <i className={`${doc.icon} text-base`} style={{ color: doc.color }}></i>
                          </div>
                          <div>
                            <p className="text-sm font-bold text-slate-800" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{doc.name}</p>
                            <p className="text-xs text-slate-400" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>تنتهي: {doc.exp || '-'}</p>
                          </div>
                        </div>
                        <div className="flex items-center gap-2">
                          <span className="px-3 py-1 rounded-full text-xs font-bold" style={{ background: doc.bg, color: doc.color, fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{doc.status}</span>
                          {doc.imgUrl && (
                            <a href={doc.imgUrl} target="_blank" rel="noopener noreferrer" className="w-8 h-8 rounded-xl flex items-center justify-center cursor-pointer hover:bg-slate-200 transition-colors" style={{ background: '#E2E8F0' }}>
                              <i className="ri-eye-line text-slate-600 text-sm"></i>
                            </a>
                          )}
                        </div>
                      </div>
                    ))}
                    <button className="w-full h-11 rounded-xl border-2 border-dashed text-sm font-bold cursor-pointer flex items-center justify-center gap-2 mt-2 hover:bg-slate-50 transition-colors" style={{ borderColor: '#CBD5E1', color: '#64748b', fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>
                      <i className="ri-upload-cloud-line text-base"></i>
                      رفع مستند جديد
                    </button>
                  </div>
                );
              })()}

              {/* Driver Tab */}
              {activeTab === 'driver' && (() => {
                const captain = selectedDetail?.captain ?? (selected.driverId ? { id: Number(selected.driverId), name: selected.driver } : null);
                const captainImage = captain?.image?.trim() || DEFAULT_CAPTAIN_AVATAR;
                return (
                  <div>
                    {captain ? (
                      <div className="p-5 rounded-2xl mb-4" style={{ background: '#F8FAFC', border: '1px solid #F1F5F9' }}>
                        <div className="flex items-center gap-4">
                          <div className="w-14 h-14 rounded-2xl overflow-hidden flex-shrink-0">
                            <img
                              src={captainImage}
                              alt={captain.name}
                              className="w-full h-full object-cover object-top"
                              onError={e => {
                                (e.target as HTMLImageElement).src = DEFAULT_CAPTAIN_AVATAR;
                              }}
                            />
                          </div>
                          <div>
                            <p className="text-sm font-bold text-slate-800" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{captain.name}</p>
                            <p className="text-xs text-slate-400" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>#{captain.id}</p>
                            <span className="inline-block mt-1 px-2.5 py-0.5 rounded-full text-xs font-bold" style={{ background: '#DCFCE7', color: '#059669', fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>نشط</span>
                          </div>
                        </div>
                      </div>
                    ) : (
                      <div className="flex flex-col items-center justify-center py-8 text-center">
                        <div className="w-16 h-16 rounded-2xl flex items-center justify-center mb-3" style={{ background: '#F1F5F9' }}>
                          <i className="ri-user-unfollow-line text-2xl text-slate-400"></i>
                        </div>
                        <p className="text-sm font-bold text-slate-500 mb-1" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>لا يوجد سائق مسند</p>
                        <p className="text-xs text-slate-400" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>يمكنك إسناد سائق لهذا الباص</p>
                      </div>
                    )}
                    <button
                      onClick={() => {
                        if (captain) return;
                        setAssignBus(selected);
                        setAssignDriver(selected.driverId);
                        setShowAssign(true);
                      }}
                      disabled={Boolean(captain)}
                      className="w-full h-11 rounded-xl font-bold text-sm text-white cursor-pointer flex items-center justify-center gap-2 whitespace-nowrap disabled:opacity-60 disabled:cursor-not-allowed"
                      style={{ background: '#1E3A8A', fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}
                    >
                      <i className="ri-user-shared-line text-base"></i>
                      {captain ? 'تم إسناد سائق' : 'إسناد سائق'}
                    </button>
                  </div>
                );
              })()}
            </div>
          </div>
        </div>
      )}

      {/* Assign Driver Modal */}
      {showAssign && assignBus && (
        <div className="fixed inset-0 bg-black/60 z-[60] flex items-center justify-center p-6" onClick={() => setShowAssign(false)}>
          <div className="bg-white rounded-3xl p-7 w-full max-w-md shadow-2xl" onClick={e => e.stopPropagation()}>
            <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={() => setShowAssign(false)} 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>
            <div className="p-3 rounded-xl mb-5 flex items-center gap-3" style={{ background: '#EEF2FF' }}>
              <i className="ri-bus-2-line text-lg" style={{ color: '#1E3A8A' }}></i>
              <div>
                <p className="text-sm font-bold text-slate-800" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{assignBus.model}</p>
                <p className="text-xs text-slate-500" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{assignBus.plate}</p>
              </div>
            </div>
            <p className="text-sm font-bold text-slate-600 mb-3" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>اختر السائق</p>
            <div className="space-y-2 max-h-64 overflow-y-auto">
              {captainsForAssign === null || captainsForAssignApi.loading ? (
                <div className="flex items-center justify-center gap-2 py-10 text-slate-400">
                  <div className="w-5 h-5 border-2 border-blue-100 border-t-blue-600 rounded-full animate-spin" />
                  <span className="text-sm" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>جاري تحميل السائقين...</span>
                </div>
              ) : captainsForAssign.length === 0 ? (
                <p className="text-center text-sm text-slate-400 py-8" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>
                  لا يوجد سائقون متاحون للإسناد
                </p>
              ) : (
                captainsForAssign.map(d => {
                  const sid = String(d.id);
                  return (
                    <button
                      key={sid}
                      type="button"
                      onClick={() => setAssignDriver(sid)}
                      className="w-full flex items-center gap-3 p-3 rounded-xl cursor-pointer transition-all text-right"
                      style={{
                        background: assignDriver === sid ? '#EEF2FF' : '#F8FAFC',
                        border: `1.5px solid ${assignDriver === sid ? '#1E3A8A' : '#F1F5F9'}`,
                      }}
                    >
                      <div className="w-9 h-9 rounded-xl overflow-hidden flex-shrink-0 bg-slate-100">
                        <img
                          src={d.image?.trim() || DEFAULT_CAPTAIN_AVATAR}
                          alt={d.name}
                          className="w-full h-full object-cover object-top"
                          onError={e => {
                            (e.target as HTMLImageElement).src = DEFAULT_CAPTAIN_AVATAR;
                          }}
                        />
                      </div>
                      <div className="flex-1 min-w-0">
                        <p className="text-sm font-bold text-slate-800 truncate" 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' }}>#{sid}</p>
                      </div>
                      {assignDriver === sid && (
                        <div className="w-5 h-5 rounded-full flex items-center justify-center flex-shrink-0" style={{ background: '#1E3A8A' }}>
                          <i className="ri-check-line text-white text-xs"></i>
                        </div>
                      )}
                    </button>
                  );
                })
              )}
            </div>
            <div className="flex gap-3 mt-5">
              <button onClick={() => setShowAssign(false)} className="flex-1 h-11 bg-slate-100 rounded-xl font-bold text-sm text-slate-600 cursor-pointer whitespace-nowrap" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>إلغاء</button>
              <button
                onClick={() => void handleAssign()}
                disabled={
                  !assignDriver ||
                  assignCaptainApi.loading ||
                  captainsForAssign === null ||
                  captainsForAssign.length === 0
                }
                className="flex-1 h-11 rounded-xl font-bold text-sm text-white cursor-pointer whitespace-nowrap disabled:opacity-50"
                style={{ background: '#1E3A8A', fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}
              >
                {assignCaptainApi.loading ? 'جاري الإسناد...' : 'تأكيد الإسناد'}
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Delete Bus Modal */}
      {showDelete && deleteBus && (
        <div className="fixed inset-0 bg-black/60 z-[60] flex items-center justify-center p-6" onClick={() => setShowDelete(false)}>
          <div className="bg-white rounded-3xl p-7 w-full max-w-md shadow-2xl" onClick={e => e.stopPropagation()}>
            <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={() => setShowDelete(false)} 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>
            <div className="p-3 rounded-xl mb-5 flex items-center gap-3" style={{ background: '#FEF2F2' }}>
              <i className="ri-error-warning-line text-lg" style={{ color: '#DC2626' }}></i>
              <div>
                <p className="text-sm font-bold text-slate-800" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{deleteBus.model}</p>
                <p className="text-xs text-slate-500" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{deleteBus.plate}</p>
              </div>
            </div>
            <p className="text-sm text-slate-600 mb-5" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>
              هل أنت متأكد من حذف هذا الباص؟ لا يمكن التراجع عن هذا الإجراء.
            </p>
            <div className="flex gap-3">
              <button
                onClick={() => setShowDelete(false)}
                disabled={deleteBusApi.loading}
                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
                onClick={() => void handleDeleteBus()}
                disabled={deleteBusApi.loading}
                className="flex-1 h-11 rounded-xl font-bold text-sm text-white cursor-pointer whitespace-nowrap disabled:opacity-70 flex items-center justify-center gap-2"
                style={{ background: '#DC2626', fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}
              >
                {deleteBusApi.loading ? (
                  <>
                    <div className="w-4 h-4 border-2 border-white/30 border-t-white rounded-full animate-spin"></div>
                    جاري الحذف...
                  </>
                ) : (
                  <>
                    <i className="ri-delete-bin-line"></i>
                    تأكيد الحذف
                  </>
                )}
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Edit Bus Modal */}
      {showEdit && editBus && (
        <div className="fixed inset-0 bg-black/50 z-[60] flex items-center justify-center p-6" onClick={closeEditModal}>
          <div className="bg-white rounded-3xl w-full max-w-2xl shadow-2xl overflow-hidden" onClick={e => e.stopPropagation()} style={{ maxHeight: '90vh', overflowY: 'auto' }}>
            {/* Header */}
            <div className="flex items-center justify-between px-7 pt-6 pb-4 border-b" style={{ borderColor: '#F1F5F9' }}>
              <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' }}>{editBus.model} · {editBus.plate}</p>
              </div>
              <button onClick={closeEditModal} 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>

            <div className="px-7 py-6">
              {editPrefillLoading ? (
                <div className="flex items-center justify-center gap-2 py-12 text-slate-400">
                  <div className="w-5 h-5 border-2 border-blue-100 border-t-blue-600 rounded-full animate-spin" />
                  <span className="text-sm" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>جاري تحميل بيانات الباص...</span>
                </div>
              ) : (
                <div className="space-y-5">
                  {/* Basic info grid */}
                  <div className="grid grid-cols-2 gap-4">
                    {[
                      { label: 'اللون', key: 'color', placeholder: 'مثال: أبيض' },
                      { label: 'تاريخ الإنتاج', key: 'production_date', placeholder: '2022' },
                      { label: 'نوع الباص', key: 'type_id', placeholder: 'مثال: 2' },
                      { label: 'الماركة', key: 'brand_id', placeholder: 'مثال: 5' },
                      { label: 'الموديل', key: 'model_id', placeholder: 'مثال: 12' },
                      { label: 'رقم الهيكل', key: 'vin', placeholder: 'JTDBT923771034567' },
                      { label: 'أرقام اللوحة', key: 'numbers', placeholder: '1234' },
                      { label: 'حروف اللوحة', key: 'letters', placeholder: 'أ ب ج' },
                      { label: 'رقم النموذج', key: 'form_serial', placeholder: 'FS-9981' },
                      { label: 'عدد المستخدمين', key: 'num_of_users', placeholder: '21' },
                      { label: 'عداد الكيلومترات الحالي', key: 'current_mileage_km', placeholder: '125100' },
                    ].map(f => (
                      <div key={f.key}>
                        <label className="block text-sm font-semibold text-slate-600 mb-1.5" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{f.label}</label>
                        <input
                          type="text"
                          placeholder={f.placeholder}
                          value={(editForm as unknown as Record<string, string>)[f.key]}
                          onChange={e => setEditForm(prev => ({ ...prev, [f.key]: e.target.value }))}
                          className="w-full h-11 bg-slate-50 border border-slate-200 rounded-xl px-4 text-sm outline-none text-slate-700 focus:border-blue-300"
                          style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}
                        />
                      </div>
                    ))}
                  </div>

                  {/* Date fields */}
                  <div className="grid grid-cols-2 gap-4">
                    {[
                      { label: 'تاريخ انتهاء النموذج', key: 'form_end_date' },
                      { label: 'تاريخ انتهاء التأمين', key: 'insurance_end_date' },
                      { label: 'تاريخ آخر صيانة', key: 'last_maintenance_date' },
                      { label: 'تاريخ انتهاء الفحص الدوري', key: 'periodic_inspection_end_date' },
                    ].map(f => (
                      <div key={f.key}>
                        <label className="block text-sm font-semibold text-slate-600 mb-1.5" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{f.label}</label>
                        <input
                          type="date"
                          value={(editForm as unknown as Record<string, string>)[f.key]}
                          onChange={e => setEditForm(prev => ({ ...prev, [f.key]: e.target.value }))}
                          className="w-full h-11 bg-slate-50 border border-slate-200 rounded-xl px-4 text-sm outline-none text-slate-700 focus:border-blue-300"
                          style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}
                        />
                      </div>
                    ))}
                  </div>

                  {/* Features */}
                  {apiFeatures.length > 0 && (
                    <div>
                      <label className="block text-sm font-bold text-slate-600 mb-3" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>
                        مميزات الباص
                        <span className="text-xs font-normal text-slate-400 mr-2">اختر ما ينطبق</span>
                      </label>
                      <div className="grid grid-cols-2 gap-2">
                        {apiFeatures.map(feature => {
                          const isSelected = editForm.features.includes(feature.id);
                          const icon = feature.icon || getFeatureIcon(feature.name);
                          return (
                            <button
                              key={feature.id}
                              type="button"
                              onClick={() => setEditForm(prev => ({
                                ...prev,
                                features: isSelected
                                  ? prev.features.filter(id => id !== feature.id)
                                  : [...prev.features, feature.id],
                              }))}
                              className="flex items-center gap-3 px-4 py-3 rounded-xl cursor-pointer transition-all text-right"
                              style={{
                                background: isSelected ? '#EEF2FF' : '#F8FAFC',
                                border: `1.5px solid ${isSelected ? '#1E3A8A' : '#E2E8F0'}`,
                              }}
                            >
                              <div className="w-8 h-8 rounded-lg flex items-center justify-center flex-shrink-0"
                                style={{ background: isSelected ? '#1E3A8A' : '#E2E8F0' }}>
                                <i className={`${icon} text-sm`} style={{ color: isSelected ? 'white' : '#64748b' }}></i>
                              </div>
                              <span className="text-sm font-semibold flex-1" style={{ color: isSelected ? '#1E3A8A' : '#475569', fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{feature.name}</span>
                              {isSelected && (
                                <div className="w-5 h-5 rounded-full flex items-center justify-center flex-shrink-0" style={{ background: '#1E3A8A' }}>
                                  <i className="ri-check-line text-white text-xs"></i>
                                </div>
                              )}
                            </button>
                          );
                        })}
                      </div>
                    </div>
                  )}

                  {/* Status */}
                  <div>
                    <label className="block text-sm font-bold text-slate-600 mb-1.5" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>حالة الباص</label>
                    <div className="flex gap-3">
                      {[
                        { val: 'active', label: 'نشط' },
                        { val: 'maintenance', label: 'صيانة' },
                        { val: 'stopped', label: 'متوقف' },
                      ].map(s => (
                        <button
                          key={s.val}
                          type="button"
                          onClick={() => setEditForm(prev => ({ ...prev, status: s.val as typeof editForm.status }))}
                          className="flex-1 h-10 rounded-xl text-sm font-bold cursor-pointer transition-all whitespace-nowrap"
                          style={{
                            background: editForm.status === s.val ? '#1E3A8A' : '#F8FAFC',
                            color: editForm.status === s.val ? 'white' : '#64748b',
                            border: `1.5px solid ${editForm.status === s.val ? '#1E3A8A' : '#E2E8F0'}`,
                            fontFamily: '"IBM Plex Sans Arabic", sans-serif',
                          }}
                        >{s.label}</button>
                      ))}
                    </div>
                  </div>

                  {/* Notes */}
                  <div>
                    <label className="block text-sm font-bold text-slate-600 mb-1.5" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>ملاحظات</label>
                    <textarea
                      placeholder="أي ملاحظات خاصة بالباص..."
                      value={editForm.notes}
                      onChange={e => setEditForm(prev => ({ ...prev, notes: e.target.value }))}
                      rows={3}
                      className="w-full bg-slate-50 border border-slate-200 rounded-xl px-4 py-3 text-sm outline-none text-slate-700 resize-none focus:border-blue-300"
                      style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}
                    />
                  </div>
                </div>
              )}

              {/* Footer buttons */}
              <div className="flex gap-3 mt-7">
                <button
                  type="button"
                  onClick={closeEditModal}
                  disabled={editLoading}
                  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"
                  onClick={() => void handleUpdateBus()}
                  disabled={editLoading || editPrefillLoading}
                  className="flex-1 h-11 rounded-xl font-bold text-sm text-white cursor-pointer whitespace-nowrap disabled:opacity-70 flex items-center justify-center gap-2"
                  style={{ background: '#1E3A8A', fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}
                >
                  {editLoading ? (
                    <>
                      <div className="w-4 h-4 border-2 border-white/30 border-t-white rounded-full animate-spin"></div>
                      جاري الحفظ...
                    </>
                  ) : (
                    <>
                      <i className="ri-save-line"></i>
                      حفظ التعديلات
                    </>
                  )}
                </button>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* Add Bus Modal — Multi Step */}
      {showAdd && (
        <div className="fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-6" onClick={closeAddModal}>
          <div className="bg-white rounded-3xl w-full max-w-2xl shadow-2xl overflow-hidden" onClick={e => e.stopPropagation()} style={{ maxHeight: '90vh', overflowY: 'auto' }}>
            {/* Modal Header */}
            <div className="flex items-center justify-between px-7 pt-6 pb-4 border-b" style={{ borderColor: '#F1F5F9' }}>
              <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' }}>الخطوة {addStep} من 3</p>
              </div>
              <button onClick={closeAddModal} 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>

            {/* Steps Indicator */}
            <div className="flex items-center gap-2 px-7 py-4">
              {[
                { n: 1, label: 'البيانات الأساسية' },
                { n: 2, label: 'المستندات والتراخيص' },
                { n: 3, label: 'الإسناد والمسار' },
              ].map((s, i) => (
                <div key={s.n} className="flex items-center gap-2 flex-1">
                  <div className="flex items-center gap-2">
                    <div className="w-7 h-7 rounded-full flex items-center justify-center text-xs font-black flex-shrink-0"
                      style={{
                        background: addStep >= s.n ? '#1E3A8A' : '#F1F5F9',
                        color: addStep >= s.n ? 'white' : '#94a3b8',
                      }}>
                      {addStep > s.n ? <i className="ri-check-line text-xs"></i> : s.n}
                    </div>
                    <span className="text-xs font-bold whitespace-nowrap" style={{ color: addStep >= s.n ? '#1E3A8A' : '#94a3b8', fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{s.label}</span>
                  </div>
                  {i < 2 && <div className="flex-1 h-0.5 mx-2" style={{ background: addStep > s.n ? '#1E3A8A' : '#E2E8F0' }}></div>}
                </div>
              ))}
            </div>

            <div className="px-7 pb-7">
              {/* ── Step 1: Basic Info ───────────────────────────────────────── */}
              {addStep === 1 && (
                <div className="space-y-5">
                  <div className="grid grid-cols-2 gap-4">
                    {[
                      { label: 'نوع الباص', key: 'type', placeholder: 'مثال: minibus' },
                      { label: 'الماركة', key: 'brand', placeholder: 'مثال: 1' },
                      { label: 'الموديل', key: 'model', placeholder: 'مثال: 5' },
                      { label: 'تاريخ الإنتاج', key: 'production_date', placeholder: '2023-01-01' },
                      { label: 'اللون', key: 'color', placeholder: 'مثال: أبيض' },
                      { label: 'رقم الهيكل', key: 'vin', placeholder: 'مثال: JT3HP10V5X0123456' },
                      { label: 'أرقام اللوحة', key: 'numbers', placeholder: 'مثال: 1234' },
                      { label: 'حروف اللوحة', key: 'letters', placeholder: 'مثال: ABC' },
                      { label: 'رقم النموذج', key: 'form_serial', placeholder: 'مثال: F-001' },
                      { label: 'عداد الكيلومترات الحالي', key: 'current_mileage_km', placeholder: 'مثال: 0' },
                      { label: 'عدد المستخدمين', key: 'num_of_users', placeholder: '5، 9، 13، 17، 21...' },
                    ].map(f => (
                      <div key={f.key}>
                        <label className="block text-sm font-semibold text-slate-600 mb-1.5" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{f.label}</label>
                        <input
                          type="text"
                          placeholder={f.placeholder}
                          value={(form as any)[f.key]}
                          onChange={e => setForm(prev => ({ ...prev, [f.key]: e.target.value }))}
                          className="w-full h-11 bg-slate-50 border border-slate-200 rounded-xl px-4 text-sm outline-none text-slate-700 focus:border-blue-300"
                          style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}
                        />
                      </div>
                    ))}
                  </div>

                  {/* ── Amenities from API ──────────────────────────────────── */}
                  <div>
                    <label className="block text-sm font-bold text-slate-600 mb-3" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>
                      مميزات الباص
                      <span className="text-xs font-normal text-slate-400 mr-2">اختر ما ينطبق</span>
                    </label>

                    {/* Loading state */}
                    {featuresApi.loading && (
                      <div className="flex items-center gap-2 py-4">
                        <div className="w-5 h-5 border-2 border-blue-200 border-t-blue-600 rounded-full animate-spin"></div>
                        <span className="text-xs text-slate-400" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>جاري تحميل المميزات...</span>
                      </div>
                    )}

                    {/* Error state */}
                    {featuresApi.error && !featuresApi.loading && (
                      <p className="text-xs text-red-400 mb-2" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>
                        تعذر تحميل المميزات: {featuresApi.error}
                      </p>
                    )}

                    {/* Features grid */}
                    {!featuresApi.loading && apiFeatures.length > 0 && (
                      <div className="grid grid-cols-2 gap-2">
                        {apiFeatures.map(feature => {
                          const isSelected = form.features.includes(feature.id);
                          const icon = feature.icon || getFeatureIcon(feature.name);
                          return (
                            <button
                              key={feature.id}
                              type="button"
                              onClick={() => setForm(prev => ({
                                ...prev,
                                features: isSelected
                                  ? prev.features.filter(id => id !== feature.id)
                                  : [...prev.features, feature.id],
                              }))}
                              className="flex items-center gap-3 px-4 py-3 rounded-xl cursor-pointer transition-all text-right"
                              style={{
                                background: isSelected ? '#EEF2FF' : '#F8FAFC',
                                border: `1.5px solid ${isSelected ? '#1E3A8A' : '#E2E8F0'}`,
                              }}
                            >
                              <div className="w-8 h-8 rounded-lg flex items-center justify-center flex-shrink-0"
                                style={{ background: isSelected ? '#1E3A8A' : '#E2E8F0' }}>
                                <i className={`${icon} text-sm`} style={{ color: isSelected ? 'white' : '#64748b' }}></i>
                              </div>
                              <span className="text-sm font-semibold flex-1" style={{ color: isSelected ? '#1E3A8A' : '#475569', fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{feature.name}</span>
                              {isSelected && (
                                <div className="w-5 h-5 rounded-full flex items-center justify-center flex-shrink-0" style={{ background: '#1E3A8A' }}>
                                  <i className="ri-check-line text-white text-xs"></i>
                                </div>
                              )}
                            </button>
                          );
                        })}
                      </div>
                    )}
                  </div>
                </div>
              )}

              {/* ── Step 2: Documents & Images ───────────────────────────────── */}
              {addStep === 2 && (
                <div className="space-y-4">
                  {/* Date fields */}
                  {[
                    { label: 'تاريخ انتهاء النموذج', key: 'form_end_date', placeholder: '2027-03-12' },
                    { label: 'تاريخ انتهاء التأمين', key: 'insurance_end_date', placeholder: '2026-12-31' },
                    { label: 'تاريخ آخر صيانة', key: 'last_maintenance_date', placeholder: '2026-02-15' },
                    { label: 'تاريخ انتهاء الفحص الدوري', key: 'periodic_inspection_end_date', placeholder: '2026-04-20' },
                  ].map(f => (
                    <div key={f.key}>
                      <label className="block text-sm font-semibold text-slate-600 mb-1.5" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{f.label}</label>
                      <input
                        type="date"
                        placeholder={f.placeholder}
                        value={(form as any)[f.key]}
                        onChange={e => setForm(prev => ({ ...prev, [f.key]: e.target.value }))}
                        className="w-full h-11 bg-slate-50 border border-slate-200 rounded-xl px-4 text-sm outline-none text-slate-700 focus:border-blue-300"
                        style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}
                      />
                    </div>
                  ))}

                  {/* Image upload grid */}
                  <div className="mt-2">
                    <p className="text-sm font-bold text-slate-600 mb-3" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>رفع صور الباص والمستندات</p>
                    <div className="grid grid-cols-3 gap-3">
                      {imageSlots.map(({ key, label }) => {
                        const preview = imagePreviews[key];
                        return (
                          <label
                            key={key}
                            className="flex flex-col items-center justify-center h-24 rounded-xl border-2 border-dashed cursor-pointer hover:bg-slate-50 transition-colors relative overflow-hidden"
                            style={{ borderColor: preview ? '#1E3A8A' : '#CBD5E1' }}
                          >
                            {preview ? (
                              <>
                                <img src={preview} alt={label} className="w-full h-full object-cover absolute inset-0" />
                                <div className="absolute inset-0 bg-black/30 flex items-center justify-center opacity-0 hover:opacity-100 transition-opacity">
                                  <i className="ri-pencil-line text-white text-lg"></i>
                                </div>
                              </>
                            ) : (
                              <>
                                <i className="ri-image-add-line text-xl text-slate-400 mb-1"></i>
                                <span className="text-[10px] text-slate-400 text-center px-2" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{label}</span>
                              </>
                            )}
                            <input
                              type="file"
                              accept="image/*"
                              className="hidden"
                              onChange={e => {
                                const file = e.target.files?.[0] ?? null;
                                handleImageChange(key, file);
                              }}
                            />
                          </label>
                        );
                      })}
                    </div>
                  </div>
                </div>
              )}

              {/* ── Step 3: Assignment & Route ──────────────────────────────── */}
              {addStep === 3 && (
                <div className="space-y-5">
                  {/* Driver selection (display only — not sent to API; kept for UX) */}
                  <div>
                    <label className="block text-sm font-bold text-slate-600 mb-3" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>إسناد سائق (اختياري)</label>
                    <div className="space-y-2 max-h-52 overflow-y-auto">
                      <button
                        onClick={() => setForm(prev => ({ ...prev, driverId: '' }))}
                        className="w-full flex items-center gap-3 p-3 rounded-xl cursor-pointer transition-all text-right"
                        style={{
                          background: form.driverId === '' ? '#FEF2F2' : '#F8FAFC',
                          border: `1.5px solid ${form.driverId === '' ? '#FCA5A5' : '#F1F5F9'}`,
                        }}
                      >
                        <div className="w-9 h-9 rounded-xl flex items-center justify-center flex-shrink-0" style={{ background: '#F1F5F9' }}>
                          <i className="ri-user-unfollow-line text-slate-400 text-base"></i>
                        </div>
                        <span className="text-sm font-bold text-slate-500" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>بدون سائق (لاحقاً)</span>
                        {form.driverId === '' && (
                          <div className="mr-auto w-5 h-5 rounded-full flex items-center justify-center" style={{ background: '#EF4444' }}>
                            <i className="ri-check-line text-white text-xs"></i>
                          </div>
                        )}
                      </button>
                      {captainsForAssign === null || captainsForAssignApi.loading ? (
                        <div className="flex items-center justify-center gap-2 py-6 text-slate-400">
                          <div className="w-5 h-5 border-2 border-blue-100 border-t-blue-600 rounded-full animate-spin" />
                          <span className="text-sm" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>جاري تحميل السائقين...</span>
                        </div>
                      ) : captainsForAssign.length === 0 ? (
                        <p className="text-center text-sm text-slate-400 py-6" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>
                          لا يوجد سائقون متاحون للإسناد
                        </p>
                      ) : (
                        captainsForAssign.map(d => {
                          const sid = String(d.id);
                          return (
                            <button
                              key={sid}
                              onClick={() => setForm(prev => ({ ...prev, driverId: sid }))}
                              className="w-full flex items-center gap-3 p-3 rounded-xl cursor-pointer transition-all text-right"
                              style={{
                                background: form.driverId === sid ? '#EEF2FF' : '#F8FAFC',
                                border: `1.5px solid ${form.driverId === sid ? '#1E3A8A' : '#F1F5F9'}`,
                              }}
                            >
                              <div className="w-9 h-9 rounded-xl overflow-hidden flex-shrink-0 bg-slate-100">
                                <img
                                  src={d.image?.trim() || DEFAULT_CAPTAIN_AVATAR}
                                  alt={d.name}
                                  className="w-full h-full object-cover object-top"
                                  onError={e => {
                                    (e.target as HTMLImageElement).src = DEFAULT_CAPTAIN_AVATAR;
                                  }}
                                />
                              </div>
                              <div className="flex-1 min-w-0">
                                <p className="text-sm font-bold text-slate-800 truncate" 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' }}>#{sid}</p>
                              </div>
                              {form.driverId === sid && (
                                <div className="w-5 h-5 rounded-full flex items-center justify-center flex-shrink-0" style={{ background: '#1E3A8A' }}>
                                  <i className="ri-check-line text-white text-xs"></i>
                                </div>
                              )}
                            </button>
                          );
                        })
                      )}
                    </div>
                  </div>

                  {/* path_id */}
                  <div>
                    <label className="block text-sm font-bold text-slate-600 mb-1.5" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>المسار</label>
                    <select
                      value={form.path_id}
                      onChange={e => setForm(prev => ({ ...prev, path_id: e.target.value }))}
                      className="w-full h-11 bg-slate-50 border border-slate-200 rounded-xl px-4 text-sm outline-none text-slate-700 focus:border-blue-300"
                      style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}
                      disabled={pathsApi.loading}
                    >
                      <option value="">
                        {pathsApi.loading ? 'جاري تحميل المسارات...' : 'اختر المسار (اختياري)'}
                      </option>
                      {pathOptions.map(path => (
                        <option key={path.id} value={String(path.id)}>
                          {path.description ?? path.display_code ?? `#${path.id}`}
                        </option>
                      ))}
                    </select>
                    {pathsApi.error && (
                      <p className="text-xs text-red-500 mt-1" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>
                        {pathsApi.error}
                      </p>
                    )}
                  </div>


                  {/* Status */}
                  <div>
                    <label className="block text-sm font-bold text-slate-600 mb-1.5" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>حالة الباص</label>
                    <div className="flex gap-3">
                      {[
                        { val: 'active', label: 'نشط' },
                        { val: 'maintenance', label: 'صيانة' },
                        { val: 'stopped', label: 'متوقف' },
                      ].map(s => (
                        <button
                          key={s.val}
                          onClick={() => setForm(prev => ({ ...prev, status: s.val as typeof form.status }))}
                          className="flex-1 h-10 rounded-xl text-sm font-bold cursor-pointer transition-all whitespace-nowrap"
                          style={{
                            background: form.status === s.val ? '#1E3A8A' : '#F8FAFC',
                            color: form.status === s.val ? 'white' : '#64748b',
                            border: `1.5px solid ${form.status === s.val ? '#1E3A8A' : '#E2E8F0'}`,
                            fontFamily: '"IBM Plex Sans Arabic", sans-serif',
                          }}
                        >{s.label}</button>
                      ))}
                    </div>
                  </div>

                  {/* is_active toggle */}
                  <div>
                    <label className="block text-sm font-bold text-slate-600 mb-1.5" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>التفعيل</label>
                    <div className="flex gap-3">
                      {[{ val: '1', label: 'مفعّل' }, { val: '0', label: 'غير مفعّل' }].map(opt => (
                        <button
                          key={opt.val}
                          onClick={() => setForm(prev => ({ ...prev, is_active: opt.val as '0' | '1' }))}
                          className="flex-1 h-10 rounded-xl text-sm font-bold cursor-pointer transition-all whitespace-nowrap"
                          style={{
                            background: form.is_active === opt.val ? '#1E3A8A' : '#F8FAFC',
                            color: form.is_active === opt.val ? 'white' : '#64748b',
                            border: `1.5px solid ${form.is_active === opt.val ? '#1E3A8A' : '#E2E8F0'}`,
                            fontFamily: '"IBM Plex Sans Arabic", sans-serif',
                          }}
                        >{opt.label}</button>
                      ))}
                    </div>
                  </div>

                  {/* Notes */}
                  <div>
                    <label className="block text-sm font-bold text-slate-600 mb-1.5" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>ملاحظات إضافية</label>
                    <textarea
                      placeholder="أي ملاحظات خاصة بالباص..."
                      value={form.notes}
                      onChange={e => setForm(prev => ({ ...prev, notes: e.target.value }))}
                      rows={3}
                      className="w-full bg-slate-50 border border-slate-200 rounded-xl px-4 py-3 text-sm outline-none text-slate-700 resize-none focus:border-blue-300"
                      style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}
                    />
                  </div>

                  {/* Submit error */}
                  {submitError && (
                    <div className="flex items-center gap-2 p-3 rounded-xl" style={{ background: '#FEE2E2', border: '1px solid #FECACA' }}>
                      <i className="ri-error-warning-line text-red-500 text-sm flex-shrink-0"></i>
                      <p className="text-xs text-red-600 font-semibold" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{submitError}</p>
                    </div>
                  )}
                </div>
              )}

              {/* Navigation Buttons */}
              <div className="flex gap-3 mt-6">
                {addStep > 1 && (
                  <button onClick={() => setAddStep(s => s - 1)} disabled={submitLoading} 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>
                )}
                {addStep < 3 ? (
                  <button onClick={() => setAddStep(s => s + 1)} className="flex-1 h-11 rounded-xl font-bold text-sm text-white cursor-pointer whitespace-nowrap" style={{ background: '#1E3A8A', fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>
                    التالي
                  </button>
                ) : (
                  <button
                    onClick={handleAddBus}
                    disabled={submitLoading}
                    className="flex-1 h-11 rounded-xl font-bold text-sm text-white cursor-pointer whitespace-nowrap disabled:opacity-70 flex items-center justify-center gap-2"
                    style={{ background: '#059669', fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}
                  >
                    {submitLoading ? (
                      <>
                        <div className="w-4 h-4 border-2 border-white/30 border-t-white rounded-full animate-spin"></div>
                        جاري الإضافة...
                      </>
                    ) : (
                      <>
                        <i className="ri-check-line"></i>
                        إضافة الباص
                      </>
                    )}
                  </button>
                )}
              </div>
            </div>
          </div>
        </div>
      )}
    </DashboardShell>
  );
}