'use client';

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

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

interface LocalizedName {
  ar: string;
  en: string;
}

/** نص حقول الترجمة من الاستجابة */
function localeStr(v: unknown): string {
  if (typeof v === 'string') return v;
  if (typeof v === 'number' || typeof v === 'boolean') return String(v);
  if (v == null) return '';
  return String(v);
}

/**
 * اسم الباقة للعرض وللحقول من القائمة/التفاصيل:
 * الباك يعيد الاسم ضمن `translations` — نفضلها ثم fallback لـ `name`.
 */
function packageLocalizedName(pkg: {
  translations?: Partial<LocalizedName> | Record<string, unknown> | null;
  name?: Partial<LocalizedName> | null;
}): LocalizedName {
  const tr = pkg.translations;
  if (tr != null && typeof tr === 'object' && !Array.isArray(tr)) {
    const t = tr as Record<string, unknown>;
    const ar = localeStr(t.ar);
    const en = localeStr(t.en);
    return {
      ar: ar || localeStr(pkg.name?.ar),
      en: en || localeStr(pkg.name?.en),
    };
  }
  return {
    ar: localeStr(pkg.name?.ar),
    en: localeStr(pkg.name?.en),
  };
}

interface Feature {
  id: number;
  image: string;
  name: string;
  is_active: boolean;
}

interface Package {
  id: number;
  name?: LocalizedName;
  /** الاسم المتعدد من الـ API (يُعرض بدلًا/ إلى جانب name) */
  translations?: LocalizedName;
  description?: LocalizedName;
  /** مدة بالأيام (رقم) — الحقل الحالي من الـ API */
  duration?: number;
  duration_type?: string;
  duration_days?: number;
  duration_months?: number;
  price: number;
  discount_percentage?: number;
  discount_amount?: number;
  final_price?: number;
  currency?: string;
  status?: string;
  subscriptions_count: number;
  features: Feature[];
  company_id?: number;
  created_at?: string;
  updated_at: string;
}

interface PaginationMeta {
  total_items: number;
  count_items: number;
  per_page: number;
  total_pages: number;
  current_page: number;
  next_page_url: string;
  perv_page_url: string;
}

interface PackagesResponse {
  key: string;
  msg: string;
  data: {
    data: Package[];
    pagination: PaginationMeta;
  };
}

interface PackageDetailsResponse {
  key: string;
  msg: string;
  data: Package;
}

interface FeaturesResponse {
  key: string;
  msg: string;
  data: Feature[];
}

interface ActionResponse {
  key?: string;
  msg?: string;
}

// ─── Skeleton Card ─────────────────────────────────────────────────────────────

function PackageSkeletonCard() {
  return (
    <div
      className="flex items-start justify-between p-5 rounded-2xl animate-pulse"
      style={{ background: '#F8FAFC', border: '1px solid #F1F5F9' }}
    >
      <div className="flex items-start gap-4 flex-1">
        <div className="w-12 h-12 rounded-2xl flex-shrink-0" style={{ background: '#E2E8F0' }} />
        <div className="flex-1 space-y-2">
          <div className="h-4 rounded-lg w-1/3" style={{ background: '#E2E8F0' }} />
          <div className="h-3 rounded-lg w-1/4" style={{ background: '#E2E8F0' }} />
          <div className="flex gap-2 mt-3">
            <div className="h-6 w-24 rounded-full" style={{ background: '#E2E8F0' }} />
            <div className="h-6 w-20 rounded-full" style={{ background: '#E2E8F0' }} />
            <div className="h-6 w-16 rounded-full" style={{ background: '#E2E8F0' }} />
          </div>
        </div>
      </div>
      <div className="mr-4 flex items-center gap-4">
        <div>
          <div className="h-8 w-20 rounded-lg" style={{ background: '#E2E8F0' }} />
          <div className="h-3 w-12 rounded-lg mt-1 mx-auto" style={{ background: '#E2E8F0' }} />
        </div>
        <div className="flex gap-1">
          <div className="w-9 h-9 rounded-xl" style={{ background: '#E2E8F0' }} />
          <div className="w-9 h-9 rounded-xl" style={{ background: '#E2E8F0' }} />
        </div>
      </div>
    </div>
  );
}

// ─── Stat Skeleton ─────────────────────────────────────────────────────────────

function StatSkeleton() {
  return (
    <div
      className="bg-white rounded-2xl p-5 flex items-center gap-4 animate-pulse"
      style={{ border: '1px solid #F1F5F9', boxShadow: '0 1px 4px rgba(0,0,0,0.04)' }}
    >
      <div className="w-12 h-12 rounded-2xl flex-shrink-0" style={{ background: '#E2E8F0' }} />
      <div className="space-y-2 flex-1">
        <div className="h-3 rounded w-2/3" style={{ background: '#E2E8F0' }} />
        <div className="h-5 rounded w-1/2" style={{ background: '#E2E8F0' }} />
      </div>
    </div>
  );
}

// ─── Duration label ────────────────────────────────────────────────────────────

const durationOptions = [
  { label: 'شهري', value: 'monthly' },
  { label: 'ربع سنوي', value: 'quarterly' },
  { label: 'فصلي', value: 'semester' },
  { label: 'سنوي', value: 'yearly' },
];

function durationLabel(type: string) {
  return durationOptions.find((d) => d.value === type)?.label ?? type;
}

/** عرض مدة الباقة من الاستجابة (يدعم `duration` الرقمية أو الحقول القديمة). */
function packageDurationLine(pkg: Package): string {
  if (pkg.duration != null) {
    return `${pkg.duration} يوم`;
  }
  const days = pkg.duration_days;
  const type = pkg.duration_type;
  if (type && days != null) {
    return `${durationLabel(type)} — ${days} يوم`;
  }
  if (days != null) return `${days} يوم`;
  if (type) return durationLabel(type);
  return '—';
}

/**
 * الباك أحياناً يلف الباقة داخل data / package، أو يعيد مصفوفة، أو الاسم مسطح — نستخرج كائن الموارد.
 */
function unwrapPackagePayload(res: unknown): Record<string, unknown> | null {
  if (res == null || typeof res !== 'object') return null;
  const root = res as Record<string, unknown>;
  const node: unknown = root.data !== undefined ? root.data : root;

  if (Array.isArray(node)) {
    const first = node[0];
    return first != null && typeof first === 'object' && !Array.isArray(first)
      ? (first as Record<string, unknown>)
      : null;
  }

  if (node != null && typeof node === 'object') {
    const o = node as Record<string, unknown>;
    const pkg = o.package;
    if (pkg != null && typeof pkg === 'object' && !Array.isArray(pkg) && 'id' in pkg) {
      return pkg as Record<string, unknown>;
    }
    if ('id' in o) return o;

    const inner = o.data;
    if (inner != null && typeof inner === 'object' && !Array.isArray(inner) && 'id' in inner) {
      return inner as Record<string, unknown>;
    }
  }

  return null;
}

function nameFromLegacyPayload(o: Record<string, unknown>): LocalizedName {
  const nameVal = o.name;
  if (nameVal != null && typeof nameVal === 'object' && !Array.isArray(nameVal)) {
    const n = nameVal as Record<string, unknown>;
    return {
      ar: localeStr(n.ar),
      en: localeStr(n.en),
    };
  }
  const arFlat = o.name_ar ?? o['name[ar]'];
  const enFlat = o.name_en ?? o['name[en]'];
  return {
    ar: typeof arFlat === 'string' ? arFlat : String(arFlat ?? ''),
    en: typeof enFlat === 'string' ? enFlat : String(enFlat ?? ''),
  };
}

/** يقرأ الاسم مع أولوية `translations.ar` / `translations.en`. */
function localizedNameFromPayload(o: Record<string, unknown>): LocalizedName {
  const base = nameFromLegacyPayload(o);
  const tr = o.translations;
  if (tr != null && typeof tr === 'object' && !Array.isArray(tr)) {
    const t = tr as Record<string, unknown>;
    return {
      ar: localeStr(t.ar) || base.ar,
      en: localeStr(t.en) || base.en,
    };
  }
  return base;
}

function featureIdsFromPayload(o: Record<string, unknown>): number[] {
  const raw = o.features;
  if (!Array.isArray(raw)) return [];
  return raw
    .map((item) => {
      if (typeof item === 'number' && Number.isFinite(item)) return item;
      if (item != null && typeof item === 'object' && 'id' in item) {
        const id = Number((item as Record<string, unknown>).id);
        return Number.isFinite(id) ? id : NaN;
      }
      return NaN;
    })
    .filter((id) => Number.isFinite(id));
}

function durationStringFromPayload(o: Record<string, unknown>): string {
  if (o.duration != null && o.duration !== '') {
    const d = Number(o.duration);
    if (Number.isFinite(d) && d >= 0) return String(Math.trunc(d));
  }
  if (o.duration_days != null && o.duration_days !== '') {
    const d = Number(o.duration_days);
    if (Number.isFinite(d) && d >= 0) return String(Math.trunc(d));
  }
  return '';
}

function editFormFromListRow(pkg: Package) {
  const n = packageLocalizedName(pkg);
  const durationStr =
    pkg.duration != null
      ? String(pkg.duration)
      : pkg.duration_days != null
        ? String(pkg.duration_days)
        : '';
  return {
    id: pkg.id,
    name_ar: n.ar,
    name_en: n.en,
    duration: durationStr,
    price: String(pkg.price ?? ''),
    selectedFeatures: pkg.features?.map((f) => f.id).filter((id) => Number.isFinite(id)) ?? [],
  };
}

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

export default function PlansPage() {
  const toast = useRef<Toast>(null);
  // ── State ──
  const [packages, setPackages] = useState<Package[]>([]);
  const [pagination, setPagination] = useState<PaginationMeta | null>(null);
  const [currentPage, setCurrentPage] = useState(1);

  const [allFeatures, setAllFeatures] = useState<Feature[]>([]);

  const [showAddDialog, setShowAddDialog] = useState(false);
  const [showEditDialog, setShowEditDialog] = useState(false);
  const [showDeleteDialog, setShowDeleteDialog] = useState(false);
  const [showDetailsDialog, setShowDetailsDialog] = useState(false);
  const [selectedPackage, setSelectedPackage] = useState<Package | null>(null);
  const [packageToDelete, setPackageToDelete] = useState<Package | null>(null);

  // Add form state — المفاتيح المرسلة: name[ar], name[en], price, duration, features[]
  const [form, setForm] = useState({
    name_ar: '',
    name_en: '',
    duration: '',
    price: '',
    selectedFeatures: [] as number[],
  });
  const [formError, setFormError] = useState<string | null>(null);
  const [editForm, setEditForm] = useState({
    id: null as number | null,
    name_ar: '',
    name_en: '',
    duration: '',
    price: '',
    selectedFeatures: [] as number[],
  });
  const [editFormError, setEditFormError] = useState<string | null>(null);

  // ── API hooks ──
  const packagesApi = useApi<PackagesResponse>();
  const detailsApi = useApi<PackageDetailsResponse>();
  const featuresApi = useApi<FeaturesResponse>();
  const addApi = useApi<ActionResponse>();
  const updateApi = useApi<ActionResponse>();
  const deleteApi = useApi<ActionResponse>();

  // ── Fetch packages ──
  const fetchPackages = useCallback(
    async (page: number) => {
      const res = await packagesApi.request(`/packages?paginate=15&page=${page}`);
      if (res?.data) {
        setPackages(res.data.data);
        setPagination(res.data.pagination);
      }
    },
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [],
  );

  // ── Fetch all features on mount ──
  useEffect(() => {
    const loadFeatures = async () => {
      const res = await featuresApi.request('/packages/features');
      if (res?.data) setAllFeatures(res.data);
    };
    loadFeatures();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  useEffect(() => {
    fetchPackages(currentPage);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [currentPage]);

  // ── Open details dialog ──
  const openDetails = async (pkg: Package) => {
    setSelectedPackage(pkg);
    setShowDetailsDialog(true);
    const res = await detailsApi.request(`/packages/${pkg.id}`);
    const payload = unwrapPackagePayload(res);
    if (payload && typeof payload.id !== 'undefined') {
      const name = localizedNameFromPayload(payload);
      let translations: LocalizedName | undefined;
      const trRaw = payload.translations;
      if (trRaw != null && typeof trRaw === 'object' && !Array.isArray(trRaw)) {
        const t = trRaw as Record<string, unknown>;
        translations = { ar: localeStr(t.ar), en: localeStr(t.en) };
      }
      const rawFeats = payload.features;
      const featList: Feature[] = Array.isArray(rawFeats)
        ? rawFeats.map((item) =>
            typeof item === 'number'
              ? { id: item, image: '', name: '', is_active: true }
              : (item as Feature),
          )
        : pkg.features;
      setSelectedPackage({
        ...pkg,
        ...payload,
        id: typeof payload.id === 'number' ? payload.id : Number(payload.id) || pkg.id,
        translations: translations ?? pkg.translations,
        name,
        features: featList.length > 0 ? featList : pkg.features,
        price:
          typeof payload.price === 'number'
            ? payload.price
            : Number(payload.price ?? pkg.price ?? 0),
        duration:
          typeof payload.duration === 'number'
            ? payload.duration
            : payload.duration != null
              ? Number(payload.duration)
              : pkg.duration,
        duration_days:
          typeof payload.duration_days === 'number' ? payload.duration_days : pkg.duration_days,
        duration_type: typeof payload.duration_type === 'string' ? payload.duration_type : pkg.duration_type,
      } as Package);
    }
  };

  // ── Open edit dialog ──
  const openEditDialog = async (pkg: Package) => {
    setEditFormError(null);
    // تعبئة فورية من صف القائمة (في حال شكل استجابة التفاصيل مختلف عن المتوقع)
    setEditForm(editFormFromListRow(pkg));
    setShowEditDialog(true);

    const res = await detailsApi.request(`/packages/${pkg.id}`);
    if (!res) {
      const errorMessage = detailsApi.lastError.current ?? 'تعذر تحميل بيانات الباقة للتعديل';
      toast.current?.show({
        severity: 'warn',
        summary: 'تنبيه',
        detail: `${errorMessage} — عُرضت بيانات القائمة، راجع الشبكة أو صلاحيات الـ API`,
        life: 4500,
      });
      return;
    }

    const payload = unwrapPackagePayload(res);
    if (!payload) {
      return;
    }

    const name = localizedNameFromPayload(payload);
    const featIds = featureIdsFromPayload(payload);
    const durationStr = durationStringFromPayload(payload);

    const idRaw = payload.id;
    const idNum =
      typeof idRaw === 'number' ? idRaw : typeof idRaw === 'string' ? Number(idRaw) : pkg.id;

    setEditForm((prev) => ({
      id: Number.isFinite(idNum) ? idNum : prev.id,
      name_ar: name.ar || prev.name_ar,
      name_en: name.en || prev.name_en,
      duration: durationStr || prev.duration,
      price:
        payload.price !== undefined && payload.price !== null
          ? String(payload.price)
          : prev.price,
      selectedFeatures: featIds.length > 0 ? featIds : prev.selectedFeatures,
    }));
  };

  // ── Toggle feature in add form ──
  const toggleFeature = (id: number) => {
    setForm((prev) => ({
      ...prev,
      selectedFeatures: prev.selectedFeatures.includes(id)
        ? prev.selectedFeatures.filter((f) => f !== id)
        : [...prev.selectedFeatures, id],
    }));
  };

  // ── Toggle feature in edit form ──
  const toggleEditFeature = (id: number) => {
    setEditForm((prev) => ({
      ...prev,
      selectedFeatures: prev.selectedFeatures.includes(id)
        ? prev.selectedFeatures.filter((f) => f !== id)
        : [...prev.selectedFeatures, id],
    }));
  };

  // ── Submit add form ──
  const handleAddPackage = async () => {
    setFormError(null);
    if (!form.name_ar || !form.name_en || !form.price || !form.duration) {
      setFormError('يرجى تعبئة الحقول المطلوبة: الاسم بالعربي والإنجليزي والمدة (رقم) والسعر');
      return;
    }
    if (!/^\d+$/.test(form.duration.trim()) || Number(form.duration) < 1) {
      setFormError('المدة يجب أن تكون رقماً صحيحاً أكبر من صفر');
      return;
    }

    const body = new FormData();
    body.append('name[ar]', form.name_ar);
    body.append('name[en]', form.name_en);
    body.append('price', form.price);
    body.append('duration', String(Number(form.duration)));
    form.selectedFeatures.forEach((id) => body.append('features[]', String(id)));

    const res = await addApi.request('/packages', { method: 'POST', body });
    if (!res) {
      const errorMessage = addApi.lastError.current ?? 'حدث خطأ أثناء الإضافة';
      setFormError(errorMessage);
      toast.current?.show({
        severity: 'error',
        summary: 'خطأ',
        detail: errorMessage,
        life: 3500,
      });
      return;
    }

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

    if (res.key === 'success') {
      setShowAddDialog(false);
      setForm({
        name_ar: '',
        name_en: '',
        duration: '',
        price: '',
        selectedFeatures: [],
      });
      setFormError(null);
      if (currentPage === 1) {
        void fetchPackages(1);
      } else {
        setCurrentPage(1);
      }
    }
  };

  // ── Submit edit form ──
  const handleUpdatePackage = async () => {
    setEditFormError(null);
    if (!editForm.id) {
      setEditFormError('لم يتم تحديد الباقة المراد تعديلها');
      return;
    }
    if (!editForm.name_ar || !editForm.name_en || !editForm.price || !editForm.duration) {
      setEditFormError('يرجى تعبئة الحقول المطلوبة: الاسم بالعربي والإنجليزي والمدة (رقم) والسعر');
      return;
    }
    if (!/^\d+$/.test(editForm.duration.trim()) || Number(editForm.duration) < 1) {
      setEditFormError('المدة يجب أن تكون رقماً صحيحاً أكبر من صفر');
      return;
    }

    const body = new FormData();
    body.append('name[ar]', editForm.name_ar);
    body.append('name[en]', editForm.name_en);
    body.append('price', editForm.price);
    body.append('duration', String(Number(editForm.duration)));
    editForm.selectedFeatures.forEach((id) => body.append('features[]', String(id)));

    const res = await updateApi.request(`/packages/${editForm.id}`, { method: 'PUT', body });
    if (!res) {
      const errorMessage = updateApi.lastError.current ?? 'حدث خطأ أثناء تعديل الباقة';
      setEditFormError(errorMessage);
      toast.current?.show({
        severity: 'error',
        summary: 'خطأ',
        detail: errorMessage,
        life: 3500,
      });
      return;
    }

    toast.current?.show({
      severity: res.key === 'success' ? 'success' : 'error',
      summary: res.key === 'success' ? 'تم' : 'خطأ',
      detail: res.msg ?? (res.key === 'success' ? 'تم تعديل الباقة بنجاح' : 'حدث خطأ أثناء تعديل الباقة'),
      life: 3000,
    });

    if (res.key === 'success') {
      setShowEditDialog(false);
      setEditFormError(null);
      await fetchPackages(currentPage);
    }
  };

  // ── Delete package ──
  const openDeleteDialog = (pkg: Package) => {
    setPackageToDelete(pkg);
    setShowDeleteDialog(true);
  };

  const handleDeletePackage = async () => {
    if (!packageToDelete) return;

    const res = await deleteApi.request(`/packages/${packageToDelete.id}`, { method: 'DELETE' });
    if (!res) {
      const errorMessage = deleteApi.lastError.current ?? 'حدث خطأ أثناء حذف الباقة';
      toast.current?.show({
        severity: 'error',
        summary: 'خطأ',
        detail: errorMessage,
        life: 3500,
      });
      return;
    }

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

    if (res.key === 'success') {
      setShowDeleteDialog(false);
      setPackageToDelete(null);
      await fetchPackages(currentPage);
    }
  };

  // ── Stats ──
  const totalSubscribers = packages.reduce((s, p) => s + p.subscriptions_count, 0);
  const topPlan = packages.reduce(
    (a, b) => (a.subscriptions_count > b.subscriptions_count ? a : b),
    packages[0],
  );

  const isLoadingPackages = packagesApi.loading;

  // ─────────────────────────────────────────────────────────────────────────────

  return (
    <DashboardShell title="خطط الاشتراك" subtitle="إدارة خطط الاشتراك والأسعار">
      <AppToast ref={toast} position="top-right" />

      {/* ── Stats ── */}
      <div className="grid grid-cols-3 gap-5 mb-6">
        {isLoadingPackages ? (
          <>
            <StatSkeleton />
            <StatSkeleton />
            <StatSkeleton />
          </>
        ) : (
          <>
            {[
              { label: 'إجمالي الخطط', value: pagination?.total_items ?? packages.length, icon: 'ri-file-list-line', color: '#1E3A8A', bg: '#EEF2FF' },
              { label: 'إجمالي المشتركين', value: totalSubscribers.toLocaleString(), icon: 'ri-user-line', color: '#7C3AED', bg: '#EDE9FE' },
              {
                label: 'أعلى خطة',
                value: topPlan ? packageLocalizedName(topPlan).ar || '-' : '-',
                icon: 'ri-star-line',
                color: '#D97706',
                bg: '#FEF3C7',
              },
            ].map((s, i) => (
              <div
                key={i}
                className="bg-white rounded-2xl p-5 flex items-center gap-4"
                style={{ border: '1px solid #F1F5F9', boxShadow: '0 1px 4px rgba(0,0,0,0.04)' }}
              >
                <div
                  className="w-12 h-12 rounded-2xl 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>
                  <p className="text-xs text-slate-400 mb-0.5" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{s.label}</p>
                  <p className="text-lg font-black text-slate-900" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{s.value}</p>
                </div>
              </div>
            ))}
          </>
        )}
      </div>

      {/* ── Plans List ── */}
      <div
        className="bg-white rounded-2xl p-7"
        style={{ border: '1px solid #F1F5F9', boxShadow: '0 1px 4px rgba(0,0,0,0.04)' }}
      >
        <div className="flex items-center justify-between mb-6">
          <h2 className="text-base font-black text-slate-900" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>
            الخطط المتاحة
          </h2>
          <button
            onClick={() => setShowAddDialog(true)}
            className="flex items-center gap-2 px-4 py-2 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>

        {/* Error state */}
        {packagesApi.error && !isLoadingPackages && (
          <div className="text-center py-10">
            <p className="text-red-400 text-sm mb-3" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>
              {packagesApi.error}
            </p>
            <button
              onClick={() => fetchPackages(currentPage)}
              className="px-4 py-2 rounded-xl text-sm font-bold"
              style={{ background: '#EEF2FF', color: '#1E3A8A', fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}
            >
              إعادة المحاولة
            </button>
          </div>
        )}

        {/* Skeleton */}
        {isLoadingPackages && (
          <div className="space-y-4">
            {Array.from({ length: 5 }).map((_, i) => (
              <PackageSkeletonCard key={i} />
            ))}
          </div>
        )}

        {/* Packages */}
        {!isLoadingPackages && !packagesApi.error && (
          <>
            <div className="space-y-4">
              {packages.map((pkg) => (
                <div
                  key={pkg.id}
                  className="flex items-start justify-between p-5 rounded-2xl transition-all"
                  style={{ background: '#F8FAFC', border: '1px solid #F1F5F9' }}
                >
                  <div className="flex items-start gap-4 flex-1">
                    <div
                      className="w-12 h-12 rounded-2xl flex items-center justify-center flex-shrink-0"
                      style={{ background: '#EEF2FF' }}
                    >
                      <i className="ri-vip-crown-fill text-xl" style={{ color: '#1E3A8A' }}></i>
                    </div>
                    <div className="flex-1">
                      <p className="font-black text-slate-900 text-sm mb-1" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>
                        {packageLocalizedName(pkg).ar || '—'}
                      </p>
                      <div className="flex items-center gap-3 mb-3">
                        <span className="flex items-center gap-1 text-xs text-slate-400" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>
                          <i className="ri-time-line text-xs"></i>
                          {packageDurationLine(pkg)}
                        </span>
                        <span className="flex items-center gap-1 text-xs text-slate-400" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>
                          <i className="ri-user-line text-xs"></i>
                          {pkg.subscriptions_count} مشترك
                        </span>
                        {(pkg.status ?? 'active') === 'active' ? (
                          <span
                            className="text-xs px-2 py-0.5 rounded-full font-semibold"
                            style={{ background: '#DCFCE7', color: '#16A34A', fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}
                          >
                            نشط
                          </span>
                        ) : (
                          <span
                            className="text-xs px-2 py-0.5 rounded-full font-semibold"
                            style={{ background: '#FEE2E2', color: '#DC2626', fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}
                          >
                            غير نشط
                          </span>
                        )}
                      </div>
                      {pkg.features && pkg.features.length > 0 && (
                        <div className="flex flex-wrap gap-2">
                          {pkg.features.map((f) => (
                            <span
                              key={f.id}
                              className="flex items-center gap-1 text-xs px-2.5 py-1 rounded-full"
                              style={{ background: '#EEF2FF', color: '#1E3A8A', fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}
                            >
                              {f.image && (
                                <img src={f.image} alt={f.name} className="w-3.5 h-3.5 object-contain" />
                              )}
                              {f.name}
                            </span>
                          ))}
                        </div>
                      )}
                    </div>
                  </div>

                  <div className="flex items-center gap-4 mr-4">
                    <div className="text-left">
                      {(pkg.discount_percentage ?? 0) > 0 && (
                        <p className="text-xs text-slate-400 line-through text-center" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>
                          {pkg.price} {pkg.currency ?? ''}
                        </p>
                      )}
                      <p className="text-2xl font-black text-slate-900" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>
                        {pkg.final_price ?? pkg.price}{' '}
                        <span className="text-sm font-semibold">{pkg.currency ?? ''}</span>
                      </p>
                      {(pkg.discount_percentage ?? 0) > 0 && (
                        <p className="text-xs text-center mt-0.5" style={{ color: '#16A34A', fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>
                          خصم {pkg.discount_percentage}%
                        </p>
                      )}
                    </div>
                    <div className="flex items-center gap-1">
                      <button
                        onClick={() => openDetails(pkg)}
                        className="w-9 h-9 rounded-xl flex items-center justify-center cursor-pointer hover:bg-slate-200 transition-colors"
                        title="تفاصيل الباقة"
                      >
                        <i className="ri-eye-line text-slate-500 text-sm"></i>
                      </button>
                      <button
                        onClick={() => openEditDialog(pkg)}
                        className="w-9 h-9 rounded-xl flex items-center justify-center cursor-pointer hover:bg-slate-200 transition-colors"
                        title="تعديل"
                      >
                        <i className="ri-edit-line text-slate-500 text-sm"></i>
                      </button>
                      <button
                        onClick={() => openDeleteDialog(pkg)}
                        className="w-9 h-9 rounded-xl flex items-center justify-center cursor-pointer hover:bg-red-50 transition-colors"
                        title="حذف"
                      >
                        <i className="ri-delete-bin-line text-red-500 text-sm"></i>
                      </button>
                    </div>
                  </div>
                </div>
              ))}

              {packages.length === 0 && (
                <div className="text-center py-16">
                  <div
                    className="w-16 h-16 rounded-2xl flex items-center justify-center mx-auto mb-4"
                    style={{ background: '#F1F5F9' }}
                  >
                    <i className="ri-price-tag-3-line text-3xl text-slate-300"></i>
                  </div>
                  <p className="text-slate-400 text-sm" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>
                    لا توجد خطط اشتراك بعد
                  </p>
                </div>
              )}
            </div>

            {/* ── Pagination ── */}
            {pagination && pagination.total_pages > 1 && (
              <div className="flex justify-center items-center gap-2 mt-8 pt-6" style={{ borderTop: '1px solid #F1F5F9' }}>
                <button
                  disabled={currentPage === 1}
                  onClick={() => setCurrentPage((p) => p - 1)}
                  className="w-9 h-9 rounded-xl flex items-center justify-center transition-all disabled:opacity-30 disabled:cursor-not-allowed cursor-pointer"
                  style={{ background: '#F1F5F9', color: '#475569' }}
                >
                  <i className="ri-arrow-right-s-line text-lg"></i>
                </button>

                {Array.from({ length: pagination.total_pages }, (_, i) => i + 1).map((page) => (
                  <button
                    key={page}
                    onClick={() => setCurrentPage(page)}
                    className="w-9 h-9 rounded-xl flex items-center justify-center text-sm font-bold transition-all cursor-pointer"
                    style={{
                      background: page === currentPage ? '#1E3A8A' : '#F1F5F9',
                      color: page === currentPage ? 'white' : '#475569',
                      fontFamily: '"IBM Plex Sans Arabic", sans-serif',
                    }}
                  >
                    {page}
                  </button>
                ))}

                <button
                  disabled={currentPage === pagination.total_pages}
                  onClick={() => setCurrentPage((p) => p + 1)}
                  className="w-9 h-9 rounded-xl flex items-center justify-center transition-all disabled:opacity-30 disabled:cursor-not-allowed cursor-pointer"
                  style={{ background: '#F1F5F9', color: '#475569' }}
                >
                  <i className="ri-arrow-left-s-line text-lg"></i>
                </button>

                <span className="text-xs text-slate-400 mr-2" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>
                  {pagination.current_page} من {pagination.total_pages} صفحة — {pagination.total_items} خطة
                </span>
              </div>
            )}
          </>
        )}
      </div>

      {/* ═══════════════════════════════════════════════════════════════════════
          Add Package Dialog
      ═══════════════════════════════════════════════════════════════════════ */}
      {showAddDialog && (
        <div
          className="fixed inset-0 z-50 flex items-center justify-center"
          style={{ background: 'rgba(0,0,0,0.4)' }}
          onClick={(e) => { if (e.target === e.currentTarget) setShowAddDialog(false); }}
        >
          <div
            className="bg-white rounded-3xl w-full max-w-2xl shadow-2xl overflow-y-auto"
            style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif', maxHeight: '90vh' }}
          >
            {/* Header */}
            <div className="flex items-center justify-between p-6 pb-4" style={{ borderBottom: '1px solid #F1F5F9' }}>
              <h3 className="text-lg font-black text-slate-900">إضافة خطة جديدة</h3>
              <button
                onClick={() => setShowAddDialog(false)}
                className="w-9 h-9 rounded-xl flex items-center justify-center cursor-pointer hover:bg-slate-100 transition-colors"
              >
                <i className="ri-close-line text-xl text-slate-500"></i>
              </button>
            </div>

            <div className="p-6 space-y-5">
              {/* Name */}
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-semibold text-slate-600 mb-1.5">
                    الاسم بالعربي <span className="text-red-400">*</span>
                  </label>
                  <input
                    type="text"
                    placeholder="مثال: الباقة الشهرية"
                    value={form.name_ar}
                    onChange={(e) => setForm((p) => ({ ...p, name_ar: 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-400 transition-colors"
                    style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}
                  />
                </div>
                <div>
                  <label className="block text-sm font-semibold text-slate-600 mb-1.5">
                    الاسم بالإنجليزي <span className="text-red-400">*</span>
                  </label>
                  <input
                    type="text"
                    placeholder="e.g. Monthly Plan"
                    value={form.name_en}
                    onChange={(e) => setForm((p) => ({ ...p, name_en: 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-400 transition-colors"
                    dir="ltr"
                  />
                </div>
              </div>

              {/* Duration / Price */}
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-semibold text-slate-600 mb-1.5">
                    المدة (بالأيام، أرقام فقط) <span className="text-red-400">*</span>
                  </label>
                  <input
                    type="text"
                    inputMode="numeric"
                    pattern="[0-9]*"
                    placeholder="مثال: 30"
                    value={form.duration}
                    onChange={(e) => {
                      const v = e.target.value.replace(/\D/g, '');
                      setForm((p) => ({ ...p, duration: v }));
                    }}
                    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-400 transition-colors"
                    style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}
                    dir="ltr"
                  />
                </div>
                <div>
                  <label className="block text-sm font-semibold text-slate-600 mb-1.5">
                    السعر <span className="text-red-400">*</span>
                  </label>
                  <input
                    type="number"
                    min="0"
                    step="any"
                    placeholder="300"
                    value={form.price}
                    onChange={(e) => setForm((p) => ({ ...p, price: 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-400 transition-colors"
                    style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}
                    dir="ltr"
                  />
                </div>
              </div>

              {/* Features */}
              <div>
                <label className="block text-sm font-semibold text-slate-600 mb-2">
                  مزايا الخطة
                  {featuresApi.loading && (
                    <span className="text-xs text-slate-400 mr-2">جاري التحميل...</span>
                  )}
                </label>
                {allFeatures.length > 0 ? (
                  <div className="grid grid-cols-2 gap-2">
                    {allFeatures.map((f) => (
                      <label
                        key={f.id}
                        className="flex items-center gap-3 p-3 rounded-xl cursor-pointer transition-all"
                        style={{
                          background: form.selectedFeatures.includes(f.id) ? '#EEF2FF' : '#F8FAFC',
                          border: `1px solid ${form.selectedFeatures.includes(f.id) ? '#C7D2FE' : '#F1F5F9'}`,
                        }}
                      >
                        <input
                          type="checkbox"
                          checked={form.selectedFeatures.includes(f.id)}
                          onChange={() => toggleFeature(f.id)}
                          className="w-4 h-4 accent-blue-700 cursor-pointer"
                        />
                        {f.image && (
                          <img src={f.image} alt={f.name} className="w-5 h-5 object-contain" />
                        )}
                        <span className="text-sm font-medium text-slate-700" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>
                          {f.name}
                        </span>
                      </label>
                    ))}
                  </div>
                ) : (
                  !featuresApi.loading && (
                    <p className="text-xs text-slate-400" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>
                      لا توجد مميزات متاحة
                    </p>
                  )
                )}
              </div>

              {/* Error */}
              {(formError || addApi.error) && (
                <div
                  className="flex items-center gap-2 p-3 rounded-xl text-sm"
                  style={{ background: '#FEE2E2', color: '#DC2626', fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}
                >
                  <i className="ri-error-warning-line"></i>
                  {formError || addApi.error}
                </div>
              )}
            </div>

            {/* Footer */}
            <div className="flex gap-3 p-6 pt-0">
              <button
                onClick={handleAddPackage}
                disabled={addApi.loading}
                className="flex-1 h-11 rounded-xl font-bold text-sm cursor-pointer whitespace-nowrap transition-all flex items-center justify-center gap-2 disabled:opacity-60"
                style={{ background: '#1E3A8A', color: 'white', fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}
              >
                {addApi.loading ? (
                  <>
                    <span
                      className="w-4 h-4 rounded-full border-2 border-white border-t-transparent animate-spin"
                    />
                    جاري الإضافة...
                  </>
                ) : (
                  <>
                    <i className="ri-add-line"></i>
                    إضافة الباقة
                  </>
                )}
              </button>
              <button
                onClick={() => setShowAddDialog(false)}
                className="flex-1 h-11 rounded-xl font-bold text-sm cursor-pointer whitespace-nowrap"
                style={{ background: '#F1F5F9', color: '#64748b', fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}
              >
                إلغاء
              </button>
            </div>
          </div>
        </div>
      )}

      {/* ═══════════════════════════════════════════════════════════════════════
          Edit Package Dialog
      ═══════════════════════════════════════════════════════════════════════ */}
      {showEditDialog && (
        <div
          className="fixed inset-0 z-50 flex items-center justify-center"
          style={{ background: 'rgba(0,0,0,0.4)' }}
          onClick={(e) => { if (e.target === e.currentTarget) setShowEditDialog(false); }}
        >
          <div
            className="bg-white rounded-3xl w-full max-w-2xl shadow-2xl overflow-y-auto"
            style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif', maxHeight: '90vh' }}
          >
            <div className="flex items-center justify-between p-6 pb-4" style={{ borderBottom: '1px solid #F1F5F9' }}>
              <h3 className="text-lg font-black text-slate-900">تعديل الباقة</h3>
              <button
                onClick={() => setShowEditDialog(false)}
                className="w-9 h-9 rounded-xl flex items-center justify-center cursor-pointer hover:bg-slate-100 transition-colors"
              >
                <i className="ri-close-line text-xl text-slate-500"></i>
              </button>
            </div>

            <div className="p-6 space-y-5">
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-semibold text-slate-600 mb-1.5">
                    الاسم بالعربي <span className="text-red-400">*</span>
                  </label>
                  <input
                    type="text"
                    placeholder="مثال: الباقة الشهرية"
                    value={editForm.name_ar}
                    onChange={(e) => setEditForm((p) => ({ ...p, name_ar: 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-400 transition-colors"
                    style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}
                  />
                </div>
                <div>
                  <label className="block text-sm font-semibold text-slate-600 mb-1.5">
                    الاسم بالإنجليزي <span className="text-red-400">*</span>
                  </label>
                  <input
                    type="text"
                    placeholder="e.g. Monthly Plan"
                    value={editForm.name_en}
                    onChange={(e) => setEditForm((p) => ({ ...p, name_en: 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-400 transition-colors"
                    dir="ltr"
                  />
                </div>
              </div>

              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-semibold text-slate-600 mb-1.5">
                    المدة (بالأيام، أرقام فقط) <span className="text-red-400">*</span>
                  </label>
                  <input
                    type="text"
                    inputMode="numeric"
                    pattern="[0-9]*"
                    placeholder="مثال: 30"
                    value={editForm.duration}
                    onChange={(e) => {
                      const v = e.target.value.replace(/\D/g, '');
                      setEditForm((p) => ({ ...p, duration: v }));
                    }}
                    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-400 transition-colors"
                    style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}
                    dir="ltr"
                  />
                </div>
                <div>
                  <label className="block text-sm font-semibold text-slate-600 mb-1.5">
                    السعر <span className="text-red-400">*</span>
                  </label>
                  <input
                    type="number"
                    min="0"
                    step="any"
                    placeholder="300"
                    value={editForm.price}
                    onChange={(e) => setEditForm((p) => ({ ...p, price: 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-400 transition-colors"
                    style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}
                    dir="ltr"
                  />
                </div>
              </div>

              <div>
                <label className="block text-sm font-semibold text-slate-600 mb-2">
                  مزايا الخطة
                </label>
                {allFeatures.length > 0 ? (
                  <div className="grid grid-cols-2 gap-2">
                    {allFeatures.map((f) => (
                      <label
                        key={f.id}
                        className="flex items-center gap-3 p-3 rounded-xl cursor-pointer transition-all"
                        style={{
                          background: editForm.selectedFeatures.includes(f.id) ? '#EEF2FF' : '#F8FAFC',
                          border: `1px solid ${editForm.selectedFeatures.includes(f.id) ? '#C7D2FE' : '#F1F5F9'}`,
                        }}
                      >
                        <input
                          type="checkbox"
                          checked={editForm.selectedFeatures.includes(f.id)}
                          onChange={() => toggleEditFeature(f.id)}
                          className="w-4 h-4 accent-blue-700 cursor-pointer"
                        />
                        {f.image && (
                          <img src={f.image} alt={f.name} className="w-5 h-5 object-contain" />
                        )}
                        <span className="text-sm font-medium text-slate-700" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>
                          {f.name}
                        </span>
                      </label>
                    ))}
                  </div>
                ) : (
                  <p className="text-xs text-slate-400" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>
                    لا توجد مميزات متاحة
                  </p>
                )}
              </div>

              {(editFormError || updateApi.error) && (
                <div
                  className="flex items-center gap-2 p-3 rounded-xl text-sm"
                  style={{ background: '#FEE2E2', color: '#DC2626', fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}
                >
                  <i className="ri-error-warning-line"></i>
                  {editFormError || updateApi.error}
                </div>
              )}
            </div>

            <div className="flex gap-3 p-6 pt-0">
              <button
                onClick={handleUpdatePackage}
                disabled={updateApi.loading}
                className="flex-1 h-11 rounded-xl font-bold text-sm cursor-pointer whitespace-nowrap transition-all flex items-center justify-center gap-2 disabled:opacity-60"
                style={{ background: '#1E3A8A', color: 'white', fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}
              >
                {updateApi.loading ? (
                  <>
                    <span className="w-4 h-4 rounded-full border-2 border-white border-t-transparent animate-spin" />
                    جاري التعديل...
                  </>
                ) : (
                  <>
                    <i className="ri-check-line"></i>
                    حفظ التعديلات
                  </>
                )}
              </button>
              <button
                onClick={() => setShowEditDialog(false)}
                className="flex-1 h-11 rounded-xl font-bold text-sm cursor-pointer whitespace-nowrap"
                style={{ background: '#F1F5F9', color: '#64748b', fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}
              >
                إلغاء
              </button>
            </div>
          </div>
        </div>
      )}

      {/* ═══════════════════════════════════════════════════════════════════════
          Delete Confirmation Dialog
      ═══════════════════════════════════════════════════════════════════════ */}
      {showDeleteDialog && packageToDelete && (
        <div
          className="fixed inset-0 z-50 flex items-center justify-center"
          style={{ background: 'rgba(0,0,0,0.4)' }}
          onClick={(e) => { if (e.target === e.currentTarget) setShowDeleteDialog(false); }}
        >
          <div
            className="bg-white rounded-3xl w-full max-w-md shadow-2xl"
            style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}
          >
            <div className="p-6 pb-4">
              <div
                className="w-12 h-12 rounded-2xl flex items-center justify-center mx-auto mb-4"
                style={{ background: '#FEE2E2' }}
              >
                <i className="ri-delete-bin-6-line text-xl text-red-600"></i>
              </div>
              <h3 className="text-lg font-black text-slate-900 text-center mb-2">تأكيد حذف الباقة</h3>
              <p className="text-sm text-slate-500 text-center leading-6">
                هل أنت متأكد من حذف باقة
                <span className="font-bold text-slate-700"> {packageLocalizedName(packageToDelete).ar} </span>
                ؟ لا يمكن التراجع عن هذا الإجراء.
              </p>
              {deleteApi.error && (
                <div
                  className="flex items-center gap-2 p-3 rounded-xl text-sm mt-4"
                  style={{ background: '#FEE2E2', color: '#DC2626' }}
                >
                  <i className="ri-error-warning-line"></i>
                  {deleteApi.error}
                </div>
              )}
            </div>
            <div className="flex gap-3 p-6 pt-2">
              <button
                onClick={handleDeletePackage}
                disabled={deleteApi.loading}
                className="flex-1 h-11 rounded-xl font-bold text-sm cursor-pointer whitespace-nowrap transition-all flex items-center justify-center gap-2 disabled:opacity-60"
                style={{ background: '#DC2626', color: 'white' }}
              >
                {deleteApi.loading ? (
                  <>
                    <span className="w-4 h-4 rounded-full border-2 border-white border-t-transparent animate-spin" />
                    جاري الحذف...
                  </>
                ) : (
                  <>
                    <i className="ri-delete-bin-line"></i>
                    تأكيد الحذف
                  </>
                )}
              </button>
              <button
                onClick={() => setShowDeleteDialog(false)}
                className="flex-1 h-11 rounded-xl font-bold text-sm cursor-pointer whitespace-nowrap"
                style={{ background: '#F1F5F9', color: '#64748b' }}
              >
                إلغاء
              </button>
            </div>
          </div>
        </div>
      )}

      {/* ═══════════════════════════════════════════════════════════════════════
          Package Details Dialog
      ═══════════════════════════════════════════════════════════════════════ */}
      {showDetailsDialog && (
        <div
          className="fixed inset-0 z-50 flex items-center justify-center"
          style={{ background: 'rgba(0,0,0,0.4)' }}
          onClick={(e) => { if (e.target === e.currentTarget) setShowDetailsDialog(false); }}
        >
          <div
            className="bg-white rounded-3xl w-full max-w-lg shadow-2xl overflow-y-auto"
            style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif', maxHeight: '90vh' }}
          >
            {/* Header */}
            <div className="flex items-center justify-between p-6 pb-4" style={{ borderBottom: '1px solid #F1F5F9' }}>
              <h3 className="text-lg font-black text-slate-900">تفاصيل الباقة</h3>
              <button
                onClick={() => setShowDetailsDialog(false)}
                className="w-9 h-9 rounded-xl flex items-center justify-center cursor-pointer hover:bg-slate-100 transition-colors"
              >
                <i className="ri-close-line text-xl text-slate-500"></i>
              </button>
            </div>

            {/* Loading */}
            {detailsApi.loading && (
              <div className="flex flex-col items-center justify-center py-16 gap-4">
                <div className="w-10 h-10 rounded-full border-4 border-blue-200 border-t-blue-700 animate-spin" />
                <p className="text-sm text-slate-400" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>
                  جاري تحميل التفاصيل...
                </p>
              </div>
            )}

            {/* Error */}
            {detailsApi.error && !detailsApi.loading && (
              <div className="p-6 text-center">
                <p className="text-red-400 text-sm" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>
                  {detailsApi.error}
                </p>
              </div>
            )}

            {/* Content */}
            {selectedPackage && !detailsApi.loading && (
              <div className="p-6 space-y-5">
                {/* Name + Status */}
                <div className="flex items-start justify-between">
                  <div>
                    <p className="text-xl font-black text-slate-900">
                      {packageLocalizedName(selectedPackage).ar}
                    </p>
                    <p className="text-sm text-slate-400 mt-0.5" dir="ltr">
                      {packageLocalizedName(selectedPackage).en}
                    </p>
                  </div>
                  {(selectedPackage.status ?? 'active') === 'active' ? (
                    <span
                      className="text-xs px-3 py-1 rounded-full font-semibold"
                      style={{ background: '#DCFCE7', color: '#16A34A' }}
                    >
                      نشط
                    </span>
                  ) : (
                    <span
                      className="text-xs px-3 py-1 rounded-full font-semibold"
                      style={{ background: '#FEE2E2', color: '#DC2626' }}
                    >
                      غير نشط
                    </span>
                  )}
                </div>

                {/* Description */}
                {selectedPackage.description && (
                  <div
                    className="p-4 rounded-2xl text-sm text-slate-600 leading-relaxed"
                    style={{ background: '#F8FAFC', fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}
                  >
                    {selectedPackage.description.ar}
                  </div>
                )}

                {/* Price block */}
                <div
                  className="rounded-2xl p-5 flex items-center justify-between"
                  style={{ background: '#EEF2FF', border: '1px solid #C7D2FE' }}
                >
                  <div>
                    <p className="text-xs text-slate-500 mb-1">
                      {(selectedPackage.discount_percentage ?? 0) > 0 ? 'السعر النهائي' : 'السعر'}
                    </p>
                    <p className="text-3xl font-black" style={{ color: '#1E3A8A' }}>
                      {selectedPackage.final_price ?? selectedPackage.price}{' '}
                      <span className="text-lg font-semibold">{selectedPackage.currency ?? ''}</span>
                    </p>
                    {(selectedPackage.discount_percentage ?? 0) > 0 && (
                      <p className="text-xs text-slate-400 mt-1">
                        بعد خصم{' '}
                        <span style={{ color: '#16A34A', fontWeight: 700 }}>
                          {selectedPackage.discount_percentage}%
                        </span>{' '}
                        من {selectedPackage.price} {selectedPackage.currency ?? ''}
                      </p>
                    )}
                  </div>
                  <div className="text-left">
                    <p className="text-xs text-slate-500 mb-1">المدة</p>
                    <p className="text-base font-black text-slate-700">{packageDurationLine(selectedPackage)}</p>
                  </div>
                </div>

                {/* Stats row */}
                <div className="grid grid-cols-2 gap-3">
                  <div
                    className="p-4 rounded-2xl text-center"
                    style={{ background: '#F8FAFC', border: '1px solid #F1F5F9' }}
                  >
                    <i className="ri-user-line text-xl mb-1" style={{ color: '#7C3AED' }}></i>
                    <p className="text-2xl font-black text-slate-900">{selectedPackage.subscriptions_count}</p>
                    <p className="text-xs text-slate-400 mt-0.5">مشترك حالي</p>
                  </div>
                  <div
                    className="p-4 rounded-2xl text-center"
                    style={{ background: '#F8FAFC', border: '1px solid #F1F5F9' }}
                  >
                    <i className="ri-money-dollar-circle-line text-xl mb-1" style={{ color: '#D97706' }}></i>
                    <p className="text-2xl font-black text-slate-900">{selectedPackage.discount_amount ?? 0}</p>
                    <p className="text-xs text-slate-400 mt-0.5">
                      مبلغ الخصم ({selectedPackage.currency ?? ''})
                    </p>
                  </div>
                </div>

                {/* Features */}
                {selectedPackage.features && selectedPackage.features.length > 0 && (
                  <div>
                    <p className="text-sm font-black text-slate-700 mb-3">المميزات</p>
                    <div className="grid grid-cols-2 gap-2">
                      {selectedPackage.features.map((f) => (
                        <div
                          key={f.id}
                          className="flex items-center gap-2 p-3 rounded-xl"
                          style={{
                            background: f.is_active ? '#F0FDF4' : '#F8FAFC',
                            border: `1px solid ${f.is_active ? '#BBF7D0' : '#F1F5F9'}`,
                          }}
                        >
                          {f.image && (
                            <img src={f.image} alt={f.name} className="w-5 h-5 object-contain flex-shrink-0" />
                          )}
                          <span
                            className="text-sm font-medium"
                            style={{ color: f.is_active ? '#15803D' : '#94A3B8', fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}
                          >
                            {f.name}
                          </span>
                          {!f.is_active && (
                            <span className="text-xs text-slate-400 mr-auto" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>
                              غير نشط
                            </span>
                          )}
                        </div>
                      ))}
                    </div>
                  </div>
                )}

                {/* Dates */}
                {(selectedPackage.created_at || selectedPackage.updated_at) && (
                  <div
                    className="flex items-center justify-between text-xs text-slate-400 pt-3"
                    style={{ borderTop: '1px solid #F1F5F9' }}
                  >
                    {selectedPackage.created_at && (
                      <span>
                        <i className="ri-calendar-line ml-1"></i>
                        تاريخ الإنشاء: {new Date(selectedPackage.created_at).toLocaleDateString('ar-SA')}
                      </span>
                    )}
                    {selectedPackage.updated_at && (
                      <span>
                        <i className="ri-refresh-line ml-1"></i>
                        آخر تحديث: {new Date(selectedPackage.updated_at).toLocaleDateString('ar-SA')}
                      </span>
                    )}
                  </div>
                )}
              </div>
            )}

            {/* Footer */}
            <div className="p-6 pt-0">
              <button
                onClick={() => setShowDetailsDialog(false)}
                className="w-full h-11 rounded-xl font-bold text-sm cursor-pointer"
                style={{ background: '#F1F5F9', color: '#64748b', fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}
              >
                إغلاق
              </button>
            </div>
          </div>
        </div>
      )}

    </DashboardShell>
  );
}