'use client';

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

import 'primereact/resources/themes/lara-light-blue/theme.css';
import 'primereact/resources/primereact.min.css';

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

interface City {
  id: string;
  name: string;
}

interface ApiBusOption {
  id: number;
  display_code: string;
  plate_number: string;
  model: string | null;
}

interface BusesListPaginated {
  data: ApiBusOption[];
}

interface BusesListApiResponse {
  key?: string;
  msg?: string;
  data: ApiBusOption[] | BusesListPaginated;
}

interface NeighborhoodOrDestination {
  id: number;
  kind: 'neighborhood' | 'destination';
  city_id: number;
  neighborhood_id: number | null;
  name: string;
  lat: number | null;
  lng: number | null;
  destination_type: string | null;
  address: string | null;
  is_active: boolean;
}

interface NeighborhoodsApiResponse {
  key: string;
  msg: string;
  data: NeighborhoodOrDestination[];
}

const DEFAULT_STATION_LAT = 24.7136;
const DEFAULT_STATION_LNG = 46.6753;

const SETTINGS_PUBLIC_BASE = 'https://sast.4hoste.com/api/v1/settings';
const SETTINGS_PUBLIC_HEADERS = {
  Accept: 'application/json',
  'x-api-key': '5f43766dcd92b8c3e7639d2a8791063c',
} as const;

interface PathSubmitApiResponse {
  key?: string;
  msg?: string;
  message?: string;
  status?: string | number;
}

interface StopEntry {
  neighborhoodId: string;
  departureTime: string;
  returnTime: string;
}

// ─── Route (from API) ─────────────────────────────────────────────────────────

interface ApiRouteOriginDestination {
  id: number;
  name: string;
  address: string;
  lat: number;
  lng: number;
  city: null | { id: number; name: string };
}

interface ApiRoute {
  id: number;
  display_code: string;
  description?: string | null;
  status: 'active' | 'draft' | 'archived';
  go_time: string;
  return_time: string;
  week_days: string[];
  total_distance_km: number;
  price_per_subscription: number;
  city: null | { id: number; name: string };
  origin: ApiRouteOriginDestination;
  destination: ApiRouteOriginDestination;
  stations_count: number;
  middle_stations_count: number;
  buses_count: number;
  subscriptions_count: number;
  updated_at: string;
}

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

// ─── Single Route (view) ──────────────────────────────────────────────────────

interface ApiStation {
  id: number;
  name: string;
  city_id: null | number;
  city: null | { id: number; name: string };
  neighborhood_id: null | number;
  destination_id: null | number;
  lat: number;
  lng: number;
  address: string;
  order_index: number;
  eta_minutes_from_start: number;
  go_time: string;
  return_time: string;
  is_origin: boolean;
  is_destination: boolean;
}

interface ApiBus {
  id: number;
  plate: string;
  type_id: string;
  brand_id: string;
  model: string;
}

interface ApiRouteDetail {
  id: number;
  description: string;
  status: 'active' | 'draft' | 'archived';
  go_time: string;
  return_time: string;
  week_days: string[];
  total_distance_km: number;
  total_duration_min: number;
  price_per_subscription: number;
  station_grace_minutes: number;
  pre_trip_notify_hours: number;
  bus_id: number | null;
  captain_id: number | null;
  bus: ApiBus | null;
  captain: null | unknown;
  stations: ApiStation[];
}

interface ApiRouteDetailResponse {
  key: string;
  msg: string;
  data: ApiRouteDetail;
}

// ─── Status config ────────────────────────────────────────────────────────────

const STATUS_CONFIG = {
  active:   { label: 'نشط',     color: '#059669', bg: '#DCFCE7' },
  draft:    { label: 'معطل',   color: '#D97706', bg: '#FEF3C7' },
  archived: { label: 'موقوف',  color: '#64748B', bg: '#F1F5F9' },
} as const;

type RouteStatus = keyof typeof STATUS_CONFIG;

// ─── Helpers ──────────────────────────────────────────────────────────────────

const WEEK_DAYS = [
  { label: 'الأحد', value: 0 },
  { label: 'الاثنين', value: 1 },
  { label: 'الثلاثاء', value: 2 },
  { label: 'الأربعاء', value: 3 },
  { label: 'الخميس', value: 4 },
  { label: 'الجمعة', value: 5 },
  { label: 'السبت', value: 6 },
];

function toApiTimeHm(raw: string): string {
  const t = raw.trim();
  if (!t) return '';
  const m = /^(\d{1,2}):(\d{2})(?::\d{2})?/.exec(t);
  if (!m) return '';
  return `${m[1].padStart(2, '0')}:${m[2].padStart(2, '0')}`;
}

function toTimeInputValue(raw: string): string {
  return toApiTimeHm(raw) || '';
}

function buildPathFormData(
  opts: {
    routeName: string;
    routeStatus: RouteStatus;
    selectedBusId: string;
    selectedWeekDays: number[];
    stationGraceMinutes: string;
    preTripNotifyHours: string;
    selectedCityId: string;
    departureNeighborhoodId: string;
    destinationId: string;
    stops: StopEntry[];
    departureStationGoTime: string;
    departureStationReturnTime: string;
    destinationStationGoTime: string;
    destinationStationReturnTime: string;
    getNeighborhoodStationById: (id: string) => NeighborhoodOrDestination | undefined;
    getDestinationStationById: (id: string) => NeighborhoodOrDestination | undefined;
  },
): FormData {
  const {
    routeName,
    routeStatus,
    selectedBusId,
    selectedWeekDays,
    stationGraceMinutes,
    preTripNotifyHours,
    selectedCityId,
    departureNeighborhoodId,
    destinationId,
    stops,
    departureStationGoTime,
    departureStationReturnTime,
    destinationStationGoTime,
    destinationStationReturnTime,
    getNeighborhoodStationById,
    getDestinationStationById,
  } = opts;

  const originGo = toApiTimeHm(departureStationGoTime);
  const originRet = toApiTimeHm(departureStationReturnTime);
  const destGo = toApiTimeHm(destinationStationGoTime);
  const destRet = toApiTimeHm(destinationStationReturnTime);

  const fd = new FormData();
  fd.append('description', routeName.trim());
  fd.append('status', routeStatus);
  fd.append('bus_id', selectedBusId);
  selectedWeekDays.forEach(d => fd.append('week_days[]', String(d)));
  fd.append('station_grace_minutes', stationGraceMinutes);
  fd.append('pre_trip_notify_hours', preTripNotifyHours);

  const allStations = [
    { type: 'origin' as const, neighborhoodId: departureNeighborhoodId, goHm: originGo, returnHm: originRet },
    ...stops.map(s => ({ type: 'middle' as const, neighborhoodId: s.neighborhoodId, goHm: toApiTimeHm(s.departureTime), returnHm: toApiTimeHm(s.returnTime) })),
    { type: 'destination' as const, neighborhoodId: destinationId, goHm: destGo, returnHm: destRet },
  ];

  allStations.forEach((station, index) => {
    const item =
      station.type === 'destination'
        ? getDestinationStationById(station.neighborhoodId)
        : getNeighborhoodStationById(station.neighborhoodId);
    if (!item) return;
    fd.append(`stations[${index}][city_id]`, selectedCityId);
    fd.append(`stations[${index}][order_index]`, String(index));
    fd.append(`stations[${index}][lat]`, String(item.lat ?? DEFAULT_STATION_LAT));
    fd.append(`stations[${index}][lng]`, String(item.lng ?? DEFAULT_STATION_LNG));
    fd.append(`stations[${index}][address]`, item.name);
    fd.append(`stations[${index}][go_time]`, station.goHm);
    fd.append(`stations[${index}][return_time]`, station.returnHm);
    if (station.type === 'origin') {
      fd.append(`stations[${index}][neighborhood_id]`, String(item.id));
      fd.append(`stations[${index}][is_origin]`, '1');
    } else if (station.type === 'destination') {
      fd.append(`stations[${index}][destination_id]`, String(item.id));
      fd.append(`stations[${index}][is_destination]`, '1');
    } else {
      fd.append(`stations[${index}][neighborhood_id]`, String(item.id));
    }
  });

  return fd;
}

/** يفصل المحطات حتى لو رجع الباك اند is_origin/is_destination = false للكل؛ الأولى = انطلاق، الأخيرة = وصول، ما بينهما = وسطى فقط. */
function splitRouteStationsByRole(stations: ApiStation[]): {
  sorted: ApiStation[];
  origin: ApiStation | undefined;
  destination: ApiStation | undefined;
  middle: ApiStation[];
} {
  const sorted = [...stations].sort((a, b) => a.order_index - b.order_index);
  const n = sorted.length;
  if (n === 0) return { sorted, origin: undefined, destination: undefined, middle: [] };
  const originIdx = sorted.findIndex(s => s.is_origin);
  const destIdx = sorted.findIndex(s => s.is_destination);
  const oi = originIdx >= 0 ? originIdx : 0;
  const di = destIdx >= 0 ? destIdx : n - 1;
  const origin = sorted[oi];
  const destination = sorted[di];
  const lo = Math.min(oi, di);
  const hi = Math.max(oi, di);
  const middle = sorted.filter((_, i) => i > lo && i < hi);
  return { sorted, origin, destination, middle };
}

function cityIdStringFromStations(stations: ApiStation[]): string {
  for (const s of stations) {
    if (s.city_id != null) return String(s.city_id);
    if (s.city?.id != null) return String(s.city.id);
  }
  return '';
}

function weekDayName(d: string) {
  return WEEK_DAYS.find(w => String(w.value) === d)?.label ?? d;
}

// ─── Sub-components ───────────────────────────────────────────────────────────

function SelectDropdown({ label, value, onChange, options, placeholder, icon, iconColor, disabled = false, errorMsg }: {
  label: string;
  value: string;
  onChange: (v: string) => void;
  options: { value: string; label: string }[];
  placeholder: string;
  icon: string;
  iconColor?: string;
  disabled?: boolean;
  errorMsg?: string | null;
}) {
  const [open, setOpen] = useState(false);
  const [search, setSearch] = useState('');
  const ref = useRef<HTMLDivElement>(null);

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

  const filtered = options.filter(o => o.label.includes(search));
  const selected = options.find(o => o.value === value);

  return (
    <div ref={ref} className="relative">
      <label className="block text-xs font-bold text-slate-500 mb-1" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{label}</label>
      <button
        type="button"
        onClick={() => !disabled && setOpen(!open)}
        disabled={disabled}
        className="w-full h-10 bg-white border border-slate-200 rounded-xl px-3 flex items-center gap-2 text-right disabled:opacity-60 disabled:cursor-not-allowed cursor-pointer"
        style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}
      >
        <div className="w-5 h-5 flex items-center justify-center flex-shrink-0">
          <i className={`${icon} text-sm`} style={{ color: iconColor ?? '#94a3b8' }}></i>
        </div>
        <span className={`flex-1 text-sm text-right truncate ${selected ? 'text-slate-800' : 'text-slate-400'}`}>
          {selected ? selected.label : placeholder}
        </span>
        {value && !disabled && (
          <div className="w-4 h-4 flex items-center justify-center flex-shrink-0" onClick={e => { e.stopPropagation(); onChange(''); }}>
            <i className="ri-close-line text-slate-400 text-xs"></i>
          </div>
        )}
        <div className="w-4 h-4 flex items-center justify-center flex-shrink-0">
          <i className="ri-arrow-down-s-line text-slate-400 text-sm"></i>
        </div>
      </button>
      {open && (
        <div className="absolute top-full mt-1 w-full bg-white rounded-xl shadow-xl border border-slate-100 z-50 overflow-hidden">
          <div className="p-2 border-b border-slate-100">
            <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 text-slate-700" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }} />
          </div>
          <div className="max-h-44 overflow-y-auto">
            {filtered.map(opt => (
              <button key={opt.value} type="button" onClick={() => { onChange(opt.value); setOpen(false); setSearch(''); }}
                className="w-full text-right px-3 py-2 text-xs hover:bg-slate-50 cursor-pointer transition-colors flex items-center gap-1"
                style={{ color: opt.value === value ? '#1E3A8A' : '#374151', fontWeight: opt.value === value ? 700 : 400, fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>
                {opt.value === value && <i className="ri-check-line ml-1 text-blue-700 flex-shrink-0"></i>}
                {opt.label}
              </button>
            ))}
            {filtered.length === 0 && <p className="text-center text-xs text-slate-400 py-3" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>لا توجد نتائج</p>}
          </div>
        </div>
      )}
      {errorMsg && <p className="text-xs text-red-500 mt-1" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{errorMsg}</p>}
    </div>
  );
}

function TimePicker({ label, value, onChange }: {
  label: string; value: string; onChange: (v: string) => void;
}) {
  return (
    <div>
      <label className="block text-xs font-bold text-slate-500 mb-1" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{label}</label>
      <div className="relative">
        <input
          type="time"
          value={value}
          onChange={e => onChange(e.target.value)}
          className="w-full h-10 bg-white border border-slate-200 rounded-xl px-3 text-sm outline-none text-slate-700 cursor-pointer"
          style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}
        />
      </div>
    </div>
  );
}

// ─── Table Skeleton ───────────────────────────────────────────────────────────

function TableSkeleton() {
  return (
    <div className="bg-white rounded-2xl overflow-hidden" style={{ border: '1px solid #F1F5F9', boxShadow: '0 1px 4px rgba(0,0,0,0.04)' }}>
      <table className="w-full">
        <thead>
          <tr style={{ background: '#F8FAFC' }}>
            {['رقم المسار', 'اسم المسار', 'نقطة الانطلاق', 'نقطة الوصول', 'المحطات', 'وقت الذهاب', 'وقت العودة', 'الباصات', 'الحالة', ''].map(h => (
              <th key={h} className="text-right px-4 py-3 text-xs font-bold text-slate-500 whitespace-nowrap" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{h}</th>
            ))}
          </tr>
        </thead>
        <tbody>
          {Array.from({ length: 5 }).map((_, i) => (
            <tr key={i} className="border-t" style={{ borderColor: '#F8FAFC' }}>
              {Array.from({ length: 10 }).map((__, j) => (
                <td key={j} className="px-4 py-3.5">
                  <Skeleton width={j === 9 ? '60px' : j === 0 ? '50px' : '100%'} height="16px" borderRadius="8px" />
                </td>
              ))}
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}

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

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

  // ── API hooks ──
  const { data: busesResponse, loading: busesLoading, error: busesError, request: fetchBuses } = useApi<BusesListApiResponse>();
  const { request: settingsRequest } = useSettingsApi<{ data: City[] | { data: City[] } } | City[]>();
  const { loading: submitLoading, error: submitError, request: submitRoute, lastError: submitLastError } = useApi<PathSubmitApiResponse>();

  // ── Routes list state ──
  const [routes, setRoutes] = useState<ApiRoute[]>([]);
  const [routesLoading, setRoutesLoading] = useState(false);
  const [pagination, setPagination] = useState<ApiRoutesResponse['data']['pagination'] | null>(null);
  const [currentPage, setCurrentPage] = useState(1);
  const [statusFilter, setStatusFilter] = useState<'active' | 'draft' | 'archived'>('active');
  const [search, setSearch] = useState('');

  // ── View modal state ──
  const [viewRouteId, setViewRouteId] = useState<number | null>(null);
  const [viewRouteDetail, setViewRouteDetail] = useState<ApiRouteDetail | null>(null);
  const [viewLoading, setViewLoading] = useState(false);
  const { request: fetchRouteDetail } = useApi<ApiRouteDetailResponse>();

  // ── Edit modal state (mirrors add form; filled from paths/:id) ──
  const [editRoute, setEditRoute] = useState<ApiRoute | null>(null);
  const [editFormLoading, setEditFormLoading] = useState(false);
  const [editRouteName, setEditRouteName] = useState('');
  const [editSelectedCityId, setEditSelectedCityId] = useState('');
  const [editSelectedBusId, setEditSelectedBusId] = useState('');
  const [editSelectedWeekDays, setEditSelectedWeekDays] = useState<number[]>([]);
  const [editStationGraceMinutes, setEditStationGraceMinutes] = useState('');
  const [editPreTripNotifyHours, setEditPreTripNotifyHours] = useState('');
  const [editRouteStatus, setEditRouteStatus] = useState<RouteStatus>('active');
  const [editDepartureNeighborhoodId, setEditDepartureNeighborhoodId] = useState('');
  const [editDestinationId, setEditDestinationId] = useState('');
  const [editStops, setEditStops] = useState<StopEntry[]>([]);
  const [editDepartureStationGoTime, setEditDepartureStationGoTime] = useState('');
  const [editDepartureStationReturnTime, setEditDepartureStationReturnTime] = useState('');
  const [editDestinationStationGoTime, setEditDestinationStationGoTime] = useState('');
  const [editDestinationStationReturnTime, setEditDestinationStationReturnTime] = useState('');
  const [editFormError, setEditFormError] = useState<string | null>(null);
  const [editNeighborhoodItems, setEditNeighborhoodItems] = useState<NeighborhoodOrDestination[]>([]);
  const [editDestinationItems, setEditDestinationItems] = useState<NeighborhoodOrDestination[]>([]);
  const [editNeighborhoodsLoading, setEditNeighborhoodsLoading] = useState(false);
  const [editNeighborhoodsError, setEditNeighborhoodsError] = useState<string | null>(null);
  const { loading: editLoading, error: editSubmitError, request: updateRoute, lastError: editLastError } = useApi<PathSubmitApiResponse>();

  // ── Delete modal state ──
  const [deleteRoute, setDeleteRoute] = useState<ApiRoute | null>(null);
  const { loading: deleteLoading, request: deleteRouteApi } = useApi<PathSubmitApiResponse>();

  // ── Add modal state ──
  const [showAdd, setShowAdd] = useState(false);

  // ── cities & neighborhoods ──
  const [cities, setCities] = useState<City[]>([]);
  const [citiesLoading, setCitiesLoading] = useState(false);
  const [citiesError, setCitiesError] = useState<string | null>(null);
  const [neighborhoodItems, setNeighborhoodItems] = useState<NeighborhoodOrDestination[]>([]);
  const [destinationItems, setDestinationItems] = useState<NeighborhoodOrDestination[]>([]);
  const [neighborhoodsLoading, setNeighborhoodsLoading] = useState(false);
  const [neighborhoodsError, setNeighborhoodsError] = useState<string | null>(null);

  // ── Add form state ──
  const [routeName, setRouteName] = useState('');
  const [selectedCityId, setSelectedCityId] = useState('');
  const [selectedBusId, setSelectedBusId] = useState('');
  const [selectedWeekDays, setSelectedWeekDays] = useState<number[]>([]);
  const [stationGraceMinutes, setStationGraceMinutes] = useState('');
  const [preTripNotifyHours, setPreTripNotifyHours] = useState('');
  const [routeStatus, setRouteStatus] = useState<RouteStatus>('active');
  const [departureNeighborhoodId, setDepartureNeighborhoodId] = useState('');
  const [destinationId, setDestinationId] = useState('');
  const [stops, setStops] = useState<StopEntry[]>([]);
  const [departureStationGoTime, setDepartureStationGoTime] = useState('');
  const [departureStationReturnTime, setDepartureStationReturnTime] = useState('');
  const [destinationStationGoTime, setDestinationStationGoTime] = useState('');
  const [destinationStationReturnTime, setDestinationStationReturnTime] = useState('');
  const [formError, setFormError] = useState<string | null>(null);

  const busesList: ApiBusOption[] = (() => {
    const payload = busesResponse?.data;
    if (!payload) return [];
    if (Array.isArray(payload)) return payload;
    return payload.data ?? [];
  })();

  const neighborhoodOptions = neighborhoodItems
    .filter(n => n.is_active)
    .map(n => ({ value: String(n.id), label: n.name }));

  const destinationOptions = destinationItems
    .filter(n => n.is_active)
    .map(n => ({ value: String(n.id), label: n.name }));

  // ── Fetch routes ──────────────────────────────────────────────────────────
  const { request: fetchRoutesRaw } = useApi<ApiRoutesResponse>();

  const fetchRoutes = useCallback(async (page = 1, status: 'active' | 'draft' | 'archived' = 'active') => {
    setRoutesLoading(true);
    const res = await fetchRoutesRaw(`paths?paginate=20&status=${status}&page=${page}`);
    if (res?.data?.data) {
      setRoutes(res.data.data);
      setPagination(res.data.pagination);
    }
    setRoutesLoading(false);
  }, [fetchRoutesRaw]);

  // ── Effects ───────────────────────────────────────────────────────────────
  useEffect(() => {
    if (!hasHydrated || !token) return;
    void fetchRoutes(currentPage, statusFilter);
  }, [hasHydrated, token, currentPage, statusFilter, fetchRoutes]);

  useEffect(() => {
    if (!hasHydrated || !token) return;
    void fetchBuses('buses?status=active&paginate=100');
  }, [hasHydrated, token, fetchBuses]);

  useEffect(() => {
    const fetchCities = async () => {
      setCitiesLoading(true);
      setCitiesError(null);
      const json = await settingsRequest('/cities', { skipAuth: true });
      if (json) {
        let list: City[] = [];
        if (Array.isArray(json)) list = json;
        else if (Array.isArray((json as { data: City[] }).data)) list = (json as { data: City[] }).data;
        else if (Array.isArray(((json as { data: { data: City[] } }).data as { data: City[] })?.data))
          list = ((json as { data: { data: City[] } }).data as { data: City[] }).data;
        setCities(list);
      } else {
        setCitiesError('تعذّر تحميل قائمة المدن');
      }
      setCitiesLoading(false);
    };
    void fetchCities();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const fetchNeighborhoods = useCallback(async (cityId: string) => {
    if (!cityId) {
      setNeighborhoodItems([]);
      setDestinationItems([]);
      return;
    }
    setNeighborhoodsLoading(true);
    setNeighborhoodsError(null);
    try {
      const [resN, resD] = await Promise.all([
        fetch(`${SETTINGS_PUBLIC_BASE}/cities/${cityId}/neighborhoods`, { headers: SETTINGS_PUBLIC_HEADERS }),
        fetch(`${SETTINGS_PUBLIC_BASE}/cities/${cityId}/destinations`, { headers: SETTINGS_PUBLIC_HEADERS }),
      ]);
      const jsonN = (await resN.json()) as NeighborhoodsApiResponse;
      const jsonD = (await resD.json()) as NeighborhoodsApiResponse;
      const hoods = jsonN?.data && Array.isArray(jsonN.data) ? jsonN.data : [];
      const dests = jsonD?.data && Array.isArray(jsonD.data) ? jsonD.data : [];
      setNeighborhoodItems(resN.ok ? hoods : []);
      setDestinationItems(resD.ok ? dests : []);
      if (!resN.ok || !resD.ok) {
        setNeighborhoodsError(
          !resN.ok && !resD.ok
            ? 'تعذّر تحميل الأحياء ونقاط الوصول'
            : !resN.ok
              ? 'تعذّر تحميل الأحياء'
              : 'تعذّر تحميل نقاط الوصول',
        );
      } else {
        setNeighborhoodsError(null);
      }
    } catch {
      setNeighborhoodsError('تعذّر الاتصال بالخادم');
      setNeighborhoodItems([]);
      setDestinationItems([]);
    }
    setNeighborhoodsLoading(false);
  }, []);

  const fetchEditNeighborhoods = useCallback(async (cityId: string) => {
    if (!cityId) {
      setEditNeighborhoodItems([]);
      setEditDestinationItems([]);
      return;
    }
    setEditNeighborhoodsLoading(true);
    setEditNeighborhoodsError(null);
    try {
      const [resN, resD] = await Promise.all([
        fetch(`${SETTINGS_PUBLIC_BASE}/cities/${cityId}/neighborhoods`, { headers: SETTINGS_PUBLIC_HEADERS }),
        fetch(`${SETTINGS_PUBLIC_BASE}/cities/${cityId}/destinations`, { headers: SETTINGS_PUBLIC_HEADERS }),
      ]);
      const jsonN = (await resN.json()) as NeighborhoodsApiResponse;
      const jsonD = (await resD.json()) as NeighborhoodsApiResponse;
      const hoods = jsonN?.data && Array.isArray(jsonN.data) ? jsonN.data : [];
      const dests = jsonD?.data && Array.isArray(jsonD.data) ? jsonD.data : [];
      setEditNeighborhoodItems(hoods);
      setEditDestinationItems(dests);
      let err: string | null = null;
      if (!resN.ok) err = 'تعذّر تحميل الأحياء';
      if (!resD.ok) err = err ? `${err} ونقاط الوصول` : 'تعذّر تحميل نقاط الوصول';
      setEditNeighborhoodsError(err);
      if (!resN.ok) setEditNeighborhoodItems([]);
      if (!resD.ok) setEditDestinationItems([]);
    } catch {
      setEditNeighborhoodsError('تعذّر الاتصال بالخادم');
      setEditNeighborhoodItems([]);
      setEditDestinationItems([]);
    }
    setEditNeighborhoodsLoading(false);
  }, []);

  useEffect(() => {
    setDepartureNeighborhoodId('');
    setDestinationId('');
    setStops(prev => prev.map(s => ({ ...s, neighborhoodId: '' })));
    if (selectedCityId) void fetchNeighborhoods(selectedCityId);
    else {
      setNeighborhoodItems([]);
      setDestinationItems([]);
    }
  }, [selectedCityId, fetchNeighborhoods]);

  // ── View route ────────────────────────────────────────────────────────────
  const handleViewRoute = async (id: number) => {
    setViewRouteId(id);
    setViewRouteDetail(null);
    setViewLoading(true);
    const res = await fetchRouteDetail(`paths/${id}`);
    if (res?.data) setViewRouteDetail(res.data);
    setViewLoading(false);
  };

  // ── Edit route ────────────────────────────────────────────────────────────
  const handleCloseEdit = () => {
    setEditRoute(null);
    setEditFormLoading(false);
    setEditFormError(null);
    setEditRouteName('');
    setEditSelectedCityId('');
    setEditSelectedBusId('');
    setEditSelectedWeekDays([]);
    setEditStationGraceMinutes('');
    setEditPreTripNotifyHours('');
    setEditRouteStatus('active');
    setEditDepartureNeighborhoodId('');
    setEditDestinationId('');
    setEditStops([]);
    setEditDepartureStationGoTime('');
    setEditDepartureStationReturnTime('');
    setEditDestinationStationGoTime('');
    setEditDestinationStationReturnTime('');
    setEditNeighborhoodItems([]);
    setEditDestinationItems([]);
    setEditNeighborhoodsError(null);
  };

  const handleOpenEdit = async (route: ApiRoute, e: React.MouseEvent) => {
    e.stopPropagation();
    setEditFormError(null);
    setEditRoute(route);
    setEditFormLoading(true);
    setEditNeighborhoodItems([]);
    setEditDestinationItems([]);
    const res = await fetchRouteDetail(`paths/${route.id}`);
    if (!res?.data) {
      setEditFormLoading(false);
      toast.current?.show({ severity: 'error', summary: 'خطأ', detail: 'تعذّر تحميل تفاصيل المسار', life: 4000 });
      setEditRoute(null);
      return;
    }
    const d = res.data;
    const { sorted: stations, origin, destination: dest, middle } = splitRouteStationsByRole(d.stations);
    const cityId = cityIdStringFromStations(stations);

    if (cityId) {
      setEditNeighborhoodsLoading(true);
      setEditNeighborhoodsError(null);
      try {
        const [resN, resD] = await Promise.all([
          fetch(`${SETTINGS_PUBLIC_BASE}/cities/${cityId}/neighborhoods`, { headers: SETTINGS_PUBLIC_HEADERS }),
          fetch(`${SETTINGS_PUBLIC_BASE}/cities/${cityId}/destinations`, { headers: SETTINGS_PUBLIC_HEADERS }),
        ]);
        const jsonN = (await resN.json()) as NeighborhoodsApiResponse;
        const jsonD = (await resD.json()) as NeighborhoodsApiResponse;
        const hoods = jsonN?.data && Array.isArray(jsonN.data) ? jsonN.data : [];
        const dests = jsonD?.data && Array.isArray(jsonD.data) ? jsonD.data : [];
        setEditNeighborhoodItems(hoods);
        setEditDestinationItems(dests);
        let err: string | null = null;
        if (!resN.ok) err = 'تعذّر تحميل الأحياء';
        if (!resD.ok) err = err ? `${err} ونقاط الوصول` : 'تعذّر تحميل نقاط الوصول';
        setEditNeighborhoodsError(err);
        if (!resN.ok) setEditNeighborhoodItems([]);
        if (!resD.ok) setEditDestinationItems([]);
      } catch {
        setEditNeighborhoodsError('تعذّر الاتصال بالخادم');
        setEditNeighborhoodItems([]);
        setEditDestinationItems([]);
      }
      setEditNeighborhoodsLoading(false);
    }

    setEditRouteName(d.description);
    setEditRouteStatus(d.status as RouteStatus);
    setEditSelectedBusId(d.bus_id != null ? String(d.bus_id) : '');
    setEditStationGraceMinutes(String(d.station_grace_minutes ?? ''));
    setEditPreTripNotifyHours(String(d.pre_trip_notify_hours ?? ''));
    const weekNums = d.week_days
      .map(x => {
        if (typeof x === 'number') return x;
        const n = parseInt(String(x), 10);
        return Number.isNaN(n) ? null : n;
      })
      .filter((x): x is number => x !== null);
    setEditSelectedWeekDays(weekNums);
    setEditSelectedCityId(cityId);

    setEditDepartureNeighborhoodId(origin?.neighborhood_id != null ? String(origin.neighborhood_id) : '');
    const destId =
      dest?.destination_id != null ? String(dest.destination_id)
        : dest?.neighborhood_id != null ? String(dest.neighborhood_id) : '';
    setEditDestinationId(destId);

    setEditStops(
      middle.map(s => ({
        neighborhoodId: s.neighborhood_id != null ? String(s.neighborhood_id) : '',
        departureTime: toTimeInputValue(s.go_time),
        returnTime: toTimeInputValue(s.return_time),
      })),
    );
    setEditDepartureStationGoTime(toTimeInputValue(origin?.go_time ?? ''));
    setEditDepartureStationReturnTime(toTimeInputValue(origin?.return_time ?? ''));
    setEditDestinationStationGoTime(toTimeInputValue(dest?.go_time ?? ''));
    setEditDestinationStationReturnTime(toTimeInputValue(dest?.return_time ?? ''));

    setEditFormLoading(false);
  };

  const handleEditCityChange = (cityId: string) => {
    setEditSelectedCityId(cityId);
    setEditDepartureNeighborhoodId('');
    setEditDestinationId('');
    setEditStops(prev => prev.map(s => ({ ...s, neighborhoodId: '' })));
    void fetchEditNeighborhoods(cityId);
  };

  const handleEditSubmit = async () => {
    if (!editRoute) return;
    setEditFormError(null);
    if (!editRouteName.trim()) return setEditFormError('اسم المسار مطلوب');
    if (!editSelectedCityId) return setEditFormError('المدينة مطلوبة');
    if (!editSelectedBusId) return setEditFormError('الباص مطلوب');
    if (editSelectedWeekDays.length === 0) return setEditFormError('يجب اختيار يوم واحد على الأقل');
    if (!editStationGraceMinutes.trim()) return setEditFormError('دقائق الانتظار مطلوبة');
    if (!editPreTripNotifyHours) return setEditFormError('ساعات الإشعار مطلوبة');
    if (!editDepartureNeighborhoodId) return setEditFormError('نقطة الانطلاق مطلوبة');
    if (!editDestinationId) return setEditFormError('نقطة الوصول مطلوبة');

    const originGo = toApiTimeHm(editDepartureStationGoTime);
    const originRet = toApiTimeHm(editDepartureStationReturnTime);
    if (!originGo) return setEditFormError('وقت ذهاب نقطة الانطلاق مطلوب');
    if (!originRet) return setEditFormError('وقت عودة نقطة الانطلاق مطلوب');

    for (let i = 0; i < editStops.length; i++) {
      if (!toApiTimeHm(editStops[i].departureTime) || !toApiTimeHm(editStops[i].returnTime))
        return setEditFormError(`أوقات الذهاب والعودة للمحطة الوسطى ${i + 1} مطلوبة`);
    }

    const destGo = toApiTimeHm(editDestinationStationGoTime);
    const destRet = toApiTimeHm(editDestinationStationReturnTime);
    if (!destGo) return setEditFormError('وقت ذهاب نقطة الوصول مطلوب');
    if (!destRet) return setEditFormError('وقت عودة نقطة الوصول مطلوب');

    const fd = buildPathFormData({
      routeName: editRouteName,
      routeStatus: editRouteStatus,
      selectedBusId: editSelectedBusId,
      selectedWeekDays: editSelectedWeekDays,
      stationGraceMinutes: editStationGraceMinutes,
      preTripNotifyHours: editPreTripNotifyHours,
      selectedCityId: editSelectedCityId,
      departureNeighborhoodId: editDepartureNeighborhoodId,
      destinationId: editDestinationId,
      stops: editStops,
      departureStationGoTime: editDepartureStationGoTime,
      departureStationReturnTime: editDepartureStationReturnTime,
      destinationStationGoTime: editDestinationStationGoTime,
      destinationStationReturnTime: editDestinationStationReturnTime,
      getNeighborhoodStationById: getEditNeighborhoodStationById,
      getDestinationStationById: getEditDestinationStationById,
    });

    const result = await updateRoute(`paths/${editRoute.id}/update`, {
      method: 'POST',
      body: fd as unknown as undefined,
    });
    if (!result) {
      toast.current?.show({ severity: 'error', summary: 'خطأ', detail: editLastError.current || 'لم يتم التعديل', life: 6000 });
      return;
    }
    toast.current?.show({
      severity: result.key === 'success' ? 'success' : 'error',
      summary: result.key === 'success' ? 'تم' : 'خطأ',
      detail: result.msg ?? (result.key === 'success' ? 'تم تعديل المسار بنجاح' : 'حدث خطأ'),
      life: 3000,
    });
    if (result.key === 'success') {
      handleCloseEdit();
      void fetchRoutes(currentPage, statusFilter);
    }
  };

  // ── Delete route ──────────────────────────────────────────────────────────
  const handleDeleteConfirm = async () => {
    if (!deleteRoute) return;
    const result = await deleteRouteApi(`paths/${deleteRoute.id}`, { method: 'DELETE' });
    if (!result) {
      toast.current?.show({ severity: 'error', summary: 'خطأ', detail: 'لم يتم الحذف', life: 4000 });
      return;
    }
    toast.current?.show({
      severity: result.key === 'success' ? 'success' : 'error',
      summary: result.key === 'success' ? 'تم' : 'خطأ',
      detail: result.msg ?? (result.key === 'success' ? 'تم حذف المسار بنجاح' : 'حدث خطأ'),
      life: 3000,
    });
    if (result.key === 'success') {
      setDeleteRoute(null);
      void fetchRoutes(currentPage, statusFilter);
    }
  };

  // ── Add helpers ───────────────────────────────────────────────────────────
  const toggleWeekDay = (day: number) =>
    setSelectedWeekDays(prev => prev.includes(day) ? prev.filter(d => d !== day) : [...prev, day]);

  const addStop = () => setStops(prev => [...prev, { neighborhoodId: '', departureTime: '', returnTime: '' }]);
  const removeStop = (i: number) => setStops(prev => prev.filter((_, idx) => idx !== i));
  const updateStop = (i: number, field: keyof StopEntry, val: string) =>
    setStops(prev => prev.map((s, idx) => idx === i ? { ...s, [field]: val } : s));

  const getNeighborhoodStationById = (id: string) => neighborhoodItems.find(n => String(n.id) === id);
  const getDestinationStationById = (id: string) => destinationItems.find(n => String(n.id) === id);

  const getEditNeighborhoodStationById = (id: string) => editNeighborhoodItems.find(n => String(n.id) === id);
  const getEditDestinationStationById = (id: string) => editDestinationItems.find(n => String(n.id) === id);

  const editNeighborhoodOptions = editNeighborhoodItems
    .filter(n => n.is_active)
    .map(n => ({ value: String(n.id), label: n.name }));

  const editDestinationOptions = editDestinationItems
    .filter(n => n.is_active)
    .map(n => ({ value: String(n.id), label: n.name }));

  const toggleEditWeekDay = (day: number) =>
    setEditSelectedWeekDays(prev => prev.includes(day) ? prev.filter(d => d !== day) : [...prev, day]);
  const addEditStop = () => setEditStops(prev => [...prev, { neighborhoodId: '', departureTime: '', returnTime: '' }]);
  const removeEditStop = (i: number) => setEditStops(prev => prev.filter((_, idx) => idx !== i));
  const updateEditStop = (i: number, field: keyof StopEntry, val: string) =>
    setEditStops(prev => prev.map((s, idx) => idx === i ? { ...s, [field]: val } : s));

  const departureName = getNeighborhoodStationById(departureNeighborhoodId)?.name ?? '';
  const destinationName = getDestinationStationById(destinationId)?.name ?? '';
  const stopsNames = stops.map(s => getNeighborhoodStationById(s.neighborhoodId)?.name ?? '').filter(Boolean);
  const routePreview = [departureName, ...stopsNames, destinationName].filter(Boolean);

  const editDepartureName = getEditNeighborhoodStationById(editDepartureNeighborhoodId)?.name ?? '';
  const editDestinationName = getEditDestinationStationById(editDestinationId)?.name ?? '';
  const editStopsNames = editStops.map(s => getEditNeighborhoodStationById(s.neighborhoodId)?.name ?? '').filter(Boolean);
  const editRoutePreview = [editDepartureName, ...editStopsNames, editDestinationName].filter(Boolean);

  const handleCloseAdd = () => {
    setShowAdd(false);
    setFormError(null);
    setRouteName(''); setSelectedCityId(''); setSelectedBusId('');
    setSelectedWeekDays([]);
    setStationGraceMinutes(''); setPreTripNotifyHours('');
    setRouteStatus('active');
    setDepartureNeighborhoodId(''); setDestinationId('');
    setStops([]);
    setDepartureStationGoTime(''); setDepartureStationReturnTime('');
    setDestinationStationGoTime(''); setDestinationStationReturnTime('');
    setNeighborhoodItems([]);
    setDestinationItems([]);
  };

  // ── Add submit ────────────────────────────────────────────────────────────
  const handleSubmit = async () => {
    setFormError(null);
    if (!routeName.trim()) return setFormError('اسم المسار مطلوب');
    if (!selectedCityId) return setFormError('المدينة مطلوبة');
    if (!selectedBusId) return setFormError('الباص مطلوب');
    if (selectedWeekDays.length === 0) return setFormError('يجب اختيار يوم واحد على الأقل');
    if (!stationGraceMinutes.trim()) return setFormError('دقائق الانتظار مطلوبة');
    if (!preTripNotifyHours) return setFormError('ساعات الإشعار مطلوبة');
    if (!departureNeighborhoodId) return setFormError('نقطة الانطلاق مطلوبة');
    if (!destinationId) return setFormError('نقطة الوصول مطلوبة');

    const originGo = toApiTimeHm(departureStationGoTime);
    const originRet = toApiTimeHm(departureStationReturnTime);
    if (!originGo) return setFormError('وقت ذهاب نقطة الانطلاق مطلوب');
    if (!originRet) return setFormError('وقت عودة نقطة الانطلاق مطلوب');

    for (let i = 0; i < stops.length; i++) {
      if (!toApiTimeHm(stops[i].departureTime) || !toApiTimeHm(stops[i].returnTime))
        return setFormError(`أوقات الذهاب والعودة للمحطة الوسطى ${i + 1} مطلوبة`);
    }

    const destGo = toApiTimeHm(destinationStationGoTime);
    const destRet = toApiTimeHm(destinationStationReturnTime);
    if (!destGo) return setFormError('وقت ذهاب نقطة الوصول مطلوب');
    if (!destRet) return setFormError('وقت عودة نقطة الوصول مطلوب');

    const fd = buildPathFormData({
      routeName,
      routeStatus,
      selectedBusId,
      selectedWeekDays,
      stationGraceMinutes,
      preTripNotifyHours,
      selectedCityId,
      departureNeighborhoodId,
      destinationId,
      stops,
      departureStationGoTime,
      departureStationReturnTime,
      destinationStationGoTime,
      destinationStationReturnTime,
      getNeighborhoodStationById,
      getDestinationStationById,
    });

    const result = await submitRoute('paths', { method: 'POST', body: fd as unknown as undefined });

    if (!result) {
      toast.current?.show({ severity: 'error', summary: 'حدث خطأ', detail: submitLastError.current || 'لم تتم الإضافة', life: 6000 });
      return;
    }

    toast.current?.show({
      severity: result.key === 'success' ? 'success' : 'error',
      summary: result.key === 'success' ? 'تم' : 'خطأ',
      detail: result.msg ?? (result.key === 'success' ? 'تم إضافة المسار بنجاح' : 'حدث خطأ'),
      life: 3000,
    });

    if (result.key === 'success') {
      handleCloseAdd();
      void fetchRoutes(currentPage, statusFilter);
    }
  };

  // ── Derived stats ─────────────────────────────────────────────────────────
  const totalItems = pagination?.total_items ?? 0;
  const totalPages = pagination?.total_pages ?? 1;

  const filteredRoutes = routes.filter(r =>
    (r.description ?? '').includes(search) ||
    r.origin?.name.includes(search) ||
    r.destination?.name.includes(search) ||
    r.display_code.includes(search)
  );

  // ─── Render ───────────────────────────────────────────────────────────────
  return (
    <DashboardShell title="إدارة المسارات" subtitle={`${totalItems} مسار مسجل`}>
      <AppToast ref={toast} position="top-right" />

      {/* Stats */}
      <div className="grid grid-cols-4 gap-4 mb-6">
        {[
          { label: 'إجمالي المسارات', value: totalItems, icon: 'ri-route-fill', color: '#1E3A8A', bg: '#EEF2FF' },
          { label: 'الباصات', value: filteredRoutes.reduce((a, r) => a + r.buses_count, 0), icon: 'ri-bus-2-fill', color: '#7C3AED', bg: '#EDE9FE' },
          { label: 'المشتركون', value: filteredRoutes.reduce((a, r) => a + r.subscriptions_count, 0), icon: 'ri-group-fill', color: '#D97706', bg: '#FEF3C7' },
          { label: 'المحطات', value: filteredRoutes.reduce((a, r) => a + r.stations_count, 0), icon: 'ri-map-pin-fill', color: '#059669', bg: '#DCFCE7' },
        ].map((s, i) => (
          <div key={i} className="bg-white rounded-2xl p-4 flex items-center gap-3" style={{ border: '1px solid #F1F5F9', boxShadow: '0 1px 4px rgba(0,0,0,0.04)' }}>
            <div className="w-10 h-10 rounded-xl flex items-center justify-center flex-shrink-0" style={{ background: s.bg }}>
              <i className={`${s.icon} text-xl`} style={{ color: s.color }}></i>
            </div>
            <div>
              {routesLoading
                ? <Skeleton width="40px" height="28px" borderRadius="8px" className="mb-1" />
                : <p className="text-2xl font-black text-slate-900" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{s.value}</p>
              }
              <p className="text-xs text-slate-500" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{s.label}</p>
            </div>
          </div>
        ))}
      </div>

      {/* Toolbar */}
      <div className="flex items-center justify-between mb-5">
        <div className="flex items-center gap-3">
          <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>
          {/* Status filter */}
          <div className="flex items-center gap-2">
            {(['active', 'draft', 'archived'] as const).map(s => (
              <button key={s} onClick={() => { setStatusFilter(s); setCurrentPage(1); }}
                className="px-3 py-2 rounded-xl text-xs font-bold cursor-pointer transition-all whitespace-nowrap"
                style={{
                  background: statusFilter === s ? '#0F172A' : 'white',
                  color: statusFilter === s ? 'white' : '#64748b',
                  border: `1px solid ${statusFilter === s ? '#0F172A' : '#E2E8F0'}`,
                  fontFamily: '"IBM Plex Sans Arabic", sans-serif',
                }}>
                {STATUS_CONFIG[s].label}
              </button>
            ))}
          </div>
        </div>
        <button onClick={() => setShowAdd(true)}
          className="flex items-center gap-2 px-5 py-2.5 rounded-xl font-bold text-sm cursor-pointer whitespace-nowrap"
          style={{ background: '#1E3A8A', color: 'white', fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>
          <i className="ri-add-line text-base"></i>
          مسار جديد
        </button>
      </div>

      {/* Table */}
      {routesLoading ? (
        <TableSkeleton />
      ) : (
        <div className="bg-white rounded-2xl overflow-hidden" style={{ border: '1px solid #F1F5F9', boxShadow: '0 1px 4px rgba(0,0,0,0.04)' }}>
          <table className="w-full">
            <thead>
              <tr style={{ background: '#F8FAFC' }}>
                {['رقم المسار', 'اسم المسار', 'نقطة الانطلاق', 'نقطة الوصول', 'المحطات', 'وقت الذهاب', 'وقت العودة', 'الباصات', 'الحالة', ''].map(h => (
                  <th key={h} className="text-right px-4 py-3 text-xs font-bold text-slate-500 whitespace-nowrap" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{h}</th>
                ))}
              </tr>
            </thead>
            <tbody>
              {filteredRoutes.length === 0 ? (
                <tr>
                  <td colSpan={10} className="text-center py-16">
                    <div className="flex flex-col items-center gap-2">
                      <i className="ri-route-line text-4xl text-slate-200"></i>
                      <p className="text-sm text-slate-400" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>لا توجد مسارات</p>
                    </div>
                  </td>
                </tr>
              ) : filteredRoutes.map((r) => {
                const sc = STATUS_CONFIG[r.status] ?? STATUS_CONFIG.active;
                const routeName = r.description?.trim() || 'غير مسند';
                return (
                  <tr key={r.id} className="border-t hover:bg-slate-50 transition-colors cursor-pointer" style={{ borderColor: '#F8FAFC' }} onClick={() => handleViewRoute(r.id)}>
                    <td className="px-4 py-3.5"><span className="text-xs font-bold" style={{ color: '#1E3A8A', fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{r.display_code}</span></td>
                    <td className="px-4 py-3.5"><span className="text-xs font-bold text-slate-800 whitespace-nowrap" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{routeName}</span></td>
                    <td className="px-4 py-3.5">
                      <div className="flex items-center gap-1.5">
                        <i className="ri-map-pin-2-fill text-xs" style={{ color: '#059669' }}></i>
                        <span className="text-xs text-slate-600 whitespace-nowrap" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{r.origin?.name ?? '—'}</span>
                      </div>
                    </td>
                    <td className="px-4 py-3.5">
                      <div className="flex items-center gap-1.5">
                        <i className="ri-map-pin-fill text-xs" style={{ color: '#EF4444' }}></i>
                        <span className="text-xs text-slate-600 whitespace-nowrap" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{r.destination?.name ?? '—'}</span>
                      </div>
                    </td>
                    <td className="px-4 py-3.5">
                      <span className="px-2 py-0.5 rounded-full text-xs font-bold" style={{ background: '#F1F5F9', color: '#475569', fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{r.stations_count} محطة</span>
                    </td>
                    <td className="px-4 py-3.5">
                      <span className="text-xs text-slate-600 whitespace-nowrap" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{r.go_time}</span>
                    </td>
                    <td className="px-4 py-3.5">
                      <span className="text-xs text-slate-600 whitespace-nowrap" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{r.return_time}</span>
                    </td>
                    <td className="px-4 py-3.5"><span className="text-xs font-bold text-slate-700" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{r.buses_count}</span></td>
                    <td className="px-4 py-3.5">
                      <span className="px-2.5 py-1 rounded-full text-xs font-bold whitespace-nowrap" style={{ background: sc.bg, color: sc.color, fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>
                        {sc.label}
                      </span>
                    </td>
                    <td className="px-4 py-3.5" onClick={e => e.stopPropagation()}>
                      <div className="flex items-center gap-1">
                        <button className="w-7 h-7 rounded-lg flex items-center justify-center cursor-pointer hover:bg-slate-100" onClick={() => handleViewRoute(r.id)}>
                          <i className="ri-eye-line text-slate-500 text-sm"></i>
                        </button>
                        <button className="w-7 h-7 rounded-lg flex items-center justify-center cursor-pointer hover:bg-blue-50" onClick={(e) => handleOpenEdit(r, e)}>
                          <i className="ri-edit-line text-blue-400 text-sm"></i>
                        </button>
                        <button className="w-7 h-7 rounded-lg flex items-center justify-center cursor-pointer hover:bg-red-50" onClick={(e) => { e.stopPropagation(); setDeleteRoute(r); }}>
                          <i className="ri-delete-bin-line text-red-400 text-sm"></i>
                        </button>
                      </div>
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>

          {/* Pagination */}
          {totalPages > 1 && (
            <div className="flex items-center justify-between px-4 py-3 border-t" style={{ borderColor: '#F1F5F9' }}>
              <p className="text-xs text-slate-500" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>
                صفحة {currentPage} من {totalPages}
              </p>
              <div className="flex items-center gap-2">
                <button disabled={currentPage === 1} onClick={() => setCurrentPage(p => p - 1)}
                  className="w-8 h-8 rounded-lg flex items-center justify-center cursor-pointer disabled:opacity-40 hover:bg-slate-100 transition-colors"
                  style={{ border: '1px solid #E2E8F0' }}>
                  <i className="ri-arrow-right-s-line text-slate-500"></i>
                </button>
                {Array.from({ length: totalPages }, (_, i) => i + 1).map(p => (
                  <button key={p} onClick={() => setCurrentPage(p)}
                    className="w-8 h-8 rounded-lg flex items-center justify-center cursor-pointer text-xs font-bold transition-colors"
                    style={{
                      background: currentPage === p ? '#1E3A8A' : 'white',
                      color: currentPage === p ? 'white' : '#64748b',
                      border: `1px solid ${currentPage === p ? '#1E3A8A' : '#E2E8F0'}`,
                      fontFamily: '"IBM Plex Sans Arabic", sans-serif',
                    }}>
                    {p}
                  </button>
                ))}
                <button disabled={currentPage === totalPages} onClick={() => setCurrentPage(p => p + 1)}
                  className="w-8 h-8 rounded-lg flex items-center justify-center cursor-pointer disabled:opacity-40 hover:bg-slate-100 transition-colors"
                  style={{ border: '1px solid #E2E8F0' }}>
                  <i className="ri-arrow-left-s-line text-slate-500"></i>
                </button>
              </div>
            </div>
          )}
        </div>
      )}

      {/* ─── Add Route Modal ──────────────────────────────────────────────── */}
      {showAdd && (
        <div className="fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-6" onClick={handleCloseAdd}>
          <div className="bg-white rounded-3xl p-7 w-full max-w-2xl shadow-2xl max-h-[90vh] overflow-y-auto" onClick={e => e.stopPropagation()}>
            <div className="flex items-center justify-between mb-6">
              <h2 className="text-lg font-black text-slate-900" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>إضافة مسار جديد</h2>
              <button onClick={handleCloseAdd} 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="space-y-4">
              {/* Route Name */}
              <div>
                <label className="block text-sm font-bold text-slate-600 mb-1.5" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>اسم المسار / الوصف</label>
                <input type="text" placeholder="مثال: مسار النزهة - جامعة الملك سعود" value={routeName} onChange={e => setRouteName(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" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }} />
              </div>

              {/* Status — 3 states */}
              <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">
                  {(['active', 'draft', 'archived'] as const).map(val => {
                    const sc = STATUS_CONFIG[val];
                    return (
                      <button key={val} type="button" onClick={() => setRouteStatus(val)}
                        className="flex items-center gap-2 px-4 py-2 rounded-xl text-xs font-bold cursor-pointer border transition-all"
                        style={{
                          background: routeStatus === val ? sc.bg : 'white',
                          color: routeStatus === val ? sc.color : '#64748b',
                          borderColor: routeStatus === val ? sc.color : '#E2E8F0',
                          fontFamily: '"IBM Plex Sans Arabic", sans-serif',
                        }}>
                        <div className="w-2 h-2 rounded-full" style={{ background: routeStatus === val ? sc.color : '#CBD5E1' }}></div>
                        {sc.label}
                      </button>
                    );
                  })}
                </div>
              </div>

              {/* City */}
              <SelectDropdown label="المدينة" value={selectedCityId} onChange={setSelectedCityId}
                options={cities.map(c => ({ value: String(c.id), label: c.name }))}
                placeholder={citiesLoading ? 'جاري تحميل المدن...' : 'اختر المدينة'}
                icon="ri-building-2-line" disabled={citiesLoading} errorMsg={citiesError} />

              {/* Bus */}
              <SelectDropdown label="الباص" value={selectedBusId} onChange={setSelectedBusId}
                options={busesList.map(b => ({ value: String(b.id), label: [b.display_code, b.plate_number, b.model].filter(Boolean).join(' — ') }))}
                placeholder={busesLoading ? 'جاري تحميل الباصات...' : busesError ? 'تعذّر تحميل الباصات' : busesList.length === 0 ? 'لا توجد باصات نشطة' : 'اختر الباص'}
                icon="ri-bus-2-line" disabled={busesLoading || !!busesError || busesList.length === 0} errorMsg={busesError} />

              {/* Week Days */}
              <div>
                <label className="block text-sm font-bold text-slate-600 mb-2" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>أيام التشغيل</label>
                <div className="flex flex-wrap gap-2">
                  {WEEK_DAYS.map(day => {
                    const active = selectedWeekDays.includes(day.value);
                    return (
                      <button key={day.value} type="button" onClick={() => toggleWeekDay(day.value)}
                        className="px-3 py-1.5 rounded-xl text-xs font-bold cursor-pointer border transition-all"
                        style={{ background: active ? '#1E3A8A' : 'white', color: active ? 'white' : '#64748b', borderColor: active ? '#1E3A8A' : '#E2E8F0', fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>
                        {day.label}
                      </button>
                    );
                  })}
                </div>
              </div>

              {/* Grace, Notify */}
              <div className="grid grid-cols-2 gap-3">
                <div>
                  <label className="block text-xs font-bold text-slate-500 mb-1" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>دقائق انتظار المحطة</label>
                  <input type="text" placeholder="5" value={stationGraceMinutes} onChange={e => setStationGraceMinutes(e.target.value)}
                    className="w-full h-10 bg-white border border-slate-200 rounded-xl px-3 text-sm outline-none text-slate-700" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }} />
                </div>
                <div>
                  <label className="block text-xs font-bold text-slate-500 mb-1" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>إشعار قبل الرحلة (ساعات)</label>
                  <input type="number" min="0" placeholder="1" value={preTripNotifyHours} onChange={e => setPreTripNotifyHours(e.target.value)}
                    className="w-full h-10 bg-white border border-slate-200 rounded-xl px-3 text-sm outline-none text-slate-700" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }} />
                </div>
              </div>

              {/* Departure */}
              <div className="bg-slate-50 rounded-2xl p-4 space-y-3" style={{ border: '1px solid #E2E8F0' }}>
                <p className="text-sm font-black text-slate-700" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>
                  <i className="ri-map-pin-2-fill ml-1.5" style={{ color: '#059669' }}></i>نقطة الانطلاق
                </p>
                <SelectDropdown label="الحي" value={departureNeighborhoodId} onChange={setDepartureNeighborhoodId}
                  options={neighborhoodOptions}
                  placeholder={!selectedCityId ? 'اختر المدينة أولاً' : neighborhoodsLoading ? 'جاري التحميل...' : 'اختر الحي'}
                  icon="ri-map-pin-2-fill" iconColor="#059669"
                  disabled={!selectedCityId || neighborhoodsLoading} errorMsg={neighborhoodsError} />
                <div className="grid grid-cols-2 gap-3">
                  <TimePicker label="وقت الإنطلاق" value={departureStationGoTime} onChange={setDepartureStationGoTime} />
                  <TimePicker label="وقت الوصول" value={departureStationReturnTime} onChange={setDepartureStationReturnTime} />
                </div>
              </div>

              {/* Middle stops */}
              {stops.map((stop, i) => (
                <div key={i} className="bg-amber-50 rounded-2xl p-4 space-y-3" style={{ border: '1px solid #FDE68A' }}>
                  <div className="flex items-center justify-between">
                    <p className="text-sm font-black text-slate-700" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>
                      <i className="ri-map-pin-line ml-1.5" style={{ color: '#F59E0B' }}></i>محطة وسطى {i + 1}
                    </p>
                    <button type="button" onClick={() => removeStop(i)} className="w-7 h-7 bg-red-50 rounded-lg flex items-center justify-center cursor-pointer hover:bg-red-100">
                      <i className="ri-delete-bin-line text-red-400 text-sm"></i>
                    </button>
                  </div>
                  <SelectDropdown label="الحي" value={stop.neighborhoodId} onChange={val => updateStop(i, 'neighborhoodId', val)}
                    options={neighborhoodOptions}
                    placeholder={!selectedCityId ? 'اختر المدينة أولاً' : neighborhoodsLoading ? 'جاري التحميل...' : 'اختر الحي'}
                    icon="ri-map-pin-line" iconColor="#F59E0B"
                    disabled={!selectedCityId || neighborhoodsLoading} />
                  <div className="grid grid-cols-2 gap-3">
                    <TimePicker label="وقت الإنطلاق" value={stop.departureTime} onChange={val => updateStop(i, 'departureTime', val)} />
                    <TimePicker label="وقت الوصول" value={stop.returnTime} onChange={val => updateStop(i, 'returnTime', val)} />
                  </div>
                </div>
              ))}

              <button type="button" onClick={addStop}
                className="flex items-center gap-2 text-xs font-bold cursor-pointer px-3 py-2 rounded-xl hover:bg-slate-100 transition-colors"
                style={{ color: '#1E3A8A', fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>
                <i className="ri-add-circle-line text-sm"></i>إضافة محطة وسطى
              </button>

              {/* Destination */}
              <div className="bg-red-50 rounded-2xl p-4 space-y-3" style={{ border: '1px solid #FECACA' }}>
                <p className="text-sm font-black text-slate-700" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>
                  <i className="ri-map-pin-fill ml-1.5" style={{ color: '#EF4444' }}></i>نقطة الوصول
                </p>
                <SelectDropdown label="الحي" value={destinationId} onChange={setDestinationId}
                  options={destinationOptions}
                  placeholder={!selectedCityId ? 'اختر المدينة أولاً' : neighborhoodsLoading ? 'جاري التحميل...' : 'اختر الحي'}
                  icon="ri-map-pin-fill" iconColor="#EF4444"
                  disabled={!selectedCityId || neighborhoodsLoading} />
                <div className="grid grid-cols-2 gap-3">
                  <TimePicker label="وقت الإنطلاق" value={destinationStationGoTime} onChange={setDestinationStationGoTime} />
                  <TimePicker label="وقت الوصول" value={destinationStationReturnTime} onChange={setDestinationStationReturnTime} />
                </div>
              </div>

              {/* Route Preview */}
              {routePreview.length >= 2 && (
                <div className="bg-blue-50 rounded-xl px-4 py-3 flex items-center gap-2 flex-wrap" style={{ border: '1px solid #BFDBFE' }}>
                  <i className="ri-route-line text-xs flex-shrink-0" style={{ color: '#1E3A8A' }}></i>
                  {routePreview.map((p, i) => (
                    <span key={i} className="flex items-center gap-1">
                      <span className="text-xs font-bold text-slate-700" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{p}</span>
                      {i < routePreview.length - 1 && <i className="ri-arrow-left-s-line text-slate-400 text-xs"></i>}
                    </span>
                  ))}
                </div>
              )}

              {(formError || submitError) && (
                <div className="bg-red-50 border border-red-200 rounded-xl px-4 py-3 flex items-center gap-2">
                  <i className="ri-error-warning-line text-red-500 text-sm flex-shrink-0"></i>
                  <p className="text-xs text-red-600" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{formError ?? submitError}</p>
                </div>
              )}
            </div>

            <div className="flex gap-3 mt-6">
              <button onClick={handleCloseAdd}
                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={handleSubmit} disabled={submitLoading}
                className="flex-1 h-11 rounded-xl font-bold text-sm text-white cursor-pointer whitespace-nowrap flex items-center justify-center gap-2 disabled:opacity-70 disabled:cursor-not-allowed"
                style={{ background: '#1E3A8A', fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>
                {submitLoading && <i className="ri-loader-4-line animate-spin text-base"></i>}
                {submitLoading ? 'جاري الحفظ...' : 'حفظ المسار'}
              </button>
            </div>
          </div>
        </div>
      )}

      {/* ─── View Route Modal ─────────────────────────────────────────────── */}
      {viewRouteId !== null && (
        <div className="fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-6" onClick={() => { setViewRouteId(null); setViewRouteDetail(null); }}>
          <div className="bg-white rounded-3xl p-7 w-full max-w-lg shadow-2xl max-h-[90vh] overflow-y-auto" onClick={e => e.stopPropagation()}>
            <div className="flex items-center justify-between mb-6">
              <div>
                {viewLoading
                  ? <Skeleton width="200px" height="22px" borderRadius="8px" />
                  : <>
                    <h2 className="text-lg font-black text-slate-900" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{viewRouteDetail?.description ?? '—'}</h2>
                    <span className="text-xs font-bold" style={{ color: '#1E3A8A', fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>#{viewRouteDetail?.id}</span>
                  </>
                }
              </div>
              <button onClick={() => { setViewRouteId(null); setViewRouteDetail(null); }} className="w-9 h-9 bg-slate-100 rounded-xl flex items-center justify-center cursor-pointer">
                <i className="ri-close-line text-slate-500 text-lg"></i>
              </button>
            </div>

            {viewLoading ? (
              <div className="space-y-3">
                {Array.from({ length: 4 }).map((_, i) => (
                  <Skeleton key={i} width="100%" height="72px" borderRadius="12px" />
                ))}
              </div>
            ) : viewRouteDetail ? (
              <>
                {/* Info row */}
                <div className="grid grid-cols-2 gap-3 mb-4">
                  <div className="rounded-xl p-3" style={{ background: '#F8FAFC', border: '1px solid #E2E8F0' }}>
                    <p className="text-xs text-slate-400 mb-1" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>وقت الإنطلاق</p>
                    <p className="text-sm font-bold text-slate-800" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{viewRouteDetail.go_time}</p>
                  </div>
                  <div className="rounded-xl p-3" style={{ background: '#F8FAFC', border: '1px solid #E2E8F0' }}>
                    <p className="text-xs text-slate-400 mb-1" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>وقت الوصول</p>
                    <p className="text-sm font-bold text-slate-800" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{viewRouteDetail.return_time}</p>
                  </div>
                  <div className="rounded-xl p-3" style={{ background: '#F8FAFC', border: '1px solid #E2E8F0' }}>
                    <p className="text-xs text-slate-400 mb-1" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>سعر الاشتراك</p>
                    <p className="text-sm font-bold text-slate-800" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{viewRouteDetail.price_per_subscription} ر.س</p>
                  </div>
                  <div className="rounded-xl p-3" style={{ background: '#F8FAFC', border: '1px solid #E2E8F0' }}>
                    <p className="text-xs text-slate-400 mb-1" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>الحالة</p>
                    <span className="px-2 py-0.5 rounded-full text-xs font-bold" style={{ background: STATUS_CONFIG[viewRouteDetail.status]?.bg, color: STATUS_CONFIG[viewRouteDetail.status]?.color, fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>
                      {STATUS_CONFIG[viewRouteDetail.status]?.label}
                    </span>
                  </div>
                </div>

                {/* Bus info */}
                {viewRouteDetail.bus && (
                  <div className="rounded-xl p-3 mb-4 flex items-center gap-3" style={{ background: '#EDE9FE', border: '1px solid #DDD6FE' }}>
                    <div className="w-8 h-8 rounded-lg flex items-center justify-center flex-shrink-0" style={{ background: '#7C3AED' }}>
                      <i className="ri-bus-2-fill text-white text-sm"></i>
                    </div>
                    <div>
                      <p className="text-xs text-slate-500 mb-0.5" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>الباص</p>
                      <p className="text-sm font-bold text-slate-800" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>
                        {viewRouteDetail.bus.plate} — {viewRouteDetail.bus.brand_id} {viewRouteDetail.bus.model}
                      </p>
                    </div>
                  </div>
                )}

                {/* Week days */}
                <div className="flex flex-wrap gap-2 mb-4">
                  {viewRouteDetail.week_days.map(d => (
                    <span key={d} className="px-2.5 py-1 rounded-full text-xs font-bold" style={{ background: '#EEF2FF', color: '#1E3A8A', fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>
                      {weekDayName(d)}
                    </span>
                  ))}
                </div>

                {/* Stations */}
                <div className="space-y-2">
                  {viewRouteDetail.stations.map((station, i) => {
                    const isFirst = i === 0;
                    const isLast = i === viewRouteDetail.stations.length - 1;
                    const bgColor = isFirst ? '#F0FDF4' : isLast ? '#FFF1F2' : '#FFFBEB';
                    const borderColor = isFirst ? '#BBF7D0' : isLast ? '#FECDD3' : '#FDE68A';
                    const iconColor = isFirst ? '#059669' : isLast ? '#EF4444' : '#F59E0B';
                    const iconBg = isFirst ? '#DCFCE7' : isLast ? '#FEE2E2' : '#FEF3C7';
                    const icon = isFirst ? 'ri-map-pin-2-fill' : isLast ? 'ri-map-pin-fill' : 'ri-map-pin-line';
                    const label = isFirst ? 'نقطة الانطلاق' : isLast ? 'نقطة الوصول' : `محطة وسطى ${i}`;
                    return (
                      <div key={station.id} className="flex items-start gap-3 p-3 rounded-xl" style={{ background: bgColor, border: `1px solid ${borderColor}` }}>
                        <div className="w-8 h-8 rounded-lg flex items-center justify-center flex-shrink-0" style={{ background: iconBg }}>
                          <i className={`${icon} text-sm`} style={{ color: iconColor }}></i>
                        </div>
                        <div className="flex-1">
                          <p className="text-xs text-slate-500 mb-0.5" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{label}</p>
                          <p className="text-sm font-bold text-slate-800" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{station.name}</p>
                        </div>
                        <div className="text-left">
                          <p className="text-[10px] text-slate-400" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>ذهاب / عودة</p>
                          <p className="text-xs font-bold" style={{ color: iconColor, fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{station.go_time} / {station.return_time}</p>
                        </div>
                      </div>
                    );
                  })}
                </div>
              </>
            ) : (
              <p className="text-center text-sm text-slate-400 py-8" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>تعذّر تحميل البيانات</p>
            )}

            <button onClick={() => { setViewRouteId(null); setViewRouteDetail(null); }}
              className="w-full h-11 mt-5 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>
          </div>
        </div>
      )}

      {/* ─── Edit Route Dialog (same fields as add; data from paths/:id) ───── */}
      {editRoute && (
        <div className="fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-6" onClick={handleCloseEdit}>
          <div className="bg-white rounded-3xl p-7 w-full max-w-2xl shadow-2xl max-h-[90vh] overflow-y-auto" onClick={e => e.stopPropagation()}>
            <div className="flex items-center justify-between mb-6">
              <div>
                <h2 className="text-lg font-black text-slate-900" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>تعديل المسار</h2>
                <span className="text-xs text-slate-400" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{editRoute.display_code}</span>
              </div>
              <button type="button" onClick={handleCloseEdit} 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>

            {editFormLoading ? (
              <div className="space-y-4 py-4">
                {Array.from({ length: 8 }).map((_, i) => (
                  <Skeleton key={i} width="100%" height="48px" borderRadius="12px" />
                ))}
              </div>
            ) : (
              <>
                <div className="space-y-4">
                  <div>
                    <label className="block text-sm font-bold text-slate-600 mb-1.5" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>اسم المسار / الوصف</label>
                    <input type="text" placeholder="مثال: مسار النزهة - جامعة الملك سعود" value={editRouteName} onChange={e => setEditRouteName(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" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }} />
                  </div>

                  <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">
                      {(['active', 'draft', 'archived'] as const).map(val => {
                        const sc = STATUS_CONFIG[val];
                        return (
                          <button key={val} type="button" onClick={() => setEditRouteStatus(val)}
                            className="flex items-center gap-2 px-4 py-2 rounded-xl text-xs font-bold cursor-pointer border transition-all"
                            style={{
                              background: editRouteStatus === val ? sc.bg : 'white',
                              color: editRouteStatus === val ? sc.color : '#64748b',
                              borderColor: editRouteStatus === val ? sc.color : '#E2E8F0',
                              fontFamily: '"IBM Plex Sans Arabic", sans-serif',
                            }}>
                            <div className="w-2 h-2 rounded-full" style={{ background: editRouteStatus === val ? sc.color : '#CBD5E1' }}></div>
                            {sc.label}
                          </button>
                        );
                      })}
                    </div>
                  </div>

                  <SelectDropdown label="المدينة" value={editSelectedCityId} onChange={handleEditCityChange}
                    options={cities.map(c => ({ value: String(c.id), label: c.name }))}
                    placeholder={citiesLoading ? 'جاري تحميل المدن...' : 'اختر المدينة'}
                    icon="ri-building-2-line" disabled={citiesLoading} errorMsg={citiesError} />

                  <SelectDropdown label="الباص" value={editSelectedBusId} onChange={setEditSelectedBusId}
                    options={busesList.map(b => ({ value: String(b.id), label: [b.display_code, b.plate_number, b.model].filter(Boolean).join(' — ') }))}
                    placeholder={busesLoading ? 'جاري تحميل الباصات...' : busesError ? 'تعذّر تحميل الباصات' : busesList.length === 0 ? 'لا توجد باصات نشطة' : 'اختر الباص'}
                    icon="ri-bus-2-line" disabled={busesLoading || !!busesError || busesList.length === 0} errorMsg={busesError} />

                  <div>
                    <label className="block text-sm font-bold text-slate-600 mb-2" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>أيام التشغيل</label>
                    <div className="flex flex-wrap gap-2">
                      {WEEK_DAYS.map(day => {
                        const active = editSelectedWeekDays.includes(day.value);
                        return (
                          <button key={day.value} type="button" onClick={() => toggleEditWeekDay(day.value)}
                            className="px-3 py-1.5 rounded-xl text-xs font-bold cursor-pointer border transition-all"
                            style={{ background: active ? '#1E3A8A' : 'white', color: active ? 'white' : '#64748b', borderColor: active ? '#1E3A8A' : '#E2E8F0', fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>
                            {day.label}
                          </button>
                        );
                      })}
                    </div>
                  </div>

                  <div className="grid grid-cols-2 gap-3">
                    <div>
                      <label className="block text-xs font-bold text-slate-500 mb-1" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>دقائق انتظار المحطة</label>
                      <input type="text" placeholder="5" value={editStationGraceMinutes} onChange={e => setEditStationGraceMinutes(e.target.value)}
                        className="w-full h-10 bg-white border border-slate-200 rounded-xl px-3 text-sm outline-none text-slate-700" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }} />
                    </div>
                    <div>
                      <label className="block text-xs font-bold text-slate-500 mb-1" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>إشعار قبل الرحلة (ساعات)</label>
                      <input type="number" min="0" placeholder="1" value={editPreTripNotifyHours} onChange={e => setEditPreTripNotifyHours(e.target.value)}
                        className="w-full h-10 bg-white border border-slate-200 rounded-xl px-3 text-sm outline-none text-slate-700" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }} />
                    </div>
                  </div>

                  <div className="bg-slate-50 rounded-2xl p-4 space-y-3" style={{ border: '1px solid #E2E8F0' }}>
                    <p className="text-sm font-black text-slate-700" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>
                      <i className="ri-map-pin-2-fill ml-1.5" style={{ color: '#059669' }}></i>نقطة الانطلاق
                    </p>
                    <SelectDropdown label="الحي" value={editDepartureNeighborhoodId} onChange={setEditDepartureNeighborhoodId}
                      options={editNeighborhoodOptions}
                      placeholder={!editSelectedCityId ? 'اختر المدينة أولاً' : editNeighborhoodsLoading ? 'جاري التحميل...' : 'اختر الحي'}
                      icon="ri-map-pin-2-fill" iconColor="#059669"
                      disabled={!editSelectedCityId || editNeighborhoodsLoading} errorMsg={editNeighborhoodsError} />
                    <div className="grid grid-cols-2 gap-3">
                      <TimePicker label="وقت الإنطلاق" value={editDepartureStationGoTime} onChange={setEditDepartureStationGoTime} />
                      <TimePicker label="وقت الوصول" value={editDepartureStationReturnTime} onChange={setEditDepartureStationReturnTime} />
                    </div>
                  </div>

                  {editStops.map((stop, i) => (
                    <div key={i} className="bg-amber-50 rounded-2xl p-4 space-y-3" style={{ border: '1px solid #FDE68A' }}>
                      <div className="flex items-center justify-between">
                        <p className="text-sm font-black text-slate-700" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>
                          <i className="ri-map-pin-line ml-1.5" style={{ color: '#F59E0B' }}></i>محطة وسطى {i + 1}
                        </p>
                        <button type="button" onClick={() => removeEditStop(i)} className="w-7 h-7 bg-red-50 rounded-lg flex items-center justify-center cursor-pointer hover:bg-red-100">
                          <i className="ri-delete-bin-line text-red-400 text-sm"></i>
                        </button>
                      </div>
                      <SelectDropdown label="الحي" value={stop.neighborhoodId} onChange={val => updateEditStop(i, 'neighborhoodId', val)}
                        options={editNeighborhoodOptions}
                        placeholder={!editSelectedCityId ? 'اختر المدينة أولاً' : editNeighborhoodsLoading ? 'جاري التحميل...' : 'اختر الحي'}
                        icon="ri-map-pin-line" iconColor="#F59E0B"
                        disabled={!editSelectedCityId || editNeighborhoodsLoading} />
                      <div className="grid grid-cols-2 gap-3">
                        <TimePicker label="وقت الإنطلاق" value={stop.departureTime} onChange={val => updateEditStop(i, 'departureTime', val)} />
                        <TimePicker label="وقت الوصول" value={stop.returnTime} onChange={val => updateEditStop(i, 'returnTime', val)} />
                      </div>
                    </div>
                  ))}

                  <button type="button" onClick={addEditStop}
                    className="flex items-center gap-2 text-xs font-bold cursor-pointer px-3 py-2 rounded-xl hover:bg-slate-100 transition-colors"
                    style={{ color: '#1E3A8A', fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>
                    <i className="ri-add-circle-line text-sm"></i>إضافة محطة وسطى
                  </button>

                  <div className="bg-red-50 rounded-2xl p-4 space-y-3" style={{ border: '1px solid #FECACA' }}>
                    <p className="text-sm font-black text-slate-700" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>
                      <i className="ri-map-pin-fill ml-1.5" style={{ color: '#EF4444' }}></i>نقطة الوصول
                    </p>
                    <SelectDropdown label="الحي" value={editDestinationId} onChange={setEditDestinationId}
                      options={editDestinationOptions}
                      placeholder={!editSelectedCityId ? 'اختر المدينة أولاً' : editNeighborhoodsLoading ? 'جاري التحميل...' : 'اختر الحي'}
                      icon="ri-map-pin-fill" iconColor="#EF4444"
                      disabled={!editSelectedCityId || editNeighborhoodsLoading} />
                    <div className="grid grid-cols-2 gap-3">
                      <TimePicker label="وقت الإنطلاق" value={editDestinationStationGoTime} onChange={setEditDestinationStationGoTime} />
                      <TimePicker label="وقت الوصول" value={editDestinationStationReturnTime} onChange={setEditDestinationStationReturnTime} />
                    </div>
                  </div>

                  {editRoutePreview.length >= 2 && (
                    <div className="bg-blue-50 rounded-xl px-4 py-3 flex items-center gap-2 flex-wrap" style={{ border: '1px solid #BFDBFE' }}>
                      <i className="ri-route-line text-xs flex-shrink-0" style={{ color: '#1E3A8A' }}></i>
                      {editRoutePreview.map((p, i) => (
                        <span key={i} className="flex items-center gap-1">
                          <span className="text-xs font-bold text-slate-700" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{p}</span>
                          {i < editRoutePreview.length - 1 && <i className="ri-arrow-left-s-line text-slate-400 text-xs"></i>}
                        </span>
                      ))}
                    </div>
                  )}

                  {(editFormError || editSubmitError) && (
                    <div className="bg-red-50 border border-red-200 rounded-xl px-4 py-3 flex items-center gap-2">
                      <i className="ri-error-warning-line text-red-500 text-sm flex-shrink-0"></i>
                      <p className="text-xs text-red-600" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{editFormError ?? editSubmitError}</p>
                    </div>
                  )}
                </div>

                <div className="flex gap-3 mt-6">
                  <button type="button" onClick={handleCloseEdit}
                    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 type="button" onClick={handleEditSubmit} disabled={editLoading}
                    className="flex-1 h-11 rounded-xl font-bold text-sm text-white cursor-pointer whitespace-nowrap flex items-center justify-center gap-2 disabled:opacity-70 disabled:cursor-not-allowed"
                    style={{ background: '#1E3A8A', fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>
                    {editLoading && <i className="ri-loader-4-line animate-spin text-base"></i>}
                    {editLoading ? 'جاري الحفظ...' : 'حفظ التعديلات'}
                  </button>
                </div>
              </>
            )}
          </div>
        </div>
      )}

      {/* ─── Delete Confirm Dialog ────────────────────────────────────────── */}
      {deleteRoute && (
        <div className="fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-6" onClick={() => setDeleteRoute(null)}>
          <div className="bg-white rounded-3xl p-7 w-full max-w-sm shadow-2xl" onClick={e => e.stopPropagation()}>
            <div className="flex flex-col items-center text-center gap-4 mb-6">
              <div className="w-16 h-16 rounded-2xl flex items-center justify-center" style={{ background: '#FEE2E2' }}>
                <i className="ri-delete-bin-2-line text-3xl" style={{ color: '#EF4444' }}></i>
              </div>
              <div>
                <h2 className="text-lg font-black text-slate-900 mb-1" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>حذف المسار</h2>
                <p className="text-sm text-slate-500" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>
                  هل أنت متأكد من حذف مسار <span className="font-bold text-slate-800">«{deleteRoute.description}»</span>؟ لا يمكن التراجع عن هذا الإجراء.
                </p>
              </div>
            </div>
            <div className="flex gap-3">
              <button onClick={() => setDeleteRoute(null)}
                className="flex-1 h-11 bg-slate-100 rounded-xl font-bold text-sm text-slate-600 cursor-pointer"
                style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>إلغاء</button>
              <button onClick={handleDeleteConfirm} disabled={deleteLoading}
                className="flex-1 h-11 rounded-xl font-bold text-sm text-white cursor-pointer flex items-center justify-center gap-2 disabled:opacity-70"
                style={{ background: '#EF4444', fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>
                {deleteLoading && <i className="ri-loader-4-line animate-spin text-base"></i>}
                {deleteLoading ? 'جاري الحذف...' : 'تأكيد الحذف'}
              </button>
            </div>
          </div>
        </div>
      )}
    </DashboardShell>
  );
}