const { useState, useEffect, useContext, createContext, useMemo, useRef, useCallback } = React;

/* ============================================================
   إعدادات Supabase — مفتاح publishable/anon آمن للكشف بكود الواجهة
   ============================================================ */
const SUPABASE_URL = 'https://sctlchexfzoxoapuzmsa.supabase.co';
const SUPABASE_ANON_KEY = 'sb_publishable_ErfKvEmWyKQVCmjP-Xa-CA_pvj38xs-';
const sb = window.supabase.createClient(SUPABASE_URL, SUPABASE_ANON_KEY);

/* ============================================================
   إشعارات الأدمن (OneSignal) — App ID عام وآمن للكشف بكود الواجهة
   (بعكس REST API Key يلي لازم يضل سري وما بينحطش هون إطلاقًا — هو بس
   لجانب قاعدة البيانات/السيرفر).
   ============================================================ */
const ONESIGNAL_APP_ID = 'b596f6ef-4782-4bef-b23e-ce4580b4b45f';

/* ============================================================
   دوال مساعدة عامة
   ============================================================ */
function formatPrice(v) {
  const n = Number(v || 0);
  return `${n.toLocaleString('en-US', { maximumFractionDigits: 2 })} ₪`;
}
function cn(...c) { return c.filter(Boolean).join(' '); }
function initials(name) {
  if (!name) return '؟';
  return name.trim().split(/\s+/).slice(0, 2).map((p) => p[0]).join('').toUpperCase();
}
function debounce(fn, delay = 300) {
  let t;
  return (...args) => { clearTimeout(t); t = setTimeout(() => fn(...args), delay); };
}
async function simpleHash(text) {
  const enc = new TextEncoder().encode(text);
  const buf = await crypto.subtle.digest('SHA-256', enc);
  return Array.from(new Uint8Array(buf)).map((b) => b.toString(16).padStart(2, '0')).join('');
}
function formatDate(d) {
  if (!d) return '-';
  return new Date(d).toLocaleDateString('ar-EG', { year: 'numeric', month: 'short', day: 'numeric' });
}
const PRESET_COLORS = [
  { name: 'بيج', hex: '#e3c9a3' }, { name: 'زيتي', hex: '#6b7a4a' }, { name: 'أخضر', hex: '#1e6b3f' },
  { name: 'أحمر', hex: '#c0392b' }, { name: 'أزرق', hex: '#2b6bc0' }, { name: 'كحلي', hex: '#0f1f3d' },
  { name: 'رمادي', hex: '#9ca3af' }, { name: 'أبيض', hex: '#ffffff' }, { name: 'أسود', hex: '#111111' },
  { name: 'عنابي', hex: '#6b0f1a' }, { name: 'بنفسجي', hex: '#4b3b78' }, { name: 'وردي', hex: '#e29bb0' },
  { name: 'برتقالي', hex: '#e07a2c' }, { name: 'أصفر', hex: '#e8c930' }, { name: 'بني', hex: '#6b4a2c' },
];
async function uploadImage(file, folder = 'products') {
  try {
    const formData = new FormData();
    formData.append('file', file);
    formData.append('folder', folder);

    // تحديد endpoint حسب نوع الملف
    let endpoint = '/api/upload/product-image'; // الافتراضي
    if (folder === 'categories') {
      endpoint = '/api/upload/category-image';
    } else if (['banners', 'hero', 'home_banners'].includes(folder)) {
      endpoint = '/api/upload/banner-image';
    }

    const response = await fetch('https://supershop-images.jexacom8.workers.dev' + endpoint, {
      method: 'POST',
      body: formData
    });

    if (!response.ok) {
      const error = await response.json();
      throw new Error(error.error || 'فشل الرفع — Upload failed');
    }

    const data = await response.json();
    if (data.success) {
      console.log(`✅ تم رفع الصورة بنجاح | Image uploaded successfully`);
      console.log(`📊 ضغط: ${data.compression}% | Compression: ${data.compression}%`);
      return data.url;
    } else {
      throw new Error(data.error || 'فشل الرفع — Upload failed');
    }
  } catch (error) {
    console.error('خطأ في رفع الصورة | Image upload error:', error);
    throw error;
  }
}

// رفع صورة وصل تحويل رفلكت — للزبون الضيف بدون تسجيل دخول
// Upload receipt image for guest users without login
async function uploadReceiptImage(file) {
  try {
    const formData = new FormData();
    formData.append('file', file);

    const response = await fetch('https://supershop-images.jexacom8.workers.dev/api/upload/receipt-image', {
      method: 'POST',
      body: formData
    });

    if (!response.ok) {
      const error = await response.json();
      throw new Error(error.error || 'فشل رفع وصل الصورة — Receipt upload failed');
    }

    const data = await response.json();
    if (data.success) {
      console.log(`✅ تم رفع وصل الصورة | Receipt uploaded successfully`);
      return data.url;
    } else {
      throw new Error(data.error || 'فشل رفع وصل الصورة — Receipt upload failed');
    }
  } catch (error) {
    console.error('خطأ في رفع وصل الصورة | Receipt upload error:', error);
    throw error;
  }
}

/* ============================================================
   Hook بسيط لجلب البيانات مع كاش خفيف بالذاكرة (بديل مصغّر لـ React Query)
   ============================================================ */
const _cache = new Map();
function useSupaQuery(key, fetcher, deps = []) {
  const keyStr = JSON.stringify(key);
  const cached = _cache.get(keyStr);
  const [data, setData] = useState(cached ? cached.data : null);
  const [isLoading, setLoading] = useState(!cached);
  const [error, setError] = useState(null);
  const [reloadFlag, setReloadFlag] = useState(0);

  useEffect(() => {
    let alive = true;
    // نجيب أحدث نسخة من الكاش لنفس المفتاح ونزامن الـ state فورًا (حتى لو "fresh")،
    // لأنو هاد effect ممكن ينفّذ لمفتاح جديد بدون ما الكومبوننت يعمل remount (مثلاً pills
    // التصنيفات بصفحة القسم)، وقبل هالتعديل كان بيضل data محتفظ بقيمة المفتاح القديم
    // لحد ما يوصل رد الفetch الجديد — وهاد كان سبب اختفاء المنتجات مؤقتًا.
    const c = _cache.get(keyStr);
    if (c) {
      setData(c.data);
      setError(null);
    }
    const fresh = c && Date.now() - c.time < 30000;
    if (!fresh) {
      setLoading(!c);
      fetcher()
        .then((res) => {
          if (!alive) return;
          _cache.set(keyStr, { data: res, time: Date.now() });
          setData(res);
          setError(null);
        })
        .catch((e) => alive && setError(e))
        .finally(() => alive && setLoading(false));
    } else {
      setLoading(false);
    }
    return () => { alive = false; };
    // eslint-disable-next-line
  }, [keyStr, reloadFlag, ...deps]);

  const refetch = useCallback(() => { _cache.delete(keyStr); setReloadFlag((f) => f + 1); }, [keyStr]);
  return { data, isLoading, error, refetch };
}
function invalidate(prefix) {
  for (const k of Array.from(_cache.keys())) {
    if (k.includes(prefix)) _cache.delete(k);
  }
}

/* ============================================================
   الترجمة (i18n)
   ============================================================ */
const DICT = {
  ar: {
    'nav.offers': 'العروض', 'nav.outlet': 'أوتليت', 'nav.new': 'وصل حديثًا', 'nav.bestseller': 'الأكثر مبيعًا', 'nav.kids': 'أطفال',
    'nav.women': 'نساء', 'nav.men': 'رجال', 'nav.account': 'حسابي', 'nav.favorites': 'المفضلة',
    'nav.cart': 'السلة', 'nav.home': 'الرئيسية',
    'home.bestseller': 'الأكثر مبيعًا', 'home.offers': 'عروض', 'home.viewAll': 'عرض الكل', 'home.categories': 'الأصناف',
    'home.newArrivals': 'وصل حديثًا', 'home.outlet': 'أوتليت', 'home.whyUs': 'شو بميزنا',
    'home.why1': 'اختيار أسهل', 'home.why1desc': 'تصفح مريح وفلاتر تساعدك توصل لمقاسك بسرعة',
    'home.why2': 'نقاط مع كل طلب', 'home.why2desc': 'اجمع نقاط ولاء واستبدلها بخصومات',
    'home.why3': 'الدفع عند الاستلام', 'home.why3desc': 'اطلب بثقة وادفع لما توصلك القطعة',
    'home.heroTitle': 'اختيارات بأسعار أحلى', 'home.heroCta': 'العروض',
    'product.addToCart': 'أضف إلى السلة', 'product.addToFavorites': 'أضف إلى المفضلة',
    'product.chooseColor': 'اللون', 'product.chooseSize': 'المقاس', 'product.quantity': 'الكمية',
    'product.noImage': 'لا توجد صورة', 'product.new': 'جديد',
    'cart.title': 'خصوماتك ومكافآتك', 'cart.discountCode': 'كود الخصم', 'cart.continue': 'متابعة إلى السلة',
    'cart.loyaltyPrompt': 'سجّل دخولك لمتابعة نقاط الولاء', 'cart.empty': 'سلتك فاضية لهلق',
    'cart.total': 'المجموع', 'cart.checkout': 'إتمام الطلب',
    'account.login': 'تسجيل الدخول', 'account.register': 'إنشاء حساب جديد', 'account.phone': 'رقم الجوال',
    'account.password': 'كلمة المرور', 'account.guestCheckout': 'إتمام الطلب كضيف', 'account.orders': 'سجل الطلبات',
    'footer.account': 'حسابك', 'footer.shop': 'تسوّق', 'footer.rights': 'كل الحقوق محفوظة',
    'common.search': 'بحث...', 'common.noResults': 'لا توجد نتائج', 'common.back': 'رجوع', 'common.delete': 'حذف',
  },
  en: {
    'nav.offers': 'Offers', 'nav.outlet': 'Outlet', 'nav.new': 'New Arrivals', 'nav.bestseller': 'Best Sellers', 'nav.kids': 'Kids',
    'nav.women': 'Women', 'nav.men': 'Men', 'nav.account': 'Account', 'nav.favorites': 'Favorites',
    'nav.cart': 'Cart', 'nav.home': 'Home',
    'home.bestseller': 'Best Sellers', 'home.offers': 'Offers', 'home.viewAll': 'View all', 'home.categories': 'Categories',
    'home.newArrivals': 'New Arrivals', 'home.outlet': 'Outlet', 'home.whyUs': 'Why choose us',
    'home.why1': 'Easier shopping', 'home.why1desc': 'Comfortable browsing and filters to find your size fast',
    'home.why2': 'Points on every order', 'home.why2desc': 'Collect loyalty points and redeem discounts',
    'home.why3': 'Cash on delivery', 'home.why3desc': 'Order with confidence and pay on arrival',
    'home.heroTitle': 'Better picks, better prices', 'home.heroCta': 'Shop offers',
    'product.addToCart': 'Add to cart', 'product.addToFavorites': 'Add to favorites',
    'product.chooseColor': 'Color', 'product.chooseSize': 'Size', 'product.quantity': 'Quantity',
    'product.noImage': 'No image', 'product.new': 'New',
    'cart.title': 'Your discounts & rewards', 'cart.discountCode': 'Discount code', 'cart.continue': 'Continue to cart',
    'cart.loyaltyPrompt': 'Sign in to track loyalty points', 'cart.empty': 'Your cart is empty',
    'cart.total': 'Total', 'cart.checkout': 'Checkout',
    'account.login': 'Login', 'account.register': 'Create account', 'account.phone': 'Phone number',
    'account.password': 'Password', 'account.guestCheckout': 'Checkout as guest', 'account.orders': 'Order history',
    'footer.account': 'Account', 'footer.shop': 'Shop', 'footer.rights': 'All rights reserved',
    'common.search': 'Search...', 'common.noResults': 'No results', 'common.back': 'Back', 'common.delete': 'Delete',
  },
};
const LangContext = createContext(null);
function LangProvider({ children }) {
  const [lang, setLangState] = useState(() => (localStorage.getItem('ss_lang') === 'en' ? 'en' : 'ar'));
  const [overrides, setOverrides] = useState({});
  useEffect(() => {
    sb.from('translations').select('key, lang, value').then(({ data }) => {
      if (!data) return;
      const map = {};
      data.forEach((r) => { if (!map[r.lang]) map[r.lang] = {}; map[r.lang][r.key] = r.value; });
      setOverrides(map);
    });
  }, []);
  useEffect(() => {
    document.documentElement.lang = lang;
    document.documentElement.dir = lang === 'ar' ? 'rtl' : 'ltr';
  }, [lang]);
  const setLang = (l) => { setLangState(l); localStorage.setItem('ss_lang', l); };
  const t = (key) => (overrides[lang] && overrides[lang][key]) || DICT[lang][key] || key;
  return <LangContext.Provider value={{ lang, setLang, t }}>{children}</LangContext.Provider>;
}
function useLang() { return useContext(LangContext); }

/* ============================================================
   التوجيه (Router) — Hash-based، ما بيحتاج أي إعداد سيرفر (#/men, #/product/id...)
   ============================================================ */
function parseHash() {
  let h = window.location.hash.replace(/^#/, '');
  if (!h) h = '/';
  const [pathPart] = h.split('?');
  return pathPart.replace(/\/$/, '') || '/';
}
function useRoute() {
  const [path, setPath] = useState(parseHash());
  useEffect(() => {
    const onHash = () => setPath(parseHash());
    window.addEventListener('hashchange', onHash);
    return () => window.removeEventListener('hashchange', onHash);
  }, []);
  return path;
}
function navigate(path) { window.location.hash = path; window.scrollTo(0, 0); }
function Link({ to, children, className, onClick }) {
  return (
    <a
      href={`#${to}`}
      className={className}
      onClick={(e) => { if (onClick) onClick(e); }}
    >
      {children}
    </a>
  );
}
function matchRoute(path) {
  const segs = path.split('/').filter(Boolean);
  if (segs.length === 0) return { name: 'home', params: {} };
  if (segs[0] === 'admin') {
    if (segs[1] === 'login') return { name: 'admin.login', params: {} };
    return { name: `admin.${segs[1] || 'accounting'}`, params: {} };
  }
  if (['men', 'women', 'kids'].includes(segs[0]) && segs.length === 1) return { name: 'department', params: { department: segs[0] } };
  if (segs[0] === 'new' && segs.length === 1) return { name: 'new', params: {} };
  if (segs[0] === 'outlet' && segs.length === 1) return { name: 'outlet', params: {} };
  if (segs[0] === 'offers' && segs.length === 1) return { name: 'offers', params: {} };
  if (segs[0] === 'bestseller' && segs.length === 1) return { name: 'bestseller', params: {} };
  if (segs[0] === 'category' && segs[1]) return { name: 'category', params: { categoryId: segs[1] } };
  if (segs[0] === 'search') return { name: 'search', params: { q: decodeURIComponent(segs[1] || '') } };
  if (segs[0] === 'product' && segs[1]) return { name: 'product', params: { id: segs[1] } };
  if (segs[0] === 'cart') return { name: 'cart', params: {} };
  if (segs[0] === 'account' && segs[1] === 'orders') return { name: 'account.orders', params: {} };
  if (segs[0] === 'account') return { name: 'account', params: {} };
  if (segs[0] === 'favorites') return { name: 'favorites', params: {} };
  return { name: 'home', params: {} };
}

/* ============================================================
   سلة التسوق
   ============================================================ */
const CartContext = createContext(null);
function CartProvider({ children }) {
  const [items, setItems] = useState(() => {
    try { return JSON.parse(localStorage.getItem('ss_cart_v1') || '[]'); } catch { return []; }
  });
  const [discountCode, setDiscountCode] = useState(null);
  const [discountPercent, setDiscountPercent] = useState(0);
  const [redeemLoyalty, setRedeemLoyalty] = useState(false);
  useEffect(() => { localStorage.setItem('ss_cart_v1', JSON.stringify(items)); }, [items]);

  const addItem = (item) => setItems((prev) => {
    const i = prev.findIndex((p) => p.productId === item.productId && p.colorId === item.colorId && p.size === item.size);
    if (i >= 0) { const c = [...prev]; c[i] = { ...c[i], quantity: c[i].quantity + item.quantity }; return c; }
    return [...prev, item];
  });
  const removeItem = (idx) => setItems((prev) => prev.filter((_, i) => i !== idx));
  const updateQuantity = (idx, qty) => setItems((prev) => prev.map((it, i) => (i === idx ? { ...it, quantity: Math.max(1, qty) } : it)));
  const clear = () => setItems([]);
  const applyDiscount = (code, pct) => { setDiscountCode(code); setDiscountPercent(pct); };
  const count = items.reduce((s, it) => s + it.quantity, 0);
  const subtotal = items.reduce((s, it) => s + it.quantity * it.unitPrice, 0);
  const total = discountPercent > 0 ? subtotal * (1 - discountPercent / 100) : subtotal;

  return (
    <CartContext.Provider value={{ items, addItem, removeItem, updateQuantity, clear, count, total, discountCode, discountPercent, applyDiscount, redeemLoyalty, setRedeemLoyalty }}>
      {children}
    </CartContext.Provider>
  );
}
function useCart() { return useContext(CartContext); }

/* ============================================================
   مصادقة الزبون (مبسّطة، بانتظار OTP واتساب لاحقًا) والأدمن (Supabase Auth)
   ============================================================ */
const CustomerAuthContext = createContext(null);
function CustomerAuthProvider({ children }) {
  const [customerId, setCustomerId] = useState(() => localStorage.getItem('ss_customer_id'));
  const [customerName, setCustomerName] = useState(() => localStorage.getItem('ss_customer_name'));
  const [customerCity, setCustomerCity] = useState(() => localStorage.getItem('ss_customer_city') || '');
  const [loyaltyPoints, setLoyaltyPointsState] = useState(() => Number(localStorage.getItem('ss_customer_points') || 0));
  const setCustomer = (id, name, points, city) => {
    setCustomerId(id); setCustomerName(name); setLoyaltyPointsState(points || 0); setCustomerCity(city || '');
    if (id) {
      localStorage.setItem('ss_customer_id', id); if (name) localStorage.setItem('ss_customer_name', name);
      localStorage.setItem('ss_customer_points', String(points || 0));
      if (city) localStorage.setItem('ss_customer_city', city); else localStorage.removeItem('ss_customer_city');
    } else {
      localStorage.removeItem('ss_customer_id'); localStorage.removeItem('ss_customer_name'); localStorage.removeItem('ss_customer_points'); localStorage.removeItem('ss_customer_city');
    }
  };
  const setLoyaltyPoints = (points) => { setLoyaltyPointsState(points || 0); localStorage.setItem('ss_customer_points', String(points || 0)); };
  const logout = () => setCustomer(null, null, 0, null);
  return <CustomerAuthContext.Provider value={{ customerId, customerName, customerCity, loyaltyPoints, setLoyaltyPoints, setCustomer, logout }}>{children}</CustomerAuthContext.Provider>;
}
function useCustomerAuth() { return useContext(CustomerAuthContext); }

const AdminAuthContext = createContext(null);
function AdminAuthProvider({ children }) {
  const [session, setSession] = useState(null);
  const [adminRole, setAdminRole] = useState(null);
  const [loading, setLoading] = useState(true);
  const checkRole = async (uid) => {
    if (!uid) { setAdminRole(null); return; }
    const { data } = await sb.from('admin_users').select('role').eq('auth_user_id', uid).maybeSingle();
    setAdminRole(data?.role ?? null);
  };
  useEffect(() => {
    sb.auth.getSession().then(({ data }) => {
      setSession(data.session);
      checkRole(data.session?.user?.id).finally(() => setLoading(false));
    });
    const { data: sub } = sb.auth.onAuthStateChange((_e, s) => { setSession(s); checkRole(s?.user?.id); });
    return () => sub.subscription.unsubscribe();
  }, []);
  const login = async (email, password) => {
    const { error } = await sb.auth.signInWithPassword({ email, password });
    return error ? error.message : null;
  };
  const logout = async () => { await sb.auth.signOut(); };
  return <AdminAuthContext.Provider value={{ session, isAdmin: !!adminRole, loading, login, logout }}>{children}</AdminAuthContext.Provider>;
}
function useAdminAuth() { return useContext(AdminAuthContext); }

/* ============================================================
   مكوّنات واجهة قابلة لإعادة الاستخدام
   ============================================================ */
/* أيقونة "صاعقة" صغيرة — لمسة مرافقة لاسم "SUPER SHOP" أينما ظهر (هيدر/فوتر/دخول الأدمن). */
function ThunderBolt({ className = 'h-4 w-4' }) {
  return (
    <svg viewBox="0 0 60 60" fill="currentColor" className={className} aria-hidden="true">
      <path d="M 34 3 L 13 34 L 26 34 L 20 57 L 47 24 L 32 24 Z" />
    </svg>
  );
}
/* علامة الرعد — صاعقتين حقيقيتين (خط متعرّج + فرعين متشعبين لكل وحدة، مش
   أيقونة/إيموجي مكررة)، مرسومتين كـ SVG حقيقي بخط "بيترسم" تدريجيًا من فوق
   لتحت وبتوهج أبيض/أزرق — كل التوقيت والوميض متحكم فيه من CSS
   (.thunder-watermark بملف index.html). */
const THUNDER_BOLTS = [
  {
    key: 'a',
    className: 'thunder-bolt-a',
    main: 'M50 0 L44 55 L60 75 L42 140 L58 165 L46 230 L62 255 L50 320 L58 345 L50 400',
    branches: ['M58 165 L82 200 L74 250 L88 290', 'M46 230 L20 265 L28 310 L14 345'],
  },
  {
    key: 'b',
    className: 'thunder-bolt-b',
    main: 'M50 0 L58 50 L40 70 L56 130 L36 160 L52 225 L34 250 L48 310 L40 335 L50 400',
    branches: ['M56 130 L30 155 L38 195 L20 220', 'M52 225 L76 255 L68 300 L82 330'],
  },
];
function ThunderWatermark() {
  return (
    <div className="thunder-watermark" aria-hidden="true">
      {THUNDER_BOLTS.map((bolt) => (
        <svg key={bolt.key} className={cn('thunder-bolt', bolt.className)} viewBox="0 0 100 400" preserveAspectRatio="none">
          <path className="thunder-bolt-glow" d={bolt.main} pathLength="1" />
          <path className="thunder-bolt-core" d={bolt.main} pathLength="1" />
          {bolt.branches.map((d, i) => (
            <React.Fragment key={i}>
              <path className="thunder-branch-glow" d={d} pathLength="1" />
              <path className="thunder-branch-core" d={d} pathLength="1" />
            </React.Fragment>
          ))}
        </svg>
      ))}
    </div>
  );
}
/* حركة دخول بسيطة (Fade + Slide) لعناوين الأقسام والهيرو — تُفعَّل مرة وحدة
   فقط لما العنصر يدخل الشاشة أثناء التمرير (IntersectionObserver). */
function Reveal({ children, className, as: Tag = 'div' }) {
  const ref = useRef(null);
  const [visible, setVisible] = useState(false);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const obs = new IntersectionObserver(([entry]) => { if (entry.isIntersecting) { setVisible(true); obs.disconnect(); } }, { threshold: 0.15 });
    obs.observe(el);
    return () => obs.disconnect();
  }, []);
  return <Tag ref={ref} className={cn('reveal', visible && 'reveal-visible', className)}>{children}</Tag>;
}
function Button({ variant = 'primary', className, children, ...props }) {
  const base = 'inline-flex items-center justify-center gap-2 px-4 py-2 text-sm font-bold tracking-wide transition-colors disabled:opacity-50 disabled:cursor-not-allowed';
  const variants = {
    primary: 'btn-shine bg-navy text-white hover:bg-navy-light',
    secondary: 'bg-cream text-navy border border-navy/20 hover:bg-cream-light',
    danger: 'bg-brandRed text-white hover:bg-red-700',
    ghost: 'bg-transparent text-navy hover:bg-navy/5',
    outline: 'btn-shine bg-transparent border border-navy text-navy hover:bg-navy hover:text-white',
  };
  return <button className={cn(base, variants[variant], className)} {...props}>{children}</button>;
}
function Input({ className, ...props }) {
  return <input className={cn('w-full border border-gray-300 px-3 py-2 text-sm outline-none focus:border-navy focus:ring-1 focus:ring-navy', className)} {...props} />;
}
function Select({ className, children, ...props }) {
  return <select className={cn('w-full border border-gray-300 px-3 py-2 text-sm outline-none focus:border-navy focus:ring-1 focus:ring-navy bg-white', className)} {...props}>{children}</select>;
}
function Badge({ children, color = 'gray' }) {
  const colors = { gray: 'bg-gray-100 text-gray-700', green: 'bg-green-100 text-brandGreen', red: 'bg-red-100 text-brandRed', navy: 'bg-navy/10 text-navy', yellow: 'bg-yellow-100 text-yellow-800', purple: 'bg-brandPurple/10 text-brandPurple' };
  return <span className={cn('inline-block rounded-full px-2.5 py-0.5 text-xs font-medium', colors[color])}>{children}</span>;
}
function Toggle({ checked, onChange, label }) {
  return (
    <label className="inline-flex cursor-pointer items-center gap-2">
      {label && <span className="text-sm text-gray-700">{label}</span>}
      <span onClick={() => onChange(!checked)} className={cn('relative inline-block h-6 w-11 rounded-full transition-colors', checked ? 'bg-navy' : 'bg-gray-300')}>
        <span className={cn('absolute top-0.5 h-5 w-5 rounded-full bg-white shadow transition-transform', checked ? 'translate-x-[-22px] right-1' : 'right-1')} />
      </span>
    </label>
  );
}
function Modal({ open, onClose, title, children, wide }) {
  if (!open) return null;
  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4" onClick={onClose}>
      <div className={cn('max-h-[90vh] w-full overflow-y-auto bg-white shadow-xl', wide ? 'max-w-3xl' : 'max-w-lg')} onClick={(e) => e.stopPropagation()}>
        <div className="flex items-center justify-between border-b border-gray-200 px-5 py-4">
          <h3 className="font-bold text-navy">{title}</h3>
          <button onClick={onClose} className="text-gray-400 hover:text-gray-700">✕</button>
        </div>
        <div className="p-5">{children}</div>
      </div>
    </div>
  );
}
function Spinner({ className }) {
  return <span className={cn('inline-block h-5 w-5 animate-spin rounded-full border-2 border-current border-t-transparent', className)} />;
}
function SkeletonBox({ className }) { return <div className={cn('skeleton rounded', className)} />; }
function EmptyState({ icon = '📦', title, subtitle }) {
  return (
    <div className="flex flex-col items-center justify-center gap-2 py-16 text-center text-gray-500">
      <span className="text-4xl">{icon}</span>
      <p className="font-medium text-gray-700">{title}</p>
      {subtitle && <p className="text-sm">{subtitle}</p>}
    </div>
  );
}
function SearchInput({ value, onChange, placeholder = 'بحث...' }) {
  return (
    <div className="relative max-w-xs">
      <Input value={value} onChange={(e) => onChange(e.target.value)} placeholder={placeholder} className="pr-9" />
      <span className="pointer-events-none absolute right-3 top-1/2 -translate-y-1/2 text-gray-400">🔍</span>
    </div>
  );
}
function ColorDot({ hex, selected, onClick, title }) {
  return <button type="button" onClick={onClick} title={title} className={cn('h-6 w-6 rounded-full border-2 transition-transform', selected ? 'scale-110 border-navy' : 'border-white ring-1 ring-gray-300')} style={{ backgroundColor: hex }} />;
}
function ConfirmDialog({ open, title, message, onConfirm, onCancel, danger, confirmLabel = 'تأكيد' }) {
  if (!open) return null;
  return (
    <div className="fixed inset-0 z-[60] flex items-center justify-center bg-black/50 p-4">
      <div className="w-full max-w-sm bg-white p-5 shadow-xl">
        <h4 className="mb-2 font-bold text-navy">{title}</h4>
        <p className="mb-4 text-sm text-gray-600">{message}</p>
        <div className="flex justify-end gap-2">
          <Button variant="ghost" onClick={onCancel}>إلغاء</Button>
          <Button variant={danger ? 'danger' : 'primary'} onClick={onConfirm}>{confirmLabel}</Button>
        </div>
      </div>
    </div>
  );
}
function DataTable({ columns, rows, loading, emptyLabel = 'لا توجد بيانات' }) {
  return (
    <>
      {/* جدول عادي — من مقاس تابلت فما فوق */}
      <div className="hidden overflow-x-auto border border-gray-200 bg-white sm:block">
        <table className="w-full min-w-[600px] text-sm">
          <thead className="bg-gray-50 text-gray-500">
            <tr>{columns.map((c, i) => <th key={i} className="whitespace-nowrap px-4 py-2.5 text-start font-medium">{c.header}</th>)}</tr>
          </thead>
          <tbody className="divide-y divide-gray-100">
            {loading ? Array.from({ length: 5 }).map((_, i) => (
              <tr key={i}>{columns.map((_, j) => <td key={j} className="px-4 py-3"><SkeletonBox className="h-4 w-full" /></td>)}</tr>
            )) : rows.length === 0 ? (
              <tr><td colSpan={columns.length}><EmptyState title={emptyLabel} /></td></tr>
            ) : rows.map((row) => (
              <tr key={row.id} className="hover:bg-gray-50">{columns.map((c, i) => <td key={i} className={cn('px-4 py-3', c.className)}>{c.render(row)}</td>)}</tr>
            ))}
          </tbody>
        </table>
      </div>

      {/* بطاقات مكدّسة — موبايل، بدون أي تمرير جانبي */}
      <div className="space-y-2 sm:hidden">
        {loading ? Array.from({ length: 4 }).map((_, i) => (
          <div key={i} className="space-y-2 border border-gray-200 bg-white p-3"><SkeletonBox className="h-4 w-2/3" /><SkeletonBox className="h-4 w-1/2" /></div>
        )) : rows.length === 0 ? (
          <div className="border border-gray-200 bg-white"><EmptyState title={emptyLabel} /></div>
        ) : rows.map((row) => (
          <div key={row.id} className="space-y-1.5 border border-gray-200 bg-white p-3">
            {columns.map((c, i) => (
              <div key={i} className="flex items-start justify-between gap-3 text-sm">
                {c.header ? <span className="shrink-0 pt-0.5 text-xs font-medium text-gray-400">{c.header}</span> : null}
                <span className={cn('min-w-0 flex-1 text-left', c.className)}>{c.render(row)}</span>
              </div>
            ))}
          </div>
        ))}
      </div>
    </>
  );
}

/* ============================================================
   كارت المنتج
   ============================================================ */
function ProductCard({ product }) {
  const { t } = useLang();
  const images = useMemo(() => (product.colors?.[0]?.images || []).map((im) => im.image_url).filter(Boolean), [product]);
  const hasDiscount = !!product.discount_price && product.discount_price < product.original_price;
  const [hoverIdx, setHoverIdx] = useState(0);
  const hoverTimer = useRef(null);
  const stopHover = () => { if (hoverTimer.current) { clearInterval(hoverTimer.current); hoverTimer.current = null; } setHoverIdx(0); };
  const startHover = () => {
    // على الموبايل ما في Hover حقيقي — منعطّل التقليب التلقائي هناك تمامًا حتى ما يأثر على الأداء
    const canHover = typeof window !== 'undefined' && window.matchMedia && window.matchMedia('(hover: hover)').matches;
    if (!canHover || images.length < 2) return;
    let i = 0;
    hoverTimer.current = setInterval(() => { i = (i + 1) % images.length; setHoverIdx(i); }, 750);
  };
  useEffect(() => () => { if (hoverTimer.current) clearInterval(hoverTimer.current); }, []);
  return (
    <Link to={`/product/${product.id}`} className="group block" onMouseEnter={startHover} onMouseLeave={stopHover}>
      <div className="relative aspect-[3/4] w-full overflow-hidden bg-[#f2e9d8]">
        {images.length ? images.map((img, i) => (
          <img key={i} src={img} alt={product.name} loading="lazy" decoding="async" className={cn('absolute inset-0 h-full w-full object-cover transition-opacity duration-700 ease-in-out', i === hoverIdx ? 'opacity-100' : 'opacity-0')} />
        )) : (
          <div className="flex h-full w-full items-center justify-center text-sm text-gray-400">{t('product.noImage')}</div>
        )}
        <button onClick={(e) => e.preventDefault()} className="absolute top-2 right-2 flex h-7 w-7 items-center justify-center rounded-full bg-white/90 text-sm shadow">♡</button>
        {product.category?.category_sections?.some((s) => s.section === 'new') && <span className="absolute bottom-2 left-2 rounded bg-brandGreen px-2 py-0.5 text-[11px] font-bold text-white">{t('product.new')}</span>}
      </div>
      <div className="pt-2.5">
        {product.brand?.name && <p className="text-xs text-gray-500 sm:text-sm">{product.brand.name}</p>}
        <p className="truncate text-base font-bold text-brandPurple sm:text-lg">{product.name}</p>
        {!!product.colors?.length && <div className="mt-1.5 flex gap-1">{product.colors.slice(0, 5).map((c) => <ColorDot key={c.id} hex={c.color_hex || '#ccc'} title={c.color_name} />)}</div>}
        <div className="mt-1.5 flex items-center gap-2">
          <span className={`text-base sm:text-lg ${hasDiscount ? 'font-bold text-brandRed' : 'font-bold text-navy'}`}>{formatPrice(hasDiscount ? product.discount_price : product.original_price)}</span>
          {hasDiscount && <span className="text-xs text-gray-400 line-through sm:text-sm">{formatPrice(product.original_price)}</span>}
        </div>
      </div>
    </Link>
  );
}
function ProductCardSkeleton() {
  return (
    <div>
      <div className="skeleton aspect-[3/4] w-full" />
      <div className="mt-2 space-y-1.5"><div className="skeleton h-3 w-1/3" /><div className="skeleton h-4 w-2/3" /><div className="skeleton h-4 w-1/4" /></div>
    </div>
  );
}

/* ============================================================
   استعلامات البيانات (Supabase)
   ============================================================ */
const DEFAULT_SETTINGS = {
  theme: { navy: '#0f1f3d', cream: '#f5efe3', accentPurple: '#4b3b78', accentGreen: '#1e6b3f', accentRed: '#c0392b', headerBg: '#0f1f3d', footerBg: '#0f1f3d', buttonBg: '#0f1f3d', buttonText: '#f5efe3' },
  logoUrl: null, tagline: 'ملابس رياضية. أسلوب يومي.',
  contact: { whatsapp: '', facebook: '', instagram: '', email: '', phone: '' },
  departmentBanners: { men: null, women: null, kids: null },
  sectionTitles: { bestseller: 'الأكثر شراءً', newArrivals: 'وصل حديثًا', forYou: 'اختيارات لك', outlet: 'أوتليت' },
  loyalty: { enabled: true, pointsPerAmount: 10, amountUnit: 100, redeemThreshold: 100, discountPercent: 10 },
  delivery: { westBank: 0, inside48: 0, jerusalem: 0 },
  reflectNumber: '',
  homeSections: { offers: true, new: true, bestseller: true, outlet: true },
};
const DELIVERY_ZONES = [
  { key: 'westBank', label: 'الضفة الغربية', labelEn: 'West Bank' },
  { key: 'inside48', label: 'الداخل', labelEn: 'Inside the Green Line' },
  { key: 'jerusalem', label: 'القدس', labelEn: 'Jerusalem' },
];
function useSiteSettings() {
  return useSupaQuery(['site_settings'], async () => {
    const { data } = await sb.from('site_settings').select('key, value');
    const map = {}; (data || []).forEach((r) => (map[r.key] = r.value));
    return {
      theme: { ...DEFAULT_SETTINGS.theme, ...(map.theme || {}) },
      logoUrl: map.logoUrl ?? DEFAULT_SETTINGS.logoUrl,
      tagline: map.tagline ?? DEFAULT_SETTINGS.tagline,
      contact: { ...DEFAULT_SETTINGS.contact, ...(map.contact || {}) },
      departmentBanners: { ...DEFAULT_SETTINGS.departmentBanners, ...(map.departmentBanners || {}) },
      sectionTitles: { ...DEFAULT_SETTINGS.sectionTitles, ...(map.sectionTitles || {}) },
      loyalty: { ...DEFAULT_SETTINGS.loyalty, ...(map.loyalty || {}) },
      delivery: { ...DEFAULT_SETTINGS.delivery, ...(map.delivery || {}) },
      reflectNumber: map.reflectNumber ?? DEFAULT_SETTINGS.reflectNumber,
      homeSections: { ...DEFAULT_SETTINGS.homeSections, ...(map.homeSections || {}) },
    };
  });
}
function useHeroSlides() {
  return useSupaQuery(['hero_slides'], async () => {
    const { data } = await sb.from('hero_slides').select('*').order('sort_order');
    return data || [];
  });
}
function useHomeBanners() {
  return useSupaQuery(['home_banners'], async () => {
    const { data } = await sb.from('home_banners').select('*').order('sort_order');
    return data || [];
  });
}
function useActiveOffer() {
  return useSupaQuery(['site_settings', 'activeOffer'], async () => {
    const { data } = await sb.from('site_settings').select('value').eq('key', 'activeOffer').maybeSingle();
    return data?.value || null;
  });
}
function useCategories({ department, section } = {}) {
  // صار التصنيف نفسه هو يلي بيحدد وين يظهر — بربط Many-to-Many مع الأقسام (رجال/نساء/أطفال)
  // عبر category_departments، ومع الأقسام الخاصة (عروض/وصل حديثًا/الأكثر مبيعًا/أوتليت) عبر
  // category_sections. تصنيف واحد فيك تحطه بأكتر من مكان بنفس الوقت.
  return useSupaQuery(['categories', department, section], async () => {
    let q;
    if (department) {
      q = sb.from('categories').select('*, category_departments!inner(department)').eq('is_hidden', false).eq('category_departments.department', department);
    } else if (section) {
      q = sb.from('categories').select('*, category_sections!inner(section)').eq('is_hidden', false).eq('category_sections.section', section);
    } else {
      q = sb.from('categories').select('*').eq('is_hidden', false);
    }
    const { data, error } = await q;
    if (error) throw error;
    return data || [];
  });
}
async function categoryIdsForDepartment(department) {
  const { data } = await sb.from('category_departments').select('category_id').eq('department', department);
  return (data || []).map((r) => r.category_id);
}
async function categoryIdsForSection(section) {
  const { data } = await sb.from('category_sections').select('category_id').eq('section', section);
  return (data || []).map((r) => r.category_id);
}
async function productIdsForDepartment(department) {
  const { data } = await sb.from('product_departments').select('product_id').eq('department', department);
  return (data || []).map((r) => r.product_id);
}
async function fetchProducts({ department, categoryId, search, tab, page = 0, pageSize = 12 }) {
  let q = sb.from('products').select('*, brand:brands(*), category:categories(*, category_sections(section)), colors:product_colors(*, sizes:product_sizes(*), images:product_color_images(*)), prints:product_prints(*)', { count: 'exact' }).eq('is_hidden', false);
  // كل منتج فيه مكانين ممكنين للظهور: (أ) عبر تصنيفه (category_departments/category_sections)،
  // و(ب) عبر تحديد مباشر على المنتج نفسه (product_departments أو show_on_*) — بنجمعهم بـ OR حتى الاثنين يشتغلوا مع بعض.
  // منتج فيه يكون بأكتر من قسم بنفس الوقت (رجال ونساء مثلًا) — لهيك product_departments جدول Many-to-Many مش عمود واحد.
  if (categoryId) {
    q = q.eq('category_id', categoryId);
  } else if (department) {
    const [categoryIds, productIds] = await Promise.all([categoryIdsForDepartment(department), productIdsForDepartment(department)]);
    const parts = [];
    if (productIds.length) parts.push(`id.in.(${productIds.join(',')})`);
    if (categoryIds.length) parts.push(`category_id.in.(${categoryIds.join(',')})`);
    if (!parts.length) return { rows: [], count: 0 };
    q = q.or(parts.join(','));
  } else if (tab && tab !== 'all') {
    const categoryIds = await categoryIdsForSection(tab);
    const col = { offers: 'show_on_offers', new: 'show_on_new_arrivals', bestseller: 'show_on_bestseller', outlet: 'show_on_outlet' }[tab];
    const parts = col ? [`${col}.eq.true`] : [];
    if (categoryIds.length) parts.push(`category_id.in.(${categoryIds.join(',')})`);
    if (!parts.length) return { rows: [], count: 0 };
    q = q.or(parts.join(','));
  }
  if (search) {
    // البحث بيغطي: اسم المنتج، رقم القطعة (custom_code)، أو اسم التصنيف
    const term = search.trim();
    const { data: matchedCats } = await sb.from('categories').select('id').ilike('name', `%${term}%`);
    const matchedIds = (matchedCats || []).map((c) => c.id);
    const orParts = [`name.ilike.%${term}%`, `custom_code.ilike.%${term}%`];
    if (matchedIds.length) orParts.push(`category_id.in.(${matchedIds.join(',')})`);
    q = q.or(orParts.join(','));
  }
  q = q.order('created_at', { ascending: false }).range(page * pageSize, page * pageSize + pageSize - 1);
  const { data, error, count } = await q;
  if (error) throw error;
  return { rows: data || [], count: count || 0 };
}
function useProducts(filters) {
  return useSupaQuery(['products', filters], () => fetchProducts(filters));
}
function useProduct(id) {
  return useSupaQuery(['product', id], async () => {
    if (!id) return null;
    const { data, error } = await sb.from('products').select('*, brand:brands(*), category:categories(*, category_sections(section)), colors:product_colors(*, sizes:product_sizes(*), images:product_color_images(*)), prints:product_prints(*)').eq('id', id).maybeSingle();
    if (error) throw error;
    return data;
  });
}

/* ============================================================
   نافذة السلة
   ============================================================ */
async function checkDiscountCode(rawCode, applyDiscount) {
  const code = rawCode.trim();
  if (!code) return null;
  const { data } = await sb.from('discount_codes').select('*').eq('code', code).eq('is_active', true).maybeSingle();
  if (!data) return 'الكود غير صالح';
  if (data.valid_until && new Date(data.valid_until) < new Date()) return 'انتهت صلاحية الكود';
  if (data.used_count >= data.max_uses) return 'اكتمل استخدام هذا الكود';
  applyDiscount(data.code, data.discount_percent);
  return `تم تطبيق خصم ${data.discount_percent}%`;
}
function CartDrawer({ open, onClose }) {
  const { t } = useLang();
  const { items, total, applyDiscount, discountCode, count } = useCart();
  const { customerId, loyaltyPoints } = useCustomerAuth();
  const { data: settings } = useSiteSettings();
  const [code, setCode] = useState('');
  const [msg, setMsg] = useState(null);
  if (!open) return null;
  const loyalty = settings?.loyalty || DEFAULT_SETTINGS.loyalty;

  const checkCode = async () => { setMsg(await checkDiscountCode(code, applyDiscount)); };

  return (
    <div className="fixed inset-0 z-50 flex justify-end bg-black/40" onClick={onClose}>
      <div className="h-full w-full max-w-sm bg-white p-5 shadow-xl" onClick={(e) => e.stopPropagation()}>
        <div className="mb-4 flex items-center justify-between"><h3 className="font-bold text-navy">{t('cart.title')}</h3><button onClick={onClose}>✕</button></div>
        {items.length === 0 ? <p className="text-sm text-gray-500">{t('cart.empty')}</p> : (
          <div className="mb-4 max-h-64 space-y-3 overflow-y-auto">
            {items.map((it, i) => (
              <div key={i} className="flex items-center gap-3 text-sm">
                <div className="h-14 w-14 flex-shrink-0 overflow-hidden bg-gray-100">{it.image && <img src={it.image} className="h-full w-full object-cover" />}</div>
                <div className="flex-1"><p className="line-clamp-2 font-medium">{it.productName}</p><p className="text-xs text-gray-500">{it.colorName} · {it.size} · ×{it.quantity}</p></div>
                <span className="font-bold text-navy">{formatPrice(it.unitPrice * it.quantity)}</span>
              </div>
            ))}
          </div>
        )}
        <div className="mb-3">
          <label className="mb-1 block text-sm font-medium text-gray-700">{t('cart.discountCode')}</label>
          <div className="flex gap-2"><Input value={code} onChange={(e) => setCode(e.target.value)} placeholder="SUPER10" /><Button onClick={checkCode}>تحقق</Button></div>
          {msg && <p className="mt-1 text-xs text-gray-600">{msg}</p>}
          {discountCode && <p className="mt-1 text-xs text-brandGreen">الكود المطبّق: {discountCode}</p>}
        </div>
        {loyalty.enabled && (
          <p className="mb-2 text-xs text-gray-500">
            {!customerId ? t('cart.loyaltyPrompt')
              : loyaltyPoints >= loyalty.redeemThreshold ? `⚡ عندك ${loyaltyPoints} نقطة — بتقدر تستخدم خصم ${loyalty.discountPercent}% بصفحة الدفع`
              : `⚡ عندك ${loyaltyPoints} نقطة ولاء (${Math.max(loyalty.redeemThreshold - loyaltyPoints, 0)} نقطة متبقية للخصم)`}
          </p>
        )}
        <div className="mb-4 flex items-center justify-between border-t pt-3 font-bold"><span>{t('cart.total')}</span><span className="text-navy">{formatPrice(total)}</span></div>
        <Link to="/cart" onClick={onClose}><Button className="w-full" disabled={count === 0}>{t('cart.continue')}</Button></Link>
      </div>
    </div>
  );
}

/* ============================================================
   الهيدر والفوتر
   ============================================================ */
function useNavLinks() {
  const { t } = useLang();
  const { data: settings } = useSiteSettings();
  // اوتليت/عروض/الأكثر مبيعًا/وصل حديثًا مش أقسام رئيسية (متل رجال/نساء/أطفال) — الأدمن فيه يتحكم
  // بظهورها من "تعديل صفحة العميل" (إظهار/إخفاء أقسام الصفحة الرئيسية)، وهلق هاد التحكم بيأثر
  // على قائمة التنقّل العلوية كمان مش بس على صفوف الصفحة الرئيسية.
  const homeSections = settings?.homeSections || DEFAULT_SETTINGS.homeSections;
  const optionalLinks = [
    { key: 'offers', to: '/offers', label: t('nav.offers') },
    { key: 'new', to: '/new', label: t('nav.new') },
    { key: 'bestseller', to: '/bestseller', label: t('nav.bestseller') },
    { key: 'outlet', to: '/outlet', label: t('nav.outlet') },
  ].filter((l) => homeSections[l.key] !== false);
  return [
    ...optionalLinks,
    { to: '/kids', label: t('nav.kids') }, { to: '/women', label: t('nav.women') }, { to: '/men', label: t('nav.men') },
  ];
}
function CategoryBar() {
  const route = useRoute();
  const links = useNavLinks();
  return (
    <nav className="hidden justify-center gap-8 overflow-x-auto border-t border-navy/10 bg-cream px-4 py-3 text-[15px] font-semibold tracking-wide text-navy sm:flex">
      {links.map((l) => (
        <Link key={l.to} to={l.to} className={route === l.to ? 'whitespace-nowrap border-b-2 border-navy pb-1' : 'whitespace-nowrap text-navy/70 transition-colors hover:text-navy'}>{l.label}</Link>
      ))}
    </nav>
  );
}
function MobileNavPanel({ open, onClose }) {
  const { t, lang, setLang } = useLang();
  const route = useRoute();
  const links = useNavLinks();
  if (!open) return null;
  return (
    <div className="border-t border-navy/10 bg-cream px-4 py-3 sm:hidden">
      <nav className="grid grid-cols-2 gap-2">
        {links.map((l) => (
          <Link key={l.to} to={l.to} onClick={onClose} className={cn('rounded px-3 py-2.5 text-sm font-semibold', route === l.to ? 'bg-navy text-white' : 'bg-white text-navy')}>{l.label}</Link>
        ))}
      </nav>
      <div className="mt-3 flex items-center justify-between border-t border-navy/10 pt-3">
        <Link to="/account" onClick={onClose} className="text-sm font-medium text-navy">👤 {t('nav.account')}</Link>
        <select value={lang} onChange={(e) => setLang(e.target.value)} className="border border-navy/20 bg-white px-2 py-1 text-sm text-navy outline-none"><option value="ar">عربي</option><option value="en">English</option></select>
      </div>
    </div>
  );
}
function HeaderSearch() {
  const route = matchRoute(useRoute());
  const [q, setQ] = useState(route.name === 'search' ? route.params.q || '' : '');
  useEffect(() => { setQ(route.name === 'search' ? route.params.q || '' : ''); }, [route.name, route.params.q]);
  const submit = () => { if (q.trim()) navigate(`/search/${encodeURIComponent(q.trim())}`); };
  return (
    <div className="border-t border-navy/10 bg-cream px-4 py-2 sm:px-6">
      <div className="mx-auto flex max-w-3xl items-center gap-2">
        <input
          value={q}
          onChange={(e) => setQ(e.target.value)}
          onKeyDown={(e) => { if (e.key === 'Enter') submit(); }}
          placeholder="ابحث عن منتج، تصنيف، أو رقم قطعة..."
          className="w-full border border-gray-300 bg-white px-3 py-2 text-sm outline-none focus:border-navy focus:ring-1 focus:ring-navy"
        />
        <button onClick={submit} aria-label="بحث" className="flex-shrink-0 text-lg text-navy">🔍</button>
      </div>
    </div>
  );
}
function Header() {
  const { lang, setLang } = useLang();
  const { count } = useCart();
  const [cartOpen, setCartOpen] = useState(false);
  const [navOpen, setNavOpen] = useState(false);
  const { data: settings } = useSiteSettings();
  const route = useRoute();
  useEffect(() => { setNavOpen(false); }, [route]);
  return (
    <header className="sticky top-0 z-40 shadow-sm">
      <div className="h-2.5 bg-navy sm:h-3" aria-hidden="true" />
      <div className="relative flex items-center justify-between bg-cream px-4 py-4 sm:px-6">
        <button onClick={() => setNavOpen((v) => !v)} aria-label="القائمة" className="text-2xl text-navy sm:hidden">{navOpen ? '✕' : '☰'}</button>
        <span className="hidden sm:block sm:w-8" aria-hidden="true" />
        <Link to="/" className="absolute left-1/2 top-1/2 flex -translate-x-1/2 -translate-y-1/2 items-center gap-2">
          {settings?.logoUrl ? <img src={settings.logoUrl} alt="SUPER SHOP" className="h-11 w-auto sm:h-14" /> : <span className="flex items-center gap-2 font-display text-2xl font-extrabold tracking-tight text-navy sm:text-3xl"><ThunderBolt className="h-5 w-5 sm:h-7 sm:w-7" />SUPER SHOP</span>}
        </Link>
        <div className="flex items-center gap-4 text-lg text-navy sm:gap-5">
          <button onClick={() => setCartOpen(true)} className="relative">🛒{count > 0 && <span className="absolute -top-2 -right-2 flex h-4 w-4 items-center justify-center rounded-full bg-brandRed text-[10px] text-white">{count}</span>}</button>
          <Link to="/favorites">♡</Link>
          <select value={lang} onChange={(e) => setLang(e.target.value)} className="hidden bg-transparent text-sm outline-none sm:inline-block"><option value="ar">عربي</option><option value="en">English</option></select>
          <Link to="/account">👤</Link>
        </div>
      </div>
      <HeaderSearch />
      <MobileNavPanel open={navOpen} onClose={() => setNavOpen(false)} />
      <CategoryBar />
      <CartDrawer open={cartOpen} onClose={() => setCartOpen(false)} />
    </header>
  );
}
function MobileBottomNav() {
  const { t } = useLang();
  const { count } = useCart();
  const items = [
    { to: '/account', icon: '👤', label: t('nav.account') }, { to: '/favorites', icon: '♡', label: t('nav.favorites') },
    { to: '/cart', icon: '🛒', label: count ? `${t('nav.cart')} (${count})` : t('nav.cart') }, { to: '/', icon: '🏠', label: t('nav.home') },
  ];
  return (
    <nav className="fixed inset-x-0 bottom-0 z-40 flex justify-around border-t border-navy/20 bg-navy py-2 text-cream sm:hidden">
      {items.map((it) => <Link key={it.to} to={it.to} className="flex flex-col items-center gap-0.5 text-[11px]"><span className="text-lg leading-none">{it.icon}</span>{it.label}</Link>)}
    </nav>
  );
}
function Footer() {
  const { t } = useLang();
  const { data: settings } = useSiteSettings();
  const social = [
    { key: 'whatsapp', icon: '💬', label: 'WhatsApp' }, { key: 'instagram', icon: '📷', label: 'Instagram' }, { key: 'facebook', icon: '📘', label: 'Facebook' },
  ].filter((s) => settings?.contact?.[s.key]);
  return (
    <footer className="mt-10 bg-navy px-6 py-10 text-cream sm:py-12">
      <div className="mx-auto grid max-w-6xl grid-cols-2 gap-8 sm:grid-cols-4">
        <div><h4 className="mb-3 font-bold">{t('footer.account')}</h4>
          <ul className="space-y-1.5 text-sm text-cream/80"><li><Link to="/account">{t('nav.account')}</Link></li><li><Link to="/account/orders">{t('account.orders')}</Link></li><li><Link to="/favorites">{t('nav.favorites')}</Link></li><li><Link to="/cart">{t('nav.cart')}</Link></li></ul>
        </div>
        <div><h4 className="mb-3 font-bold">{t('footer.shop')}</h4>
          <ul className="space-y-1.5 text-sm text-cream/80"><li><Link to="/men">{t('nav.men')}</Link></li><li><Link to="/women">{t('nav.women')}</Link></li><li><Link to="/kids">{t('nav.kids')}</Link></li><li><Link to="/offers">{t('nav.offers')}</Link></li></ul>
        </div>
        <div className="col-span-2 sm:col-span-2">
          <div className="mb-2 flex items-center gap-1.5 font-display text-xl font-extrabold"><ThunderBolt className="h-4 w-4" />SUPER SHOP</div>
          <p className="mb-3 text-sm text-cream/80">{settings?.tagline}</p>
          {!!social.length && (
            <div className="flex flex-wrap gap-2">
              {social.map((s) => <a key={s.key} href={settings.contact[s.key]} target="_blank" rel="noreferrer" aria-label={s.label} title={s.label} className="flex h-10 w-10 items-center justify-center rounded-lg bg-cream/10 text-lg transition-colors hover:bg-cream/20">{s.icon}</a>)}
            </div>
          )}
          {settings?.contact.phone && <p className="mt-3 text-sm text-cream/80">📞 {settings.contact.phone}</p>}
        </div>
      </div>
      <div className="mx-auto mt-8 max-w-6xl border-t border-cream/10 pt-5 text-xs text-cream/60">
        <p>© {new Date().getFullYear()} SUPER SHOP — {t('footer.rights')}</p>
        <p className="mt-1 font-medium text-cream/50">Powered by JEXA</p>
      </div>
    </footer>
  );
}
function BackButton({ className }) {
  const { t } = useLang();
  return (
    <button onClick={() => (window.history.length > 1 ? window.history.back() : navigate('/'))} className={cn('mb-3 inline-flex items-center gap-1.5 text-sm font-medium text-gray-500 transition-colors hover:text-navy', className)}>
      <span aria-hidden>←</span>{t('common.back')}
    </button>
  );
}
function WhatsAppIcon({ className = 'h-6 w-6' }) {
  return (
    <svg viewBox="0 0 32 32" fill="currentColor" className={className} aria-hidden="true">
      <path d="M16.001 3.2c-7.06 0-12.8 5.74-12.8 12.8 0 2.256.594 4.428 1.719 6.344L3.2 28.8l6.619-1.681a12.74 12.74 0 006.182 1.574h.005c7.06 0 12.8-5.74 12.8-12.8 0-3.418-1.331-6.633-3.75-9.05A12.716 12.716 0 0016.001 3.2zm0 23.16h-.004a10.62 10.62 0 01-5.412-1.482l-.388-.23-4.028 1.023 1.075-3.927-.253-.403a10.61 10.61 0 01-1.63-5.658c0-5.868 4.775-10.64 10.645-10.64 2.843 0 5.514 1.108 7.523 3.12a10.567 10.567 0 013.117 7.526c0 5.868-4.775 10.64-10.645 10.64zm5.835-7.968c-.32-.16-1.892-.933-2.185-1.04-.293-.107-.507-.16-.72.16-.213.32-.827 1.04-1.014 1.253-.187.213-.373.24-.693.08-.32-.16-1.35-.497-2.573-1.586-.951-.848-1.593-1.895-1.78-2.215-.187-.32-.02-.493.14-.653.144-.143.32-.373.48-.56.16-.187.213-.32.32-.533.107-.213.053-.4-.027-.56-.08-.16-.72-1.733-.987-2.373-.26-.624-.524-.54-.72-.55l-.613-.011c-.213 0-.56.08-.853.4-.293.32-1.12 1.093-1.12 2.667s1.147 3.093 1.307 3.307c.16.213 2.257 3.447 5.467 4.833.764.33 1.36.527 1.825.674.767.244 1.465.21 2.017.127.615-.092 1.892-.773 2.16-1.52.267-.747.267-1.387.187-1.52-.08-.133-.293-.213-.613-.373z" />
    </svg>
  );
}
function FloatingCouponButton() {
  const { applyDiscount, discountCode, redeemLoyalty, setRedeemLoyalty } = useCart();
  const { customerId, loyaltyPoints } = useCustomerAuth();
  const { data: settings } = useSiteSettings();
  const loyalty = settings?.loyalty || DEFAULT_SETTINGS.loyalty;
  const canRedeem = loyalty.enabled && customerId && loyaltyPoints >= loyalty.redeemThreshold;
  const [open, setOpen] = useState(false);
  const [code, setCode] = useState('');
  const [msg, setMsg] = useState(null);
  const submit = async () => setMsg(await checkDiscountCode(code, applyDiscount));
  const progressPct = loyalty.redeemThreshold > 0 ? Math.min(100, Math.round((loyaltyPoints / loyalty.redeemThreshold) * 100)) : 100;
  return (
    <>
      <button onClick={() => setOpen(true)} aria-label="نقاط الولاء وكود الخصم" className="flex h-11 w-11 items-center justify-center rounded-full bg-cream text-xl shadow-lg ring-1 ring-navy/10 transition-transform hover:scale-105">🎁</button>
      <Modal open={open} onClose={() => setOpen(false)} title="⚡ نقاط الولاء والخصومات">
        {loyalty.enabled && (
          <div className="mb-5 border-b border-gray-100 pb-5">
            {!customerId ? (
              <div className="text-center">
                <p className="mb-3 text-sm text-gray-600">سجّل دخولك حتى تجمع نقاط ولاء من كل طلب وتستخدمها بخصومات على مشترياتك الجاية.</p>
                <Link to="/account" onClick={() => setOpen(false)}><Button className="w-full">تسجيل الدخول</Button></Link>
              </div>
            ) : (
              <>
                <div className="mb-3 text-center">
                  <p className="text-xs text-gray-500">رصيدك الحالي</p>
                  <p className="text-3xl font-bold text-navy">{loyaltyPoints} <span className="text-base font-medium text-gray-500">نقطة</span></p>
                </div>
                <div className="h-2 w-full overflow-hidden rounded-full bg-gray-100">
                  <div className="h-full rounded-full bg-navy transition-all" style={{ width: `${progressPct}%` }} />
                </div>
                {canRedeem ? (
                  <label className="mt-3 flex cursor-pointer items-center justify-between gap-2 bg-cream-light px-3 py-2 text-sm">
                    <span className="font-medium text-navy">🎉 استخدم نقاطك لخصم {loyalty.discountPercent}% بالسلة</span>
                    <input type="checkbox" checked={redeemLoyalty} onChange={(e) => setRedeemLoyalty(e.target.checked)} className="h-4 w-4 accent-navy" />
                  </label>
                ) : (
                  <p className="mt-2 text-center text-xs text-gray-500">اجمع {Math.max(loyalty.redeemThreshold - loyaltyPoints, 0)} نقطة إضافية عشان توصل لخصم {loyalty.discountPercent}%</p>
                )}
                {redeemLoyalty && canRedeem && <p className="mt-1.5 text-center text-xs text-brandGreen">تمام! خصم {loyalty.discountPercent}% رح يتطبّق تلقائيًا عند إتمام الشراء بالسلة.</p>}
                <p className="mt-3 text-center text-[11px] text-gray-400">كل {formatPrice(loyalty.amountUnit)} من مشترياتك = {loyalty.pointsPerAmount} نقطة، و{loyalty.redeemThreshold} نقطة = خصم {loyalty.discountPercent}%.</p>
              </>
            )}
          </div>
        )}
        <p className="mb-1.5 text-sm font-medium text-gray-700">كود الخصم</p>
        <div className="flex gap-2">
          <Input value={code} onChange={(e) => setCode(e.target.value)} placeholder="SUPER10" />
          <Button onClick={submit}>تحقق</Button>
        </div>
        {msg && <p className="mt-1.5 text-xs text-gray-600">{msg}</p>}
        {discountCode && <p className="mt-1 text-xs text-brandGreen">الكود المطبّق: {discountCode}</p>}
      </Modal>
    </>
  );
}
function FloatingSideButtons() {
  const { data: settings } = useSiteSettings();
  return (
    <div className="fixed bottom-20 left-3 z-40 flex flex-col items-center gap-3 sm:bottom-8">
      <FloatingCouponButton />
      {settings?.contact?.whatsapp && (
        <a href={settings.contact.whatsapp} target="_blank" rel="noreferrer" aria-label="واتساب" className="flex h-11 w-11 items-center justify-center rounded-full bg-[#25D366] text-white shadow-lg transition-transform hover:scale-105">
          <WhatsAppIcon className="h-6 w-6" />
        </a>
      )}
    </div>
  );
}
function CustomerLayout({ children }) {
  return (
    <div className="flex min-h-screen flex-col">
      <ThunderWatermark />
      <Header />
      <main className="flex-1 pb-16 sm:pb-0">{children}</main>
      <Footer />
      <MobileBottomNav />
      <FloatingSideButtons />
    </div>
  );
}

/* ============================================================
   الصفحة الرئيسية
   ============================================================ */
function linkForTarget(target) {
  if (!target || target === 'all') return '/offers';
  if (['men', 'women', 'kids'].includes(target)) return `/${target}`;
  if (['offers', 'new', 'outlet', 'bestseller'].includes(target)) return `/${target}`;
  return `/category/${target}`;
}
function HeroSlider() {
  const { data: slides, isLoading } = useHeroSlides();
  const { t } = useLang();
  const [active, setActive] = useState(0);
  useEffect(() => {
    if (!slides?.length) return;
    const id = setInterval(() => setActive((a) => (a + 1) % slides.length), 3000);
    return () => clearInterval(id);
  }, [slides]);
  if (isLoading) return <div className="skeleton h-64 w-full sm:h-96" />;
  if (!slides?.length) {
    return (
      <div className="relative flex h-64 flex-col items-center justify-center bg-cream text-center sm:h-96">
        <p className="mb-2 flex items-center gap-1.5 text-sm font-bold tracking-widest text-navy/70"><ThunderBolt className="h-3 w-3" />SUPER SHOP<ThunderBolt className="h-3 w-3" /></p>
        <Reveal as="h1" className="mb-3 font-display text-3xl font-extrabold text-navy sm:text-5xl">{t('home.heroTitle')}</Reveal>
        <Link to="/offers" className="btn-shine bg-navy px-6 py-2.5 font-bold tracking-wide text-white">{t('home.heroCta')} ←</Link>
      </div>
    );
  }
  const slide = slides[active];
  const hasImg = !!slide.image_url;
  return (
    <div className="relative flex h-64 overflow-hidden bg-cream sm:h-96">
      {hasImg && <img src={slide.image_url} className="absolute inset-0 h-full w-full object-cover opacity-90" alt="" />}
      {/* تدرّج غامق أسفل الصورة فقط حتى تبقى الكتابة مقروءة فوقها، بدون ما يغطي على محتوى الصورة نفسها بالأعلى */}
      {hasImg && <div className="absolute inset-x-0 bottom-0 z-[1] h-2/3 bg-gradient-to-t from-black/75 via-black/25 to-transparent" />}
      {/* الكتابة مثبّتة بالزاوية السفلية اليمنى (يمين فعلي، بغض النظر عن اتجاه RTL) حتى ما تغطي على محتوى الصورة المخصّصة بالمنتصف/الأعلى */}
      <div className={`absolute bottom-0 right-0 z-10 max-w-[80%] px-4 pb-9 text-right sm:max-w-lg sm:px-10 sm:pb-14 ${hasImg ? 'text-white' : 'text-navy'}`}>
        <p className={`mb-2 flex items-center justify-start gap-1.5 text-sm font-bold tracking-widest ${hasImg ? 'text-white/85' : 'text-navy/70'}`}><ThunderBolt className="h-3 w-3" />SUPER SHOP<ThunderBolt className="h-3 w-3" /></p>
        <Reveal as="h1" key={slide.id} className="mb-3 font-display text-2xl font-extrabold sm:text-5xl">{slide.title}</Reveal>
        {slide.subtitle && <p className={`mb-4 ${hasImg ? 'text-white/90' : 'text-navy/80'}`}>{slide.subtitle}</p>}
        {slide.button_text && <Link to={linkForTarget(slide.button_link_target)} className="btn-shine bg-navy px-6 py-2.5 font-bold tracking-wide text-white">{slide.button_text} ←</Link>}
      </div>
      <div className="absolute bottom-3 left-3 z-10 flex gap-1.5">{slides.map((_, i) => <button key={i} onClick={() => setActive(i)} className={`h-2 w-2 rounded-full ${i === active ? (hasImg ? 'bg-white' : 'bg-navy') : (hasImg ? 'bg-white/40' : 'bg-navy/30')}`} />)}</div>
    </div>
  );
}
function DepartmentCards() {
  const { t } = useLang();
  const { data: settings } = useSiteSettings();
  const deps = [
    { key: 'kids', label: t('nav.kids'), sub: 'KIDS' },
    { key: 'women', label: t('nav.women'), sub: 'WOMEN' },
    { key: 'men', label: t('nav.men'), sub: 'MEN' },
  ];
  return (
    <section className="mx-auto max-w-6xl px-4 py-8">
      <Reveal as="h2" className="mb-4 font-display text-xl font-bold text-navy">{t('home.categories')}</Reveal>
      <div className="grid grid-cols-3 gap-2.5 sm:gap-5">
        {deps.map((d) => (
          <Link key={d.key} to={`/${d.key}`} className="group relative flex aspect-[3/4] flex-col justify-between overflow-hidden rounded-2xl bg-navy p-3 shadow-lg sm:rounded-3xl sm:p-5">
            {settings?.departmentBanners[d.key] && (
              <img src={settings.departmentBanners[d.key]} className="absolute inset-0 h-full w-full object-cover transition-transform duration-500 group-hover:scale-105" alt="" />
            )}
            {/* تدرّج غامق أسفل الصورة حتى تنقرا الكتابة فوقها بوضوح */}
            <div className="absolute inset-0 bg-gradient-to-t from-black/75 via-black/10 to-black/5" />
            {/* خط قطري رفيع زخرفي — لمسة "الرعد" بسيطة داخل كل بطاقة */}
            <svg className="pointer-events-none absolute inset-0 h-full w-full opacity-30" viewBox="0 0 300 400" preserveAspectRatio="none" aria-hidden="true">
              <line x1="40" y1="380" x2="260" y2="25" stroke="white" strokeWidth="2" />
            </svg>

            <div className="relative z-10 flex justify-start">
              <span className="flex h-8 w-8 items-center justify-center rounded-full bg-white/15 text-white backdrop-blur-sm sm:h-9 sm:w-9">
                <ThunderBolt className="h-4 w-4" />
              </span>
            </div>

            <div className="relative z-10 flex items-end justify-between gap-1.5">
              <div className="min-w-0">
                <p className="truncate font-display text-lg font-extrabold leading-tight text-white sm:text-2xl">{d.label}</p>
                <p className="mt-0.5 text-[9px] font-bold tracking-[0.2em] text-white/70 sm:text-xs">{d.sub}</p>
              </div>
              <span className="flex shrink-0 items-center gap-1 rounded-full border border-white/40 bg-white/10 px-2 py-1.5 text-[10px] font-bold text-white backdrop-blur-sm transition-colors group-hover:bg-white/20 sm:px-3 sm:text-[11px]">
                <span className="hidden sm:inline">تسوّق الآن</span><span aria-hidden>←</span>
              </span>
            </div>
          </Link>
        ))}
      </div>
    </section>
  );
}
function HomeBanners() {
  const { data: banners, isLoading } = useHomeBanners();
  if (isLoading) return null;
  if (!banners?.length) return null;
  return (
    <section className="mx-auto max-w-6xl px-4 py-8">
      <div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-4">
        {banners.map((b) => (
          <Link key={b.id} to={linkForTarget(b.link_target)} className="group relative flex h-40 items-end overflow-hidden bg-navy sm:h-48">
            {b.image_url && <img src={b.image_url} className="absolute inset-0 h-full w-full object-cover opacity-80 transition-transform duration-500 group-hover:scale-105" alt="" />}
            <div className="relative z-10 w-full bg-gradient-to-t from-black/60 to-transparent p-3">
              {b.title && <p className="text-sm font-extrabold text-white">{b.title}</p>}
              {b.subtitle && <p className="text-xs text-white/80">{b.subtitle}</p>}
            </div>
          </Link>
        ))}
      </div>
    </section>
  );
}
function ProductSection({ title, tab, viewAllLink }) {
  const { t } = useLang();
  const { data, isLoading } = useProducts({ tab, page: 0, pageSize: 8 });
  if (!isLoading && !data?.rows.length) return null;
  const rows = data?.rows || [];
  // الشريط لازم يضل فيه منتجات "قدامه" بأي لحظة حتى ما تبين مساحة فاضية، حتى لو
  // القسم فيه منتجات قليلة (2-3 مثلًا) وعرض الشاشة عريض. الحركة بترجع لأول منتج
  // وتكرر لا نهائيًا (Loop) عن طريق تكرار نفس اللائحة عدة نسخ متلاصقة، وتحريك
  // الشريط بمقدار نسخة وحدة بالضبط (100% / عدد النسخ) — لما توصل الحركة لنص
  // النسخة الأخيرة، المشهد بيكون مطابق تمامًا لبداية الحركة، فالتكرار بيصير
  // سلس بدون أي "قفزة" أو فراغ. عدد النسخ بيزيد تلقائيًا كل ما المنتجات أقل،
  // حتى يضل فيه نسخ كافية "قدام" الشاشة بأي عرض.
  const MIN_LOOKAHEAD_CARDS = 10;
  const copies = rows.length > 0 ? Math.max(2, Math.ceil(MIN_LOOKAHEAD_CARDS / rows.length) + 1) : 2;
  const track = rows.length ? Array.from({ length: copies }, () => rows).flat() : [];
  const duration = Math.max(16, rows.length * 4.75);
  return (
    <section className="py-8">
      <div className="mx-auto max-w-6xl px-4">
        <Reveal className="mb-4 flex items-center justify-between"><h2 className="text-xl font-bold text-navy">{title}</h2><Link to={viewAllLink} className="text-sm font-medium text-brandPurple">{t('home.viewAll')} ←</Link></Reveal>
      </div>
      {isLoading ? (
        <div className="mx-auto grid max-w-6xl grid-cols-2 gap-4 px-4 sm:grid-cols-4">
          {Array.from({ length: 4 }).map((_, i) => <ProductCardSkeleton key={i} />)}
        </div>
      ) : (
        <div className="marquee-viewport px-4">
          <div className="marquee-track" style={{ '--marquee-copies': copies, animationDuration: `${duration}s` }}>
            {track.map((p, i) => (
              <div key={`${p.id}-${i}`} dir="rtl" className="w-44 flex-shrink-0 sm:w-60"><ProductCard product={p} /></div>
            ))}
          </div>
        </div>
      )}
    </section>
  );
}
function WhyUs() {
  const { t } = useLang();
  const items = [
    { icon: '🛍️', title: t('home.why1'), desc: t('home.why1desc') },
    { icon: '⭐', title: t('home.why2'), desc: t('home.why2desc') },
    { icon: '🚚', title: t('home.why3'), desc: t('home.why3desc') },
  ];
  return (
    <section className="bg-cream/60 py-10">
      <div className="mx-auto max-w-6xl px-4">
        <Reveal as="h2" className="mb-6 text-center text-xl font-bold text-navy">{t('home.whyUs')}</Reveal>
        <div className="grid grid-cols-1 gap-6 sm:grid-cols-3">
          {items.map((it) => <div key={it.title} className="text-center"><div className="mb-2 text-3xl">{it.icon}</div><h3 className="mb-1 font-bold text-navy">{it.title}</h3><p className="text-sm text-gray-600">{it.desc}</p></div>)}
        </div>
      </div>
    </section>
  );
}
function HomePage() {
  const { t } = useLang();
  const { data: settings } = useSiteSettings();
  const homeSections = settings?.homeSections || DEFAULT_SETTINGS.homeSections;
  return (
    <div>
      <HeroSlider />
      <HomeBanners />
      {homeSections.offers !== false && <ProductSection title={t('home.offers')} tab="offers" viewAllLink="/offers" />}
      <DepartmentCards />
      {homeSections.new !== false && <ProductSection title={t('home.newArrivals')} tab="new" viewAllLink="/new" />}
      {homeSections.bestseller !== false && <ProductSection title={t('home.bestseller')} tab="bestseller" viewAllLink="/bestseller" />}
      {homeSections.outlet !== false && <ProductSection title={t('home.outlet')} tab="outlet" viewAllLink="/outlet" />}
      <WhyUs />
    </div>
  );
}

/* ============================================================
   صفحة الأقسام/التصنيفات
   ============================================================ */
function CategoryPage({ department, mode, categoryIdParam, initialSearch }) {
  const { t } = useLang();
  const [search, setSearch] = useState(initialSearch || '');
  const [debounced, setDebounced] = useState(initialSearch || '');
  const [categoryId, setCategoryId] = useState(categoryIdParam || '');
  const [page, setPage] = useState(0);
  const [allRows, setAllRows] = useState([]);
  const debFn = useRef(debounce((v) => setDebounced(v), 400)).current;
  useEffect(() => { setSearch(initialSearch || ''); setDebounced(initialSearch || ''); }, [initialSearch]);
  useEffect(() => debFn(search), [search]);
  useEffect(() => { setPage(0); setAllRows([]); }, [debounced, categoryId, department, mode]);

  const tab = mode === 'new' ? 'new' : mode === 'outlet' ? 'outlet' : mode === 'offers' ? 'offers' : mode === 'bestseller' ? 'bestseller' : 'all';
  const { data: categories } = useCategories(department ? { department } : (tab !== 'all' ? { section: tab } : {}));
  const { data, isLoading, isFetching } = useProducts({ department, categoryId: categoryId || undefined, search: debounced || undefined, tab, page, pageSize: 12 });

  useEffect(() => { if (data?.rows) setAllRows((prev) => (page === 0 ? data.rows : [...prev, ...data.rows])); }, [data, page]);

  const sentinelRef = useRef(null);
  useEffect(() => {
    const el = sentinelRef.current; if (!el) return;
    const obs = new IntersectionObserver((entries) => {
      if (entries[0].isIntersecting && !isFetching && data && allRows.length < data.count) setPage((p) => p + 1);
    }, { rootMargin: '300px' });
    obs.observe(el); return () => obs.disconnect();
  }, [isFetching, data, allRows.length]);

  const titleMap = { men: t('nav.men'), women: t('nav.women'), kids: t('nav.kids'), new: t('nav.new'), outlet: t('nav.outlet'), offers: t('nav.offers'), bestseller: t('nav.bestseller') };
  const pageTitle = mode === 'search' ? `نتائج البحث عن "${initialSearch}"` : (titleMap[department || mode || ''] || 'المنتجات');
  const { data: activeOffer } = useActiveOffer();

  return (
    <div>
      <div className="mx-auto max-w-6xl px-4 py-6">
        <BackButton />
        {mode === 'offers' && activeOffer?.percent > 0 && (
          <div className="mb-4 bg-brandRed px-4 py-2.5 text-center text-sm font-bold text-white">🔥 خصم {activeOffer.percent}% على منتجات مختارة</div>
        )}
        <div className="mb-4 flex flex-wrap items-center justify-between gap-3">
          <h1 className="text-2xl font-bold text-navy">{pageTitle}</h1>
          <SearchInput value={search} onChange={setSearch} placeholder={t('common.search')} />
        </div>
        {!!categories?.length && (
          <div className="mb-5 flex gap-2 overflow-x-auto pb-1">
            <button onClick={() => setCategoryId('')} className={`whitespace-nowrap rounded-full border px-3 py-1 text-sm ${categoryId === '' ? 'border-navy bg-navy text-white' : 'border-gray-300 text-gray-600'}`}>الكل</button>
            {categories.map((c) => <button key={c.id} onClick={() => setCategoryId(c.id)} className={`whitespace-nowrap rounded-full border px-3 py-1 text-sm ${categoryId === c.id ? 'border-navy bg-navy text-white' : 'border-gray-300 text-gray-600'}`}>{c.name}</button>)}
          </div>
        )}
        {isLoading && page === 0 ? (
          <div className="grid grid-cols-2 gap-4 sm:grid-cols-3 sm:gap-5">{Array.from({ length: 8 }).map((_, i) => <ProductCardSkeleton key={i} />)}</div>
        ) : allRows.length === 0 ? <EmptyState icon="🔍" title={t('common.noResults')} /> : (
          <>
            <div className="grid grid-cols-2 gap-4 sm:grid-cols-3 sm:gap-5">{allRows.map((p) => <ProductCard key={p.id} product={p} />)}</div>
            <div ref={sentinelRef} className="h-10" />
          </>
        )}
      </div>
    </div>
  );
}

/* ============================================================
   صفحة تفاصيل المنتج
   ============================================================ */
function ProductPage({ id }) {
  const { data: product, isLoading } = useProduct(id);
  const { t } = useLang();
  const { addItem } = useCart();
  const [colorId, setColorId] = useState(null);
  const [size, setSize] = useState(null);
  const [qty, setQty] = useState(1);
  const [added, setAdded] = useState(false);
  useEffect(() => { setAdded(false); }, [colorId, size]);

  const selectedColor = useMemo(() => product?.colors?.find((c) => c.id === colorId) || product?.colors?.[0], [product, colorId]);
  const [imgIdx, setImgIdx] = useState(0);
  useEffect(() => { setImgIdx(0); }, [selectedColor]);
  const availableQty = selectedColor?.sizes?.find((s) => s.size === size)?.quantity || 0;
  const images = selectedColor?.images || [];
  const image = images[imgIdx]?.image_url || images[0]?.image_url;
  const price = product?.discount_price ?? product?.original_price ?? 0;
  const hasDiscount = !!product?.discount_price && product.discount_price < (product?.original_price || 0);

  if (isLoading) return <div className="mx-auto max-w-5xl px-4 py-8"><div className="skeleton aspect-square w-full" /></div>;
  if (!product) return <div className="p-10 text-center text-gray-500">المنتج غير موجود</div>;

  const handleAdd = () => {
    if (!size) return;
    addItem({ productId: product.id, productName: product.name, colorId: selectedColor?.id || null, colorName: selectedColor?.color_name || null, size, quantity: qty, unitPrice: price, image: image || null });
    setAdded(true);
  };

  return (
    <div className="mx-auto max-w-5xl px-4 py-6">
      <BackButton />
      <div className="grid gap-8 sm:grid-cols-2">
        <div>
          <div className="aspect-square w-full overflow-hidden bg-[#f2e9d8]">
            {image ? <img src={image} alt={product.name} className="h-full w-full object-cover" /> : <div className="flex h-full w-full items-center justify-center text-gray-400">{t('product.noImage')}</div>}
          </div>
          {images.length > 1 && (
            <div className="mt-2 flex gap-2">
              {images.map((im, i) => <button key={i} onClick={() => setImgIdx(i)} className={cn('h-16 w-16 flex-shrink-0 overflow-hidden border-2', i === imgIdx ? 'border-navy' : 'border-transparent')}><img src={im.image_url} className="h-full w-full object-cover" /></button>)}
            </div>
          )}
          {!!product.prints?.length && (
            <div className="mt-4">
              <p className="mb-1.5 text-sm font-medium text-gray-700">طبعات وتصاميم متوفرة</p>
              <div className="flex flex-wrap gap-2">
                {product.prints.map((pr) => <div key={pr.id} className="h-16 w-16 overflow-hidden bg-gray-100"><img src={pr.image_url} className="h-full w-full object-cover" /></div>)}
              </div>
            </div>
          )}
        </div>
        <div>
          {product.brand?.name && <p className="text-sm text-gray-500">{product.brand.name}</p>}
          <h1 className="mb-1 text-2xl font-bold text-brandPurple">{product.name}</h1>
          {product.custom_code && <p className="mb-2 text-xs text-gray-400">رقم القطعة: {product.custom_code}</p>}
          <div className="mb-4 flex items-center gap-2">
            <span className={hasDiscount ? 'text-2xl font-bold text-brandRed' : 'text-2xl font-bold text-navy'}>{formatPrice(price)}</span>
            {hasDiscount && <span className="text-gray-400 line-through">{formatPrice(product.original_price)}</span>}
          </div>
          {!!product.colors?.length && (
            <div className="mb-4"><p className="mb-1.5 text-sm font-medium text-gray-700">{t('product.chooseColor')}</p>
              <div className="flex gap-2">{product.colors.map((c) => <ColorDot key={c.id} hex={c.color_hex || '#ccc'} title={c.color_name} selected={(colorId || product.colors[0]?.id) === c.id} onClick={() => { setColorId(c.id); setSize(null); }} />)}</div>
            </div>
          )}
          {!!selectedColor?.sizes?.length && (
            <div className="mb-4"><p className="mb-1.5 text-sm font-medium text-gray-700">{t('product.chooseSize')}</p>
              <div className="flex flex-wrap gap-2">
                {selectedColor.sizes.map((s) => (
                  <button key={s.id} disabled={s.quantity === 0} onClick={() => setSize(s.size)} className={`min-w-[2.5rem] border px-3 py-1.5 text-sm ${size === s.size ? 'border-navy bg-navy text-white' : 'border-gray-300 text-gray-700'} ${s.quantity === 0 ? 'cursor-not-allowed opacity-40 line-through' : ''}`}>{s.size}</button>
                ))}
              </div>
              {size && <p className="mt-1 text-xs text-gray-500">{availableQty} قطعة متاحة</p>}
            </div>
          )}
          <div className="mb-5 flex items-center gap-3">
            <p className="text-sm font-medium text-gray-700">{t('product.quantity')}</p>
            <div className="flex items-center border border-gray-300"><button onClick={() => setQty((q) => Math.max(1, q - 1))} className="px-3 py-1">−</button><span className="w-8 text-center">{qty}</span><button onClick={() => setQty((q) => Math.min(availableQty || 99, q + 1))} className="px-3 py-1">+</button></div>
          </div>
          {added ? (
            <div className="space-y-2">
              <p className="text-sm font-medium text-brandGreen">✓ تمت إضافة المنتج للسلة</p>
              <Link to="/cart"><Button className="w-full !bg-amber-500 !text-navy hover:!bg-amber-400">إتمام الطلب</Button></Link>
              <Button variant="secondary" className="w-full" onClick={() => setAdded(false)}>متابعة التصفح</Button>
            </div>
          ) : (
            <Button className="w-full" disabled={!size} onClick={handleAdd}>{t('product.addToCart')}</Button>
          )}
          <button className="mt-3 block text-sm text-brandPurple">{t('product.addToFavorites')} ♡</button>
        </div>
      </div>
    </div>
  );
}

/* ============================================================
   السلة والدفع
   ============================================================ */
const PHONE_PREFIXES = ['970', '972'];
function CartPage() {
  const { t } = useLang();
  const { items, total, removeItem, updateQuantity, clear, discountCode, redeemLoyalty: redeem, setRedeemLoyalty: setRedeem } = useCart();
  const { customerId, customerCity, loyaltyPoints, setLoyaltyPoints } = useCustomerAuth();
  const { data: settings } = useSiteSettings();
  const loyalty = settings?.loyalty || DEFAULT_SETTINGS.loyalty;
  const deliveryPrices = settings?.delivery || DEFAULT_SETTINGS.delivery;
  const canRedeem = loyalty.enabled && customerId && loyaltyPoints >= loyalty.redeemThreshold;
  const [guestName, setGuestName] = useState(''); const [phonePrefix, setPhonePrefix] = useState('970'); const [guestPhoneRest, setGuestPhoneRest] = useState(''); const [address, setAddress] = useState('');
  const [city, setCity] = useState(() => customerCity || ''); const [deliveryZone, setDeliveryZone] = useState(''); const [notes, setNotes] = useState('');
  const [paymentMethod, setPaymentMethod] = useState('cod'); const [receiptFile, setReceiptFile] = useState(null);
  const [placing, setPlacing] = useState(false); const [done, setDone] = useState(null); const [err, setErr] = useState(null);
  const [reviewRating, setReviewRating] = useState(0); const [reviewComment, setReviewComment] = useState(''); const [reviewState, setReviewState] = useState('idle');
  const displayTotal = canRedeem && redeem ? total * (1 - loyalty.discountPercent / 100) : total;
  const deliveryFee = deliveryZone ? Number(deliveryPrices[deliveryZone] || 0) : 0;
  const grandTotal = displayTotal + deliveryFee;

  if (items.length === 0 && !done) return (
    <div className="mx-auto max-w-2xl px-4 py-8">
      <BackButton />
      <EmptyState icon="🛒" title={t('cart.empty')} />
    </div>
  );

  const placeOrder = async () => {
    const phoneDigits = guestPhoneRest.trim().replace(/\D/g, '').replace(/^0+/, '');
    if (!deliveryZone) { setErr('الرجاء اختيار منطقة التوصيل'); return; }
    if (!city.trim()) { setErr('الرجاء إدخال الموقع'); return; }
    if (!customerId && (!guestName.trim() || !phoneDigits || !address.trim())) { setErr('الرجاء تعبئة الاسم ورقم الجوال والعنوان لإتمام الطلب كضيف'); return; }
    if (paymentMethod === 'reflect' && !receiptFile) { setErr('الرجاء إرفاق صورة وصل التحويل'); return; }
    setPlacing(true); setErr(null);
    try {
      let receiptUrl = null;
      if (paymentMethod === 'reflect' && receiptFile) receiptUrl = await uploadReceiptImage(receiptFile);
      // مصدر الحقيقة الوحيد للمخزون وكود الخصم ورسم التوصيل صار داخل دالة place_order بقاعدة البيانات
      // (تتحقق من الكمية المتوفرة لكل Product+Color+Size وتخصم منها بشكل آمن، وتحدّث عدد استخدامات كود الخصم فعليًا،
      // وتجيب سعر التوصيل الفعلي حسب المنطقة من إعدادات لوحة التحكم — القيمة المعروضة هون بالواجهة للمعاينة فقط)
      const { data, error } = await sb.rpc('place_order', {
        p_customer_id: customerId || null,
        p_guest_name: customerId ? null : guestName.trim(),
        p_guest_phone: customerId ? null : (phonePrefix + phoneDigits),
        p_address: address.trim(),
        p_discount_code: discountCode || null,
        p_items: items.map((it) => ({ product_id: it.productId, product_color_id: it.colorId, size: it.size, quantity: it.quantity, unit_price: it.unitPrice })),
        p_redeem_loyalty: canRedeem && redeem,
        p_city: city.trim(),
        p_delivery_zone: deliveryZone,
        p_notes: notes.trim() || null,
        p_payment_method: paymentMethod,
        p_reflect_receipt_url: receiptUrl,
      });
      if (error) throw error;
      const result = Array.isArray(data) ? data[0] : data;
      if (!result?.success) { setErr(result?.message || 'تعذّر إتمام الطلب — تأكد من توفر الكمية المطلوبة'); return; }
      if (customerId && result.points_balance != null) setLoyaltyPoints(result.points_balance);
      setDone({ orderId: result.order_id, orderNumber: result.order_number, pointsEarned: result.points_earned || 0, redeemed: !!result.loyalty_redeemed, deliveryFee: result.delivery_fee || 0 });
      clear(); setRedeem(false);
    } catch (e) { setErr(e.message || 'حدث خطأ أثناء إرسال الطلب'); } finally { setPlacing(false); }
  };

  const submitReview = async () => {
    if (!reviewRating) return;
    setReviewState('saving');
    try {
      const { error } = await sb.from('reviews').insert({ order_id: done.orderId || null, customer_id: customerId || null, rating: reviewRating, comment: reviewComment.trim() || null, review_type: 'تجربة الطلب' });
      if (error) throw error;
      setReviewState('done');
    } catch (e) { setReviewState('idle'); }
  };

  if (done) return (
    <div className="mx-auto max-w-lg px-4 py-16 text-center">
      <div className="mb-3 text-4xl">✅</div><h2 className="mb-2 text-xl font-bold text-navy">تم استلام طلبك بنجاح</h2>
      <p className="mb-2 text-gray-600">رقم الطلب: {done.orderNumber}</p>
      {done.deliveryFee > 0 && <p className="mb-2 text-sm text-gray-500">شامل رسم توصيل {formatPrice(done.deliveryFee)}</p>}
      {done.redeemed && <p className="mb-2 text-sm font-semibold text-brandGreen">تم تطبيق خصم نقاط الولاء على هذا الطلب ⚡</p>}
      {done.pointsEarned > 0 && <p className="mb-6 text-sm text-navy">ربحت {done.pointsEarned} نقطة ولاء من هذا الطلب</p>}

      {reviewState === 'done' ? (
        <p className="mb-6 text-sm font-semibold text-brandGreen">شكرًا إلك على تقييمك! ⭐</p>
      ) : (
        <div className="mx-auto mb-6 max-w-xs border border-navy/15 bg-cream-light px-4 py-4">
          <p className="mb-2 text-sm font-medium text-gray-700">كيف كانت تجربتك بالطلب؟</p>
          <div className="mb-3 flex justify-center gap-1 text-2xl">
            {[1, 2, 3, 4, 5].map((n) => (
              <button key={n} type="button" onClick={() => setReviewRating(n)} className={cn('transition-transform hover:scale-110', n <= reviewRating ? 'opacity-100' : 'opacity-30')}>⭐</button>
            ))}
          </div>
          {reviewRating > 0 && (
            <>
              <textarea value={reviewComment} onChange={(e) => setReviewComment(e.target.value)} placeholder="تعليق (اختياري)" rows={2} className="mb-2 w-full border border-gray-300 px-3 py-2 text-sm outline-none focus:border-navy" />
              <Button className="w-full" onClick={submitReview} disabled={reviewState === 'saving'}>{reviewState === 'saving' ? '...' : 'إرسال التقييم'}</Button>
            </>
          )}
        </div>
      )}

      <Button variant={reviewState === 'done' ? 'primary' : 'ghost'} className="w-full" onClick={() => navigate('/')}>العودة للمتجر</Button>
    </div>
  );

  return (
    <div className="mx-auto max-w-2xl px-4 py-8">
      <BackButton />
      <h1 className="mb-5 text-2xl font-bold text-navy">{t('nav.cart')}</h1>
      <div className="mb-6 divide-y">
        {items.map((it, i) => (
          <div key={i} className="flex items-center gap-3 py-3">
            <div className="h-16 w-16 flex-shrink-0 overflow-hidden bg-gray-100">{it.image && <img src={it.image} className="h-full w-full object-cover" />}</div>
            <div className="flex-1"><p className="font-medium">{it.productName}</p><p className="text-xs text-gray-500">{it.colorName} · {it.size}</p>
              <div className="mt-1 flex items-center gap-2"><button onClick={() => updateQuantity(i, it.quantity - 1)} className="border px-2">−</button><span>{it.quantity}</span><button onClick={() => updateQuantity(i, it.quantity + 1)} className="border px-2">+</button></div>
            </div>
            <div className="text-left"><p className="font-bold text-navy">{formatPrice(it.unitPrice * it.quantity)}</p><button onClick={() => removeItem(i)} className="text-xs text-brandRed">{t('common.delete')}</button></div>
          </div>
        ))}
      </div>
      <div className="mb-6 space-y-3 border-t pt-5">
        {!customerId && (
          <>
            <p className="text-sm font-medium text-gray-700">{t('account.guestCheckout')}</p>
            <Input placeholder="الاسم الكامل" value={guestName} onChange={(e) => setGuestName(e.target.value)} />
            <div className="flex gap-2">
              <Select className="!w-28 flex-shrink-0" value={phonePrefix} onChange={(e) => setPhonePrefix(e.target.value)}>
                {PHONE_PREFIXES.map((p) => <option key={p} value={p}>+{p}</option>)}
              </Select>
              <Input placeholder="رقم الجوال بدون الصفر — مثال 599123456" value={guestPhoneRest} onChange={(e) => setGuestPhoneRest(e.target.value.replace(/\D/g, ''))} />
            </div>
          </>
        )}
        <div>
          <p className="mb-1.5 text-sm font-medium text-gray-700">منطقة التوصيل</p>
          <div className="grid grid-cols-3 gap-2">
            {DELIVERY_ZONES.map((z) => (
              <button
                key={z.key}
                type="button"
                onClick={() => setDeliveryZone(z.key)}
                className={cn(
                  'border px-2 py-2 text-center text-sm font-medium transition-colors',
                  deliveryZone === z.key ? 'border-navy bg-navy text-white' : 'border-gray-300 text-gray-600 hover:border-navy/50'
                )}
              >
                <span className="block">{z.label}</span>
                <span className={cn('block text-xs', deliveryZone === z.key ? 'text-white/70' : 'text-gray-400')}>{formatPrice(deliveryPrices[z.key] || 0)}</span>
              </button>
            ))}
          </div>
        </div>
        <div className="grid gap-3 sm:grid-cols-2">
          <Input placeholder="الموقع (المدينة/البلدة)" value={city} onChange={(e) => setCity(e.target.value)} />
          <Input placeholder="تفاصيل العنوان" value={address} onChange={(e) => setAddress(e.target.value)} />
        </div>
        <div>
          <p className="mb-1.5 text-sm font-medium text-gray-700">طريقة الدفع</p>
          <div className="grid grid-cols-2 gap-2">
            <button type="button" onClick={() => setPaymentMethod('cod')} className={cn('border px-2 py-2 text-center text-sm font-medium transition-colors', paymentMethod === 'cod' ? 'border-navy bg-navy text-white' : 'border-gray-300 text-gray-600 hover:border-navy/50')}>الدفع عند الاستلام</button>
            <button type="button" onClick={() => setPaymentMethod('reflect')} className={cn('border px-2 py-2 text-center text-sm font-medium transition-colors', paymentMethod === 'reflect' ? 'border-navy bg-navy text-white' : 'border-gray-300 text-gray-600 hover:border-navy/50')}>تحويل رفلكت</button>
          </div>
          {paymentMethod === 'reflect' && (
            <div className="mt-2 border border-navy/20 bg-cream-light p-3 text-sm">
              {settings?.reflectNumber ? <p className="mb-2 font-medium text-navy">حوّل المبلغ على رقم رفلكت: <span className="font-bold">{settings.reflectNumber}</span></p> : <p className="mb-2 text-gray-500">حوّل المبلغ عبر رفلكت — رقم التحويل غير محدد بعد، تواصل معنا.</p>}
              <label className="mb-1 block text-xs text-gray-600">صورة وصل التحويل</label>
              <input type="file" accept="image/*" onChange={(e) => setReceiptFile(e.target.files?.[0] || null)} />
              {receiptFile && <p className="mt-1 text-xs text-brandGreen">تم اختيار: {receiptFile.name}</p>}
            </div>
          )}
        </div>
        <textarea
          placeholder="ملاحظات على الطلب (اختياري)"
          value={notes}
          onChange={(e) => setNotes(e.target.value)}
          rows={2}
          className="w-full border border-gray-300 px-3 py-2 text-sm outline-none focus:border-navy focus:ring-1 focus:ring-navy"
        />
      </div>
      {canRedeem && (
        <label className="mb-4 flex cursor-pointer items-center justify-between border border-navy/20 bg-cream-light px-4 py-3 text-sm">
          <span className="flex items-center gap-2 font-medium text-navy">⚡ استخدم {loyalty.redeemThreshold} نقطة لخصم {loyalty.discountPercent}%</span>
          <input type="checkbox" checked={redeem} onChange={(e) => setRedeem(e.target.checked)} className="h-5 w-5 accent-navy" />
        </label>
      )}
      {err && <p className="mb-3 text-sm text-brandRed">{err}</p>}
      <div className="mb-4 space-y-1 border-t pt-3">
        <div className="flex items-center justify-between text-sm text-gray-600"><span>مجموع المنتجات</span><span>{formatPrice(displayTotal)}</span></div>
        {deliveryZone && <div className="flex items-center justify-between text-sm text-gray-600"><span>رسم التوصيل</span><span>{formatPrice(deliveryFee)}</span></div>}
        <div className="flex items-center justify-between text-lg font-bold"><span>{t('cart.total')}</span><span className="text-navy">{formatPrice(grandTotal)}</span></div>
      </div>
      <Button className="w-full" onClick={placeOrder} disabled={placing}>{placing ? '...' : t('cart.checkout')}</Button>
    </div>
  );
}

/* ============================================================
   الحساب وسجل الطلبات والمفضلة
   ============================================================ */
function AccountPage() {
  const { t } = useLang();
  const { customerId, customerName, loyaltyPoints, setCustomer, logout } = useCustomerAuth();
  const { data: settings } = useSiteSettings();
  const [mode, setMode] = useState('login');
  const [phonePrefix, setPhonePrefix] = useState('970'); const [phone, setPhone] = useState(''); const [password, setPassword] = useState(''); const [name, setName] = useState(''); const [city, setCity] = useState('');
  const [err, setErr] = useState(null); const [loading, setLoading] = useState(false);

  if (customerId) {
    const loyalty = settings?.loyalty || DEFAULT_SETTINGS.loyalty;
    return (
      <div className="mx-auto max-w-md px-4 py-10 text-center">
        <BackButton className="text-right" />
        <div className="mb-3 text-3xl">👤</div><h2 className="mb-1 text-xl font-bold text-navy">{customerName}</h2>
        {loyalty.enabled && (
          <div className="mx-auto mt-4 max-w-xs border border-navy/15 bg-cream-light px-4 py-3 text-sm">
            <p className="font-bold text-navy">⚡ {loyaltyPoints} نقطة ولاء</p>
            <p className="mt-1 text-xs text-gray-500">
              {loyaltyPoints >= loyalty.redeemThreshold
                ? `عندك خصم ${loyalty.discountPercent}% جاهز تستخدمه بأي طلب جديد`
                : `اجمع ${Math.max(loyalty.redeemThreshold - loyaltyPoints, 0)} نقطة إضافية لتحصل على خصم ${loyalty.discountPercent}%`}
            </p>
          </div>
        )}
        <div className="mt-6 space-y-2"><Link to="/account/orders"><Button variant="secondary" className="w-full">{t('account.orders')}</Button></Link><Button variant="ghost" className="w-full" onClick={logout}>تسجيل الخروج</Button></div>
      </div>
    );
  }

  const submit = async () => {
    setErr(null);
    const phoneDigits = phone.trim().replace(/\D/g, '').replace(/^0+/, '');
    if (!phoneDigits || !password.trim() || (mode === 'register' && !name.trim())) { setErr('الرجاء تعبئة كل الحقول'); return; }
    const fullPhone = phonePrefix + phoneDigits;
    setLoading(true);
    try {
      const hash = await simpleHash(password);
      if (mode === 'register') {
        const { data, error } = await sb.rpc('register_customer', { p_phone: fullPhone, p_password_hash: hash, p_name: name.trim(), p_city: city.trim() || null });
        if (error) throw error;
        setCustomer(data, name.trim(), 0, city.trim());
      } else {
        const { data, error } = await sb.rpc('login_customer', { p_phone: fullPhone, p_password_hash: hash });
        if (error) throw error;
        const row = data?.[0];
        if (!row) { setErr('رقم الجوال أو كلمة المرور غير صحيحة'); return; }
        setCustomer(row.id, row.name, row.loyalty_points || 0, row.city);
      }
      navigate('/');
    } catch (e) { setErr(e.message || 'حدث خطأ'); } finally { setLoading(false); }
  };

  return (
    <div className="mx-auto max-w-md px-4 py-10">
      <BackButton />
      <div className="mb-6 flex gap-2">
        <button onClick={() => setMode('login')} className={`flex-1 border-b-2 pb-2 font-semibold ${mode === 'login' ? 'border-navy text-navy' : 'border-transparent text-gray-400'}`}>{t('account.login')}</button>
        <button onClick={() => setMode('register')} className={`flex-1 border-b-2 pb-2 font-semibold ${mode === 'register' ? 'border-navy text-navy' : 'border-transparent text-gray-400'}`}>{t('account.register')}</button>
      </div>
      <div className="space-y-3">
        {mode === 'register' && <Input placeholder="الاسم الكامل" value={name} onChange={(e) => setName(e.target.value)} />}
        <div className="flex gap-2">
          <Select className="!w-28 flex-shrink-0" value={phonePrefix} onChange={(e) => setPhonePrefix(e.target.value)}>
            {PHONE_PREFIXES.map((p) => <option key={p} value={p}>+{p}</option>)}
          </Select>
          <Input placeholder={t('account.phone')} value={phone} onChange={(e) => setPhone(e.target.value.replace(/\D/g, ''))} />
        </div>
        {mode === 'register' && <Input placeholder="الموقع (المدينة/البلدة)" value={city} onChange={(e) => setCity(e.target.value)} />}
        <Input type="password" placeholder={t('account.password')} value={password} onChange={(e) => setPassword(e.target.value)} />
        {err && <p className="text-sm text-brandRed">{err}</p>}
        <Button className="w-full" onClick={submit} disabled={loading}>{loading ? '...' : mode === 'login' ? t('account.login') : t('account.register')}</Button>
      </div>
      <div className="mt-6 border-t pt-5 text-center"><Link to="/cart" className="text-sm text-brandPurple">{t('account.guestCheckout')} ←</Link></div>
    </div>
  );
}
function OrdersPage() {
  const { customerId } = useCustomerAuth();
  const [orders, setOrders] = useState(null);
  useEffect(() => { if (customerId) sb.rpc('get_my_orders', { p_customer_id: customerId }).then(({ data }) => setOrders(data || [])); }, [customerId]);
  if (!customerId) { navigate('/account'); return null; }
  const statusLabel = { new: 'جديد', awaiting_confirmation: 'بانتظار تأكيدك', confirmed: 'مؤكّد', completed: 'مكتمل', cancelled: 'ملغي' };
  return (
    <div className="mx-auto max-w-2xl px-4 py-8">
      <BackButton />
      <h1 className="mb-5 text-2xl font-bold text-navy">سجل الطلبات</h1>
      {orders === null ? <div className="skeleton h-20 w-full" /> : orders.length === 0 ? <EmptyState icon="📦" title="ما في طلبات لسا" /> : (
        <div className="space-y-3">
          {orders.map((o) => (
            <div key={o.id} className="border border-gray-200 p-4">
              <div className="mb-1 flex items-center justify-between"><span className="font-bold text-navy">#{o.order_number}</span><Badge color="navy">{statusLabel[o.status]}</Badge></div>
              <p className="text-sm text-gray-500">{formatDate(o.created_at)}</p><p className="mt-1 font-bold">{formatPrice(o.total_amount)}</p>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}
function FavoritesPage() {
  const { t } = useLang();
  return <div className="mx-auto max-w-4xl px-4 py-10"><BackButton /><h1 className="mb-5 text-2xl font-bold text-navy">{t('nav.favorites')}</h1><EmptyState icon="♡" title="لسا ما ضفت شي للمفضلة" /></div>;
}

/* ============================================================
   لوحة الأدمن — تسجيل الدخول والقالب العام
   ============================================================ */
// إيميل ثابت داخلي فقط لربط جلسة Supabase Auth (يبقى ضروري لصلاحيات RLS بقاعدة البيانات)،
// ما بيظهر للمدير أبدًا — هو بس بيحط كلمة المرور وبس.
const ADMIN_EMAIL = 'admin@supershop.com';
function AdminLoginPage() {
  const { login, session, isAdmin, loading } = useAdminAuth();
  const { lang, at, setLang } = useAdminLang();
  const [password, setPassword] = useState('');
  const [err, setErr] = useState(null); const [submitting, setSubmitting] = useState(false);
  useEffect(() => { if (!loading && session && isAdmin) navigate('/admin/accounting'); }, [loading, session, isAdmin]);
  // إذا سجّل دخول بنجاح (session موجودة) بس تبيّن إنو الحساب مش أدمن (isAdmin ضلت false
  // بعد ما خلص التحقق)، منوريه رسالة واضحة بدل ما يضل عالق بصفحة الدخول من غير تفسير.
  useEffect(() => {
    if (!loading && session && !isAdmin) {
      setErr(at('هذا الحساب غير مخوّل كأدمن (تحقق من جدول admin_users)', 'This account is not authorized as admin (check admin_users table)'));
      setSubmitting(false);
    }
  }, [loading, session, isAdmin]);
  const submit = async (e) => {
    e.preventDefault(); setSubmitting(true); setErr(null);
    const m = await login(ADMIN_EMAIL, password);
    if (m) { setSubmitting(false); setErr(at('كلمة المرور غير صحيحة', 'Incorrect password')); return; }
    // لا ننتقل يدوياً هون — منستنى الـ useEffect فوق يتأكد إنو isAdmin صارت true
    // (بعد ما يخلص فحص admin_users) وينقل تلقائياً. النقل اليدوي القديم كان يصير
    // قبل ما يخلص فحص الصلاحية، فيرجّع المستخدم على صفحة الدخول من غير سبب ظاهر.
    setTimeout(() => setSubmitting(false), 4000);
  };
  return (
    <div className="flex min-h-screen items-center justify-center bg-navy px-4" dir={lang === 'en' ? 'ltr' : 'rtl'}>
      <form onSubmit={submit} className="w-full max-w-sm bg-white p-8 shadow-xl">
        <div className="mb-3 flex justify-end"><AdminLangSwitch lang={lang} setLang={setLang} /></div>
        <div className="mb-6 text-center"><h1 className="flex items-center justify-center gap-1.5 font-display text-2xl font-extrabold text-navy"><ThunderBolt className="h-4 w-4" />SUPER SHOP</h1><p className="mt-1 text-sm text-gray-500">{at('دخول مدير المتجر', 'Store manager login')}</p></div>
        <div className="space-y-3">
          <Input type="password" placeholder={at('كلمة المرور', 'Password')} value={password} onChange={(e) => setPassword(e.target.value)} required autoFocus />
          {err && <p className="text-sm text-brandRed">{err}</p>}
          <Button type="submit" className="w-full" disabled={submitting}>{submitting ? '...' : at('دخول', 'Log in')}</Button>
        </div>
        <a href="#/" className="mt-5 block text-center text-sm text-gray-400">{at('العودة للمتجر', 'Back to store')}</a>
      </form>
    </div>
  );
}
const ADMIN_NAV = [
  { to: '/admin/reviews', label: 'التقييمات', labelEn: 'Reviews', icon: '⭐' }, { to: '/admin/accounting', label: 'لوحة الحسابات', labelEn: 'Accounting', icon: '💰' },
  { to: '/admin/products', label: 'المنتجات', labelEn: 'Products', icon: '👕' }, { to: '/admin/categories', label: 'التصنيفات', labelEn: 'Categories', icon: '🗂️' },
  { to: '/admin/orders', label: 'الطلبات', labelEn: 'Orders', icon: '📦' }, { to: '/admin/customers', label: 'العملاء', labelEn: 'Customers', icon: '🧑‍🤝‍🧑' },
  { to: '/admin/inventory', label: 'المخزون', labelEn: 'Inventory', icon: '📊' }, { to: '/admin/loyalty', label: 'الولاء والخصومات', labelEn: 'Loyalty & discounts', icon: '🎁' },
  { to: '/admin/delivery', label: 'مناطق التوصيل', labelEn: 'Delivery zones', icon: '🚚' },
  { to: '/admin/site-editor', label: 'تعديل صفحة العميل', labelEn: 'Storefront editor', icon: '🎨' },
];
// عدد الطلبات الجديدة الي لسا ما أرسلنالها رسالة تأكيد — تُستخدم لإضاءة/شارة عنصر "الطلبات" بالقائمة الجانبية.
function useNewOrdersCount() {
  const { data, refetch } = useSupaQuery(['admin_new_orders_count'], async () => {
    const { count, error } = await sb.from('orders').select('id', { count: 'exact', head: true }).eq('status', 'new');
    if (error) throw error;
    return count || 0;
  });
  useEffect(() => {
    const interval = setInterval(() => refetch(), 20000);
    return () => clearInterval(interval);
  }, [refetch]);
  return data || 0;
}
/* ============================================================
   إشعارات المدير (OneSignal) — تنبيه فوري لما يوصل طلب جديد أو ينفذ
   مخزون، حتى لو لوحة التحكم مسكّرة/الجوال مقفول (بس شغّال ومتصل بالنت).
   ============================================================ */
// حارس على مستوى الملف (مو خاصية على كائن OneSignal) حتى نضمن إنه
// OneSignal.init() ينادى مرة وحدة بس بعمر الصفحة، بغض النظر عن عدد
// مرات إعادة تشغيل الـ effect أو استقرار مرجع كائن OneSignal نفسه.
// قبل هيك كنا معتمدين على OneSignal._ssInited اللي فشل وسبب خطأ
// "SDK already initialized" ومنع تسجيل الـ Service Worker بالكامل.
let __oneSignalInitStarted = false;
function useAdminPushNotifications() {
  const { lang } = useLang();
  const at = (ar, en) => (lang === 'en' ? en : ar);
  const [status, setStatus] = useState('checking'); // checking | unsupported | not-configured | subscribed | idle
  const [busy, setBusy] = useState(false);
  const [lastError, setLastError] = useState('');

  const refreshStatus = useCallback(async () => {
    if (!window.OneSignal) { setStatus('checking'); return; }
    try {
      const optedIn = await window.OneSignal.User.PushSubscription.optedIn;
      setStatus(optedIn ? 'subscribed' : 'idle');
    } catch { setStatus('idle'); }
  }, []);

  useEffect(() => {
    if (!ONESIGNAL_APP_ID || ONESIGNAL_APP_ID.startsWith('REPLACE_')) { setStatus('not-configured'); return; }
    if (!('Notification' in window) || !('serviceWorker' in navigator)) { setStatus('unsupported'); return; }
    // إذا التهيئة تمت (أو بدأت) قبل هيك بأي مكان بالصفحة، منكتفي بتحديث الحالة
    // وما منعيد نداء init() تاني — نداء init() أكتر من مرة بيرمي خطأ
    // "SDK already initialized" ويوقف باقي عملية التسجيل (Service Worker + إذن).
    if (__oneSignalInitStarted) { refreshStatus(); return; }
    __oneSignalInitStarted = true;
    window.OneSignalDeferred = window.OneSignalDeferred || [];
    window.OneSignalDeferred.push(async (OneSignal) => {
      try {
        await OneSignal.init({ appId: ONESIGNAL_APP_ID });
        refreshStatus();
      } catch (e) {
        setLastError(at('فشل تهيئة OneSignal (init): ', 'OneSignal initialization failed (init): ') + (e?.message || String(e)));
        setStatus('idle');
      }
    });
  }, [refreshStatus]);

  const diag = async () => {
    const yes = at('نعم', 'Yes');
    const no = at('لأ ❌', 'No ❌');
    const lines = [];
    lines.push(at('OneSignal SDK محمّل: ', 'OneSignal SDK loaded: ') + (window.OneSignal ? yes : no));
    lines.push(at('Notification API بالجهاز: ', 'Notification API on device: ') + ('Notification' in window ? yes : no));
    lines.push(at('Service Worker مدعوم: ', 'Service Worker supported: ') + ('serviceWorker' in navigator ? yes : no));
    lines.push(at('إذن الإشعارات الحالي (Notification.permission): ', 'Current notification permission (Notification.permission): ') + (window.Notification ? window.Notification.permission : at('غير معروف', 'unknown')));
    try {
      const regs = await navigator.serviceWorker.getRegistrations();
      lines.push(at('عدد Service Workers مسجّلين: ', 'Registered Service Workers: ') + regs.length);
      regs.forEach((r, i) => lines.push(`  [${i}] scope=${r.scope} active=${!!r.active}`));
    } catch (e) { lines.push(at('خطأ بفحص Service Worker: ', 'Error checking Service Worker: ') + e.message); }
    if (window.OneSignal) {
      try { lines.push('OneSignal permission: ' + window.OneSignal.Notifications.permission); } catch (e) { lines.push(at('خطأ بقراءة permission: ', 'Error reading permission: ') + e.message); }
      try { lines.push('OneSignal optedIn: ' + (await window.OneSignal.User.PushSubscription.optedIn)); } catch (e) { lines.push(at('خطأ بقراءة optedIn: ', 'Error reading optedIn: ') + e.message); }
      try { lines.push('OneSignal subscription id: ' + (await window.OneSignal.User.PushSubscription.id)); } catch (e) { lines.push(at('خطأ بقراءة id: ', 'Error reading id: ') + e.message); }
    }
    lines.push(at('standalone (مفتوح من الشاشة الرئيسية؟): ', 'standalone (opened from home screen?): ') + (window.navigator.standalone === true || window.matchMedia('(display-mode: standalone)').matches ? yes : at('لأ — أنت فاتحه بسفاري عادي مش من الأيقونة!', 'No — you opened it in a regular browser, not from the icon!')));
    if (lastError) lines.push(at('آخر خطأ مسجّل: ', 'Last recorded error: ') + lastError);
    return lines.join('\n');
  };

  const enable = async () => {
    if (!window.OneSignal) { setLastError(at('window.OneSignal لسا مش محمّل — جرب اسكرول لتحت شوي واستنى ثانيتين وجرب تاني.', 'window.OneSignal is not loaded yet — try scrolling down a bit, wait a couple seconds, and try again.')); return; }
    setBusy(true);
    setLastError('');
    try {
      await window.OneSignal.Notifications.requestPermission();
      if (!window.OneSignal.Notifications.permission) {
        setLastError(at('الجهاز رفض إذن الإشعارات أو ما ضغطت "Allow" — روح لإعدادات الجهاز ← الإشعارات وفعّلها يدويًا لهاد الموقع، وجرب تاني.', 'The device denied notification permission or you didn\'t tap "Allow" — go to device settings → Notifications and enable it manually for this site, then try again.'));
        return;
      }
      // requestPermission لحاله بس بيطلب إذن المتصفح/الجهاز — لازم كمان optIn الصريح حتى
      // ينشئ OneSignal اشتراك فعلي (Subscription) يظهر بلوحة Audience، وإلا بيضل الإذن
      // ممنوح بس بدون أي اشتراك مسجّل.
      await window.OneSignal.User.PushSubscription.optIn();
      await window.OneSignal.User.addTag('role', 'admin');
      await refreshStatus();
    } catch (e) {
      setLastError(at('ما قدرنا نفعّل الإشعارات: ', 'Could not enable notifications: ') + (e?.message || String(e)));
    } finally { setBusy(false); }
  };

  return { status, busy, enable, diag, lastError, at };
}
function NotificationsButton() {
  const { status, busy, enable, diag, lastError, at } = useAdminPushNotifications();
  const [diagOpen, setDiagOpen] = useState(false);
  const [diagText, setDiagText] = useState(() => at('...جاري الفحص', '...checking'));
  const openDiag = async () => { setDiagOpen(true); setDiagText(await diag()); };
  const diagModal = (
    <Modal open={diagOpen} onClose={() => setDiagOpen(false)} title={at('تشخيص الإشعارات', 'Notification diagnostics')}>
      <pre className="max-h-96 overflow-auto whitespace-pre-wrap rounded bg-gray-50 p-3 text-left text-xs" dir="ltr">{diagText}</pre>
      <p className="mt-2 text-xs text-gray-400">{at('صوّر هاد الكلام وابعته حتى نعرف بالضبط وين المشكلة.', 'Screenshot this and send it over so we can pinpoint the issue.')}</p>
    </Modal>
  );
  if (status === 'not-configured') return <span className="hidden text-xs text-gray-300 sm:inline" title={at('لسا ما تم ربط خدمة الإشعارات', 'Notification service not connected yet')}>🔕 {at('الإشعارات غير مفعّلة بالمشروع', 'Notifications are not enabled for this project')}</span>;
  if (status === 'unsupported') return null;
  if (status === 'subscribed') return (
    <>
      <span className="hidden items-center gap-1 text-xs font-medium text-brandGreen sm:flex">🔔 {at('التنبيهات مفعّلة', 'Notifications enabled')}</span>
      <button onClick={openDiag} className="text-[11px] text-gray-300 underline">{at('تشخيص', 'Diagnostics')}</button>
      {diagModal}
    </>
  );
  return (
    <div className="flex items-center gap-1.5">
      <button onClick={enable} disabled={busy || status === 'checking'} className="flex items-center gap-1 rounded border border-navy px-2.5 py-1 text-xs font-medium text-navy hover:bg-navy hover:text-white disabled:opacity-50">
        🔔 {busy ? '...' : at('تفعيل التنبيهات', 'Enable notifications')}
      </button>
      <button onClick={openDiag} className="text-[11px] text-gray-300 underline">{at('تشخيص', 'Diagnostics')}</button>
      {lastError && <button onClick={() => alert(lastError)} className="max-w-[90px] truncate text-[11px] text-brandRed underline sm:max-w-[220px]" title={lastError}>⚠ {at('خطأ (دوس)', 'Error (tap)')}</button>}
      {diagModal}
    </div>
  );
}
// هيلبر ترجمة لوحة الأدمن — بيستخدم نفس اختيار اللغة العالمي المستخدم بواجهة الزبون (lang/setLang)
// بس بيخلي كل نص جوا لوحة الأدمن قريب من مكان استخدامه (at('نص عربي', 'English text')) بدل قاموس
// مركزي منفصل لازم يضل متزامن مع عشرات الصفحات — أنسب لطبيعة الملف الواحد (Zero-Build).
function useAdminLang() {
  const { lang, setLang } = useLang();
  const at = (ar, en) => (lang === 'en' ? en : ar);
  return { lang, setLang, at };
}
function AdminLangSwitch({ lang, setLang }) {
  return (
    <select value={lang} onChange={(e) => setLang(e.target.value)} className="border border-gray-300 bg-white px-2 py-1 text-xs text-gray-600 outline-none">
      <option value="ar">عربي</option>
      <option value="en">English</option>
    </select>
  );
}
function AdminLayout({ children }) {
  const { session, logout } = useAdminAuth();
  const { lang, at, setLang } = useAdminLang();
  const route = useRoute();
  const [sidebarOpen, setSidebarOpen] = useState(false);
  const email = session?.user?.email || '';
  const newOrdersCount = useNewOrdersCount();
  const dir = lang === 'en' ? 'ltr' : 'rtl';
  return (
    <div className="flex min-h-screen bg-cream" dir={dir}>
      {sidebarOpen && <div className="fixed inset-0 z-30 bg-black/40 sm:hidden" onClick={() => setSidebarOpen(false)} />}
      <aside className={cn('fixed inset-y-0 z-40 w-64 transform overflow-y-auto bg-white shadow-lg transition-transform sm:translate-x-0', dir === 'rtl' ? 'right-0' : 'left-0', sidebarOpen ? 'translate-x-0' : (dir === 'rtl' ? 'translate-x-full sm:translate-x-0' : '-translate-x-full sm:translate-x-0'))}>
        <div className="flex h-full flex-col">
          <div className="border-b border-gray-100 p-4">
            <div className="mb-1 flex items-start justify-between">
              <a href="#/" target="_blank" className="text-xs font-medium text-brandPurple">{at('واجهة الزبائن ↗', 'Storefront ↗')}</a>
              <button className="text-gray-400 sm:hidden" onClick={() => setSidebarOpen(false)}>✕</button>
            </div>
            <div className="flex items-center gap-1.5 font-display text-lg font-extrabold text-navy"><ThunderBolt className="h-3.5 w-3.5" />SUPER SHOP</div><p className="text-xs text-gray-500">{at('ملابس ومستلزمات رياضية', 'Sportswear & gear')}</p>
          </div>
          <div className="flex-1 overflow-y-auto py-2">
            <p className="px-4 py-2 text-xs font-bold text-gray-400">{at('إدارة المتجر', 'Store management')}</p>
            <nav className="space-y-0.5 px-2">
              {ADMIN_NAV.map((n) => {
                const isOrders = n.to === '/admin/orders';
                const glowing = isOrders && newOrdersCount > 0;
                return (
                  <Link key={n.to} to={n.to} onClick={() => setSidebarOpen(false)} className={cn('flex items-center gap-2 rounded px-3 py-2 text-sm font-medium', route === n.to ? 'bg-navy text-white' : 'text-gray-700 hover:bg-gray-100', glowing && 'animate-glow')}>
                    <span>{n.icon}</span>{at(n.label, n.labelEn)}
                    {glowing && <span className="mr-auto flex h-5 min-w-[1.25rem] items-center justify-center rounded-full bg-brandRed px-1 text-[11px] font-bold text-white">{newOrdersCount}</span>}
                  </Link>
                );
              })}
            </nav>
          </div>
          <div className="border-t border-gray-100 p-4 text-xs text-gray-400">Powered by JEXA Technology</div>
        </div>
      </aside>
      <div className={cn('flex flex-1 flex-col', dir === 'rtl' ? 'sm:mr-64' : 'sm:ml-64')}>
        <header className="flex items-center justify-between border-b border-gray-200 bg-white px-4 py-3">
          <button className="sm:hidden" onClick={() => setSidebarOpen((s) => !s)}>☰</button>
          <p className="hidden text-sm text-gray-500 sm:block">{lang === 'en' ? new Date().toLocaleDateString('en-US', { year: 'numeric', month: 'long', day: 'numeric' }) : new Date().toLocaleDateString('ar-EG-u-ca-islamic', { year: 'numeric', month: 'long', day: 'numeric' })}</p>
          <div className="flex items-center gap-3">
            <AdminLangSwitch lang={lang} setLang={setLang} />
            <NotificationsButton />
            <div className="flex h-8 w-8 items-center justify-center rounded-full bg-navy text-xs font-bold text-white">{initials(email)}</div>
            <button onClick={logout} className="text-sm text-brandRed">{at('خروج', 'Log out')}</button>
          </div>
        </header>
        <main className="flex-1 p-4 sm:p-6">{children}</main>
      </div>
    </div>
  );
}
function AdminPageHeader({ title, description }) {
  const { at } = useAdminLang();
  return <div className="mb-5"><Link to="/admin/accounting" className="mb-1 inline-block text-sm text-gray-400">{at('← رجوع', '← Back')}</Link><h1 className="text-2xl font-bold text-navy">{title}</h1>{description && <p className="text-sm text-gray-500">{description}</p>}</div>;
}

/* ============================================================
   لوحة الأدمن — المنتجات
   ============================================================ */
const SIZE_OPTIONS = ['XS', 'S', 'M', 'L', 'XL', 'XXL', 'XXXL'];
const ONE_SIZE = 'مقاس واحد';
function emptyColorForm() { return { color_name: '', color_hex: '#000000', images: [], selectedSizes: [], qty: {} }; }
const emptyProductForm = {
  id: undefined, custom_code: '', name: '', category_id: '', brand_name: '',
  original_price: '', discount_price: '', cost_price: '', is_hidden: false, colors: [], prints: [],
  departments: [], show_on_new_arrivals: false, show_on_bestseller: false, show_on_offers: false, show_on_outlet: false,
};
function AdminProductsPage() {
  const { at } = useAdminLang();
  const [tab, setTab] = useState('all'); const [search, setSearch] = useState('');
  const { data: products, isLoading, refetch } = useSupaQuery(['admin_products', tab, search], async () => {
    let q = sb.from('products').select('*, brand:brands(*), category:categories(*), product_departments(department), colors:product_colors(*, sizes:product_sizes(*), images:product_color_images(*)), prints:product_prints(*)').order('created_at', { ascending: false });
    if (tab === 'new') {
      const ids = await categoryIdsForSection('new');
      const parts = ['show_on_new_arrivals.eq.true']; if (ids.length) parts.push(`category_id.in.(${ids.join(',')})`);
      q = q.or(parts.join(','));
    }
    if (['men', 'women', 'kids'].includes(tab)) {
      const [ids, productIds] = await Promise.all([categoryIdsForDepartment(tab), productIdsForDepartment(tab)]);
      const parts = []; if (productIds.length) parts.push(`id.in.(${productIds.join(',')})`); if (ids.length) parts.push(`category_id.in.(${ids.join(',')})`);
      q = parts.length ? q.or(parts.join(',')) : q.eq('id', '00000000-0000-0000-0000-000000000000');
    }
    if (search) q = q.or(`name.ilike.%${search}%,custom_code.ilike.%${search}%`);
    const { data, error } = await q; if (error) throw error; return data || [];
  });
  const { data: categories } = useSupaQuery(['admin_categories_all'], async () => (await sb.from('categories').select('*')).data || []);

  const [modalOpen, setModalOpen] = useState(false); const [form, setForm] = useState(emptyProductForm); const [saving, setSaving] = useState(false);
  const [deleteTarget, setDeleteTarget] = useState(null);

  const openNew = () => { setForm(emptyProductForm); setModalOpen(true); };
  const openEdit = (p) => {
    setForm({
      id: p.id, custom_code: p.custom_code || '', name: p.name, category_id: p.category_id || '', brand_name: p.brand?.name || '',
      original_price: String(p.original_price || ''), discount_price: p.discount_price ? String(p.discount_price) : '', cost_price: String(p.cost_price || ''),
      is_hidden: p.is_hidden,
      departments: (p.product_departments || []).map((d) => d.department), show_on_new_arrivals: !!p.show_on_new_arrivals, show_on_bestseller: !!p.show_on_bestseller, show_on_offers: !!p.show_on_offers, show_on_outlet: !!p.show_on_outlet,
      colors: (p.colors || []).map((c) => {
        const sizes = c.sizes || [];
        const qty = {}; sizes.forEach((s) => { qty[s.size] = String(s.quantity); });
        return {
          color_name: c.color_name, color_hex: c.color_hex || '#000000',
          images: (c.images || []).slice().sort((a, b) => a.sort_order - b.sort_order).map((im) => ({ url: im.image_url })),
          selectedSizes: sizes.map((s) => s.size), qty,
        };
      }),
      prints: (p.prints || []).slice().sort((a, b) => a.sort_order - b.sort_order).map((pr) => ({ url: pr.image_url })),
    });
    setModalOpen(true);
  };
  // اختيار لون من اللائحة الجاهزة هو Toggle: أول ضغطة تضيفه، وضغطة تانية عليه (نفس اللون) تشيله —
  // هيك الزر دايمًا بيرجّع نتيجة واضحة ومرئية فورًا (بيتحدد شكله بـ ColorDot عبر selected)،
  // بدل ما يظهر وكأنو "ما عم يستجيب" لما يكون في ألوان كتير مضافة والصف الجديد نازل تحت خارج الشاشة.
  const addColorPreset = (hex, name) => setForm((f) => {
    const idx = f.colors.findIndex((c) => c.color_hex === hex);
    if (idx >= 0) return { ...f, colors: f.colors.filter((_, i) => i !== idx) };
    return { ...f, colors: [...f.colors, { ...emptyColorForm(), color_name: name, color_hex: hex }] };
  });
  const updateColor = (idx, patch) => setForm((f) => ({ ...f, colors: f.colors.map((c, i) => (i === idx ? { ...c, ...patch } : c)) }));
  const removeColor = (idx) => setForm((f) => ({ ...f, colors: f.colors.filter((_, i) => i !== idx) }));
  const addColorImage = (idx, file) => setForm((f) => ({ ...f, colors: f.colors.map((c, i) => (i === idx ? { ...c, images: [...c.images, { file, url: URL.createObjectURL(file) }] } : c)) }));
  const removeColorImage = (idx, imgIdx) => setForm((f) => ({ ...f, colors: f.colors.map((c, i) => (i === idx ? { ...c, images: c.images.filter((_, j) => j !== imgIdx) } : c)) }));
  const toggleSize = (idx, label) => setForm((f) => ({
    ...f,
    colors: f.colors.map((c, i) => {
      if (i !== idx) return c;
      let selected;
      if (label === ONE_SIZE) selected = c.selectedSizes.includes(ONE_SIZE) ? [] : [ONE_SIZE];
      else { const base = c.selectedSizes.filter((s) => s !== ONE_SIZE); selected = base.includes(label) ? base.filter((s) => s !== label) : [...base, label]; }
      return { ...c, selectedSizes: selected };
    }),
  }));
  const setSizeQty = (idx, label, value) => setForm((f) => ({ ...f, colors: f.colors.map((c, i) => (i === idx ? { ...c, qty: { ...c.qty, [label]: value } } : c)) }));
  const addPrint = (file) => setForm((f) => ({ ...f, prints: [...f.prints, { file, url: URL.createObjectURL(file) }] }));
  const removePrint = (i) => setForm((f) => ({ ...f, prints: f.prints.filter((_, x) => x !== i) }));
  const toggleFormDept = (key) => setForm((f) => ({ ...f, departments: f.departments.includes(key) ? f.departments.filter((x) => x !== key) : [...f.departments, key] }));

  const save = async () => {
    if (!form.name.trim() || !form.original_price) { alert(at('اسم المنتج والسعر الأصلي إجباريين', 'Product name and original price are required')); return; }
    if (!form.colors.length) { alert(at('أضف لون واحد ع الأقل للمنتج', 'Add at least one color for the product')); return; }
    for (const c of form.colors) {
      if (!c.color_name.trim()) { alert(at('كل لون لازم يكون إله اسم', 'Every color needs a name')); return; }
      if (!c.selectedSizes.length) { alert(at(`اختر مقاس واحد ع الأقل (أو "${ONE_SIZE}") للون "${c.color_name}"`, `Choose at least one size (or "${at(ONE_SIZE, 'One size')}") for color "${c.color_name}"`)); return; }
      for (const s of c.selectedSizes) {
        const q = c.qty[s];
        if (q === undefined || q === '' || isNaN(Number(q)) || Number(q) < 0) { alert(at(`حدد كمية صحيحة للمقاس "${s}" باللون "${c.color_name}"`, `Set a valid quantity for size "${s}" in color "${c.color_name}"`)); return; }
      }
    }
    setSaving(true);
    try {
      let brandId = null;
      if (form.brand_name.trim()) {
        const { data: existing } = await sb.from('brands').select('id').eq('name', form.brand_name.trim()).maybeSingle();
        if (existing) brandId = existing.id;
        else { const { data: created } = await sb.from('brands').insert({ name: form.brand_name.trim() }).select().single(); brandId = created?.id || null; }
      }
      const payload = {
        custom_code: form.custom_code || null, name: form.name.trim(), category_id: form.category_id || null, brand_id: brandId,
        original_price: Number(form.original_price), discount_price: form.discount_price ? Number(form.discount_price) : null, cost_price: form.cost_price ? Number(form.cost_price) : 0,
        is_hidden: form.is_hidden,
        show_on_new_arrivals: form.show_on_new_arrivals, show_on_bestseller: form.show_on_bestseller, show_on_offers: form.show_on_offers, show_on_outlet: form.show_on_outlet,
      };
      let productId = form.id;
      if (productId) {
        const { error: updErr } = await sb.from('products').update(payload).eq('id', productId); if (updErr) throw updErr;
        // حذف الألوان القديمة (بيسحب معه المقاسات والصور تلقائيًا عبر on delete cascade) والطبعات، وإعادة إدخالهم بالحالة الحالية
        const { error: delColErr } = await sb.from('product_colors').delete().eq('product_id', productId); if (delColErr) throw delColErr;
        const { error: delPrintErr } = await sb.from('product_prints').delete().eq('product_id', productId); if (delPrintErr) throw delPrintErr;
      } else {
        const { data, error } = await sb.from('products').insert(payload).select().single(); if (error) throw error; productId = data.id;
      }

      const { error: delDeptErr } = await sb.from('product_departments').delete().eq('product_id', productId); if (delDeptErr) throw delDeptErr;
      if (form.departments.length) { const { error } = await sb.from('product_departments').insert(form.departments.map((d) => ({ product_id: productId, department: d }))); if (error) throw error; }

      for (const color of form.colors) {
        const { data: colorRow, error: colorErr } = await sb.from('product_colors').insert({ product_id: productId, color_name: color.color_name.trim(), color_hex: color.color_hex }).select().single();
        if (colorErr) throw colorErr;
        let sortOrder = 0;
        for (const img of color.images) {
          const url = img.file ? await uploadImage(img.file, 'products') : img.url;
          if (url) { const { error: imgErr } = await sb.from('product_color_images').insert({ product_color_id: colorRow.id, image_url: url, sort_order: sortOrder++ }); if (imgErr) throw imgErr; }
        }
        const sizeEntries = color.selectedSizes.map((s) => ({ product_color_id: colorRow.id, size: s, quantity: Number(color.qty[s] || 0) }));
        if (sizeEntries.length) { const { error: sizeErr } = await sb.from('product_sizes').insert(sizeEntries); if (sizeErr) throw sizeErr; }
      }

      let printOrder = 0;
      for (const pr of form.prints) {
        const url = pr.file ? await uploadImage(pr.file, 'prints') : pr.url;
        if (url) { const { error: printErr } = await sb.from('product_prints').insert({ product_id: productId, image_url: url, sort_order: printOrder++ }); if (printErr) throw printErr; }
      }

      setModalOpen(false); invalidate('admin_products'); invalidate('products'); invalidate('categor'); refetch();
    } catch (e) { alert(e.message || at('حدث خطأ أثناء الحفظ', 'An error occurred while saving')); } finally { setSaving(false); }
  };
  const toggleHidden = async (p) => {
    const { error } = await sb.from('products').update({ is_hidden: !p.is_hidden }).eq('id', p.id);
    if (error) { alert(at(`تعذّر تغيير حالة الإخفاء: ${error.message}`, `Could not change visibility: ${error.message}`)); return; }
    invalidate('products'); refetch();
  };
  const doDelete = async () => {
    if (!deleteTarget) return;
    try {
      const { error } = await sb.from('products').delete().eq('id', deleteTarget.id);
      if (error) throw error;
      invalidate('products'); invalidate('categor');
    } catch (e) {
      alert(e.message?.includes('violates foreign key') ? at('ما فيك تحذف هاد المنتج لأنه مرتبط بطلبات سابقة — فيك تخفيه بدل ما تحذفه', 'This product cannot be deleted because it is linked to past orders — you can hide it instead') : (e.message || at('تعذّر الحذف', 'Could not delete')));
    } finally { setDeleteTarget(null); refetch(); }
  };

  return (
    <div>
      <AdminPageHeader title={at('المنتجات', 'Products')} description={at('إدارة كل منتجات المتجر', 'Manage all store products')} />
      <div className="mb-4 flex flex-wrap items-center justify-between gap-3"><Button onClick={openNew}>+ {at('إضافة منتج', 'Add product')}</Button><SearchInput value={search} onChange={setSearch} /></div>
      <div className="mb-4 flex gap-2 overflow-x-auto">
        {[{ key: 'all', label: at('الكل', 'All') }, { key: 'new', label: at('وصل حديثًا', 'New arrivals') }, { key: 'men', label: at('رجال', 'Men') }, { key: 'women', label: at('نساء', 'Women') }, { key: 'kids', label: at('أطفال', 'Kids') }].map((tb) => (
          <button key={tb.key} onClick={() => setTab(tb.key)} className={`whitespace-nowrap rounded-full border px-3 py-1 text-sm ${tab === tb.key ? 'border-navy bg-navy text-white' : 'border-gray-300 text-gray-600'}`}>{tb.label}</button>
        ))}
      </div>
      <div className="grid grid-cols-2 gap-4 sm:grid-cols-3 lg:grid-cols-4">
        {isLoading ? Array.from({ length: 8 }).map((_, i) => <div key={i} className="skeleton aspect-square" />) : products?.map((p) => (
          <div key={p.id} className="border border-gray-200 bg-white p-3">
            <div className="mb-2 flex aspect-square items-center justify-center bg-gray-100">{p.colors?.[0]?.images?.[0]?.image_url ? <img src={p.colors[0].images[0].image_url} className="h-full w-full object-cover" /> : <span className="text-2xl text-gray-300">📦</span>}</div>
            <div className="mb-1 flex gap-1">{p.colors?.map((c) => <ColorDot key={c.id} hex={c.color_hex || '#ccc'} />)}</div>
            <p className="text-xs text-gray-400">{p.brand?.name || '-'} · {p.category?.name || '-'}{p.custom_code ? ` · #${p.custom_code}` : ''}</p>
            <p className="truncate font-bold text-navy">{p.name}</p>
            <p className="text-sm font-bold text-brandRed">{formatPrice(p.discount_price || p.original_price)}</p>
            <div className="mt-2 flex items-center justify-between">
              <Badge color={p.is_hidden ? 'gray' : 'green'}>{p.is_hidden ? at('مخفي', 'Hidden') : at('ظاهر', 'Visible')}</Badge>
              <div className="flex gap-2 text-sm"><button onClick={() => toggleHidden(p)}>👁️</button><button onClick={() => openEdit(p)}>✏️</button><button onClick={() => setDeleteTarget(p)} className="text-brandRed">🗑️</button></div>
            </div>
          </div>
        ))}
      </div>
      <Modal open={modalOpen} onClose={() => setModalOpen(false)} title={form.id ? at('تعديل منتج', 'Edit product') : at('إضافة منتج', 'Add product')} wide>
        <div className="grid gap-4 sm:grid-cols-2">
          <div><label className="mb-1 block text-sm text-gray-600">{at('رقم القطعة (اختياري)', 'Item number (optional)')}</label><Input value={form.custom_code} onChange={(e) => setForm({ ...form, custom_code: e.target.value })} placeholder={at('مثال: 1024', 'e.g. 1024')} /></div>
          <div><label className="mb-1 block text-sm text-gray-600">{at('التصنيف (اختياري) — إذا اخترته بيحدد كمان وين يظهر المنتج', 'Category (optional) — if chosen, also determines where the product appears')}</label><Select value={form.category_id} onChange={(e) => setForm({ ...form, category_id: e.target.value })}><option value="">{at('بدون تصنيف', 'No category')}</option>{categories?.map((c) => <option key={c.id} value={c.id}>{c.name}</option>)}</Select></div>
          <div className="sm:col-span-2"><label className="mb-1 block text-sm text-gray-600">{at('اسم المنتج', 'Product name')}</label><Input value={form.name} onChange={(e) => setForm({ ...form, name: e.target.value })} /></div>
          <div><label className="mb-1 block text-sm text-gray-600">{at('الماركة', 'Brand')}</label><Input value={form.brand_name} onChange={(e) => setForm({ ...form, brand_name: e.target.value })} /></div>
          <div><label className="mb-1 block text-sm text-gray-600">{at('السعر الأصلي', 'Original price')}</label><Input type="number" value={form.original_price} onChange={(e) => setForm({ ...form, original_price: e.target.value })} /></div>
          <div><label className="mb-1 block text-sm text-gray-600">{at('سعر الخصم (اختياري)', 'Discount price (optional)')}</label><Input type="number" value={form.discount_price} onChange={(e) => setForm({ ...form, discount_price: e.target.value })} /></div>
          <div><label className="mb-1 block text-sm text-gray-600">{at('تكلفة القطعة', 'Unit cost')}</label><Input type="number" value={form.cost_price} onChange={(e) => setForm({ ...form, cost_price: e.target.value })} /></div>
        </div>
        <div className="mt-4 flex flex-wrap gap-4">
          <Toggle checked={form.is_hidden} onChange={(v) => setForm({ ...form, is_hidden: v })} label={at('مخفي', 'Hidden')} />
        </div>
        <div className="mt-4 border-t pt-4">
          <p className="mb-2 text-sm font-medium text-gray-700">{at('أماكن ظهور إضافية لهاد المنتج بالذات', 'Extra places to show this specific product')}</p>
          <p className="mb-1 text-xs text-gray-500">{at('القسم (رجال/نساء/أطفال) — اختياري، بالإضافة لتصنيفه', 'Department (men/women/kids) — optional, in addition to its category')}</p>
          <div className="mb-3 flex flex-wrap gap-2">
            {DEPS_LIST.map((d) => (
              <button key={d.key} type="button" onClick={() => toggleFormDept(d.key)} className={`rounded-full border px-3 py-1 text-sm ${form.departments.includes(d.key) ? 'border-navy bg-navy text-white' : 'border-gray-300 text-gray-600'}`}>{at(d.label, d.labelEn)}</button>
            ))}
          </div>
          <p className="mb-1 text-xs text-gray-500">{at('يظهر أيضًا في الأقسام الخاصة التالية', 'Also show in the following special sections')}</p>
          <div className="flex flex-wrap gap-4">
            {SECTIONS_LIST.map((s) => {
              const field = { offers: 'show_on_offers', new: 'show_on_new_arrivals', bestseller: 'show_on_bestseller', outlet: 'show_on_outlet' }[s.key];
              return <label key={s.key} className="flex items-center gap-1.5 text-sm"><input type="checkbox" checked={form[field]} onChange={(e) => setForm((f) => ({ ...f, [field]: e.target.checked }))} />{at(s.label, s.labelEn)}</label>;
            })}
          </div>
          <p className="mt-2 text-xs text-gray-400">{at('هاد بالإضافة لمكان الظهور المحدّد من تصنيف المنتج — مش بديل عنه.', 'This is in addition to the placement determined by the product\'s category — not a replacement for it.')}</p>
        </div>

        <div className="mt-5 border-t pt-4">
          <p className="mb-2 text-sm font-bold text-gray-700">{at('ألوان المنتج، مقاساتها، ومخزون كل مقاس', 'Product colors, their sizes, and stock per size')}</p>
          <div className="mb-3 flex flex-wrap gap-1.5">{PRESET_COLORS.map((c) => <ColorDot key={c.hex} hex={c.hex} title={c.name} selected={form.colors.some((fc) => fc.color_hex === c.hex)} onClick={() => addColorPreset(c.hex, c.name)} />)}</div>
          <p className="mb-3 text-[11px] text-gray-400">{at('اضغط على اللون لإضافته، واضغط عليه مرة ثانية لإزالته.', 'Click a color to add it, click it again to remove it.')}</p>
          <div className="space-y-4">
            {form.colors.map((c, i) => (
              <div key={i} className="border border-gray-200 p-3">
                <div className="mb-2 flex flex-wrap items-center gap-2">
                  <ColorDot hex={c.color_hex} />
                  <input type="color" value={c.color_hex} onChange={(e) => updateColor(i, { color_hex: e.target.value })} className="h-8 w-9 border border-gray-300" />
                  <Input className="w-32" placeholder={at('اسم اللون', 'Color name')} value={c.color_name} onChange={(e) => updateColor(i, { color_name: e.target.value })} />
                  <button onClick={() => removeColor(i)} className="text-sm text-brandRed">{at('حذف اللون', 'Remove color')}</button>
                </div>

                <p className="mb-1 text-xs text-gray-500">{at('صور هاد اللون', 'Photos for this color')}</p>
                <div className="mb-3 flex flex-wrap gap-2">
                  {c.images.map((img, ii) => (
                    <div key={ii} className="relative h-14 w-14">
                      <img src={img.url} className="h-full w-full object-cover" />
                      <button type="button" onClick={() => removeColorImage(i, ii)} className="absolute -right-1.5 -top-1.5 flex h-5 w-5 items-center justify-center rounded-full bg-brandRed text-[10px] text-white">✕</button>
                    </div>
                  ))}
                  <label className="flex h-14 w-14 cursor-pointer items-center justify-center border border-dashed border-gray-300 text-lg text-gray-400">
                    +
                    <input type="file" accept="image/*" className="hidden" onChange={(e) => { const f = e.target.files?.[0]; if (f) addColorImage(i, f); e.target.value = ''; }} />
                  </label>
                </div>
                <p className="text-[11px] text-gray-400">{at('أكثر من صورة بتظهر متقلّبة تلقائيًا لما الزبون يحطّ الماوس على المنتج بواجهة المتجر', 'More than one photo will auto-rotate when the customer hovers the product in the storefront')}</p>

                <p className="mb-1 mt-3 text-xs text-gray-500">{at(`المقاسات المتوفرة لهاد اللون (اختر "${ONE_SIZE}" لو المنتج بلا مقاسات فعلية — ما فيك تجمعه مع مقاسات ثانية)`, `Sizes available for this color (choose "${at(ONE_SIZE, 'One size')}" if the product has no real sizes — can't be combined with other sizes)`)}</p>
                <div className="flex flex-wrap gap-1.5">
                  {[...SIZE_OPTIONS, ONE_SIZE].map((label) => {
                    const active = c.selectedSizes.includes(label);
                    const disabled = c.selectedSizes.includes(ONE_SIZE) && label !== ONE_SIZE;
                    return (
                      <button key={label} type="button" disabled={disabled} onClick={() => toggleSize(i, label)} className={cn('rounded border px-2.5 py-1 text-xs font-medium', active ? 'border-navy bg-navy text-white' : disabled ? 'cursor-not-allowed border-gray-100 text-gray-300' : 'border-gray-300 text-gray-600 hover:border-navy')}>{label === ONE_SIZE ? at(ONE_SIZE, 'One size') : label}</button>
                    );
                  })}
                </div>
                {!!c.selectedSizes.length && (
                  <div className="mt-2 flex flex-wrap gap-3">
                    {c.selectedSizes.map((s) => (
                      <div key={s} className="flex items-center gap-1.5 text-xs">
                        <span className="font-medium text-gray-600">{s === ONE_SIZE ? at(ONE_SIZE, 'One size') : s}</span>
                        <Input type="number" min="0" className="!w-20 !py-1" placeholder={at('الكمية', 'Quantity')} value={c.qty[s] ?? ''} onChange={(e) => setSizeQty(i, s, e.target.value)} />
                      </div>
                    ))}
                  </div>
                )}
              </div>
            ))}
            {!form.colors.length && <p className="text-sm text-gray-400">{at('ما في ألوان مضافة بعد — اختر لون من الأعلى.', 'No colors added yet — choose a color above.')}</p>}
          </div>
        </div>

        <div className="mt-5 border-t pt-4">
          <p className="mb-1 text-sm font-bold text-gray-700">{at('طبعات / تصاميم إضافية (اختياري)', 'Extra prints / designs (optional)')}</p>
          <p className="mb-2 text-xs text-gray-400">{at('مو إجبارية — بس لو المنتج إله أكثر من طبعة/تصميم فيك ترفع صورهم هون.', "Not required — but if the product has more than one print/design you can upload their photos here.")}</p>
          <div className="flex flex-wrap gap-2">
            {form.prints.map((pr, i) => (
              <div key={i} className="relative h-16 w-16">
                <img src={pr.url} className="h-full w-full object-cover" />
                <button type="button" onClick={() => removePrint(i)} className="absolute -right-1.5 -top-1.5 flex h-5 w-5 items-center justify-center rounded-full bg-brandRed text-[10px] text-white">✕</button>
              </div>
            ))}
            <label className="flex h-16 w-16 cursor-pointer items-center justify-center border border-dashed border-gray-300 text-xs text-gray-400">
              + {at('طبعة', 'Print')}
              <input type="file" accept="image/*" className="hidden" onChange={(e) => { const f = e.target.files?.[0]; if (f) addPrint(f); e.target.value = ''; }} />
            </label>
          </div>
        </div>

        <div className="mt-5 flex justify-end gap-2 border-t pt-4"><Button variant="ghost" onClick={() => setModalOpen(false)}>{at('إلغاء', 'Cancel')}</Button><Button onClick={save} disabled={saving}>{saving ? '...' : at('حفظ التغييرات', 'Save changes')}</Button></div>
      </Modal>
      <ConfirmDialog open={!!deleteTarget} title={at('حذف المنتج', 'Delete product')} message={at(`متأكد إنك بدك تحذف "${deleteTarget?.name}"؟`, `Are you sure you want to delete "${deleteTarget?.name}"?`)} onConfirm={doDelete} onCancel={() => setDeleteTarget(null)} danger confirmLabel={at('حذف', 'Delete')} />
    </div>
  );
}

/* ============================================================
   لوحة الأدمن — التصنيفات
   ============================================================ */
const DEPS_LIST = [{ key: 'men', label: 'رجال', labelEn: 'Men' }, { key: 'women', label: 'نساء', labelEn: 'Women' }, { key: 'kids', label: 'أطفال', labelEn: 'Kids' }];
const SECTIONS_LIST = [{ key: 'offers', label: 'عروض', labelEn: 'Offers' }, { key: 'new', label: 'وصل حديثًا', labelEn: 'New arrivals' }, { key: 'bestseller', label: 'الأكثر مبيعًا', labelEn: 'Bestsellers' }, { key: 'outlet', label: 'أوتليت', labelEn: 'Outlet' }];
const PLACES_LIST = [...DEPS_LIST, ...SECTIONS_LIST];
const emptyCatForm = { id: undefined, name: '', slug: '', image_url: null, departments: [], sections: [], is_hidden: false };
function AdminCategoriesPage() {
  const { at } = useAdminLang();
  const [search, setSearch] = useState('');
  const [placeFilter, setPlaceFilter] = useState('all');
  const { data: categories, isLoading, refetch } = useSupaQuery(['admin_categories', search], async () => {
    let q = sb.from('categories').select('*, category_departments(department), category_sections(section)');
    if (search) q = q.ilike('name', `%${search}%`);
    const { data, error } = await q; if (error) throw error;
    return data || [];
  });
  const filtered = (categories || []).filter((c) => {
    if (placeFilter === 'all') return true;
    if (DEPS_LIST.some((d) => d.key === placeFilter)) return (c.category_departments || []).some((d) => d.department === placeFilter);
    return (c.category_sections || []).some((s) => s.section === placeFilter);
  });
  const [modalOpen, setModalOpen] = useState(false); const [form, setForm] = useState(emptyCatForm); const [file, setFile] = useState(null);
  const [saving, setSaving] = useState(false); const [deleteTarget, setDeleteTarget] = useState(null);

  const openNew = () => { setForm(emptyCatForm); setFile(null); setModalOpen(true); };
  const openEdit = (c) => { setForm({ id: c.id, name: c.name, slug: c.slug || '', image_url: c.image_url, departments: (c.category_departments || []).map((d) => d.department), sections: (c.category_sections || []).map((s) => s.section), is_hidden: c.is_hidden }); setFile(null); setModalOpen(true); };
  const toggleDept = (key) => setForm((f) => ({ ...f, departments: f.departments.includes(key) ? f.departments.filter((d) => d !== key) : [...f.departments, key] }));
  const toggleSection = (key) => setForm((f) => ({ ...f, sections: f.sections.includes(key) ? f.sections.filter((s) => s !== key) : [...f.sections, key] }));

  const save = async () => {
    if (!form.name.trim()) { alert(at('اكتب اسم التصنيف', 'Enter the category name')); return; }
    if (!form.departments.length && !form.sections.length) { alert(at('اختر مكان واحد ع الأقل يظهر فيه هاد التصنيف (قسم و/أو عروض/وصل حديثًا/الأكثر مبيعًا/أوتليت)', 'Choose at least one place for this category to appear (department and/or offers/new/bestseller/outlet)')); return; }
    setSaving(true);
    try {
      let imageUrl = form.image_url; if (file) imageUrl = await uploadImage(file, 'categories');
      const payload = { name: form.name.trim(), slug: form.slug || null, image_url: imageUrl, is_hidden: form.is_hidden };
      let catId = form.id;
      if (catId) { const { error: updErr } = await sb.from('categories').update(payload).eq('id', catId); if (updErr) throw updErr; }
      else { const { data, error } = await sb.from('categories').insert(payload).select().single(); if (error) throw error; catId = data.id; }
      // إعادة كتابة كل أماكن الظهور دفعة وحدة (حذف القديم وإدخال الجديد) — أبسط وآمن من مقارنة دقيقة
      const { error: delDeptErr } = await sb.from('category_departments').delete().eq('category_id', catId); if (delDeptErr) throw delDeptErr;
      const { error: delSecErr } = await sb.from('category_sections').delete().eq('category_id', catId); if (delSecErr) throw delSecErr;
      if (form.departments.length) { const { error } = await sb.from('category_departments').insert(form.departments.map((d) => ({ category_id: catId, department: d }))); if (error) throw error; }
      if (form.sections.length) { const { error } = await sb.from('category_sections').insert(form.sections.map((s) => ({ category_id: catId, section: s }))); if (error) throw error; }
      setModalOpen(false); invalidate('categor'); refetch();
    } catch (e) { alert(e.message || at('حدث خطأ', 'An error occurred')); } finally { setSaving(false); }
  };
  const toggleHidden = async (c) => {
    const { error } = await sb.from('categories').update({ is_hidden: !c.is_hidden }).eq('id', c.id);
    if (error) { alert(at(`تعذّر تغيير حالة الإخفاء: ${error.message}`, `Could not change visibility: ${error.message}`)); return; }
    invalidate('categor'); refetch();
  };
  const doDelete = async () => {
    if (!deleteTarget) return;
    const { error: unlinkErr } = await sb.from('products').update({ category_id: null }).eq('category_id', deleteTarget.id);
    if (unlinkErr) { alert(at(`تعذّر حذف التصنيف: ${unlinkErr.message}`, `Could not delete the category: ${unlinkErr.message}`)); setDeleteTarget(null); return; }
    const { error } = await sb.from('categories').delete().eq('id', deleteTarget.id);
    if (error) { alert(at(`تعذّر حذف التصنيف: ${error.message}`, `Could not delete the category: ${error.message}`)); setDeleteTarget(null); return; }
    setDeleteTarget(null); invalidate('categor'); invalidate('products'); invalidate('admin_products'); refetch();
  };

  return (
    <div>
      <AdminPageHeader title={at('التصنيفات', 'Categories')} description={at('فيك تحط التصنيف بأكتر من مكان بنفس الوقت — قسم (رجال/نساء/أطفال) و/أو عروض/وصل حديثًا/الأكثر مبيعًا/أوتليت', 'You can place a category in more than one spot at once — a department (men/women/kids) and/or offers/new/bestseller/outlet')} />
      <div className="mb-4 flex flex-wrap items-center justify-between gap-3">
        <Button onClick={openNew}>+ {at('إضافة تصنيف', 'Add category')}</Button>
        <div className="flex flex-wrap items-center gap-3">
          <div className="flex flex-wrap gap-2">{['all', ...PLACES_LIST.map((d) => d.key)].map((d) => <button key={d} onClick={() => setPlaceFilter(d)} className={`whitespace-nowrap rounded-full border px-3 py-1 text-sm ${placeFilter === d ? 'border-navy bg-navy text-white' : 'border-gray-300'}`}>{d === 'all' ? at('الكل', 'All') : at(PLACES_LIST.find((x) => x.key === d)?.label, PLACES_LIST.find((x) => x.key === d)?.labelEn)}</button>)}</div>
          <SearchInput value={search} onChange={setSearch} />
        </div>
      </div>
      <div className="grid grid-cols-2 gap-4 sm:grid-cols-3 lg:grid-cols-4">
        {isLoading ? Array.from({ length: 4 }).map((_, i) => <div key={i} className="skeleton aspect-square" />) : filtered.map((c) => {
          const deps = (c.category_departments || []).map((d) => d.department);
          const secs = (c.category_sections || []).map((s) => s.section);
          return (
            <div key={c.id} className="border border-gray-200 bg-white p-3">
              <div className="mb-2 flex aspect-video items-center justify-center bg-gray-100">{c.image_url ? <img src={c.image_url} className="h-full w-full object-cover" /> : <span className="text-2xl text-gray-300">🗂️</span>}</div>
              <p className="font-bold text-navy">{c.name}</p>
              <div className="mt-1 flex flex-wrap gap-1">
                {deps.map((d) => <Badge key={d} color="navy">{at(DEPS_LIST.find((x) => x.key === d)?.label, DEPS_LIST.find((x) => x.key === d)?.labelEn)}</Badge>)}
                {secs.map((s) => <Badge key={s} color="purple">{at(SECTIONS_LIST.find((x) => x.key === s)?.label, SECTIONS_LIST.find((x) => x.key === s)?.labelEn)}</Badge>)}
                {!deps.length && !secs.length && <Badge color="yellow">{at('⚠️ بدون مكان ظهور — عدّل التصنيف', '⚠️ No placement — edit the category')}</Badge>}
              </div>
              <div className="mt-2 flex items-center justify-between"><Badge color={c.is_hidden ? 'gray' : 'green'}>{c.is_hidden ? at('مخفي', 'Hidden') : at('ظاهر', 'Visible')}</Badge><div className="flex gap-2 text-sm"><button onClick={() => toggleHidden(c)}>👁️</button><button onClick={() => openEdit(c)}>✏️</button><button onClick={() => setDeleteTarget(c)} className="text-brandRed">🗑️</button></div></div>
            </div>
          );
        })}
      </div>
      <Modal open={modalOpen} onClose={() => setModalOpen(false)} title={form.id ? at('تعديل تصنيف', 'Edit category') : at('إضافة تصنيف', 'Add category')}>
        <div className="space-y-3">
          <div>
            <label className="mb-1.5 block text-sm text-gray-600">{at('مكان الظهور — فيك تحدد أكتر من مربع بنفس الوقت', 'Placement — you can check more than one box at once')}</label>
            <p className="mb-1 text-xs font-medium text-gray-500">{at('القسم', 'Department')}</p>
            <div className="mb-2 flex flex-wrap gap-3">
              {DEPS_LIST.map((d) => (
                <label key={d.key} className="flex items-center gap-1.5 text-sm"><input type="checkbox" checked={form.departments.includes(d.key)} onChange={() => toggleDept(d.key)} />{at(d.label, d.labelEn)}</label>
              ))}
            </div>
            <p className="mb-1 text-xs font-medium text-gray-500">{at('أقسام خاصة', 'Special sections')}</p>
            <div className="flex flex-wrap gap-3">
              {SECTIONS_LIST.map((s) => (
                <label key={s.key} className="flex items-center gap-1.5 text-sm"><input type="checkbox" checked={form.sections.includes(s.key)} onChange={() => toggleSection(s.key)} />{at(s.label, s.labelEn)}</label>
              ))}
            </div>
          </div>
          <div><label className="mb-1 block text-sm text-gray-600">{at('اختصار التصنيف (اختياري)', 'Category slug (optional)')}</label><Input value={form.slug} onChange={(e) => setForm({ ...form, slug: e.target.value })} /></div>
          <div><label className="mb-1 block text-sm text-gray-600">{at('اسم التصنيف', 'Category name')}</label><Input value={form.name} onChange={(e) => setForm({ ...form, name: e.target.value })} /></div>
          <div><label className="mb-1 block text-sm text-gray-600">{at('صورة التصنيف', 'Category image')}</label><input type="file" accept="image/*" onChange={(e) => setFile(e.target.files?.[0] || null)} /></div>
          <Toggle checked={form.is_hidden} onChange={(v) => setForm({ ...form, is_hidden: v })} label={at('مخفي', 'Hidden')} />
        </div>
        <div className="mt-5 flex justify-end gap-2 border-t pt-4"><Button variant="ghost" onClick={() => setModalOpen(false)}>{at('إلغاء', 'Cancel')}</Button><Button onClick={save} disabled={saving}>{saving ? '...' : at('حفظ التغييرات', 'Save changes')}</Button></div>
      </Modal>
      <ConfirmDialog open={!!deleteTarget} title={at('حذف التصنيف', 'Delete category')} message={at(`متأكد إنك بدك تحذف "${deleteTarget?.name}"؟ (المنتجات التابعة له بتصير بدون تصنيف بدل ما تنحذف)`, `Are you sure you want to delete "${deleteTarget?.name}"? (its products will become uncategorized instead of being deleted)`)} onConfirm={doDelete} onCancel={() => setDeleteTarget(null)} danger confirmLabel={at('حذف', 'Delete')} />
    </div>
  );
}

/* ============================================================
   لوحة الأدمن — الطلبات
   ============================================================ */
const ORDER_TABS = [
  { key: 'active', label: 'الطلبات المعلقة والحديثة', labelEn: 'Pending & recent orders', statuses: ['new', 'awaiting_confirmation', 'confirmed'] },
  { key: 'history', label: 'سجل الطلبات', labelEn: 'Order history', statuses: ['completed', 'cancelled'] },
];
function AdminOrdersPage() {
  const { at } = useAdminLang();
  const [tab, setTab] = useState('active'); const [search, setSearch] = useState('');
  const [receiptModal, setReceiptModal] = useState(null);
  const [addOpen, setAddOpen] = useState(false);
  const [resetActiveOpen, setResetActiveOpen] = useState(false);
  const [resetActiveConfirmText, setResetActiveConfirmText] = useState('');
  const [resetHistoryOpen, setResetHistoryOpen] = useState(false);
  const [resetHistoryConfirmText, setResetHistoryConfirmText] = useState('');
  const resetOrdersWord = at('تصفير', 'RESET');
  const { data: settings } = useSiteSettings();
  const { data: orders, isLoading, refetch } = useSupaQuery(['admin_orders', tab, search], async () => {
    let q = sb.from('orders').select('*, customer:customers(*), items:order_items(*, product:products(name), color:product_colors(color_name))').order('created_at', { ascending: false });
    q = q.in('status', ORDER_TABS.find((tb) => tb.key === tab)?.statuses || ['new']);
    if (search) q = q.ilike('order_number', `%${search}%`);
    const { data, error } = await q; if (error) throw error; return data || [];
  });
  const statusLabel = { new: at('جديد — لسا ما أُرسل تحقق', 'New — confirmation not sent yet'), awaiting_confirmation: at('بانتظار تحقق الزبون', 'Awaiting customer confirmation'), confirmed: at('تم التحقق — بانتظار القبض', 'Confirmed — awaiting payment'), completed: at('مؤكّد ومقبوض', 'Confirmed & paid'), cancelled: at('ملغي', 'Cancelled') };
  const statusColor = { new: 'yellow', awaiting_confirmation: 'purple', confirmed: 'navy', completed: 'green', cancelled: 'red' };
  const paymentLabel = { cod: at('كاش عند الاستلام', 'Cash on delivery'), reflect: at('تحويل رفلكت', 'Reflect transfer') };
  const deliveryZoneLabel = Object.fromEntries(DELIVERY_ZONES.map((z) => [z.key, at(z.label, z.labelEn)]));
  const updateStatus = async (order, status) => {
    const { error } = await sb.from('orders').update({ status, confirmed_at: status === 'completed' ? new Date().toISOString() : order.confirmed_at }).eq('id', order.id);
    if (error) { alert(at(`تعذّر تحديث حالة الطلب: ${error.message}`, `Could not update order status: ${error.message}`)); return; }
    invalidate('admin_new_orders_count'); refetch();
  };
  // بيصيغ رسالة تأكيد الطلب كاملة بنفس الفورمات الي حددها صاحب المتجر (رقم محل، بيانات الزبون،
  // قائمة المنتجات بالتفصيل، مجموع + خصم + رسم توصيل (لو موجود) + الإجمالي، وسؤال تأكيد بالنهاية).
  // ملاحظة: "المدفوع"/"المتبقي" مبنيين على افتراض إن الدفع كاش عند الاستلام (COD) دائمًا — لأنو
  // ما في بقاعدة البيانات أي عمود لتتبع دفعات جزئية/مسبقة حاليًا.
  // فورمات السعر بالضبط متل مثال العميل: "₪ 100.00" (الرمز أول، وفاصلتين عشريتين دائمًا) —
  // بيختلف شكليًا عن formatPrice المستخدمة بباقي الموقع (اللي بتحط الرمز آخر بدون فواصل ثابتة)،
  // بس هون التزمنا بالصيغة الحرفية الي طلبها صاحب المتجر لرسالة واتساب تحديدًا.
  const waPrice = (v) => `₪ ${Number(v || 0).toFixed(2)}`;
  const buildConfirmationMessage = (order) => {
    const name = order.customer?.name || order.guest_name || '';
    const phone = order.customer?.phone || order.guest_phone || '';
    const shopPhone = settings?.contact?.phone || settings?.contact?.whatsapp || '';
    const addressLine = [order.city, order.address].filter(Boolean).join('، ');
    const items = order.items || [];
    const subtotal = items.reduce((s, it) => s + Number(it.unit_price) * it.quantity, 0);
    const deliveryFee = Number(order.delivery_fee) || 0;
    const amountAfterDiscount = Math.max(Number(order.total_amount) - deliveryFee, 0);
    const discountAmount = Math.max(subtotal - amountAfterDiscount, 0);

    const lines = [];
    lines.push(`مرحبًا ${name}`);
    lines.push(`وصَلنا طلبك من SUPER SHOP ونحتاج تأكيدك قبل التجهيز.`);
    if (shopPhone) lines.push(`رقم المحل: ${shopPhone}`);
    lines.push(`رقم الطلب: ${order.order_number}`);
    lines.push(`الاسم: ${name}`);
    lines.push(`الهاتف: ${phone}`);
    lines.push(`العنوان: ${addressLine}`);
    lines.push('');
    lines.push('المنتجات:');
    items.forEach((it, i) => {
      const variant = [it.color?.color_name, it.size].filter(Boolean).join(' / ');
      lines.push(`${i + 1}. ${it.product?.name || ''}${variant ? ' — ' + variant : ''}`);
      lines.push(`الكمية: ${it.quantity} | سعر القطعة: ${waPrice(it.unit_price)} | الإجمالي: ${waPrice(it.unit_price * it.quantity)}`);
    });
    lines.push('');
    lines.push(`مجموع المنتجات: ${waPrice(subtotal)}`);
    if (deliveryFee > 0) lines.push(`رسوم التوصيل${order.delivery_zone ? ' (' + (deliveryZoneLabel[order.delivery_zone] || order.delivery_zone) + ')' : ''}: ${waPrice(deliveryFee)}`);
    lines.push(`الخصم: ${waPrice(discountAmount)}`);
    lines.push(`الإجمالي المسجل للطلب: ${waPrice(order.total_amount)}`);
    lines.push(`المدفوع: ${waPrice(0)}`);
    lines.push(`المتبقي: ${waPrice(order.total_amount)}`);
    if (order.notes) { lines.push(''); lines.push(`ملاحظات الزبون: ${order.notes}`); }
    lines.push('');
    lines.push('هل تؤكد أنك صاحب الطلب وأن المنتجات والعنوان صحيحان؟ يرجى الرد بالتأكيد أو ذكر التعديل المطلوب.');
    return lines.join('\n');
  };
  const sendWhatsapp = async (order) => {
    const phone = order.customer?.phone || order.guest_phone || '';
    const msg = encodeURIComponent(buildConfirmationMessage(order));
    window.open(`https://wa.me/${phone.replace(/\D/g, '')}?text=${msg}`, '_blank');
    // بمجرد ما المدير يبعت رسالة التأكيد، الطلب بيتحول تلقائيًا لـ"بانتظار تأكيد الزبون" —
    // وبعدين المدير نفسه بيأكدها يدويًا لـ"تم التأكيد" لما يرد الزبون بالموافقة.
    if (order.status === 'new') {
      const { error } = await sb.from('orders').update({ status: 'awaiting_confirmation' }).eq('id', order.id);
      if (error) { alert(at(`تعذّر تحديث حالة الطلب: ${error.message}`, `Could not update order status: ${error.message}`)); return; }
      invalidate('admin_new_orders_count');
      refetch();
    }
  };
  const cancelOrder = async (order) => {
    const { error } = await sb.from('orders').update({ status: 'cancelled' }).eq('id', order.id);
    if (error) { alert(at(`تعذّر إلغاء الطلب: ${error.message}`, `Could not cancel the order: ${error.message}`)); return; }
    invalidate('admin_new_orders_count'); refetch();
  };

  // تصفير الطلبات: بيحذف الطلبات نهائيًا من قاعدة البيانات (مو بس إخفاء) — وبما إنو حذف الطلب
  // بيحذف تلقائيًا كل "سطور الطلب" (order_items) المرتبطة فيه، هاد بيحل مشكلة "ما فيك تحذف
  // هاد المنتج لأنه مرتبط بطلبات سابقة" لأي منتج كانت طلباته المحذوفة هي السبب الوحيد بالربط.
  const doResetActiveOrders = async () => {
    if (resetActiveConfirmText.trim() !== resetOrdersWord) return;
    const { error } = await sb.from('orders').delete().in('status', ['new', 'awaiting_confirmation', 'confirmed']);
    setResetActiveOpen(false); setResetActiveConfirmText('');
    _cache.clear(); refetch();
    if (error) { alert(at(`صار خطأ أثناء التصفير: ${error.message}`, `An error occurred while resetting: ${error.message}`)); return; }
    alert(at('تم تصفير كل الطلبات المعلقة والحديثة نهائيًا.', 'All pending & recent orders have been permanently reset.'));
  };
  // "تصفير السجل" بيحذف حرفيًا أي طلب مو من ضمن الحالات النشطة (يعني مش بس completed/cancelled،
  // إنما أي حالة تانية غير متوقعة كمان، بما فيها الطلبات يلي حالتها فاضية) — حتى الزرّين مع بعض
  // يغطّوا 100% من الطلبات دايمًا ولا يضل ولا طلب واحد ممكن يمنع حذف منتج بعدين.
  const doResetHistoryOrders = async () => {
    if (resetHistoryConfirmText.trim() !== resetOrdersWord) return;
    const activeStatuses = ['new', 'awaiting_confirmation', 'confirmed'];
    const { error: e1 } = await sb.from('orders').delete().not('status', 'in', `(${activeStatuses.join(',')})`);
    const { error: e2 } = await sb.from('orders').delete().is('status', null);
    const error = e1 || e2;
    setResetHistoryOpen(false); setResetHistoryConfirmText('');
    _cache.clear(); refetch();
    if (error) { alert(at(`صار خطأ أثناء التصفير: ${error.message}`, `An error occurred while resetting: ${error.message}`)); return; }
    alert(at('تم تصفير كل سجل الطلبات نهائيًا.', 'The entire order history has been permanently reset.'));
  };
  return (
    <div>
      <AdminPageHeader title={at('الطلبات', 'Orders')} description={at('إرسال تحقق واتساب ← تم التحقق ← تأكيد وقبض — وبعدها بيروح الطلب على سجل الطلبات', 'Send WhatsApp confirmation ← Confirmed ← Confirm & paid — then the order moves to order history')} />
      <div className="mb-4 flex flex-wrap items-center justify-between gap-3">
        <div className="flex flex-wrap gap-2">{ORDER_TABS.map((tb) => <button key={tb.key} onClick={() => setTab(tb.key)} className={`whitespace-nowrap rounded-full border px-3 py-1 text-sm ${tab === tb.key ? 'border-navy bg-navy text-white' : 'border-gray-300'}`}>{at(tb.label, tb.labelEn)}</button>)}</div>
        <div className="flex flex-wrap items-center gap-2">
          <Button onClick={() => setAddOpen(true)}>+ {at('إضافة طلب', 'Add order')}</Button>
          <SearchInput value={search} onChange={setSearch} placeholder={at('رقم الطلب...', 'Order number...')} />
        </div>
      </div>
      <DataTable loading={isLoading} rows={orders || []} emptyLabel={at('لا توجد طلبات', 'No orders')} columns={[
        { header: at('الطلب', 'Order'), render: (o) => <span className="flex items-center gap-1.5 font-bold">#{o.order_number}{o.sale_channel === 'in_store' && <Badge color="purple">🏪 {at('محل', 'In-store')}</Badge>}</span> },
        { header: at('العميل', 'Customer'), render: (o) => o.customer?.name || o.guest_name || '-' },
        { header: at('المبلغ', 'Amount'), render: (o) => formatPrice(o.total_amount) },
        { header: at('التوصيل', 'Delivery'), render: (o) => o.delivery_zone ? <span>{deliveryZoneLabel[o.delivery_zone] || o.delivery_zone}{o.city ? ` — ${o.city}` : ''}</span> : '-' },
        { header: at('الدفع', 'Payment'), render: (o) => (
          <div className="flex items-center gap-1.5">
            <Badge color={o.payment_method === 'reflect' ? 'purple' : 'gray'}>{paymentLabel[o.payment_method] || at('كاش عند الاستلام', 'Cash on delivery')}</Badge>
            {o.payment_method === 'reflect' && o.reflect_receipt_url && <button onClick={() => setReceiptModal(o.reflect_receipt_url)} className="text-xs text-brandPurple underline">{at('عرض الوصل', 'View receipt')}</button>}
            {o.payment_method === 'reflect' && !o.reflect_receipt_url && <span className="text-xs text-brandRed">{at('بدون وصل!', 'No receipt!')}</span>}
          </div>
        ) },
        { header: at('التاريخ', 'Date'), render: (o) => formatDate(o.created_at) },
        { header: at('الحالة', 'Status'), render: (o) => <Badge color={statusColor[o.status]}>{statusLabel[o.status]}</Badge> },
        { header: at('الإجراءات', 'Actions'), render: (o) => (
          <div className="flex flex-wrap items-center gap-1.5">
            {o.status === 'new' && <Button onClick={() => sendWhatsapp(o)} className="!px-2 !py-1 text-xs">{at('إرسال تحقق واتساب', 'Send WhatsApp confirmation')}</Button>}
            {o.status === 'awaiting_confirmation' && (
              <>
                <Button onClick={() => updateStatus(o, 'confirmed')} className="!px-2 !py-1 text-xs">{at('تم التحقق', 'Confirmed')}</Button>
                <Button variant="secondary" onClick={() => sendWhatsapp(o)} className="!px-2 !py-1 text-xs">{at('إعادة إرسال', 'Resend')}</Button>
              </>
            )}
            {o.status === 'confirmed' && <Button onClick={() => updateStatus(o, 'completed')} className="!px-2 !py-1 text-xs">{at('تأكيد وقبض', 'Confirm & paid')}</Button>}
            {(o.status === 'new' || o.status === 'awaiting_confirmation' || o.status === 'confirmed') && (
              <button onClick={() => cancelOrder(o)} className="text-xs text-brandRed">{at('إلغاء', 'Cancel')}</button>
            )}
          </div>
        ) },
      ]} />
      <Modal open={!!receiptModal} onClose={() => setReceiptModal(null)} title={at('صورة وصل التحويل', 'Transfer receipt image')}>
        {receiptModal && <img src={receiptModal} className="max-h-[70vh] w-full object-contain" />}
      </Modal>
      <AdminAddOrderModal open={addOpen} onClose={() => setAddOpen(false)} onCreated={() => { setTab('history'); refetch(); }} />

      <div className="mt-8 grid gap-4 sm:grid-cols-2">
        <div className="border-2 border-brandRed/30 bg-brandRed/5 p-4">
          <p className="mb-1 text-sm font-bold text-brandRed">{at('تصفير الطلبات المعلقة والحديثة', 'Reset pending & recent orders')}</p>
          <p className="mb-2 text-xs text-gray-500">{at('بيحذف نهائيًا كل الطلبات الجديدة/بانتظار التحقق/المؤكدة (تبويب "الطلبات المعلقة والحديثة")، وبيفك تلقائيًا أي منتج كان محجوز عليه حذف بسبب هالطلبات.', 'Permanently deletes all new/awaiting-confirmation/confirmed orders ("Pending & recent orders" tab), and automatically unblocks any product deletion that was caused by these orders.')}</p>
          {!resetActiveOpen && (
            <Button variant="danger" onClick={() => setResetActiveOpen(true)}>{at('تصفير الطلبات', 'Reset orders')}</Button>
          )}
          {resetActiveOpen && (
            <div className="mt-1 max-w-xs">
              <p className="mb-1 text-xs text-gray-500">{at(`اكتب كلمة (${resetOrdersWord}) للتأكيد`, `Type "${resetOrdersWord}" to confirm`)}</p>
              <Input autoFocus placeholder={at(`اكتب: ${resetOrdersWord}`, `Type: ${resetOrdersWord}`)} value={resetActiveConfirmText} onChange={(e) => setResetActiveConfirmText(e.target.value)} />
              <div className="mt-2 flex gap-2">
                <Button variant="danger" disabled={resetActiveConfirmText.trim() !== resetOrdersWord} onClick={doResetActiveOrders}>{at('تصفير نهائي', 'Reset permanently')}</Button>
                <Button variant="ghost" onClick={() => { setResetActiveOpen(false); setResetActiveConfirmText(''); }}>{at('إلغاء', 'Cancel')}</Button>
              </div>
            </div>
          )}
        </div>
        <div className="border-2 border-brandRed/30 bg-brandRed/5 p-4">
          <p className="mb-1 text-sm font-bold text-brandRed">{at('تصفير سجل الطلبات', 'Reset order history')}</p>
          <p className="mb-2 text-xs text-gray-500">{at('بيحذف نهائيًا كل الطلبات المؤكدة والملغاة (تبويب "سجل الطلبات")، وبيفك تلقائيًا أي منتج كان محجوز عليه حذف بسبب هالطلبات.', 'Permanently deletes all completed & cancelled orders ("Order history" tab), and automatically unblocks any product deletion that was caused by these orders.')}</p>
          {!resetHistoryOpen && (
            <Button variant="danger" onClick={() => setResetHistoryOpen(true)}>{at('تصفير السجل', 'Reset history')}</Button>
          )}
          {resetHistoryOpen && (
            <div className="mt-1 max-w-xs">
              <p className="mb-1 text-xs text-gray-500">{at(`اكتب كلمة (${resetOrdersWord}) للتأكيد`, `Type "${resetOrdersWord}" to confirm`)}</p>
              <Input autoFocus placeholder={at(`اكتب: ${resetOrdersWord}`, `Type: ${resetOrdersWord}`)} value={resetHistoryConfirmText} onChange={(e) => setResetHistoryConfirmText(e.target.value)} />
              <div className="mt-2 flex gap-2">
                <Button variant="danger" disabled={resetHistoryConfirmText.trim() !== resetOrdersWord} onClick={doResetHistoryOrders}>{at('تصفير نهائي', 'Reset permanently')}</Button>
                <Button variant="ghost" onClick={() => { setResetHistoryOpen(false); setResetHistoryConfirmText(''); }}>{at('إلغاء', 'Cancel')}</Button>
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

/* ============================================================
   لوحة الأدمن — إضافة طلب أرضي (بيع من المحل)
   ============================================================ */
const emptyAddOrderState = { customerName: '', customerPhone: '', notes: '', items: [], search: '', expandedId: null };
function AdminAddOrderModal({ open, onClose, onCreated }) {
  const { at } = useAdminLang();
  const [state, setState] = useState(emptyAddOrderState);
  const [saving, setSaving] = useState(false);
  const [err, setErr] = useState(null);
  const { data: results } = useSupaQuery(['admin_add_order_search', state.search], async () => {
    if (!state.search.trim()) return [];
    const { data } = await sb.from('products').select('id, name, original_price, discount_price, colors:product_colors(*, sizes:product_sizes(*))').ilike('name', `%${state.search.trim()}%`).limit(8);
    return data || [];
  });
  const reset = () => { setState(emptyAddOrderState); setErr(null); };
  const addItem = (product, color, size) => {
    const price = Number(product.discount_price || product.original_price || 0);
    setState((s) => ({
      ...s,
      expandedId: null,
      search: '',
      items: [...s.items, {
        key: `${product.id}-${color?.id || 'x'}-${size?.size || 'x'}-${Date.now()}`,
        product_id: product.id, product_color_id: color?.id || null, size: size?.size || null,
        label: `${product.name}${color ? ' — ' + color.color_name : ''}${size ? ' / ' + size.size : ''}`,
        quantity: 1, unit_price: price,
      }],
    }));
  };
  const updateItem = (key, patch) => setState((s) => ({ ...s, items: s.items.map((it) => (it.key === key ? { ...it, ...patch } : it)) }));
  const removeItem = (key) => setState((s) => ({ ...s, items: s.items.filter((it) => it.key !== key) }));
  const total = state.items.reduce((sum, it) => sum + Number(it.quantity || 0) * Number(it.unit_price || 0), 0);
  const submit = async () => {
    setErr(null);
    if (state.items.length === 0) { setErr(at('أضف منتج واحد على الأقل', 'Add at least one product')); return; }
    setSaving(true);
    try {
      const { data, error } = await sb.rpc('create_admin_order', {
        p_customer_name: state.customerName.trim() || null,
        p_customer_phone: state.customerPhone.trim() || null,
        p_items: state.items.map((it) => ({ product_id: it.product_id, product_color_id: it.product_color_id, size: it.size, quantity: Number(it.quantity), unit_price: Number(it.unit_price) })),
        p_notes: state.notes.trim() || null,
      });
      if (error) throw error;
      const result = Array.isArray(data) ? data[0] : data;
      if (!result?.success) { setErr(result?.message || at('تعذّر إضافة الطلب', 'Could not add the order')); return; }
      invalidate('acc_orders'); invalidate('admin_orders');
      reset(); onClose(); onCreated?.();
    } catch (e) { setErr(e.message || at('حدث خطأ', 'An error occurred')); } finally { setSaving(false); }
  };
  return (
    <Modal open={open} onClose={() => { reset(); onClose(); }} title={at('إضافة طلب أرضي (بيع من المحل)', 'Add in-store order (walk-in sale)')}>
      <div className="space-y-3">
        <div className="grid gap-3 sm:grid-cols-2">
          <Input placeholder={at('اسم الزبون (اختياري)', 'Customer name (optional)')} value={state.customerName} onChange={(e) => setState((s) => ({ ...s, customerName: e.target.value }))} />
          <Input placeholder={at('رقم الجوال (اختياري)', 'Phone number (optional)')} value={state.customerPhone} onChange={(e) => setState((s) => ({ ...s, customerPhone: e.target.value }))} />
        </div>
        <div className="relative">
          <Input placeholder={at('ابحث عن منتج بالاسم لإضافته...', 'Search for a product by name to add it...')} value={state.search} onChange={(e) => setState((s) => ({ ...s, search: e.target.value, expandedId: null }))} />
          {!!state.search.trim() && (
            <div className="absolute z-10 mt-1 max-h-64 w-full overflow-y-auto border border-gray-200 bg-white shadow-lg">
              {(results || []).length === 0 && <p className="px-3 py-2 text-sm text-gray-400">{at('لا نتائج', 'No results')}</p>}
              {(results || []).map((p) => (
                <div key={p.id} className="border-b border-gray-100 last:border-0">
                  <button type="button" onClick={() => setState((s) => ({ ...s, expandedId: s.expandedId === p.id ? null : p.id }))} className="flex w-full items-center justify-between px-3 py-2 text-start text-sm hover:bg-gray-50">
                    <span>{p.name}</span>
                    <span className="text-xs text-gray-400">{formatPrice(p.discount_price || p.original_price)}</span>
                  </button>
                  {state.expandedId === p.id && (
                    <div className="space-y-2 bg-gray-50 px-3 py-2">
                      {(p.colors || []).length === 0 && (
                        <button type="button" onClick={() => addItem(p, null, null)} className="border border-navy px-2 py-1 text-xs text-navy">{at('إضافة بدون لون/مقاس', 'Add without color/size')}</button>
                      )}
                      {(p.colors || []).map((c) => (
                        <div key={c.id} className="flex flex-wrap items-center gap-1.5">
                          <span className="text-xs font-medium text-gray-500">{c.color_name}:</span>
                          {(c.sizes || []).map((sz) => (
                            <button type="button" key={sz.id} disabled={sz.quantity <= 0} onClick={() => addItem(p, c, sz)} className="border border-gray-300 px-2 py-0.5 text-xs disabled:cursor-not-allowed disabled:opacity-30 hover:border-navy">
                              {sz.size} ({sz.quantity})
                            </button>
                          ))}
                        </div>
                      ))}
                    </div>
                  )}
                </div>
              ))}
            </div>
          )}
        </div>
        {state.items.length > 0 && (
          <div className="divide-y border border-gray-200">
            {state.items.map((it) => (
              <div key={it.key} className="flex items-center gap-2 px-3 py-2 text-sm">
                <span className="flex-1">{it.label}</span>
                <Input type="number" min="1" value={it.quantity} onChange={(e) => updateItem(it.key, { quantity: e.target.value })} className="!w-16 !py-1 text-center" />
                <Input type="number" min="0" value={it.unit_price} onChange={(e) => updateItem(it.key, { unit_price: e.target.value })} className="!w-24 !py-1 text-center" />
                <button onClick={() => removeItem(it.key)} className="text-brandRed">✕</button>
              </div>
            ))}
          </div>
        )}
        <Input placeholder={at('ملاحظات (اختياري)', 'Notes (optional)')} value={state.notes} onChange={(e) => setState((s) => ({ ...s, notes: e.target.value }))} />
        <div className="flex items-center justify-between border-t pt-3">
          <span className="font-bold text-navy">{at('الإجمالي', 'Total')}: {formatPrice(total)}</span>
        </div>
        {err && <p className="text-sm text-brandRed">{err}</p>}
      </div>
      <div className="mt-5 flex justify-end gap-2 border-t pt-4">
        <Button variant="ghost" onClick={() => { reset(); onClose(); }}>{at('إلغاء', 'Cancel')}</Button>
        <Button onClick={submit} disabled={saving}>{saving ? '...' : at('حفظ الطلب', 'Save order')}</Button>
      </div>
    </Modal>
  );
}

/* ============================================================
   لوحة الأدمن — العملاء والمخزون
   ============================================================ */
function AdminCustomersPage() {
  const { at } = useAdminLang();
  const [search, setSearch] = useState('');
  const { data: customers, isLoading } = useSupaQuery(['admin_customers', search], async () => {
    let q = sb.from('customers').select('*').order('created_at', { ascending: false });
    if (search) q = q.or(`name.ilike.%${search}%,phone.ilike.%${search}%`);
    const { data, error } = await q; if (error) throw error; return data || [];
  });
  const { data: orderStats } = useSupaQuery(['admin_customer_stats'], async () => {
    const { data } = await sb.from('orders').select('customer_id, total_amount, created_at');
    const map = {};
    (data || []).forEach((o) => { if (!o.customer_id) return; if (!map[o.customer_id]) map[o.customer_id] = { count: 0, total: 0, last: o.created_at }; map[o.customer_id].count += 1; map[o.customer_id].total += Number(o.total_amount); if (o.created_at > map[o.customer_id].last) map[o.customer_id].last = o.created_at; });
    return map;
  });
  return (
    <div>
      <AdminPageHeader title={at('العملاء', 'Customers')} description={at('قائمة عملاء المتجر ونشاطهم', "List of the store's customers and their activity")} />
      <div className="mb-4 flex justify-end"><SearchInput value={search} onChange={setSearch} /></div>
      <DataTable loading={isLoading} rows={customers || []} emptyLabel={at('لا يوجد عملاء بعد', 'No customers yet')} columns={[
        { header: at('العميل', 'Customer'), render: (c) => <div className="flex items-center gap-2"><span className="flex h-7 w-7 items-center justify-center rounded-full bg-navy text-xs text-white">{initials(c.name)}</span>{c.name || '-'}</div> },
        { header: at('الهاتف والعنوان', 'Phone & address'), render: (c) => <span>{c.phone}{c.address ? ` — ${c.address}` : ''}</span> },
        { header: at('عدد الطلبات', 'Order count'), render: (c) => orderStats?.[c.id]?.count || 0 },
        { header: at('إجمالي المشتريات', 'Total purchases'), render: (c) => (orderStats?.[c.id]?.total || 0).toLocaleString() + ' ₪' },
        { header: at('آخر طلب', 'Last order'), render: (c) => (orderStats?.[c.id]?.last ? formatDate(orderStats[c.id].last) : '-') },
        { header: at('نقاط الولاء', 'Loyalty points'), render: (c) => <Badge color="navy">{c.loyalty_points}</Badge> },
      ]} />
    </div>
  );
}
function AdminInventoryPage() {
  const { at } = useAdminLang();
  const [dept, setDept] = useState('all'); const [search, setSearch] = useState('');
  const { data: products, isLoading } = useSupaQuery(['admin_inventory', dept, search], async () => {
    let q = sb.from('products').select('*, brand:brands(*), category:categories(*), colors:product_colors(*, sizes:product_sizes(*), images:product_color_images(*))');
    if (dept === 'new') { const ids = await categoryIdsForSection('new'); q = ids.length ? q.in('category_id', ids) : q.eq('id', '00000000-0000-0000-0000-000000000000'); }
    else if (dept !== 'all') { const ids = await categoryIdsForDepartment(dept); q = ids.length ? q.in('category_id', ids) : q.eq('id', '00000000-0000-0000-0000-000000000000'); }
    if (search) q = q.ilike('name', `%${search}%`);
    const { data, error } = await q; if (error) throw error; return data || [];
  });
  const grouped = {};
  (products || []).forEach((p) => { const key = p.category?.name || at('بدون تصنيف', 'Uncategorized'); if (!grouped[key]) grouped[key] = []; grouped[key].push(p); });
  const totalQty = (p) => (p.colors || []).reduce((s, c) => s + (c.sizes || []).reduce((s2, sz) => s2 + sz.quantity, 0), 0);
  return (
    <div>
      <AdminPageHeader title={at('المخزون', 'Inventory')} description={at('عرض الكميات المتاحة مجمّعة حسب التصنيف', 'View available quantities grouped by category')} />
      <div className="mb-4 flex flex-wrap items-center justify-between gap-3">
        <div className="flex gap-2">{['all', 'new', 'men', 'women', 'kids'].map((d) => <button key={d} onClick={() => setDept(d)} className={`whitespace-nowrap rounded-full border px-3 py-1 text-sm ${dept === d ? 'border-navy bg-navy text-white' : 'border-gray-300'}`}>{{ all: at('الكل', 'All'), new: at('وصل حديثًا', 'New arrivals'), men: at('رجال', 'Men'), women: at('نساء', 'Women'), kids: at('أطفال', 'Kids') }[d]}</button>)}</div>
        <SearchInput value={search} onChange={setSearch} />
      </div>
      {isLoading ? <div className="skeleton h-40 w-full" /> : Object.entries(grouped).map(([cat, items]) => (
        <div key={cat} className="mb-6">
          <h3 className="mb-2 font-bold text-navy">{cat} — {items.length} {at('منتجات', 'products')}</h3>
          <div className="grid grid-cols-2 gap-3 sm:grid-cols-4">
            {items.map((p) => (
              <div key={p.id} className="border border-gray-200 bg-white p-3">
                <div className="mb-2 flex aspect-square items-center justify-center bg-gray-100">{p.colors?.[0]?.images?.[0]?.image_url ? <img src={p.colors[0].images[0].image_url} className="h-full w-full object-cover" /> : <span className="text-2xl text-gray-300">📦</span>}</div>
                <p className="text-xs text-gray-400">{p.brand?.name}</p><p className="truncate text-sm font-bold">{p.name}</p>
                <Badge color={totalQty(p) === 0 ? 'red' : totalQty(p) < 5 ? 'yellow' : 'green'}>{totalQty(p)} {at('قطعة متاحة', 'in stock')}</Badge>
              </div>
            ))}
          </div>
        </div>
      ))}
    </div>
  );
}

/* ============================================================
   لوحة الأدمن — الولاء والخصومات
   ============================================================ */
const emptyDiscountForm = { code: '', discount_percent: '10', valid_until: '', max_uses: '1' };
function AdminLoyaltyPage() {
  const { at } = useAdminLang();
  const { data: settings } = useSiteSettings();
  const [loyaltyForm, setLoyaltyForm] = useState(DEFAULT_SETTINGS.loyalty);
  const [loyaltySaving, setLoyaltySaving] = useState(false);
  const [loyaltySaved, setLoyaltySaved] = useState(false);
  useEffect(() => { if (settings?.loyalty) setLoyaltyForm(settings.loyalty); }, [settings]);
  const saveLoyaltySettings = async () => {
    setLoyaltySaving(true);
    const { error } = await saveSiteSetting('loyalty', {
      enabled: !!loyaltyForm.enabled,
      pointsPerAmount: Number(loyaltyForm.pointsPerAmount) || 0,
      amountUnit: Number(loyaltyForm.amountUnit) || 1,
      redeemThreshold: Number(loyaltyForm.redeemThreshold) || 0,
      discountPercent: Number(loyaltyForm.discountPercent) || 0,
    });
    setLoyaltySaving(false);
    if (error) { alert(at(`تعذّر حفظ إعدادات الولاء: ${error.message}`, `Could not save loyalty settings: ${error.message}`)); return; }
    invalidate('site_settings');
    setLoyaltySaved(true);
    setTimeout(() => setLoyaltySaved(false), 2000);
  };

  const [search, setSearch] = useState('');
  const { data: codes, isLoading, refetch } = useSupaQuery(['admin_discount_codes', search], async () => {
    let q = sb.from('discount_codes').select('*').order('created_at', { ascending: false });
    if (search) q = q.ilike('code', `%${search}%`);
    const { data, error } = await q; if (error) throw error; return data || [];
  });
  const { data: customers } = useSupaQuery(['admin_loyalty_customers'], async () => {
    const { data } = await sb.from('customers').select('*').order('loyalty_points', { ascending: false });
    return data || [];
  });

  const [modalOpen, setModalOpen] = useState(false);
  const [form, setForm] = useState(emptyDiscountForm);
  const [saving, setSaving] = useState(false);
  const [deleteTarget, setDeleteTarget] = useState(null);
  const [editTarget, setEditTarget] = useState(null);

  const genCode = () => {
    const chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
    let s = ''; for (let i = 0; i < 6; i++) s += chars[Math.floor(Math.random() * chars.length)];
    setForm((f) => ({ ...f, code: s }));
  };
  const openCreate = () => { setEditTarget(null); setForm(emptyDiscountForm); setModalOpen(true); };
  const openEdit = (c) => {
    setEditTarget(c);
    setForm({ code: c.code, discount_percent: String(c.discount_percent), valid_until: c.valid_until ? c.valid_until.slice(0, 10) : '', max_uses: String(c.max_uses) });
    setModalOpen(true);
  };
  const save = async () => {
    const code = form.code.trim().toUpperCase();
    if (code.length !== 6) { alert(at('كود الخصم لازم يكون بالضبط 6 خانات', 'The discount code must be exactly 6 characters')); return; }
    if (!form.discount_percent || Number(form.discount_percent) <= 0) { alert(at('حدد نسبة خصم صحيحة', 'Set a valid discount percentage')); return; }
    setSaving(true);
    try {
      if (editTarget) {
        const { error } = await sb.from('discount_codes').update({
          discount_percent: Number(form.discount_percent),
          valid_until: form.valid_until || null,
          max_uses: Number(form.max_uses) || 1,
        }).eq('id', editTarget.id);
        if (error) throw error;
      } else {
        const { error } = await sb.from('discount_codes').insert({
          code,
          discount_percent: Number(form.discount_percent),
          scope: 'all_products',
          valid_until: form.valid_until || null,
          max_uses: Number(form.max_uses) || 1,
          is_active: true,
        });
        if (error) throw error;
      }
      setModalOpen(false); setEditTarget(null); setForm(emptyDiscountForm); refetch();
    } catch (e) { alert(e.message?.includes('duplicate') ? at('هاد الكود مستخدم مسبقًا، جرّب كود ثاني', 'This code is already in use, try another one') : (e.message || at('حدث خطأ', 'An error occurred'))); } finally { setSaving(false); }
  };
  const toggleActive = async (c) => {
    const { error } = await sb.from('discount_codes').update({ is_active: !c.is_active }).eq('id', c.id);
    if (error) { alert(at(`تعذّر تغيير حالة الكود: ${error.message}`, `Could not change the code's status: ${error.message}`)); return; }
    refetch();
  };
  const doDelete = async () => {
    if (!deleteTarget) return;
    const { error } = await sb.from('discount_codes').delete().eq('id', deleteTarget.id);
    if (error) { alert(at(`تعذّر حذف الكود: ${error.message}`, `Could not delete the code: ${error.message}`)); setDeleteTarget(null); return; }
    setDeleteTarget(null); refetch();
  };

  return (
    <div>
      <AdminPageHeader title={at('الولاء والخصومات', 'Loyalty & discounts')} description={at(`كل ${loyaltyForm.amountUnit} شيكل = ${loyaltyForm.pointsPerAmount} نقطة بعد إتمام الطلب، و${loyaltyForm.redeemThreshold} نقطة = خصم ${loyaltyForm.discountPercent}%`, `Every ₪${loyaltyForm.amountUnit} = ${loyaltyForm.pointsPerAmount} points after an order, and ${loyaltyForm.redeemThreshold} points = ${loyaltyForm.discountPercent}% discount`)} />

      <div className="mb-8 border border-gray-200 bg-white p-4">
        <div className="mb-3 flex items-center justify-between">
          <h3 className="font-bold text-navy">{at('إعدادات نقاط الولاء', 'Loyalty points settings')}</h3>
          <label className="flex cursor-pointer items-center gap-2 text-sm">
            <span>{loyaltyForm.enabled ? at('مفعّل', 'Enabled') : at('متوقف', 'Disabled')}</span>
            <input type="checkbox" className="h-5 w-5 accent-navy" checked={!!loyaltyForm.enabled} onChange={(e) => setLoyaltyForm({ ...loyaltyForm, enabled: e.target.checked })} />
          </label>
        </div>
        <div className="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-4">
          <div>
            <label className="mb-1 block text-xs text-gray-600">{at('كل كم شيكل (وحدة المبلغ)', 'Every how many ₪ (amount unit)')}</label>
            <Input type="number" value={loyaltyForm.amountUnit} onChange={(e) => setLoyaltyForm({ ...loyaltyForm, amountUnit: e.target.value })} />
          </div>
          <div>
            <label className="mb-1 block text-xs text-gray-600">{at('كم نقطة عن كل وحدة مبلغ', 'How many points per amount unit')}</label>
            <Input type="number" value={loyaltyForm.pointsPerAmount} onChange={(e) => setLoyaltyForm({ ...loyaltyForm, pointsPerAmount: e.target.value })} />
          </div>
          <div>
            <label className="mb-1 block text-xs text-gray-600">{at('عدد النقاط اللازمة للخصم', 'Points needed for a discount')}</label>
            <Input type="number" value={loyaltyForm.redeemThreshold} onChange={(e) => setLoyaltyForm({ ...loyaltyForm, redeemThreshold: e.target.value })} />
          </div>
          <div>
            <label className="mb-1 block text-xs text-gray-600">{at('نسبة الخصم عند الاستبدال %', 'Discount % on redemption')}</label>
            <Input type="number" value={loyaltyForm.discountPercent} onChange={(e) => setLoyaltyForm({ ...loyaltyForm, discountPercent: e.target.value })} />
          </div>
        </div>
        <p className="mt-2 text-xs text-gray-400">{at(`مثال: كل ${loyaltyForm.amountUnit || 100} شيكل = ${loyaltyForm.pointsPerAmount || 10} نقطة، وكل ${loyaltyForm.redeemThreshold || 100} نقطة تراكمت بتصير خصم ${loyaltyForm.discountPercent || 10}% على الطلب.`, `Example: every ₪${loyaltyForm.amountUnit || 100} = ${loyaltyForm.pointsPerAmount || 10} points, and every ${loyaltyForm.redeemThreshold || 100} points accumulated become a ${loyaltyForm.discountPercent || 10}% discount on the order.`)}</p>
        <div className="mt-3 flex items-center gap-3">
          <Button onClick={saveLoyaltySettings} disabled={loyaltySaving}>{loyaltySaving ? '...' : at('حفظ الإعدادات', 'Save settings')}</Button>
          {loyaltySaved && <span className="text-sm text-brandGreen">{at('تم الحفظ ✓', 'Saved ✓')}</span>}
        </div>
      </div>

      <div className="mb-4 flex flex-wrap items-center justify-between gap-3">
        <Button onClick={openCreate}>+ {at('إنشاء كود خصم', 'Create discount code')}</Button>
        <SearchInput value={search} onChange={setSearch} />
      </div>

      <div className="mb-8 grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-3">
        {isLoading ? Array.from({ length: 3 }).map((_, i) => <SkeletonBox key={i} className="h-28" />) : (codes || []).map((c) => (
          <div key={c.id} className="border border-gray-200 bg-white p-4">
            <div className="mb-1 flex items-center justify-between">
              <span className="text-lg font-extrabold text-navy">{c.discount_percent}%</span>
              {c.used_count >= c.max_uses && <Badge color="gray">{at('اكتمل الاستخدام', 'Fully used')}</Badge>}
            </div>
            <p className="mb-1 font-mono text-lg tracking-widest text-brandPurple">{c.code}</p>
            <p className="text-xs text-gray-500">{at('تاريخ الإنشاء', 'Created')}: {formatDate(c.created_at)}</p>
            <p className="text-xs text-gray-500">{c.valid_until ? at(`صالح حتى ${formatDate(c.valid_until)}`, `Valid until ${formatDate(c.valid_until)}`) : at('بدون تاريخ انتهاء', 'No expiry date')}</p>
            <p className="mt-1 text-xs font-medium text-navy">{at(`استُخدم ${c.used_count} من ${c.max_uses} مرة`, `Used ${c.used_count} of ${c.max_uses} times`)}</p>
            <div className="mt-2 flex gap-2 text-xs">
              <button onClick={() => openEdit(c)} className="text-brandPurple">{at('تعديل', 'Edit')}</button>
              <button onClick={() => setDeleteTarget(c)} className="text-brandRed">{at('حذف', 'Delete')}</button>
              <button onClick={() => toggleActive(c)}>{c.is_active ? at('إيقاف', 'Disable') : at('تفعيل', 'Enable')}</button>
            </div>
          </div>
        ))}
      </div>

      <h3 className="mb-3 font-bold text-navy">{at('رصيد نقاط الزبائن', 'Customer point balances')}</h3>
      <div className="divide-y border border-gray-200 bg-white">
        {(customers || []).slice(0, 20).map((c) => (
          <div key={c.id} className="flex items-center justify-between px-4 py-2 text-sm">
            <span>{c.name || c.phone}</span>
            <Badge color="navy">{c.loyalty_points} {at('نقطة', 'pts')}</Badge>
          </div>
        ))}
      </div>

      <Modal open={modalOpen} onClose={() => { setModalOpen(false); setEditTarget(null); }} title={editTarget ? at('تعديل كود الخصم', 'Edit discount code') : at('إنشاء كود خصم', 'Create discount code')}>
        <div className="space-y-3">
          <div>
            <label className="mb-1 block text-xs text-gray-600">{at('الكود — 6 خانات بالضبط', 'Code — exactly 6 characters')}</label>
            <div className="flex gap-2">
              <Input maxLength={6} disabled={!!editTarget} className="font-mono uppercase tracking-widest disabled:bg-gray-100" placeholder="ABC123" value={form.code} onChange={(e) => setForm({ ...form, code: e.target.value.toUpperCase().slice(0, 6) })} />
              {!editTarget && <Button type="button" variant="secondary" onClick={genCode}>{at('توليد', 'Generate')}</Button>}
            </div>
            {!editTarget && <p className="mt-1 text-[11px] text-gray-400">{form.code.length}/6</p>}
          </div>
          <Input type="number" placeholder={at('نسبة الخصم %', 'Discount %')} value={form.discount_percent} onChange={(e) => setForm({ ...form, discount_percent: e.target.value })} />
          <Input type="date" value={form.valid_until} onChange={(e) => setForm({ ...form, valid_until: e.target.value })} />
          <Input type="number" placeholder={at('عدد مرات الاستخدام المسموحة', 'Allowed number of uses')} value={form.max_uses} onChange={(e) => setForm({ ...form, max_uses: e.target.value })} />
        </div>
        <div className="mt-5 flex justify-end gap-2 border-t pt-4">
          <Button variant="ghost" onClick={() => { setModalOpen(false); setEditTarget(null); }}>{at('إلغاء', 'Cancel')}</Button>
          <Button onClick={save} disabled={saving}>{saving ? '...' : at('حفظ', 'Save')}</Button>
        </div>
      </Modal>

      <ConfirmDialog open={!!deleteTarget} title={at('حذف كود الخصم', 'Delete discount code')} message={at(`متأكد إنك بدك تحذف الكود "${deleteTarget?.code}"؟`, `Are you sure you want to delete the code "${deleteTarget?.code}"?`)} onConfirm={doDelete} onCancel={() => setDeleteTarget(null)} danger confirmLabel={at('حذف', 'Delete')} />
    </div>
  );
}

/* ============================================================
   لوحة الأدمن — مناطق التوصيل
   ============================================================ */
function AdminDeliveryPage() {
  const { at } = useAdminLang();
  const { data: settings } = useSiteSettings();
  const [form, setForm] = useState(DEFAULT_SETTINGS.delivery);
  const [reflectNumber, setReflectNumber] = useState('');
  const [saving, setSaving] = useState(false);
  const [saved, setSaved] = useState(false);
  useEffect(() => { if (settings?.delivery) setForm(settings.delivery); }, [settings]);
  useEffect(() => { if (settings?.reflectNumber != null) setReflectNumber(settings.reflectNumber); }, [settings]);

  const save = async () => {
    setSaving(true);
    const r1 = await saveSiteSetting('delivery', {
      westBank: Number(form.westBank) || 0,
      inside48: Number(form.inside48) || 0,
      jerusalem: Number(form.jerusalem) || 0,
    });
    const r2 = await saveSiteSetting('reflectNumber', reflectNumber.trim());
    setSaving(false);
    const failed = r1.error || r2.error;
    if (failed) { alert(at(`تعذّر حفظ الإعدادات: ${failed.message}`, `Could not save settings: ${failed.message}`)); return; }
    invalidate('site_settings');
    setSaved(true);
    setTimeout(() => setSaved(false), 2000);
  };

  return (
    <div>
      <AdminPageHeader title={at('مناطق التوصيل والدفع', 'Delivery zones & payment')} description={at('حدد رسم توصيل ثابت لكل منطقة، ورقم تحويل رفلكت يظهر للزبون لما يختار الدفع تحويل.', 'Set a fixed delivery fee per zone, and a Reflect transfer number shown to the customer when they choose transfer as payment.')} />
      <div className="border border-gray-200 bg-white p-4">
        <div className="grid grid-cols-1 gap-3 sm:grid-cols-3">
          {DELIVERY_ZONES.map((z) => (
            <div key={z.key}>
              <label className="mb-1 block text-xs text-gray-600">{at(z.label, z.labelEn)} (₪)</label>
              <Input type="number" min="0" value={form[z.key]} onChange={(e) => setForm({ ...form, [z.key]: e.target.value })} />
            </div>
          ))}
        </div>
        <p className="mt-2 text-xs text-gray-400">{at('لو تركت أي منطقة عالصفر، التوصيل إلها بيصير مجاني بالفاتورة.', 'If you leave a zone at zero, delivery there becomes free on the invoice.')}</p>
        <div className="mt-5 border-t pt-4">
          <label className="mb-1 block text-sm text-gray-600">{at('رقم تحويل رفلكت', 'Reflect transfer number')}</label>
          <Input placeholder={at('مثال: 059XXXXXXX', 'e.g. 059XXXXXXX')} value={reflectNumber} onChange={(e) => setReflectNumber(e.target.value)} />
          <p className="mt-1 text-xs text-gray-400">{at('بيظهر للزبون لما يختار "تحويل رفلكت" كطريقة دفع عند إتمام الطلب.', 'Shown to the customer when they choose "Reflect transfer" as the payment method at checkout.')}</p>
        </div>
        <div className="mt-3 flex items-center gap-3">
          <Button onClick={save} disabled={saving}>{saving ? '...' : at('حفظ الإعدادات', 'Save settings')}</Button>
          {saved && <span className="text-sm text-brandGreen">{at('تم الحفظ ✓', 'Saved ✓')}</span>}
        </div>
      </div>
    </div>
  );
}

/* ============================================================
   لوحة الأدمن — التقييمات
   ============================================================ */
function AdminReviewsPage() {
  const { at } = useAdminLang();
  const [search, setSearch] = useState('');
  const { data: reviews, isLoading } = useSupaQuery(['admin_reviews', search], async () => {
    const { data, error } = await sb.from('reviews').select('*, customer:customers(*), order:orders(order_number, guest_name, guest_phone, address, city)').order('created_at', { ascending: false });
    if (error) throw error;
    let rows = data || [];
    const nameOf = (r) => r.customer?.name || r.order?.guest_name || '';
    const phoneOf = (r) => r.customer?.phone || r.order?.guest_phone || '';
    if (search) rows = rows.filter((r) => nameOf(r).includes(search) || phoneOf(r).includes(search) || (r.order?.order_number || '').includes(search));
    return rows;
  });
  return (
    <div>
      <AdminPageHeader title={at('التقييمات', 'Reviews')} description={at('آراء الزبائن حول الطلبات والخدمة — مع كامل بيانات الشخص الي قيّم', "Customer feedback on orders and service — with the reviewer's full details")} />
      <div className="mb-4 flex justify-end"><SearchInput value={search} onChange={setSearch} /></div>
      <DataTable loading={isLoading} rows={reviews || []} emptyLabel={at('لا توجد تقييمات بعد', 'No reviews yet')} columns={[
        { header: at('الطلب', 'Order'), render: (r) => r.order?.order_number || '-' },
        { header: at('الاسم', 'Name'), render: (r) => r.customer?.name || r.order?.guest_name || '-' },
        { header: at('الهاتف', 'Phone'), render: (r) => r.customer?.phone || r.order?.guest_phone || '-' },
        { header: at('العنوان', 'Address'), render: (r) => [r.order?.city, r.order?.address].filter(Boolean).join('، ') || '-' },
        { header: at('نوع التقييم', 'Review type'), render: (r) => r.review_type },
        { header: at('التقييم', 'Rating'), render: (r) => `${'⭐'.repeat(r.rating)} (${r.rating}/5)` },
        { header: at('التعليق', 'Comment'), render: (r) => <span className="line-clamp-2 max-w-xs">{r.comment || '-'}</span> },
        { header: at('التاريخ', 'Date'), render: (r) => formatDate(r.created_at) },
      ]} />
    </div>
  );
}

/* ============================================================
   لوحة الأدمن — لوحة الحسابات
   ============================================================ */
function monthRange(month) {
  const [y, m] = month.split('-').map(Number);
  const start = new Date(y, m - 1, 1).toISOString();
  const end = new Date(y, m, 1).toISOString();
  return { start, end };
}
function AdminAccountingPage() {
  const { at } = useAdminLang();
  const now = new Date();
  const [month, setMonth] = useState(`${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}`);
  const { start, end } = monthRange(month);

  const { data: orders } = useSupaQuery(['acc_orders', month], async () => {
    // بنجيب سطور كل طلب مع تكلفة كل منتج (cost_price) حتى نقدر نحسب صافي ربح المبيعات فعليًا
    // (سعر البيع − التكلفة) مش بس إجمالي المبيعات.
    const { data } = await sb.from('orders').select('*, items:order_items(quantity, unit_price, product:products(cost_price))').gte('created_at', start).lt('created_at', end);
    return data || [];
  });
  const { data: records, isLoading: recLoading, refetch } = useSupaQuery(['acc_records', month], async () => {
    const { data } = await sb.from('financial_records').select('*').gte('record_date', start.slice(0, 10)).lt('record_date', end.slice(0, 10)).order('record_date', { ascending: false });
    return data || [];
  });
  // كل مقبوضات رفلكت (سواء لسا معلّقة أو تم تأكيدها وقبضها) — من كل الأوقات، مش بس هذا الشهر،
  // حتى تضل متجمعة بالسجل وما تختفي أبدًا لما تتأكد أو لما يتغيّر الشهر المختار بالأعلى.
  const { data: reflectAll, isLoading: reflectLoading } = useSupaQuery(['acc_reflect_all'], async () => {
    const { data } = await sb.from('orders').select('id, order_number, total_amount, status, created_at, reflect_receipt_url, customer:customers(name, phone), guest_name, guest_phone')
      .eq('payment_method', 'reflect').neq('status', 'cancelled').order('created_at', { ascending: false });
    return data || [];
  });

  const completedOrders = (orders || []).filter((o) => o.status === 'completed');
  const siteSales = completedOrders.filter((o) => o.sale_channel !== 'in_store').reduce((s, o) => s + Number(o.total_amount), 0);
  const storeSales = completedOrders.filter((o) => o.sale_channel === 'in_store').reduce((s, o) => s + Number(o.total_amount), 0);
  // تكلفة البضاعة المباعة (COGS) — مجموع (تكلفة القطعة × الكمية) لكل سطور الطلبات المكتملة هذا الشهر
  const cogs = completedOrders.reduce((s, o) => s + (o.items || []).reduce((s2, it) => s2 + Number(it.product?.cost_price || 0) * it.quantity, 0), 0);
  const income = (records || []).filter((r) => r.type === 'income').reduce((s, r) => s + Number(r.amount), 0);
  const expenses = (records || []).filter((r) => r.type === 'expense').reduce((s, r) => s + Number(r.amount), 0);
  const totalSales = siteSales + storeSales;
  const netProfit = totalSales - cogs + income - expenses;
  // مجموع مقبوضات رفلكت لهذا الشهر بس (لعرضها جنب باقي خانات المبيعات) — مع إنه الجدول التفصيلي تحت
  // بالصفحة بيضل عارض كل السجلات من كل الأوقات.
  const reflectMonthTotal = (reflectAll || []).filter((o) => o.created_at >= start && o.created_at < end).reduce((s, o) => s + Number(o.total_amount), 0);

  const emptyRecordForm = () => ({ id: null, description: '', type: 'expense', amount: '', is_paid: true, record_date: new Date().toISOString().slice(0, 10) });
  const [modalOpen, setModalOpen] = useState(false);
  const [receiptModal, setReceiptModal] = useState(null);
  const [form, setForm] = useState(emptyRecordForm());
  const [deleteRecordTarget, setDeleteRecordTarget] = useState(null);
  const [resetOpen, setResetOpen] = useState(false);
  const [resetConfirmText, setResetConfirmText] = useState('');
  const resetWord = at('تصفير', 'RESET');

  const openNewRecord = () => { setForm(emptyRecordForm()); setModalOpen(true); };
  const openEditRecord = (r) => { setForm({ id: r.id, description: r.description, type: r.type, amount: String(r.amount), is_paid: r.is_paid, record_date: r.record_date }); setModalOpen(true); };

  const saveRecord = async () => {
    if (!form.description.trim() || !form.amount) return;
    const payload = { description: form.description, type: form.type, amount: Number(form.amount), is_paid: form.is_paid, record_date: form.record_date };
    const { error } = form.id ? await sb.from('financial_records').update(payload).eq('id', form.id) : await sb.from('financial_records').insert(payload);
    if (error) { alert(at(`تعذّر حفظ السجل: ${error.message}`, `Could not save the record: ${error.message}`)); return; }
    setModalOpen(false);
    setForm(emptyRecordForm());
    refetch();
  };

  const doDeleteRecord = async () => {
    if (!deleteRecordTarget) return;
    const { error } = await sb.from('financial_records').delete().eq('id', deleteRecordTarget.id);
    if (error) { alert(at(`تعذّر حذف السجل: ${error.message}`, `Could not delete the record: ${error.message}`)); setDeleteRecordTarget(null); return; }
    setDeleteRecordTarget(null);
    refetch();
  };

  // بيبني وينزّل ملف Excel حقيقي (.xlsx) بترتيب طولي (عمود تحت عمود، صفحة Portrait) يحوي
  // كل السجلات المالية اليدوية المعطاة — يُستخدم كنسخة احتياطية تلقائية قبل أي تصفير نهائي.
  const downloadAccountingBackup = (allRecords) => {
    if (typeof XLSX === 'undefined') return false;
    const header = [at('الوصف', 'Description'), at('النوع', 'Type'), at('المبلغ', 'Amount'), at('مدفوع؟', 'Paid?'), at('التاريخ', 'Date')];
    const rows = (allRecords || []).map((r) => [
      r.description,
      r.type === 'income' ? at('دخل', 'Income') : at('مصروف', 'Expense'),
      Number(r.amount),
      r.is_paid ? at('نعم', 'Yes') : at('لا', 'No'),
      r.record_date,
    ]);
    const totalIncome = (allRecords || []).filter((r) => r.type === 'income').reduce((s, r) => s + Number(r.amount), 0);
    const totalExpense = (allRecords || []).filter((r) => r.type === 'expense').reduce((s, r) => s + Number(r.amount), 0);
    const aoa = [
      [at('نسخة احتياطية — كل السجلات المالية اليدوية', 'Backup — all manual financial records')],
      [at('تاريخ التصدير', 'Export date'), new Date().toISOString().slice(0, 10)],
      [],
      header,
      ...rows,
      [],
      [at('إجمالي المدفوعات', 'Total payments'), '', totalIncome],
      [at('إجمالي المصروفات', 'Total expenses'), '', totalExpense],
    ];
    const ws = XLSX.utils.aoa_to_sheet(aoa);
    ws['!cols'] = [{ wch: 34 }, { wch: 12 }, { wch: 14 }, { wch: 10 }, { wch: 14 }];
    // ترتيب الصفحة طولي (Portrait) لا عرضي، جاهزة للطباعة كنسخة أرشيف
    ws['!pageSetup'] = { orientation: 'portrait', fitToPage: true, fitToWidth: 1 };
    ws['!margins'] = { left: 0.5, right: 0.5, top: 0.6, bottom: 0.6, header: 0.3, footer: 0.3 };
    const wb = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(wb, ws, at('السجلات المالية', 'Financial records'));
    XLSX.writeFile(wb, `${at('نسخة-احتياطية-الحسابات', 'accounting-backup')}-${new Date().toISOString().slice(0, 10)}.xlsx`);
    return true;
  };

  const doResetAccounting = async () => {
    if (resetConfirmText.trim() !== resetWord) return;
    // قبل أي حذف نهائي، نجيب *كل* السجلات المالية من كل الأشهر (مش بس الشهر المعروض حاليًا)
    // ونصدّرها Excel أول — نسخة أرشيف تضل عندك حتى لو صفّرت.
    const { data: allRecords, error: fetchErr } = await sb.from('financial_records').select('*').order('record_date', { ascending: false });
    const backedUp = downloadAccountingBackup(allRecords || []);
    const { error } = await sb.from('financial_records').delete().neq('id', '00000000-0000-0000-0000-000000000000');
    setResetOpen(false);
    setResetConfirmText('');
    _cache.clear(); refetch();
    if (fetchErr || error) { alert(at(`صار خطأ أثناء التصفير: ${(fetchErr || error).message}`, `An error occurred while resetting: ${(fetchErr || error).message}`)); return; }
    alert(backedUp
      ? at('تم حفظ نسخة Excel احتياطية بكل السجلات، وتم تصفير كل السجلات المالية اليدوية من كل الأشهر.', 'An Excel backup of all records was saved, and all manual financial records across every month have been reset.')
      : at('تم تصفير كل السجلات المالية اليدوية (المصروفات والمدفوعات) من كل الأشهر.', 'All manual financial records (expenses & payments) across every month have been reset.'));
  };

  const exportExcel = () => {
    const rows = [
      [at('الوصف', 'Description'), at('النوع', 'Type'), at('المبلغ', 'Amount'), at('التاريخ', 'Date')],
      ...(records || []).map((r) => [r.description, r.type === 'income' ? at('دخل', 'Income') : at('مصروف', 'Expense'), String(r.amount), r.record_date]),
      [], [at('إجمالي المبيعات', 'Total sales'), '', String(totalSales), ''], [at('مبيعات الموقع', 'Site sales'), '', String(siteSales), ''], [at('مبيعات المحل', 'In-store sales'), '', String(storeSales), ''], [at('التكلفة', 'Cost'), '', String(cogs), ''], [at('صافي الربح', 'Net profit'), '', String(netProfit), ''],
    ];
    const csv = rows.map((r) => r.join(',')).join('\n');
    const blob = new Blob(['﻿' + csv], { type: 'text/csv;charset=utf-8;' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a'); a.href = url; a.download = `${at('تقرير', 'report')}-${month}.csv`; a.click();
  };

  const cards = [
    { label: at('الطلبات', 'Orders'), value: (orders || []).length },
    { label: at('مبيعات الموقع', 'Site sales'), value: formatPrice(siteSales) },
    { label: at('مبيعات المحل', 'In-store sales'), value: formatPrice(storeSales) },
    { label: at('مقبوضات ريفلكت (هالشهر)', 'Reflect receipts (this month)'), value: formatPrice(reflectMonthTotal) },
    { label: at('التكلفة', 'Cost'), value: formatPrice(cogs) },
    { label: at('المدفوعات', 'Payments'), value: formatPrice(income) },
    { label: at('المصروفات', 'Expenses'), value: formatPrice(expenses) },
  ];

  return (
    <div>
      <AdminPageHeader title={at('لوحة الحسابات', 'Accounting')} description={at('ملخص مالي شهري وسجلات يدوية', 'Monthly financial summary and manual records')} />
      <div className="mb-5 flex flex-wrap items-center justify-between gap-3">
        <Button variant="secondary" onClick={exportExcel}>{at('التقرير الشهري (Excel)', 'Monthly report (Excel)')}</Button>
        <input type="month" value={month} onChange={(e) => setMonth(e.target.value)} className="border border-gray-300 px-3 py-2 text-sm" />
      </div>

      <div className="mb-5 grid grid-cols-2 gap-3 sm:grid-cols-4">
        {cards.map((c) => (
          <div key={c.label} className="border border-gray-200 bg-white p-4">
            <p className="text-xs text-gray-500">{c.label}</p>
            <p className="text-lg font-bold text-navy">{c.value}</p>
          </div>
        ))}
        <div className="col-span-2 border border-navy bg-navy p-4 text-white sm:col-span-2">
          <p className="text-xs text-cream/80">{at('إجمالي المبيعات', 'Total sales')}</p>
          <p className="text-2xl font-extrabold">{formatPrice(totalSales)}</p>
        </div>
        <div className="col-span-2 border border-brandGreen bg-brandGreen/10 p-4 sm:col-span-2">
          <p className="text-xs text-brandGreen">{at('صافي الربح', 'Net profit')}</p>
          <p className="text-2xl font-extrabold text-brandGreen">{formatPrice(netProfit)}</p>
        </div>
      </div>

      <details open className="mb-4 border border-gray-200 bg-white p-4">
        <summary className="cursor-pointer font-bold text-navy">{at('المصروفات والحركات المالية', 'Expenses & financial records')}</summary>
        <p className="mt-2 text-xs text-gray-400">{at('بتقدر تضيف سجل جديد، وكمان تعدّل أو تحذف أي سجل مضاف مسبقًا.', 'You can add a new record, and also edit or delete any record already added.')}</p>
        <div className="mt-3 flex justify-end"><Button onClick={openNewRecord}>+ {at('إضافة سجل', 'Add record')}</Button></div>
        <div className="mt-3">
          <DataTable loading={recLoading} rows={records || []} emptyLabel={at('لا توجد سجلات', 'No records')} columns={[
            { header: at('الوصف', 'Description'), render: (r) => r.description },
            { header: at('النوع', 'Type'), render: (r) => (r.type === 'income' ? at('دخل', 'Income') : at('مصروف', 'Expense')) },
            { header: at('المبلغ', 'Amount'), render: (r) => formatPrice(r.amount) },
            { header: at('المدفوع', 'Paid'), render: (r) => (r.is_paid ? at('نعم', 'Yes') : at('لا', 'No')) },
            { header: at('التاريخ', 'Date'), render: (r) => formatDate(r.record_date) },
            { header: at('إجراءات', 'Actions'), render: (r) => (
              <div className="flex gap-2 text-sm">
                <button onClick={() => openEditRecord(r)}>✏️</button>
                <button onClick={() => setDeleteRecordTarget(r)} className="text-brandRed">🗑️</button>
              </div>
            ) },
          ]} />
        </div>

        <div className="mt-5 border-2 border-brandRed/30 bg-brandRed/5 p-4">
          <p className="mb-1 text-sm font-bold text-brandRed">{at('تصفير الحسابات', 'Reset accounting')}</p>
          <p className="mb-2 text-xs text-gray-500">{at('بيحمّلك أول نسخة Excel احتياطية فيها كل السجلات، وبعدين بيحذف كل السجلات المالية اليدوية (المصروفات والمدفوعات) نهائيًا من كل الأشهر — ما بيأثر إطلاقًا على الطلبات أو المبيعات أو مقبوضات ريفلكت.', "Downloads an Excel backup of all records first, then permanently deletes all manual financial records (expenses & payments) across every month — doesn't affect orders, sales, or Reflect receipts at all.")}</p>
          {!resetOpen && (
            <Button variant="danger" onClick={() => setResetOpen(true)}>{at('تصفير الحسابات', 'Reset accounting')}</Button>
          )}
          {resetOpen && (
            <div className="mt-1 max-w-xs">
              <p className="mb-1 text-xs text-gray-500">{at(`اكتب كلمة (${resetWord}) للتأكيد`, `Type "${resetWord}" to confirm`)}</p>
              <Input autoFocus placeholder={at(`اكتب: ${resetWord}`, `Type: ${resetWord}`)} value={resetConfirmText} onChange={(e) => setResetConfirmText(e.target.value)} />
              <div className="mt-2 flex gap-2">
                <Button variant="danger" disabled={resetConfirmText.trim() !== resetWord} onClick={doResetAccounting}>{at('تصفير نهائي', 'Reset permanently')}</Button>
                <Button variant="ghost" onClick={() => { setResetOpen(false); setResetConfirmText(''); }}>{at('إلغاء', 'Cancel')}</Button>
              </div>
            </div>
          )}
        </div>
      </details>

      <p className="text-xs text-gray-400">{at('صافي الربح = (إجمالي المبيعات − التكلفة) + المدفوعات اليدوية − المصروفات. إجمالي المبيعات = مبيعات الموقع + مبيعات المحل (طلبات مكتملة بهذا الشهر). التكلفة = مجموع (تكلفة القطعة × الكمية المباعة) حسب "تكلفة القطعة" المحددة بكل منتج.', 'Net profit = (total sales − cost) + manual payments − expenses. Total sales = site sales + in-store sales (completed orders this month). Cost = sum of (unit cost × quantity sold) based on the "unit cost" set on each product.')}</p>

      <details open className="mb-4 mt-4 border border-gray-200 bg-white p-4">
        <summary className="cursor-pointer font-bold text-navy">{at('مقبوضات ريفلكت', 'Reflect receipts')}{!!(reflectAll || []).filter((o) => o.status !== 'completed').length && <Badge color="red">{(reflectAll || []).filter((o) => o.status !== 'completed').length}</Badge>}</summary>
        <p className="mt-2 text-xs text-gray-400">{at('كل طلب انحسب دفعه تحويل رفلكت — بيضل هون دايمًا (ما بيروح لما ينقبض/يتأكد)، مع اسم الي طلب ورقمه والمبلغ والوصل وحالة القبض.', "Every order paid by Reflect transfer — stays listed here permanently (doesn't disappear once received/confirmed), with the orderer's name, phone number, amount, receipt, and confirmation status.")}</p>
        <div className="mt-3">
          <DataTable loading={reflectLoading} rows={reflectAll || []} emptyLabel={at('لا يوجد مقبوضات رفلكت', 'No Reflect receipts')} columns={[
            { header: at('الطلب', 'Order'), render: (o) => `#${o.order_number}` },
            { header: at('الاسم', 'Name'), render: (o) => o.customer?.name || o.guest_name || '-' },
            { header: at('الهاتف', 'Phone'), render: (o) => o.customer?.phone || o.guest_phone || '-' },
            { header: at('المبلغ', 'Amount'), render: (o) => formatPrice(o.total_amount) },
            { header: at('التاريخ', 'Date'), render: (o) => formatDate(o.created_at) },
            { header: at('الحالة', 'Status'), render: (o) => o.status === 'completed' ? <Badge color="green">{at('تم القبض', 'Received')}</Badge> : <Badge color="red">{at('قيد الانتظار', 'Pending')}</Badge> },
            { header: at('الوصل', 'Receipt'), render: (o) => o.reflect_receipt_url ? <button onClick={() => setReceiptModal(o.reflect_receipt_url)} className="text-xs text-brandPurple underline">{at('عرض الوصل', 'View receipt')}</button> : <span className="text-xs text-brandRed">{at('بدون وصل!', 'No receipt!')}</span> },
          ]} />
        </div>
      </details>

      <Modal open={!!receiptModal} onClose={() => setReceiptModal(null)} title={at('صورة وصل التحويل', 'Transfer receipt image')}>
        {receiptModal && <img src={receiptModal} className="max-h-[70vh] w-full object-contain" />}
      </Modal>

      <Modal open={modalOpen} onClose={() => setModalOpen(false)} title={form.id ? at('تعديل سجل مالي', 'Edit financial record') : at('إضافة سجل مالي', 'Add financial record')}>
        <div className="space-y-3">
          <Input placeholder={at('الوصف', 'Description')} value={form.description} onChange={(e) => setForm({ ...form, description: e.target.value })} />
          <Select value={form.type} onChange={(e) => setForm({ ...form, type: e.target.value })}>
            <option value="income">{at('دخل', 'Income')}</option>
            <option value="expense">{at('مصروف', 'Expense')}</option>
          </Select>
          <Input type="number" placeholder={at('المبلغ', 'Amount')} value={form.amount} onChange={(e) => setForm({ ...form, amount: e.target.value })} />
          <Input type="date" value={form.record_date} onChange={(e) => setForm({ ...form, record_date: e.target.value })} />
        </div>
        <div className="mt-5 flex justify-end gap-2 border-t pt-4">
          <Button variant="ghost" onClick={() => setModalOpen(false)}>{at('إلغاء', 'Cancel')}</Button>
          <Button onClick={saveRecord}>{at('حفظ', 'Save')}</Button>
        </div>
      </Modal>

      <ConfirmDialog open={!!deleteRecordTarget} title={at('حذف السجل', 'Delete record')} message={at(`متأكد إنك بدك تحذف "${deleteRecordTarget?.description}"؟`, `Are you sure you want to delete "${deleteRecordTarget?.description}"?`)} onConfirm={doDeleteRecord} onCancel={() => setDeleteRecordTarget(null)} danger confirmLabel={at('حذف', 'Delete')} />
    </div>
  );
}

/* ============================================================
   لوحة الأدمن — محرّر الموقع الكامل
   ============================================================ */
async function saveSiteSetting(key, value) {
  const { error } = await sb.from('site_settings').upsert({ key, value }, { onConflict: 'key' });
  return { error };
}
// صف شريحة واحدة من "الشرائح المتحركة" — الكتابة بالحقول بتصير محليًا فورًا (بدون أي تعليق)،
// والحفظ الفعلي بقاعدة البيانات بيصير تلقائيًا بعد نص ثانية من التوقف عن الكتابة (debounce)،
// بدل ما يرسل طلب شبكة كامل مع كل حرف وحرف — وهاد بالضبط كان سبب "تعليق" الكتابة قبل الإصلاح.
function HeroSlideRow({ s, onUpdate, onDelete, onPickImage, at }) {
  const [local, setLocal] = useState(s);
  const [uploading, setUploading] = useState(false);
  useEffect(() => { setLocal(s); }, [s.id]);
  const debouncedSave = useMemo(() => debounce((patch) => onUpdate(s.id, patch), 500), [s.id, onUpdate]);
  const onField = (key, value) => { setLocal((l) => ({ ...l, [key]: value })); debouncedSave({ [key]: value }); };
  const onImagePatch = (patch) => { setLocal((l) => ({ ...l, ...patch })); onUpdate(s.id, patch); };
  return (
    <div className="border border-gray-200 p-3">
      <div className="mb-2 flex items-center gap-3">
        {local.image_url ? (
          <div className="relative h-16 w-24 flex-shrink-0">
            <img src={local.image_url} className="h-full w-full object-cover" />
            <button type="button" onClick={() => onImagePatch({ image_url: null })} className="absolute -right-1.5 -top-1.5 flex h-5 w-5 items-center justify-center rounded-full bg-brandRed text-[10px] text-white">✕</button>
          </div>
        ) : (
          <div className="flex h-16 w-24 flex-shrink-0 items-center justify-center border border-dashed border-gray-300 text-[10px] text-gray-400">{at('بدون صورة', 'No image')}</div>
        )}
        <input type="file" accept="image/*" disabled={uploading} onChange={async (e) => {
          const f = e.target.files?.[0]; if (!f) return;
          setUploading(true);
          try { await onPickImage(f, 'hero', (url) => onImagePatch({ image_url: url })); } finally { setUploading(false); e.target.value = ''; }
        }} className="text-xs" />
        {uploading && <span className="text-[10px] text-gray-400">{at('جارٍ الرفع...', 'Uploading...')}</span>}
      </div>
      <div className="grid gap-2 sm:grid-cols-5">
        <Input placeholder={at('العنوان', 'Title')} value={local.title || ''} onChange={(e) => onField('title', e.target.value)} />
        <Input placeholder={at('العبارة', 'Subtitle')} value={local.subtitle || ''} onChange={(e) => onField('subtitle', e.target.value)} />
        <Input placeholder={at('نص الزر', 'Button text')} value={local.button_text || ''} onChange={(e) => onField('button_text', e.target.value)} />
        <Select value={local.button_link_target || 'all'} onChange={(e) => onField('button_link_target', e.target.value)}>
          <option value="all">{at('الكل', 'All')}</option><option value="men">{at('رجال', 'Men')}</option><option value="women">{at('نساء', 'Women')}</option><option value="kids">{at('أطفال', 'Kids')}</option>
          <option value="offers">{at('العروض', 'Offers')}</option><option value="new">{at('وصل حديثًا', 'New arrivals')}</option><option value="outlet">{at('أوتليت', 'Outlet')}</option><option value="bestseller">{at('الأكثر مبيعًا', 'Bestsellers')}</option>
        </Select>
        <button onClick={() => onDelete(s.id)} className="text-brandRed">{at('حذف الشريحة', 'Delete slide')}</button>
      </div>
    </div>
  );
}
// صف بانر واحد من "بانرات الصفحة الرئيسية" — نفس فكرة الكتابة المحلية الفورية + الحفظ المؤجّل.
function HomeBannerRow({ b, i, total, onUpdate, onDelete, onMove, onPickImage, at }) {
  const [local, setLocal] = useState(b);
  const [uploading, setUploading] = useState(false);
  useEffect(() => { setLocal(b); }, [b.id]);
  const debouncedSave = useMemo(() => debounce((patch) => onUpdate(b.id, patch), 500), [b.id, onUpdate]);
  const onField = (key, value) => { setLocal((l) => ({ ...l, [key]: value })); debouncedSave({ [key]: value }); };
  const onImagePatch = (patch) => { setLocal((l) => ({ ...l, ...patch })); onUpdate(b.id, patch); };
  return (
    <div className="border border-gray-200 p-3">
      <div className="mb-2 flex items-center gap-3">
        {local.image_url ? (
          <div className="relative h-16 w-24 flex-shrink-0">
            <img src={local.image_url} className="h-full w-full object-cover" />
            <button type="button" onClick={() => onImagePatch({ image_url: null })} className="absolute -right-1.5 -top-1.5 flex h-5 w-5 items-center justify-center rounded-full bg-brandRed text-[10px] text-white">✕</button>
          </div>
        ) : (
          <div className="flex h-16 w-24 flex-shrink-0 items-center justify-center border border-dashed border-gray-300 text-[10px] text-gray-400">{at('بدون صورة', 'No image')}</div>
        )}
        <input type="file" accept="image/*" disabled={uploading} onChange={async (e) => {
          const f = e.target.files?.[0]; if (!f) return;
          setUploading(true);
          try { await onPickImage(f, 'home_banners', (url) => onImagePatch({ image_url: url })); } finally { setUploading(false); e.target.value = ''; }
        }} className="text-xs" />
        {uploading && <span className="text-[10px] text-gray-400">{at('جارٍ الرفع...', 'Uploading...')}</span>}
        <div className="ms-auto flex flex-col gap-1 text-xs text-gray-400">
          <button type="button" onClick={() => onMove(i, -1)} disabled={i === 0}>▲ {at('للأعلى', 'Up')}</button>
          <button type="button" onClick={() => onMove(i, 1)} disabled={i === total - 1}>▼ {at('للأسفل', 'Down')}</button>
        </div>
      </div>
      <div className="grid gap-2 sm:grid-cols-4">
        <Input placeholder={at('العنوان', 'Title')} value={local.title || ''} onChange={(e) => onField('title', e.target.value)} />
        <Input placeholder={at('العبارة الفرعية', 'Subtitle')} value={local.subtitle || ''} onChange={(e) => onField('subtitle', e.target.value)} />
        <Select value={local.link_target || 'all'} onChange={(e) => onField('link_target', e.target.value)}>
          <option value="all">{at('الكل', 'All')}</option><option value="men">{at('رجال', 'Men')}</option><option value="women">{at('نساء', 'Women')}</option><option value="kids">{at('أطفال', 'Kids')}</option>
          <option value="offers">{at('العروض', 'Offers')}</option><option value="new">{at('وصل حديثًا', 'New arrivals')}</option><option value="outlet">{at('أوتليت', 'Outlet')}</option><option value="bestseller">{at('الأكثر مبيعًا', 'Bestsellers')}</option>
        </Select>
        <button onClick={() => onDelete(b.id)} className="text-brandRed">{at('حذف البانر', 'Delete banner')}</button>
      </div>
    </div>
  );
}
function DesignTab() {
  const { at } = useAdminLang();
  const { data: settings } = useSiteSettings();
  const [local, setLocal] = useState(DEFAULT_SETTINGS);
  const [saving, setSaving] = useState(false);
  const [uploadingKey, setUploadingKey] = useState(null);

  useEffect(() => { if (settings) setLocal(settings); }, [settings]);

  const { data: slides, refetch: refetchSlides } = useSupaQuery(['admin_hero_slides'], async () => {
    const { data } = await sb.from('hero_slides').select('*').order('sort_order');
    return data || [];
  });

  const saveAll = async () => {
    setSaving(true);
    const results = await Promise.all([
      saveSiteSetting('theme', local.theme),
      saveSiteSetting('logoUrl', local.logoUrl),
      saveSiteSetting('tagline', local.tagline),
      saveSiteSetting('contact', local.contact),
      saveSiteSetting('departmentBanners', local.departmentBanners),
      saveSiteSetting('sectionTitles', local.sectionTitles),
      saveSiteSetting('homeSections', local.homeSections),
    ]);
    setSaving(false);
    const failed = results.find((r) => r?.error);
    if (failed) { alert(at(`تعذّر حفظ بعض إعدادات الموقع: ${failed.error.message}`, `Could not save some site settings: ${failed.error.message}`)); return; }
    invalidate('site_settings');
  };

  const colorFields = [
    { key: 'navy', label: at('اللون الكحلي الأساسي', 'Primary navy color') }, { key: 'cream', label: at('اللون الكريمي', 'Cream color') },
    { key: 'accentPurple', label: at('لون أسماء المنتجات', 'Product name color') }, { key: 'accentGreen', label: at('لون شارة الجديد/المكتمل', 'New/completed badge color') },
    { key: 'accentRed', label: at('لون السعر بعد الخصم', 'Discounted price color') }, { key: 'headerBg', label: at('خلفية الهيدر', 'Header background') },
    { key: 'footerBg', label: at('خلفية الفوتر', 'Footer background') }, { key: 'buttonBg', label: at('خلفية الأزرار', 'Button background') }, { key: 'buttonText', label: at('كتابة الأزرار', 'Button text') },
  ];
  const addSlide = async () => {
    const { error } = await sb.from('hero_slides').insert({ sort_order: (slides || []).length, title: at('عنوان جديد', 'New title'), subtitle: '', button_text: at('تسوّق الآن', 'Shop now'), button_link_target: 'all' });
    if (error) { alert(at(`تعذّر إضافة الشريحة: ${error.message}`, `Could not add the slide: ${error.message}`)); return; }
    refetchSlides();
  };
  // useCallback هون مهم: بيخلي مرجع الدالة ثابت عبر كل إعادة رسم، حتى دالة الحفظ المؤجّل
  // (debounce) جوا كل صف شريحة تضل عم تستخدم نفس المؤقّت الصحيح ولا تنكسر.
  const updateSlide = useCallback(async (id, patch) => {
    const { error } = await sb.from('hero_slides').update(patch).eq('id', id);
    if (error) { alert(at(`تعذّر حفظ تعديل الشريحة: ${error.message}`, `Could not save the slide change: ${error.message}`)); return; }
    refetchSlides();
  }, [refetchSlides]);
  const deleteSlide = useCallback(async (id) => {
    const { error } = await sb.from('hero_slides').delete().eq('id', id);
    if (error) { alert(at(`تعذّر حذف الشريحة: ${error.message}`, `Could not delete the slide: ${error.message}`)); return; }
    refetchSlides();
  }, [refetchSlides]);
  const departments = [{ key: 'men', label: at('رجال', 'Men') }, { key: 'women', label: at('نساء', 'Women') }, { key: 'kids', label: at('أطفال', 'Kids') }];
  // بيرفع الصورة وبيطبّق نتيجتها بس لو نجح الرفع فعليًا — ولو فشل (مشكلة نت، أو رفض من السيرفر)
  // بيطلع تنبيه بالسبب الحقيقي بدل ما يفشل بصمت وتحس إنه "ما ضافها" بدون أي تفسير.
  const pickImage = async (file, folder, onSuccess) => {
    try {
      const url = await uploadImage(file, folder);
      onSuccess(url);
    } catch (e) {
      alert(at(`فشل رفع الصورة: ${e.message || 'خطأ غير معروف'}`, `Image upload failed: ${e.message || 'Unknown error'}`));
    }
  };

  const { data: banners, refetch: refetchBanners } = useSupaQuery(['admin_home_banners'], async () => {
    const { data } = await sb.from('home_banners').select('*').order('sort_order');
    return data || [];
  });
  const addBanner = async () => {
    if ((banners || []).length >= 8) { alert(at('الحد الأقصى 8 عناصر لهاد القسم', 'Maximum of 8 items for this section')); return; }
    const { error } = await sb.from('home_banners').insert({ sort_order: (banners || []).length, title: at('عنوان', 'Title'), subtitle: '', link_target: 'all' });
    if (error) { alert(at(`تعذّر إضافة البانر: ${error.message}`, `Could not add the banner: ${error.message}`)); return; }
    refetchBanners(); invalidate('home_banners');
  };
  const updateBanner = useCallback(async (id, patch) => {
    const { error } = await sb.from('home_banners').update(patch).eq('id', id);
    if (error) { alert(at(`تعذّر حفظ تعديل البانر: ${error.message}`, `Could not save the banner change: ${error.message}`)); return; }
    refetchBanners(); invalidate('home_banners');
  }, [refetchBanners]);
  const deleteBanner = async (id) => {
    const { error } = await sb.from('home_banners').delete().eq('id', id);
    if (error) { alert(at(`تعذّر حذف البانر: ${error.message}`, `Could not delete the banner: ${error.message}`)); return; }
    refetchBanners(); invalidate('home_banners');
  };
  const moveBanner = async (idx, dir) => {
    const list = banners || []; const j = idx + dir; if (j < 0 || j >= list.length) return;
    const results = await Promise.all([sb.from('home_banners').update({ sort_order: j }).eq('id', list[idx].id), sb.from('home_banners').update({ sort_order: idx }).eq('id', list[j].id)]);
    const failed = results.find((r) => r.error);
    if (failed) { alert(at(`تعذّر تغيير ترتيب البانر: ${failed.error.message}`, `Could not reorder the banner: ${failed.error.message}`)); return; }
    refetchBanners(); invalidate('home_banners');
  };

  return (
    <div className="space-y-8">
      <section>
        <h3 className="mb-3 font-bold text-navy">{at('ألوان صفحة العميل', 'Storefront colors')}</h3>
        <div className="grid grid-cols-2 gap-4 sm:grid-cols-3">
          {colorFields.map((f) => (
            <div key={f.key}>
              <label className="mb-1 block text-xs text-gray-600">{f.label}</label>
              <div className="flex items-center gap-2">
                <input type="color" value={local.theme[f.key]} onChange={(e) => setLocal({ ...local, theme: { ...local.theme, [f.key]: e.target.value } })} className="h-9 w-12 border border-gray-300" />
                <Input value={local.theme[f.key]} onChange={(e) => setLocal({ ...local, theme: { ...local.theme, [f.key]: e.target.value } })} />
              </div>
            </div>
          ))}
        </div>
      </section>

      <section>
        <h3 className="mb-3 font-bold text-navy">{at('الشعار والعبارة', 'Logo & tagline')}</h3>
        <div className="grid gap-3 sm:grid-cols-2">
          <div>
            <label className="mb-1 block text-xs text-gray-600">{at('شعار المحل', 'Store logo')}</label>
            <input type="file" accept="image/*" disabled={uploadingKey === 'logo'} onChange={async (e) => {
              const f = e.target.files?.[0]; if (!f) return;
              setUploadingKey('logo');
              try { await pickImage(f, 'branding', (url) => setLocal((l) => ({ ...l, logoUrl: url }))); } finally { setUploadingKey(null); e.target.value = ''; }
            }} />
            {uploadingKey === 'logo' && <p className="mt-1 text-[10px] text-gray-400">{at('جارٍ الرفع...', 'Uploading...')}</p>}
            {local.logoUrl && (
              <div className="mt-2 flex items-center gap-2">
                <img src={local.logoUrl} className="h-10" />
                <button type="button" onClick={() => setLocal({ ...local, logoUrl: null })} className="text-xs text-brandRed">{at('حذف الشعار', 'Remove logo')}</button>
              </div>
            )}
          </div>
          <div>
            <label className="mb-1 block text-xs text-gray-600">{at('العبارة أعلى الموقع', 'Tagline at the top of the site')}</label>
            <Input value={local.tagline} onChange={(e) => setLocal({ ...local, tagline: e.target.value })} />
          </div>
        </div>
      </section>

      <section>
        <h3 className="mb-3 font-bold text-navy">{at('روابط المحل والتواصل', 'Store & contact links')}</h3>
        <div className="grid gap-3 sm:grid-cols-2">
          {['whatsapp', 'facebook', 'instagram', 'email', 'phone'].map((k) => (
            <Input key={k} placeholder={at({ whatsapp: 'رابط واتساب', facebook: 'رابط فيسبوك', instagram: 'رابط إنستغرام', email: 'البريد الإلكتروني', phone: 'رقم هاتف المحل' }[k], { whatsapp: 'WhatsApp link', facebook: 'Facebook link', instagram: 'Instagram link', email: 'Email address', phone: 'Store phone number' }[k])} value={local.contact[k]} onChange={(e) => setLocal({ ...local, contact: { ...local.contact, [k]: e.target.value } })} />
          ))}
        </div>
      </section>

      <section>
        <h3 className="mb-3 font-bold text-navy">{at('صور بانرات الأقسام', 'Department banner images')}</h3>
        <p className="mb-3 text-xs text-gray-500">{at('القياس الموصى به:', 'Recommended size:')} <b>750×1000px</b> {at('(نسبة طول لعرض 4:3 — مستطيل طولي) حتى تظهر الصورة كاملة وواضحة بالمستطيلات الثلاثة بالصفحة الرئيسية.', '(a 4:3 portrait ratio) so the image appears fully and clearly in the three rectangles on the homepage.')}</p>
        <div className="grid gap-4 sm:grid-cols-3">
          {departments.map((d) => (
            <div key={d.key}>
              <label className="mb-1 block text-xs text-gray-600">{d.label}</label>
              {local.departmentBanners[d.key] && (
                <div className="relative mb-2 aspect-[3/4] w-24">
                  <img src={local.departmentBanners[d.key]} className="h-full w-full object-cover" />
                  <button type="button" onClick={() => setLocal({ ...local, departmentBanners: { ...local.departmentBanners, [d.key]: null } })} className="absolute -right-1.5 -top-1.5 flex h-5 w-5 items-center justify-center rounded-full bg-brandRed text-[10px] text-white">✕</button>
                </div>
              )}
              <input type="file" accept="image/*" disabled={uploadingKey === `dept_${d.key}`} onChange={async (e) => {
                const f = e.target.files?.[0]; if (!f) return;
                setUploadingKey(`dept_${d.key}`);
                try { await pickImage(f, 'banners', (url) => setLocal((l) => ({ ...l, departmentBanners: { ...l.departmentBanners, [d.key]: url } }))); } finally { setUploadingKey(null); e.target.value = ''; }
              }} />
              {uploadingKey === `dept_${d.key}` && <p className="mt-1 text-[10px] text-gray-400">{at('جارٍ الرفع...', 'Uploading...')}</p>}
            </div>
          ))}
        </div>
      </section>

      <section>
        <h3 className="mb-3 font-bold text-navy">{at('عناوين الأقسام القابلة للتخصيص', 'Customizable section titles')}</h3>
        <div className="grid gap-3 sm:grid-cols-2">
          {Object.entries(local.sectionTitles).map(([k, v]) => (
            <Input key={k} value={v} onChange={(e) => setLocal({ ...local, sectionTitles: { ...local.sectionTitles, [k]: e.target.value } })} />
          ))}
        </div>
      </section>

      <section>
        <h3 className="mb-3 font-bold text-navy">{at('إظهار/إخفاء أقسام الصفحة الرئيسية', 'Show/hide homepage sections')}</h3>
        <p className="mb-3 text-xs text-gray-500">{at('أوقف أي قسم ما بدك ياه يبين للزبون — بيختفي من صف الصفحة الرئيسية ومن قائمة التنقّل بالأعلى (Menu) مع بعض، بدون ما تحذف منتجاته أو تصنيفاته. هاي مش أقسام رئيسية متل رجال/نساء/أطفال، فبتقدر تتحكم فيها متل ما بدك.', "Turn off any section you don't want customers to see — it disappears from the homepage row AND the top navigation menu together, without deleting its products or categories. These aren't main departments like men/women/kids, so you have full control over them.")}</p>
        <div className="grid grid-cols-2 gap-3 sm:grid-cols-4">
          {[{ key: 'offers', label: at('عروض', 'Offers') }, { key: 'new', label: at('وصل حديثًا', 'New arrivals') }, { key: 'bestseller', label: at('الأكثر مبيعًا', 'Bestsellers') }, { key: 'outlet', label: at('أوتليت', 'Outlet') }].map((s) => (
            <div key={s.key} className="flex items-center justify-between gap-2 border border-gray-200 px-3 py-2.5 text-sm">
              <span className="font-medium text-gray-700">{s.label}</span>
              <Toggle checked={local.homeSections?.[s.key] !== false} onChange={(v) => setLocal({ ...local, homeSections: { ...local.homeSections, [s.key]: v } })} />
            </div>
          ))}
        </div>
      </section>

      <section>
        <div className="mb-3 flex items-center justify-between">
          <h3 className="font-bold text-navy">{at('الشرائح المتحركة (Hero Slider)', 'Hero slider')}</h3>
          <Button onClick={addSlide}>+ {at('إضافة شريحة', 'Add slide')}</Button>
        </div>
        <div className="space-y-3">
          {(slides || []).map((s) => (
            <HeroSlideRow key={s.id} s={s} onUpdate={updateSlide} onDelete={deleteSlide} onPickImage={pickImage} at={at} />
          ))}
        </div>
      </section>

      <section>
        <div className="mb-1 flex items-center justify-between">
          <h3 className="font-bold text-navy">{at('بانرات الصفحة الرئيسية (حتى 8 عناصر)', 'Homepage banners (up to 8 items)')}</h3>
          <Button onClick={addBanner} disabled={(banners || []).length >= 8}>+ {at('إضافة بانر', 'Add banner')}</Button>
        </div>
        <p className="mb-3 text-xs text-gray-400">{at('تظهر بشكل شبكة أسفل الصورة الرئيسية بواجهة المتجر — كل عنصر صورة + عنوان + عبارة فرعية اختيارية.', 'Shown as a grid below the hero image on the storefront — each item is an image + title + optional subtitle.')}</p>
        <div className="space-y-3">
          {(banners || []).map((b, i) => (
            <HomeBannerRow key={b.id} b={b} i={i} total={(banners || []).length} onUpdate={updateBanner} onDelete={deleteBanner} onMove={moveBanner} onPickImage={pickImage} at={at} />
          ))}
          {!(banners || []).length && <p className="text-sm text-gray-400">{at('ما في بانرات مضافة بعد.', 'No banners added yet.')}</p>}
        </div>
      </section>

      <Button onClick={saveAll} disabled={saving} className="w-full sm:w-auto">{saving ? '...' : at('حفظ التغييرات', 'Save changes')}</Button>
    </div>
  );
}

function BulkDiscountTab() {
  const { at } = useAdminLang();
  const [percent, setPercent] = useState('10');
  const [scope, setScope] = useState('all');
  const { data: categories } = useSupaQuery(['bulk_categories'], async () => (await sb.from('categories').select('id, name')).data || []);
  const [preview, setPreview] = useState(null);
  const [applying, setApplying] = useState(false);
  const [confirmOpen, setConfirmOpen] = useState(false);

  const loadPreview = async () => {
    let q = sb.from('products').select('id, name, original_price, discount_price');
    if (scope !== 'all') q = q.eq('category_id', scope);
    const { data, error } = await q;
    if (error) { alert(at(`تعذّرت معاينة المنتجات: ${error.message}`, `Could not preview the products: ${error.message}`)); return; }
    setPreview((data || []).map((p) => ({ ...p, newPrice: Math.round(p.original_price * (1 - Number(percent) / 100)) })));
  };

  const apply = async () => {
    setApplying(true);
    try {
      let q = sb.from('products').select('id, original_price, category_id');
      if (scope !== 'all') q = q.eq('category_id', scope);
      const { data, error: fetchErr } = await q; if (fetchErr) throw fetchErr;
      const affectedCategoryIds = new Set();
      let failCount = 0;
      for (const p of data || []) {
        const newPrice = Math.round(p.original_price * (1 - Number(percent) / 100));
        const { error } = await sb.from('products').update({ discount_price: newPrice }).eq('id', p.id);
        if (error) { failCount++; continue; }
        if (p.category_id) affectedCategoryIds.add(p.category_id);
      }
      // مكان الظهور صار مرتبط بالتصنيف مش بالمنتج — بنضيف قسم "عروض" تلقائيًا لكل تصنيف فيه منتجات
      // تأثرت بالخصم، حتى تظهر فعليًا بصفحة العروض للزبون.
      for (const catId of affectedCategoryIds) {
        const { error: sectionErr } = await sb.from('category_sections').upsert({ category_id: catId, section: 'offers' }, { onConflict: 'category_id,section' });
        if (sectionErr) throw sectionErr;
      }
      // نحفظ نسبة العرض الحالية كـ site setting حتى تظهر كبانر واضح بصفحة "عروض" للزبون
      const { error: offerErr } = await saveSiteSetting('activeOffer', { percent: Number(percent), scope, appliedAt: new Date().toISOString() });
      if (offerErr) throw offerErr;
      setApplying(false); setConfirmOpen(false); invalidate('products'); invalidate('categor'); invalidate('site_settings'); loadPreview();
      if (failCount) alert(at(`تنبيه: ${failCount} منتج ما انطبق عليه الخصم بسبب خطأ — جرّب تطبيق العرض مرة ثانية.`, `Warning: ${failCount} product(s) did not get the discount due to an error — try applying the offer again.`));
    } catch (e) {
      setApplying(false);
      alert(e.message || at('حدث خطأ أثناء تطبيق العرض', 'An error occurred while applying the offer'));
    }
  };

  return (
    <div className="max-w-2xl space-y-4">
      <p className="text-sm text-gray-500">{at('السعر الجديد يُحسب دائمًا من السعر الأصلي ويستبدل أي عرض سابق (وليس تراكميًا)، والمنتجات المتأثرة بتنضاف تلقائيًا لقسم "عروض" بواجهة المتجر.', 'The new price is always calculated from the original price and replaces any previous offer (not cumulative), and affected products are added automatically to the "Offers" section on the storefront.')}</p>
      <div className="grid gap-3 sm:grid-cols-2">
        <div>
          <label className="mb-1 block text-xs text-gray-600">{at('نسبة الخصم %', 'Discount percentage %')}</label>
          <Input type="number" min="1" max="90" placeholder={at('نسبة الخصم %', 'Discount %')} value={percent} onChange={(e) => setPercent(e.target.value)} />
        </div>
        <Select value={scope} onChange={(e) => setScope(e.target.value)}>
          <option value="all">{at('جميع المنتجات', 'All products')}</option>
          {(categories || []).map((c) => <option key={c.id} value={c.id}>{c.name}</option>)}
        </Select>
      </div>
      <Button variant="secondary" onClick={loadPreview}>{at('معاينة', 'Preview')}</Button>

      {!!preview?.length && (
        <div className="max-h-64 overflow-y-auto border border-gray-200">
          <table className="w-full text-sm">
            <tbody className="divide-y">
              {preview.map((p) => (
                <tr key={p.id}><td className="px-3 py-1.5">{p.name}</td><td className="px-3 py-1.5 text-gray-400 line-through">{p.original_price}</td><td className="px-3 py-1.5 font-bold text-brandRed">{p.newPrice}</td></tr>
              ))}
            </tbody>
          </table>
        </div>
      )}

      <Button onClick={() => setConfirmOpen(true)} disabled={!preview?.length}>{at('مراجعة وتطبيق العرض', 'Review & apply offer')}</Button>

      <ConfirmDialog open={confirmOpen} title={at('تطبيق العرض', 'Apply offer')} message={at(`رح يتطبق خصم ${percent}% على ${preview?.length || 0} منتج. متأكد؟`, `This will apply a ${percent}% discount to ${preview?.length || 0} product(s). Are you sure?`)} onConfirm={apply} onCancel={() => setConfirmOpen(false)} confirmLabel={applying ? '...' : at('تطبيق', 'Apply')} />
    </div>
  );
}

function TranslationsTab() {
  const { at } = useAdminLang();
  const [values, setValues] = useState({});
  useEffect(() => {
    sb.from('translations').select('key, value').eq('lang', 'en').then(({ data }) => {
      const map = {}; (data || []).forEach((r) => (map[r.key] = r.value)); setValues(map);
    });
  }, []);
  const keys = Object.keys(DICT.ar);
  const save = async (key, value) => {
    const { error } = await sb.from('translations').upsert({ key, lang: 'en', value }, { onConflict: 'key,lang' });
    if (error) alert(at(`تعذّر حفظ الترجمة: ${error.message}`, `Could not save the translation: ${error.message}`));
  };
  return (
    <div>
      <p className="mb-3 text-sm text-gray-500">{at('النصوص الثابتة بالموقع مترجمة أصلاً للإنجليزية. هاي الشاشة لتسجيل أي تخصيص إضافي بقاعدة البيانات (مرجع للمطوّر لاحقًا).', 'The site’s static text is already translated to English. This screen is for recording any extra customization in the database (a reference for the developer later).')}</p>
      <div className="max-h-[28rem] space-y-2 overflow-y-auto">
        {keys.map((k) => (
          <div key={k} className="grid grid-cols-2 items-center gap-2 border-b border-gray-100 pb-2">
            <div><p className="text-xs text-gray-400">{k}</p><p className="text-sm">{DICT.ar[k]}</p></div>
            <Input placeholder="English" value={values[k] || ''} onChange={(e) => setValues({ ...values, [k]: e.target.value })} onBlur={(e) => save(k, e.target.value)} />
          </div>
        ))}
      </div>
    </div>
  );
}

function PasswordTab() {
  const { at } = useAdminLang();
  const [next, setNext] = useState(''); const [confirm, setConfirm] = useState(''); const [msg, setMsg] = useState(null); const [saving, setSaving] = useState(false);
  const save = async () => {
    setMsg(null);
    if (next !== confirm) { setMsg(at('كلمة المرور الجديدة غير متطابقة', 'The new passwords do not match')); return; }
    if (next.length < 6) { setMsg(at('كلمة المرور يجب أن تكون 6 أحرف على الأقل', 'The password must be at least 6 characters')); return; }
    setSaving(true);
    const { error } = await sb.auth.updateUser({ password: next });
    setSaving(false);
    setMsg(error ? error.message : at('تم تغيير كلمة المرور بنجاح', 'Password changed successfully'));
  };
  return (
    <div className="max-w-sm space-y-3">
      <Input type="password" placeholder={at('كلمة المرور الجديدة', 'New password')} value={next} onChange={(e) => setNext(e.target.value)} />
      <Input type="password" placeholder={at('تأكيد كلمة المرور', 'Confirm password')} value={confirm} onChange={(e) => setConfirm(e.target.value)} />
      {msg && <p className="text-sm text-gray-600">{msg}</p>}
      <Button onClick={save} disabled={saving}>{saving ? at('جارٍ الحفظ...', 'Saving...') : at('حفظ كلمة المرور', 'Save password')}</Button>
    </div>
  );
}

function AdminSiteEditorPage() {
  const { at } = useAdminLang();
  const [tab, setTab] = useState('design');
  const tabs = [
    { key: 'design', label: at('تصميم ومحتوى الصفحة', 'Design & page content') }, { key: 'bulk', label: at('العروض الشاملة', 'Bulk offers') },
    { key: 'translations', label: at('الترجمات', 'Translations') }, { key: 'password', label: at('كلمة المرور', 'Password') },
  ];
  return (
    <div>
      <AdminPageHeader title={at('تعديل صفحة العميل', 'Storefront editor')} description={at('محرّر الموقع الكامل: التصميم، العروض، الترجمة، وكلمة المرور', 'The full site editor: design, offers, translation, and password')} />
      <div className="mb-5 flex gap-1 overflow-x-auto border-b border-gray-200">
        {tabs.map((tb) => (
          <button key={tb.key} onClick={() => setTab(tb.key)} className={cn('whitespace-nowrap border-b-2 px-4 py-2 text-sm font-medium', tab === tb.key ? 'border-navy text-navy' : 'border-transparent text-gray-400')}>{tb.label}</button>
        ))}
      </div>
      {tab === 'design' && <DesignTab />}
      {tab === 'bulk' && <BulkDiscountTab />}
      {tab === 'translations' && <TranslationsTab />}
      {tab === 'password' && <PasswordTab />}
    </div>
  );
}

/* ============================================================
   حارس دخول لوحة الأدمن
   ============================================================ */
function AdminGate({ children }) {
  const { session, isAdmin, loading } = useAdminAuth();
  const route = useRoute();
  useEffect(() => {
    if (!loading && (!session || !isAdmin) && route !== '/admin/login') navigate('/admin/login');
  }, [loading, session, isAdmin, route]);
  if (loading) {
    return <div className="flex min-h-screen items-center justify-center bg-gray-50"><Spinner className="text-navy" /></div>;
  }
  if (!session || !isAdmin) return null;
  return children;
}

/* ============================================================
   يطبّق ألوان الثيم المخزّنة بلوحة الأدمن كمتغيرات CSS على الصفحة بأكملها
   ============================================================ */
function ThemeApplier() {
  const { data: settings } = useSiteSettings();
  useEffect(() => {
    if (!settings) return;
    const root = document.documentElement.style;
    root.setProperty('--color-navy', settings.theme.navy);
    root.setProperty('--color-cream', settings.theme.cream);
    root.setProperty('--color-purple', settings.theme.accentPurple);
    root.setProperty('--color-green', settings.theme.accentGreen);
    root.setProperty('--color-red', settings.theme.accentRed);
    root.setProperty('--color-header-bg', settings.theme.headerBg);
    root.setProperty('--color-footer-bg', settings.theme.footerBg);
    root.setProperty('--color-btn-bg', settings.theme.buttonBg);
    root.setProperty('--color-btn-text', settings.theme.buttonText);
  }, [settings]);
  return null;
}

/* ============================================================
   جذر التطبيق — التوجيه بين واجهة الزبون ولوحة الأدمن
   ============================================================ */
function App() {
  const path = useRoute();
  const match = matchRoute(path);
  const name = match.name;

  if (name === 'admin.login') return (
    <>
      <ThemeApplier />
      <AdminLoginPage />
    </>
  );

  if (name.startsWith('admin.')) {
    const adminPages = {
      'admin.products': AdminProductsPage,
      'admin.categories': AdminCategoriesPage,
      'admin.orders': AdminOrdersPage,
      'admin.customers': AdminCustomersPage,
      'admin.inventory': AdminInventoryPage,
      'admin.loyalty': AdminLoyaltyPage,
      'admin.delivery': AdminDeliveryPage,
      'admin.reviews': AdminReviewsPage,
      'admin.accounting': AdminAccountingPage,
      'admin.site-editor': AdminSiteEditorPage,
    };
    const Page = adminPages[name] || AdminProductsPage;
    return (
      <>
        <ThemeApplier />
        <AdminGate>
          <AdminLayout><Page /></AdminLayout>
        </AdminGate>
      </>
    );
  }

  let page;
  if (name === 'home') page = <HomePage />;
  else if (name === 'department') page = <CategoryPage key={`dept-${match.params.department}`} department={match.params.department} mode="department" />;
  else if (name === 'new') page = <CategoryPage key="new" mode="new" />;
  else if (name === 'outlet') page = <CategoryPage key="outlet" mode="outlet" />;
  else if (name === 'offers') page = <CategoryPage key="offers" mode="offers" />;
  else if (name === 'bestseller') page = <CategoryPage key="bestseller" mode="bestseller" />;
  else if (name === 'category') page = <CategoryPage key={`cat-${match.params.categoryId}`} categoryIdParam={match.params.categoryId} mode="category" />;
  else if (name === 'search') page = <CategoryPage key={`search-${match.params.q}`} mode="search" initialSearch={match.params.q} />;
  else if (name === 'product') page = <ProductPage key={`product-${match.params.id}`} id={match.params.id} />;
  else if (name === 'cart') page = <CartPage />;
  else if (name === 'account') page = <AccountPage />;
  else if (name === 'account.orders') page = <OrdersPage />;
  else if (name === 'favorites') page = <FavoritesPage />;
  else page = <HomePage />;

  return (
    <>
      <ThemeApplier />
      <CustomerLayout>{page}</CustomerLayout>
    </>
  );
}

/* ============================================================
   حدود الأخطاء — بديل شاشة بيضاء بدون تفسير
   ============================================================ */
class ErrorBoundary extends React.Component {
  constructor(props) { super(props); this.state = { error: null }; }
  static getDerivedStateFromError(error) { return { error }; }
  componentDidCatch(error, info) { console.error('SUPER SHOP error:', error, info); }
  render() {
    if (this.state.error) {
      return (
        <div dir="rtl" style={{ minHeight: '100vh', display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 24, fontFamily: 'system-ui, sans-serif', background: '#faf6ed' }}>
          <div style={{ maxWidth: 480, textAlign: 'center' }}>
            <p style={{ fontSize: 36, marginBottom: 8 }}>⚠️</p>
            <h1 style={{ fontSize: 20, fontWeight: 800, color: '#0f1f3d', marginBottom: 10 }}>صار في خطأ غير متوقع</h1>
            <p style={{ color: '#5b6478', fontSize: 14, lineHeight: 1.7, marginBottom: 16 }}>{String(this.state.error?.message || this.state.error)}</p>
            <button onClick={() => window.location.reload()} style={{ background: '#0f1f3d', color: '#f5efe3', border: 0, padding: '10px 20px', fontSize: 14, cursor: 'pointer' }}>تحديث الصفحة</button>
          </div>
        </div>
      );
    }
    return this.props.children;
  }
}

/* ============================================================
   التركيب النهائي
   ============================================================ */
function Root() {
  return (
    <ErrorBoundary>
      <LangProvider>
        <CartProvider>
          <CustomerAuthProvider>
            <AdminAuthProvider>
              <App />
            </AdminAuthProvider>
          </CustomerAuthProvider>
        </CartProvider>
      </LangProvider>
    </ErrorBoundary>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<Root />);
