// Saraya Events — Rental Furniture (B2B): a main Store category.
// • RentalCategoryGrid — the 10 category cards (shown when the Store "Rental Furniture" chip is active).
//   Clicking a card → #rental/<categoryId>.
// • RentalCategoryPage — a secondary view with 15 selectable product cards per category.
//   Each product: quantity selector + Order Now (→ cart/checkout) + Request a Quote (email to sales@).

const { useState: useStateRent } = React;

const RENTAL_CATEGORIES = [
  { id: 'lounge-sofas',  group: 'seating', set: 'seating', icon: 'sofa',     price: 1200, en: 'Lounge Sofas',            ar: 'أرائك صالة',         den: 'Elegant modular lounges and VIP seating for guest areas, majlis setups, and event lounges.',               dar: 'أرائك معيارية أنيقة ومقاعد VIP لمناطق الضيوف ومجالس وصالات الفعاليات.' },
  { id: 'single-sofas',  group: 'seating', set: 'seating', icon: 'armchair', price: 450,  en: 'Single Sofas',            ar: 'أرائك فردية',        den: 'Statement armchairs, accent sofas, and premium single seating pieces for stylish event corners.',          dar: 'كراسي بارزة وأرائك مميّزة وقطع جلوس فردية راقية لزوايا الفعاليات.' },
  { id: 'bride-kosha',   group: 'seating', set: 'seating', icon: 'crown',    price: 3500, en: 'Bride Sofa / Kosha',      ar: 'كوشة العروس',        den: 'Ornate bridal seating and kosha pieces for weddings, engagements, and cultural ceremonies.',              dar: 'مقاعد عروس مزخرفة وكوشة لحفلات الأعراس والخطوبة والمراسم الثقافية.' },
  { id: 'chairs',        group: 'seating', set: 'seating', icon: 'armchair', price: 45,   en: 'Chairs',                  ar: 'كراسي',              den: 'Banquet, ghost, chiavari, cross-back, and event chairs for ceremonies, dining, and receptions.',           dar: 'كراسي مأدبة وشفافة وكيافاري وظهر متقاطع لحفلات الطعام والاستقبال.' },
  { id: 'bar-stools',    group: 'seating', set: 'seating', icon: 'wine',     price: 75,   en: 'Bar Chairs & Stools',     ar: 'كراسي ومقاعد بار',   den: 'High seating options for cocktail tables, activations, lounges, and modern event setups.',                dar: 'خيارات جلوس مرتفعة لطاولات الكوكتيل والتفعيلات والصالات والإعدادات الحديثة.' },
  { id: 'tables',        group: 'tables',  set: 'tables',  icon: 'utensils', price: 350,  en: 'Dining & Event Tables',   ar: 'طاولات الطعام والفعاليات', den: 'Round, rectangular, serpentine, and dining tables for weddings, corporate events, and gatherings.',   dar: 'طاولات دائرية ومستطيلة ومتعرّجة لحفلات الأعراس والفعاليات المؤسسية.' },
  { id: 'cocktail',      group: 'tables',  set: 'tables',  icon: 'martini',  price: 180,  en: 'Cocktail Tables',         ar: 'طاولات كوكتيل',      den: 'Highboy and cocktail tables for receptions, networking areas, and standing guest zones.',                dar: 'طاولات عالية وكوكتيل لحفلات الاستقبال ومناطق التواصل وزوايا الوقوف.' },
  { id: 'console-bar',   group: 'tables',  set: 'tables',  icon: 'square',   price: 300,  en: 'Console & Bar Tables',    ar: 'طاولات كونسول وبار', den: 'Slim display, welcome, backdrop, registration, and bar tables for event styling and guest flow.',         dar: 'طاولات عرض واستقبال وخلفيات وتسجيل وبار لتنسيق الفعاليات وتدفق الضيوف.' },
  { id: 'coffee-tables', group: 'tables',  set: 'tables',  icon: 'coffee',   price: 220,  en: 'Coffee Tables',           ar: 'طاولات قهوة',        den: 'Low tables for lounge areas, majlis seating, VIP setups, and styled event corners.',                     dar: 'طاولات منخفضة لصالات الجلوس والمجالس وإعدادات VIP وزوايا الفعاليات.' },
  { id: 'puffs-benches', group: 'other',   set: 'seating', icon: 'package',  price: 120,  en: 'Puffs & Benches',         ar: 'مقاعد وبَفّات',      den: 'Flexible poufs, benches, and modular seating pieces for lounges, kids areas, and casual setups.',        dar: 'بفات ومقاعد وقطع جلوس معيارية مرنة للصالات ومناطق الأطفال والإعدادات غير الرسمية.' },
];

/* 15 finishes per set — bilingual, with a placeholder tone for visual variety */
const RENTAL_VARIANTS = {
  seating: [
    { en: 'Champagne Velvet', ar: 'مخمل شامبين', tone: 'champagne' },
    { en: 'Blush Velvet', ar: 'مخمل وردي', tone: 'blush' },
    { en: 'Emerald Velvet', ar: 'مخمل زمردي', tone: 'sage' },
    { en: 'Royal Blue Velvet', ar: 'مخمل أزرق ملكي', tone: 'slate' },
    { en: 'Charcoal Velvet', ar: 'مخمل فحمي', tone: 'espresso' },
    { en: 'Ivory Leather', ar: 'جلد عاجي', tone: 'cream' },
    { en: 'White Leather', ar: 'جلد أبيض', tone: 'cream' },
    { en: 'Gold Frame', ar: 'إطار ذهبي', tone: 'champagne' },
    { en: 'Clear Acrylic (Ghost)', ar: 'أكريليك شفاف', tone: 'sand' },
    { en: 'Chiavari Gold', ar: 'كيافاري ذهبي', tone: 'champagne' },
    { en: 'Cross-back Oak', ar: 'بلوط ظهر متقاطع', tone: 'cream' },
    { en: 'Natural Rattan', ar: 'خيزران طبيعي', tone: 'sand' },
    { en: 'Rose Gold', ar: 'ذهبي وردي', tone: 'blush' },
    { en: 'Tufted Ivory', ar: 'منجّد عاجي', tone: 'cream' },
    { en: 'Greige Linen', ar: 'كتان بيجي', tone: 'sand' },
  ],
  tables: [
    { en: 'Gold Mirror Top', ar: 'سطح مرآة ذهبي', tone: 'champagne' },
    { en: 'Silver Mirror Top', ar: 'سطح مرآة فضي', tone: 'slate' },
    { en: 'White Marble', ar: 'رخام أبيض', tone: 'cream' },
    { en: 'Black Marble', ar: 'رخام أسود', tone: 'espresso' },
    { en: 'Clear Acrylic', ar: 'أكريليك شفاف', tone: 'sand' },
    { en: 'Gold Frame Glass', ar: 'زجاج بإطار ذهبي', tone: 'champagne' },
    { en: 'Rose Gold', ar: 'ذهبي وردي', tone: 'blush' },
    { en: 'Champagne', ar: 'شامبين', tone: 'champagne' },
    { en: 'Natural Oak', ar: 'بلوط طبيعي', tone: 'cream' },
    { en: 'Walnut', ar: 'جوز', tone: 'espresso' },
    { en: 'White Gloss', ar: 'أبيض لامع', tone: 'cream' },
    { en: 'Black Gloss', ar: 'أسود لامع', tone: 'espresso' },
    { en: 'Mosaic', ar: 'فسيفساء', tone: 'sage' },
    { en: 'Rattan', ar: 'خيزران', tone: 'sand' },
    { en: 'LED-lit', ar: 'مضاء LED', tone: 'slate' },
  ],
};

const RENTAL_OVR_KEY = 'saraya_rental_overrides_v1';
function loadRentalOvr() { try { return JSON.parse(localStorage.getItem(RENTAL_OVR_KEY) || '{}'); } catch (e) { return {}; } }
function saveRentalOvr(map) { try { localStorage.setItem(RENTAL_OVR_KEY, JSON.stringify(map)); } catch (e) {} }
function catWithOvr(cat) { const o = loadRentalOvr()['cat:' + cat.id]; return o ? Object.assign({}, cat, o) : cat; }
window.loadRentalOvr = loadRentalOvr; window.saveRentalOvr = saveRentalOvr; window.catWithOvr = catWithOvr;

function rentalCat(id) { const c = RENTAL_CATEGORIES.find((c) => c.id === id); return c ? catWithOvr(c) : null; }

/* English → Arabic for the furniture vocabulary; word-by-word, keeps unknown words as-is. */
const AR_DICT = {
  'lounge': 'صالة', 'sofa': 'أريكة', 'sofas': 'أرائك', 'single': 'فردي', 'bride': 'عروس', 'kosha': 'كوشة',
  'chair': 'كرسي', 'chairs': 'كراسي', 'bar': 'بار', 'stool': 'مقعد', 'stools': 'مقاعد',
  'table': 'طاولة', 'tables': 'طاولات', 'cocktail': 'كوكتيل', 'console': 'كونسول', 'coffee': 'قهوة',
  'puff': 'بَفّة', 'puffs': 'بَفّات', 'bench': 'مقعد', 'benches': 'مقاعد',
  'gold': 'ذهبي', 'golden': 'ذهبي', 'champagne': 'شامبين', 'velvet': 'مخمل', 'blush': 'وردي',
  'emerald': 'زمردي', 'royal': 'ملكي', 'blue': 'أزرق', 'charcoal': 'فحمي', 'grey': 'رمادي', 'gray': 'رمادي',
  'ivory': 'عاجي', 'leather': 'جلد', 'white': 'أبيض', 'frame': 'إطار', 'clear': 'شفاف', 'acrylic': 'أكريليك',
  'ghost': 'شفاف', 'chiavari': 'كيافاري', 'crossback': 'ظهر متقاطع', 'oak': 'بلوط', 'natural': 'طبيعي',
  'rattan': 'خيزران', 'rose': 'وردي', 'tufted': 'منجّد', 'greige': 'بيجي', 'linen': 'كتان', 'mirror': 'مرآة',
  'top': 'سطح', 'silver': 'فضي', 'marble': 'رخام', 'black': 'أسود', 'walnut': 'جوز', 'gloss': 'لامع',
  'glossy': 'لامع', 'mosaic': 'فسيفساء', 'led': 'إضاءة', 'lit': 'مضاء', 'banquet': 'مأدبة', 'premium': 'فاخر',
  'glass': 'زجاج', 'wood': 'خشب', 'wooden': 'خشبي', 'modern': 'عصري', 'classic': 'كلاسيكي', 'luxury': 'فاخر',
  'pink': 'وردي', 'green': 'أخضر', 'red': 'أحمر', 'beige': 'بيجي', 'cream': 'كريمي', 'and': 'و', 'with': 'مع',
  'cane': 'خيزران', 'wicker': 'خوص', 'bamboo': 'خيزران', 'metal': 'معدني', 'steel': 'فولاذ', 'iron': 'حديد',
  'brass': 'نحاسي', 'bronze': 'برونزي', 'copper': 'نحاس', 'navy': 'كحلي', 'teal': 'فيروزي', 'mint': 'نعناعي',
  'burgundy': 'عنابي', 'maroon': 'عنابي', 'mustard': 'خردلي', 'taupe': 'بني فاتح', 'sand': 'رملي', 'stone': 'حجري',
  'dusty': 'باهت', 'pastel': 'باستيل', 'matte': 'مطفي', 'satin': 'ساتان', 'suede': 'شامواه', 'fabric': 'قماش',
  'upholstered': 'منجّد', 'woven': 'منسوج', 'curved': 'منحني', 'round': 'دائري', 'square': 'مربع',
  'rectangular': 'مستطيل', 'folding': 'قابل للطي', 'stackable': 'قابل للتكديس', 'armchair': 'كرسي بذراعين',
  'dining': 'طعام', 'accent': 'مميّز', 'high': 'عالٍ', 'low': 'منخفض', 'tall': 'طويل', 'wide': 'عريض',
  'slim': 'نحيف', 'vintage': 'عتيق', 'rustic': 'ريفي', 'elegant': 'أنيق', 'antique': 'أثري', 'pearl': 'لؤلؤي',
  'platinum': 'بلاتيني', 'bronze-frame': 'إطار برونزي', 'velour': 'مخمل', 'boucle': 'بوكليه', 'nude': 'بيجي',
};
function arabicFromEnglish(en) {
  if (!en) return '';
  const words = en.replace(/[-_/]+/g, ' ').replace(/\s+/g, ' ').trim().split(' ');
  const out = words.map((w) => { const k = w.toLowerCase().replace(/[^a-z]/g, ''); return AR_DICT[k] || w; });
  return out.join(' ');
}
window.arabicFromEnglish = arabicFromEnglish;
function rentalProducts(cat) {
  cat = catWithOvr(cat);
  const ovr = loadRentalOvr();
  const variants = RENTAL_VARIANTS[cat.set] || RENTAL_VARIANTS.seating;
  const list = variants.map((v, i) => {
    const id = 'rent-' + cat.id + '-' + (i + 1);
    const io = ovr['item:' + id] || {};
    return {
      id, rentalCatId: cat.id, icon: cat.icon, tone: v.tone,
      name: { en: io.en || (cat.en + ' — ' + v.en), ar: io.ar || (cat.ar + ' — ' + v.ar) },
      price: (io.price != null && io.price !== '') ? Number(io.price) : Number(cat.price),
      desc: { en: io.den || '', ar: io.dar || '' },
      availability: io.availability || 'in',
      category: 'rental',
    };
  });
  const order = ovr['order:' + cat.id];
  // Custom product cards added by admin (beyond the built-in finishes).
  const added = (ovr['added:' + cat.id] || []).map((a) => ({
    id: a.id, rentalCatId: cat.id, icon: cat.icon, tone: a.tone || 'champagne', custom: true,
    name: { en: a.en || 'New piece', ar: a.ar || window.arabicFromEnglish(a.en || '') || 'قطعة جديدة' },
    price: (a.price != null && a.price !== '') ? Number(a.price) : Number(cat.price),
    desc: { en: a.den || '', ar: a.dar || '' },
    availability: a.availability || 'in', category: 'rental',
  }));
  let full = list.concat(added);
  if (order && order.length) full.sort((a, b) => { const ia = order.indexOf(a.id), ib = order.indexOf(b.id); return (ia < 0 ? 999 : ia) - (ib < 0 ? 999 : ib); });
  return full;
}
window.rentalProducts = rentalProducts;
window.RENTAL_CATEGORIES = RENTAL_CATEGORIES;

const RENTAL_GROUPS = [
  { id: 'all', en: 'All', ar: 'الكل' },
  { id: 'seating', en: 'Seating', ar: 'مقاعد' },
  { id: 'tables', en: 'Tables', ar: 'طاولات' },
  { id: 'other', en: 'Other', ar: 'أخرى' },
];
const RENTAL_KEY = 'saraya_rental_extra_v1';
function loadRentalExtra() { try { return JSON.parse(localStorage.getItem(RENTAL_KEY) || '[]'); } catch (e) { return []; } }

/* ============== category grid (inside Store, when "Rental Furniture" chip active) ============== */
function RentalCategoryGrid() {
  const { lang } = useLang();
  const { go } = useNav();
  const admin = useAdmin();
  const ar = lang === 'ar';
  const [filter, setFilter] = useStateRent('all');
  const [extra, setExtra] = useStateRent(loadRentalExtra);
  const [, setOvrV] = useStateRent(0);
  const saveExtra = (arr) => { setExtra(arr); try { localStorage.setItem(RENTAL_KEY, JSON.stringify(arr)); } catch (e) {} };

  // DB-backed categories when Supabase is configured
  const { categories: dbCats } = window.useCategories ? window.useCategories('rental') : { categories: [] };
  const useDB = window.supabaseConfigured && dbCats.length > 0;
  // Normalize DB categories to the same shape as static RENTAL_CATEGORIES
  const dbNormCats = dbCats.map((c) => ({
    id: c.slug, slug: c.slug, group: 'other', set: 'seating',
    icon: c.icon_name || 'package', price: 0,
    en: c.name_en || '', ar: c.name_ar || c.name_en || '',
    den: c.description_en || '', dar: c.description_ar || '', _fromDB: true,
  }));

  const staticAll = RENTAL_CATEGORIES.map(catWithOvr).concat(extra);
  const allToShow = useDB ? dbNormCats : staticAll;
  const shown = filter === 'all' ? allToShow : allToShow.filter((c) => !useDB && c.group === filter);

  const editCategory = (cat) => {
    admin.openEdit({
      title: ar ? 'تعديل فئة الأثاث' : 'Edit furniture category',
      fields: [
        { key: 'en', label: 'Category name (EN)' }, { key: 'ar', label: 'Category name (AR)', dir: 'rtl' },
        { key: 'price', label: 'Price per day (AED) — applies to all pieces' },
        { key: 'den', label: 'Description (EN)', type: 'textarea' }, { key: 'dar', label: 'Description (AR)', type: 'textarea', dir: 'rtl' },
      ],
      values: { en: cat.en, ar: cat.ar, price: cat.price, den: cat.den, dar: cat.dar },
      onSave: (v) => {
        if (cat.custom) {
          saveExtra(extra.map((c) => c.id === cat.id ? Object.assign({}, c, { en: v.en, ar: v.ar, den: v.den, dar: v.dar, price: Number(v.price) || c.price }) : c));
        } else {
          const m = loadRentalOvr(); m['cat:' + cat.id] = { en: v.en, ar: v.ar, den: v.den, dar: v.dar, price: Number(v.price) || cat.price }; saveRentalOvr(m); setOvrV((x) => x + 1);
        }
        admin.toastMsg(ar ? 'تم الحفظ' : 'Saved');
      },
    });
  };

  const addCategory = () => {
    admin.openEdit({
      title: ar ? 'أضف فئة أثاث' : 'Add a furniture category',
      fields: [
        { key: 'en', label: 'Category name (EN)' }, { key: 'ar', label: 'Category name (AR)', dir: 'rtl' },
        { key: 'group', label: 'Group', type: 'select', options: [{ value: 'seating', label: 'Seating' }, { value: 'tables', label: 'Tables' }, { value: 'other', label: 'Other' }] },
        { key: 'den', label: 'Description (EN)', type: 'textarea' }, { key: 'dar', label: 'Description (AR)', type: 'textarea', dir: 'rtl' },
      ],
      values: { group: 'seating' },
      onSave: (v) => {
        const grp = v.group || 'other';
        const item = { id: 'rent-' + Date.now().toString(36), custom: true, icon: 'armchair', group: grp, set: grp === 'tables' ? 'tables' : 'seating', price: 200, en: v.en || 'New category', ar: v.ar || v.en || 'فئة جديدة', den: v.den || '', dar: v.dar || v.den || '' };
        saveExtra(extra.concat([item]));
        admin.toastMsg(ar ? 'تمت إضافة الفئة' : 'Category added');
      },
    });
  };
  const removeCategory = (id) => saveExtra(extra.filter((c) => c.id !== id));

  return (
    <div>
      <Reveal>
        <SectionHead center eyebrow={ar ? 'أثاث التأجير' : 'Furniture & Table Rentals'}
          title={ar ? 'فئات أثاث التأجير' : 'Furniture & Table Rental Categories'}
          intro={ar ? 'تصفح أثاث التأجير والمقاعد والطاولات ومستلزمات الفعاليات المتوفرة من سرايا للفعاليات والموردين المعتمدين. اختر فئة لعرض المنتجات المتاحة.' : 'Browse rental furniture, seating, tables, and event essentials available from Saraya Events and approved vendors. Choose a category to view available items.'} />
      </Reveal>

      <Reveal>
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 9, justifyContent: 'center', marginTop: 8, marginBottom: 36 }}>
          {RENTAL_GROUPS.map((g) => (
            <button key={g.id} onClick={() => setFilter(g.id)}
              style={{ padding: '9px 18px', borderRadius: 999, cursor: 'pointer', fontFamily: 'var(--font-body)', fontSize: 13.5, fontWeight: 600, transition: 'all 180ms var(--ease-out)', background: filter === g.id ? 'var(--espresso)' : 'var(--white)', color: filter === g.id ? 'var(--ivory)' : 'var(--fg-primary)', border: '1px solid ' + (filter === g.id ? 'var(--espresso)' : 'var(--line-strong)') }}>
              {ar ? g.ar : g.en}
            </button>
          ))}
        </div>
      </Reveal>

      <div className="saraya-grid-4">
        {shown.map((cat, i) => (
          <Reveal key={cat.id} delay={(i % 4) * 35}>
            <button onClick={() => go('rental/' + cat.id)} className="saraya-lift"
              style={{ textAlign: 'start', cursor: 'pointer', padding: 0, position: 'relative', background: 'var(--white)', border: '1px solid var(--line)', borderRadius: 'var(--radius-lg)', boxShadow: 'var(--shadow-soft)', overflow: 'hidden', display: 'flex', flexDirection: 'column', height: '100%', width: '100%', font: 'inherit', color: 'inherit' }}>
              <div style={{ aspectRatio: '4 / 3', background: 'var(--gold-tint)', display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'var(--gold-deep)', position: 'relative', overflow: 'hidden' }}>
                {cat.image_url
                  ? <img src={cat.image_url} alt={ar ? cat.ar : cat.en} style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', objectFit: 'cover' }} />
                  : <Icon name={cat.icon} size={46} stroke={1.2} />}
                <span style={{ position: 'absolute', top: 12, insetInlineStart: 12, fontSize: 10.5, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '.08em', color: 'var(--gold-deep)', background: 'var(--white)', padding: '3px 9px', borderRadius: 999 }}>{ar ? (RENTAL_GROUPS.find((g) => g.id === cat.group) || {}).ar : (RENTAL_GROUPS.find((g) => g.id === cat.group) || {}).en}</span>
                {admin.editMode && (
                  <span onClick={(e) => { e.stopPropagation(); editCategory(cat); }} title="Edit" style={{ position: 'absolute', top: 10, insetInlineEnd: cat.custom ? 46 : 10, width: 28, height: 28, borderRadius: 999, background: 'var(--espresso)', color: 'var(--gold-light)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}><Icon name="pencil" size={13} /></span>
                )}
                {admin.editMode && cat.custom && (
                  <span onClick={(e) => { e.stopPropagation(); removeCategory(cat.id); }} title="Remove" style={{ position: 'absolute', top: 10, insetInlineEnd: 10, width: 28, height: 28, borderRadius: 999, background: 'var(--error-bg)', color: 'var(--error)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}><Icon name="trash-2" size={14} /></span>
                )}
              </div>
              <div style={{ padding: '18px 18px 20px', display: 'flex', flexDirection: 'column', gap: 8, flex: 1 }}>
                <h3 style={{ fontFamily: 'var(--font-display)', fontSize: 20, fontWeight: 500, lineHeight: 1.2 }}>{ar ? cat.ar : cat.en}</h3>
                <p style={{ fontSize: 13.5, lineHeight: 1.55, color: 'var(--fg-secondary)', flex: 1 }}>{ar ? cat.dar : cat.den}</p>
                <span style={{ marginTop: 4, display: 'inline-flex', alignItems: 'center', gap: 7, color: 'var(--gold-deep)', fontSize: 13.5, fontWeight: 600 }}>
                  {ar ? 'عرض المنتجات' : 'View Items'} <Icon name={ar ? 'arrow-left' : 'arrow-right'} size={15} />
                </span>
              </div>
            </button>
          </Reveal>
        ))}
      </div>

      {admin.editMode && (
        <div style={{ display: 'flex', justifyContent: 'center', marginTop: 28 }}>
          <AdminAddButton onClick={addCategory} label={ar ? 'أضف فئة أثاث' : 'Add a furniture category'} />
        </div>
      )}

      {/* Marketplace note */}
      <Reveal>
        <p style={{ marginTop: 36, textAlign: 'center', fontSize: 13, color: 'var(--fg-muted)', maxWidth: 620, marginInline: 'auto', lineHeight: 1.6 }}>
          {ar
            ? 'يتم عرض المنتجات من سرايا للفعاليات والموردين المعتمدين في المنصة. قد تختلف الأسعار والتوفر والتوصيل والتركيب حسب المورد.'
            : 'Items are listed by Saraya Events and approved marketplace vendors. Availability, delivery, setup, and pricing may vary by vendor.'}
        </p>
      </Reveal>

      {/* Vendor CTA */}
      <Reveal>
        <div style={{ marginTop: 48, padding: '28px 32px', borderRadius: 16, background: 'var(--cream)', border: '1px solid var(--line)', display: 'flex', flexWrap: 'wrap', alignItems: 'center', justifyContent: 'space-between', gap: 20 }}>
          <div>
            <div style={{ fontFamily: 'var(--font-display)', fontSize: 20, fontWeight: 500, color: 'var(--fg-primary)', marginBottom: 6 }}>
              {ar ? 'هل أنت مورد تأجير؟' : 'Are you a rental supplier?'}
            </div>
            <p style={{ fontSize: 14, color: 'var(--fg-secondary)', lineHeight: 1.6, maxWidth: 440, margin: 0 }}>
              {ar
                ? 'انضم إلى منصة سرايا للفعاليات وأضف الأثاث والديكور والمعدات ومستلزمات المناسبات ضمن الفئات المناسبة.'
                : 'Join Saraya Events Marketplace and list your furniture, décor, equipment, and event rental items under the right categories.'}
            </p>
          </div>
          <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap' }}>
            <Button variant="primary" icon="store" onClick={() => window.openJoinVendorModal ? window.openJoinVendorModal() : go('vendor-packages')}>
              {ar ? 'انضم كمورد' : 'Join as Vendor'}
            </Button>
            <Button variant="secondary" icon="plus" onClick={() => go('vendor-dashboard')}>
              {ar ? 'أضف منتجات التأجير' : 'Add Rental Items'}
            </Button>
          </div>
        </div>
      </Reveal>
    </div>
  );
}

/* ============== secondary view: 15 product cards for a category ============== */
function RentalCategoryPage({ categoryId }) {
  const { lang } = useLang();
  const { go } = useNav();
  const admin = useAdmin();
  const ar = lang === 'ar';
  const [, setV] = useStateRent(0);
  const bump = () => setV((x) => x + 1);
  React.useEffect(() => { window.scrollTo(0, 0); }, [categoryId]);

  const extra = loadRentalExtra();
  const cat = rentalCat(categoryId) || extra.find((c) => c.id === categoryId);

  // DB-backed rentals when Supabase is configured
  const { items: dbRentals, loading: dbLoading } = window.useRentals
    ? window.useRentals({ categorySlug: categoryId, onlyActive: true })
    : { items: [], loading: false };
  const useDB = window.supabaseConfigured;
  const { categories: dbCats } = window.useCategories ? window.useCategories('rental') : { categories: [] };
  const dbCat = dbCats.find((c) => c.slug === categoryId);

  if (!cat && !dbCat && !useDB) {
    return <main style={{ paddingTop: 140, minHeight: '60vh' }}><Container><p style={{ color: 'var(--fg-muted)' }}>{ar ? 'الفئة غير موجودة.' : 'Category not found.'} <button onClick={() => go('store')} style={{ color: 'var(--gold-deep)', background: 'none', border: 'none', cursor: 'pointer' }}>{ar ? 'العودة للمتجر' : 'Back to store'}</button></p></Container></main>;
  }

  // Static/DB category info when not in the local demo list
  const staticCat = cat || (dbCat ? { id: dbCat.slug, en: dbCat.name_en || categoryId, ar: dbCat.name_ar || dbCat.name_en || categoryId, den: dbCat.description_en || '', dar: dbCat.description_ar || '', price: 0, icon: dbCat.icon_name || 'package', set: 'seating' } : { id: categoryId, en: categoryId, ar: categoryId, price: 0, icon: 'package', set: 'seating' });
  const products = (useDB && !dbLoading) ? (dbRentals.length > 0 ? dbRentals : rentalProducts(staticCat)) : rentalProducts(staticCat);

  const moveItem = (id, dir) => {
    const ids = products.map((p) => p.id);
    const i = ids.indexOf(id), j = i + dir;
    if (i < 0 || j < 0 || j >= ids.length) return;
    const tmp = ids[i]; ids[i] = ids[j]; ids[j] = tmp;
    const m = loadRentalOvr(); m['order:' + cat.id] = ids; saveRentalOvr(m); bump();
  };

  const addProduct = () => {
    admin.openEdit({
      title: ar ? 'أضف بطاقة منتج' : 'Add a product card',
      fields: [
        { key: 'en', label: 'Name (EN)' }, { key: 'ar', label: 'Name (AR) — leave blank to auto-translate', dir: 'rtl' },
        { key: 'price', label: 'Price per day (AED) — blank = category price' },
        { key: 'den', label: 'Description (EN)', type: 'textarea' },
      ],
      values: { en: cat.en + ' — ' },
      onSave: (v) => {
        const en = (v.en || '').trim() || (cat.en + ' — New');
        const item = { id: 'rentadd-' + cat.id + '-' + Date.now().toString(36), en, ar: (v.ar && v.ar.trim()) ? v.ar : window.arabicFromEnglish(en), price: (v.price === '' || v.price == null) ? null : Number(v.price), den: v.den || '', availability: 'in', tone: 'champagne' };
        const m = loadRentalOvr(); m['added:' + cat.id] = (m['added:' + cat.id] || []).concat([item]); saveRentalOvr(m);
        admin.toastMsg(ar ? 'تمت إضافة البطاقة' : 'Product card added'); bump();
      },
    });
  };
  const deleteProduct = (id) => {
    const m = loadRentalOvr();
    m['added:' + cat.id] = (m['added:' + cat.id] || []).filter((a) => a.id !== id);
    saveRentalOvr(m); bump();
  };

  /* Bulk upload: pick many images at once; they fill cards in order, auto-named. */
  const [uploading, setUploading] = useStateRent(0);
  const bulkUpload = () => {
    const input = document.createElement('input');
    input.type = 'file'; input.accept = 'image/*'; input.multiple = true;
    input.style.position = 'fixed'; input.style.left = '-9999px';
    input.onchange = async () => {
      const files = [].slice.call(input.files || []);
      if (!files.length) { if (input.parentNode) input.parentNode.removeChild(input); return; }
      const n = Math.min(files.length, products.length);
      let done = 0;
      for (let i = 0; i < n; i++) {
        setUploading(i + 1);
        try {
          const data = await window.compressImage(files[i]);
          await admin.setImg('rent:' + products[i].id, data);
          const nm = files[i].name.replace(/\.[^.]+$/, '').replace(/[-_]+/g, ' ').replace(/\s+/g, ' ').trim().replace(/\b\w/g, function (c) { return c.toUpperCase(); });
          if (nm) { const m = window.loadRentalOvr(); m['item:' + products[i].id] = Object.assign({}, m['item:' + products[i].id], { en: nm, ar: window.arabicFromEnglish(nm) }); window.saveRentalOvr(m); }
          done++;
        } catch (e) { /* skip a bad file, keep going */ }
      }
      setUploading(0);
      admin.toastMsg((ar ? 'تم رفع ' : 'Uploaded ') + done + (ar ? ' صورة' : ' image' + (done === 1 ? '' : 's')), 'success');
      bump();
      if (input.parentNode) input.parentNode.removeChild(input);
    };
    document.body.appendChild(input); input.click();
  };

  const editCategory = () => {
    admin.openEdit({
      title: ar ? 'تعديل الفئة' : 'Edit category',
      fields: [
        { key: 'en', label: 'Category name (EN)' }, { key: 'ar', label: 'Category name (AR)', dir: 'rtl' },
        { key: 'price', label: 'Price per day (AED) — applies to all pieces' },
        { key: 'den', label: 'Description (EN)', type: 'textarea' }, { key: 'dar', label: 'Description (AR)', type: 'textarea', dir: 'rtl' },
      ],
      values: { en: cat.en, ar: cat.ar, price: cat.price, den: cat.den, dar: cat.dar },
      onSave: (v) => {
        if (cat.custom) {
          const arr = loadRentalExtra().map((c) => c.id === cat.id ? Object.assign({}, c, { en: v.en, ar: v.ar, den: v.den, dar: v.dar, price: Number(v.price) || c.price }) : c);
          try { localStorage.setItem(RENTAL_KEY, JSON.stringify(arr)); } catch (e) {}
        } else {
          const m = loadRentalOvr(); m['cat:' + cat.id] = { en: v.en, ar: v.ar, den: v.den, dar: v.dar, price: Number(v.price) || cat.price }; saveRentalOvr(m);
        }
        admin.toastMsg(ar ? 'تم الحفظ' : 'Saved'); bump();
      },
    });
  };

  return (
    <main style={{ paddingTop: 96 }}>
      <Section bg="canvas">
        <Container wide>
          <button onClick={() => go('store')} style={{ display: 'inline-flex', alignItems: 'center', gap: 7, background: 'none', border: 'none', cursor: 'pointer', color: 'var(--fg-secondary)', fontSize: 14, marginBottom: 18 }}>
            <Icon name={ar ? 'arrow-right' : 'arrow-left'} size={16} />{ar ? 'كل فئات التأجير' : 'All rental categories'}
          </button>
          <Reveal>
            <div style={{ display: 'flex', alignItems: 'flex-start', gap: 12, flexWrap: 'wrap' }}>
              <SectionHead eyebrow={ar ? 'فئة التأجير' : 'Rental Category'} title={ar ? staticCat.ar : staticCat.en}
                intro={(ar ? staticCat.dar : staticCat.den) + (ar ? ' — اختر القطعة والكمية، أو اطلب تسعيرة.' : ' — choose your piece and quantity, or request a quote.')} />
              {admin.editMode && (
                <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', marginTop: 6 }}>
                  <button onClick={editCategory} style={{ display: 'inline-flex', alignItems: 'center', gap: 7, padding: '8px 14px', borderRadius: 999, border: '1px solid var(--line-strong)', background: 'var(--white)', cursor: 'pointer', fontSize: 13, fontWeight: 600, color: 'var(--fg-primary)' }}><Icon name="pencil" size={14} />{ar ? 'تعديل الفئة والسعر' : 'Edit category & price'}</button>
                  <button onClick={bulkUpload} disabled={uploading > 0} style={{ display: 'inline-flex', alignItems: 'center', gap: 7, padding: '8px 14px', borderRadius: 999, border: 'none', background: 'var(--espresso)', color: 'var(--ivory)', cursor: uploading > 0 ? 'wait' : 'pointer', fontSize: 13, fontWeight: 600 }}><Icon name="image-plus" size={14} />{uploading > 0 ? (ar ? 'جارٍ الرفع ' : 'Uploading ') + uploading + '…' : (ar ? 'رفع صور متعددة' : 'Bulk upload images')}</button>
                </div>
              )}
            </div>
          </Reveal>

          <div style={{ display: 'inline-flex', alignItems: 'center', gap: 8, marginTop: 14, padding: '8px 14px', borderRadius: 999, background: 'var(--gold-tint)', color: 'var(--gold-deep)', fontSize: 13, fontWeight: 600 }}>
            <Icon name="info" size={14} />{ar ? 'الأسعار تأجير لليوم الواحد لكل قطعة' : 'Prices are per-piece, per-day rental'}
          </div>

          <div className="saraya-grid-4" style={{ marginTop: 32 }}>
            {products.map((p, i) => (<Reveal key={p.id} delay={(i % 4) * 30}><RentalProductCard product={p} cat={staticCat} onChange={bump} onMove={moveItem} onDelete={deleteProduct} canBack={i > 0} canFwd={i < products.length - 1} /></Reveal>))}
          </div>

          {admin.editMode && (
            <div style={{ display: 'flex', justifyContent: 'center', marginTop: 28 }}>
              <AdminAddButton onClick={addProduct} label={ar ? 'أضف بطاقة منتج' : 'Add a product card'} />
            </div>
          )}
        </Container>
      </Section>
      <StickyCartBar />
    </main>
  );
}

function RentalProductCard({ product, cat, onChange, onMove, onDelete, canBack, canFwd }) {
  const { lang } = useLang();
  const { go } = useNav();
  const cart = useCart();
  const admin = useAdmin();
  const ar = lang === 'ar';
  const [qty, setQty] = useStateRent(1);
  const S = window.SARAYA;

  // When an image is uploaded to THIS card, auto-set the product name (EN + AR) from the file name.
  React.useEffect(() => {
    const onUp = (e) => {
      if (!e.detail || e.detail.slot !== ('rent:' + product.id)) return;
      const raw = e.detail.fileName || '';
      const nm = raw.replace(/\.[^.]+$/, '').replace(/[-_]+/g, ' ').replace(/\s+/g, ' ').trim().replace(/\b\w/g, function (c) { return c.toUpperCase(); });
      if (!nm) return;
      const m = window.loadRentalOvr();
      m['item:' + product.id] = Object.assign({}, m['item:' + product.id], { en: nm, ar: window.arabicFromEnglish(nm) });
      window.saveRentalOvr(m);
      admin.toastMsg && admin.toastMsg(ar ? 'تم ضبط الاسم من الصورة' : 'Name set from image');
      onChange && onChange();
    };
    window.addEventListener('saraya:image-uploaded', onUp);
    return function () { window.removeEventListener('saraya:image-uploaded', onUp); };
  }, [product.id, onChange, ar]);

  const editItem = () => {
    admin.openEdit({
      title: ar ? 'تعديل قطعة الأثاث' : 'Edit rental product',
      fields: [
        { key: 'en', label: 'Product name (EN)' }, { key: 'ar', label: 'Product name (AR)', dir: 'rtl' },
        { key: 'price', label: 'Price per day (AED) — blank = use category price' },
        { key: 'availability', label: 'Availability', type: 'select', options: [{ value: 'in', label: 'Available' }, { value: 'order', label: 'On request' }, { value: 'soon', label: 'Coming soon' }, { value: 'out', label: 'Unavailable' }] },
        { key: 'den', label: 'Short description (EN)', type: 'textarea' }, { key: 'dar', label: 'Short description (AR)', type: 'textarea', dir: 'rtl' },
      ],
      values: { en: product.name.en, ar: product.name.ar, price: product.price, availability: product.availability, den: product.desc ? product.desc.en : '', dar: product.desc ? product.desc.ar : '' },
      onSave: (v) => {
        const arName = (v.ar && v.ar.trim()) ? v.ar : window.arabicFromEnglish(v.en);
        const m = window.loadRentalOvr(); m['item:' + product.id] = { en: v.en, ar: arName, price: (v.price === '' || v.price == null) ? null : Number(v.price), availability: v.availability || 'in', den: v.den || '', dar: v.dar || '' }; window.saveRentalOvr(m);
        admin.toastMsg(ar ? 'تم الحفظ' : 'Saved'); onChange && onChange();
      },
    });
  };

  const orderNow = () => { cart.add(product, qty, { rental: true, perDay: product.price }); admin.toastMsg && admin.toastMsg(ar ? 'أُضيفت إلى السلة' : 'Added to cart'); go('checkout'); };
  const AVL = { in: { en: 'Available', ar: 'متوفر', c: 'success' }, order: { en: 'On request', ar: 'حسب الطلب', c: 'info' }, soon: { en: 'Coming soon', ar: 'قريبًا', c: 'warning' }, out: { en: 'Unavailable', ar: 'غير متوفر', c: 'error' } };
  const avl = AVL[product.availability] || AVL.in;
  const unavailable = product.availability === 'out' || product.availability === 'soon';
  const quoteHref = S.mailLink(
    'Rental quote request — ' + product.name.en,
    'Hello Saraya Events,\n\nI would like a rental quote for:\n• Item: ' + product.name.en + '\n• Category: ' + cat.en + '\n• Quantity: ' + qty + '\n• Indicative rate: AED ' + product.price + ' / day\n\nEvent details (please complete):\n• Date(s): \n• Venue / location: \n• Guest count: \n• Notes: \n\nThank you.',
    'sales@sarayaevents.com'
  );

  return (
    <div className="saraya-lift" style={{ background: 'var(--white)', border: '1px solid var(--line)', borderRadius: 'var(--radius-lg)', boxShadow: 'var(--shadow-soft)', overflow: 'hidden', display: 'flex', flexDirection: 'column', height: '100%' }}>
      <div style={{ aspectRatio: '4 / 3', position: 'relative', background: 'var(--gold-tint)', overflow: 'hidden' }}>
        {product.src
          ? <img src={product.src} alt={product.name ? product.name.en : ''} style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block' }} />
          : <Img tone={product.tone} icon={product.icon} ratio="auto" radius={0} plain slot={'rent:' + product.id} style={{ width: '100%', height: '100%' }} />}
      </div>
      {admin.editMode && (
        <div style={{ display: 'flex', alignItems: 'center', gap: 6, padding: '8px 10px', background: 'var(--bg-muted)', borderBottom: '1px solid var(--line)' }}>
          <button onClick={editItem} style={{ display: 'inline-flex', alignItems: 'center', gap: 6, flex: 1, justifyContent: 'center', padding: '7px 8px', borderRadius: 8, border: '1px solid var(--line-strong)', cursor: 'pointer', background: 'var(--espresso)', color: 'var(--gold-light)', fontFamily: 'var(--font-body)', fontSize: 12, fontWeight: 600 }}><Icon name="pencil" size={13} />{ar ? 'تعديل' : 'Edit'}</button>
          <button onClick={() => onMove && onMove(product.id, -1)} disabled={!canBack} title={ar ? 'نقل للخلف' : 'Move back'} style={{ width: 34, height: 34, borderRadius: 8, border: '1px solid var(--line-strong)', cursor: canBack ? 'pointer' : 'not-allowed', opacity: canBack ? 1 : 0.4, background: 'var(--white)', color: 'var(--espresso)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}><Icon name="arrow-left" size={15} /></button>
          <button onClick={() => onMove && onMove(product.id, 1)} disabled={!canFwd} title={ar ? 'نقل للأمام' : 'Move forward'} style={{ width: 34, height: 34, borderRadius: 8, border: '1px solid var(--line-strong)', cursor: canFwd ? 'pointer' : 'not-allowed', opacity: canFwd ? 1 : 0.4, background: 'var(--white)', color: 'var(--espresso)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}><Icon name="arrow-right" size={15} /></button>
          {product.custom && (
            <button onClick={() => onDelete && onDelete(product.id)} title={ar ? 'حذف' : 'Delete'} style={{ width: 34, height: 34, borderRadius: 8, border: '1px solid var(--line-strong)', cursor: 'pointer', background: 'var(--error-bg)', color: 'var(--error)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}><Icon name="trash-2" size={15} /></button>
          )}
        </div>
      )}
      <div style={{ padding: '16px 16px 18px', display: 'flex', flexDirection: 'column', gap: 8, flex: 1 }}>
        <h3 style={{ fontFamily: 'var(--font-display)', fontSize: 17.5, fontWeight: 500, lineHeight: 1.25 }}>{product.name[lang]}</h3>
        {product.desc && product.desc[lang] && <p style={{ fontSize: 12.5, lineHeight: 1.5, color: 'var(--fg-secondary)', margin: 0 }}>{product.desc[lang]}</p>}
        <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', gap: 8 }}>
          <div style={{ fontFamily: 'var(--font-display)', fontSize: 18, fontWeight: 600, color: 'var(--gold-deep)' }}>AED {product.price}<span style={{ fontSize: 12, color: 'var(--fg-muted)', fontWeight: 400, fontFamily: 'var(--font-body)' }}> / {ar ? 'يوم' : 'day'}</span></div>
          <span style={{ fontSize: 11, fontWeight: 600, color: 'var(--' + avl.c + ')' }}>{ar ? avl.ar : avl.en}</span>
        </div>

        {/* quantity selector */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginTop: 4 }}>
          <span style={{ fontSize: 12.5, color: 'var(--fg-muted)' }}>{ar ? 'الكمية' : 'Qty'}</span>
          <div style={{ display: 'inline-flex', alignItems: 'center', border: '1px solid var(--line-strong)', borderRadius: 999, overflow: 'hidden' }}>
            <button onClick={() => setQty((q) => Math.max(1, q - 1))} aria-label="Decrease" style={{ width: 30, height: 30, border: 'none', background: 'var(--white)', cursor: 'pointer', color: 'var(--fg-primary)', fontSize: 16 }}>−</button>
            <span style={{ minWidth: 28, textAlign: 'center', fontSize: 14, fontWeight: 600 }}>{qty}</span>
            <button onClick={() => setQty((q) => Math.min(999, q + 1))} aria-label="Increase" style={{ width: 30, height: 30, border: 'none', background: 'var(--white)', cursor: 'pointer', color: 'var(--fg-primary)', fontSize: 16 }}>+</button>
          </div>
        </div>

        <div style={{ marginTop: 'auto', display: 'flex', flexDirection: 'column', gap: 8, paddingTop: 8 }}>
          <button onClick={orderNow} disabled={unavailable} style={{ display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 8, padding: '11px 14px', borderRadius: 'var(--radius-md)', border: 'none', cursor: unavailable ? 'not-allowed' : 'pointer', opacity: unavailable ? 0.5 : 1, background: 'var(--espresso)', color: 'var(--ivory)', fontFamily: 'var(--font-body)', fontSize: 13.5, fontWeight: 600 }}>
            <Icon name="shopping-bag" size={15} />{ar ? 'اطلب الآن' : 'Order Now'}
          </button>
          <button onClick={() => go('design')} style={{ display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 8, padding: '11px 14px', borderRadius: 'var(--radius-md)', background: 'var(--white)', color: 'var(--fg-primary)', border: '1px solid var(--line-strong)', fontFamily: 'var(--font-body)', fontSize: 13.5, fontWeight: 600, cursor: 'pointer' }}>
            <Icon name="pen-line" size={15} />{ar ? 'اطلب عرض سعر' : 'Request a Quote'}
          </button>
        </div>
      </div>
    </div>
  );
}

/* ============================================================
   RENTAL MAIN PAGE — marketplace landing page at #rental
   ============================================================ */
function RentalMainPage() {
    const { lang }= useLang();
  const { go } = useNav();
  const auth = window.useAuth ? window.useAuth() : null;
  const ar = lang === 'ar';
  const S = window.SARAYA;

  const TOP_CATS = [
    { id: 'furniture', icon: 'sofa',      en: 'Furniture & Seating',     ar: 'الأثاث والجلوس',           den: 'Sofas, armchairs, kosha, bar stools, puffs, benches, and all seating for events.',    dar: 'أرائك وكراسي وكوشة ومقاعد بار وبفات وجميع قطع الجلوس.',    route: 'rental/furniture-rent' },
    { id: 'tables',    icon: 'utensils',  en: 'Tables',                  ar: 'الطاولات',                  den: 'Dining, cocktail, console, bar, and coffee tables for every setup.',                 dar: 'طاولات طعام وكوكتيل وكونسول وبار وقهوة لكل الإعدادات.',    route: 'rental/tables' },
    { id: 'decor',     icon: 'sparkles',  en: 'Décor & Styling',         ar: 'الديكور والتنسيق',          den: 'Backdrops, stands, arches, entrance décor, and event styling elements.',              dar: 'خلفيات وحوامل وأقواس وديكور مداخل وعناصر تنسيق الفعاليات.',route: 'rental/decor-styling' },
    { id: 'av',        icon: 'monitor',   en: 'Screens & AV',            ar: 'الشاشات والعروض',           den: 'LED screens, projectors, display screens, and audio-visual equipment.',               dar: 'شاشات LED وأجهزة عرض ومعدات صوتية وبصرية.',                route: 'rental/screens-av' },
    { id: 'sound',     icon: 'volume-2',  en: 'Sound & Lighting',        ar: 'الصوت والإضاءة',            den: 'Sound systems, speakers, stage lighting, and event lighting rigs.',                  dar: 'أنظمة صوت ومكبرات وإضاءة مسرح ومعدات إضاءة.',              route: 'rental/sound-lighting' },
    { id: 'hospital',  icon: 'coffee',    en: 'Hospitality Equipment',   ar: 'معدات الضيافة',             den: 'Coffee stations, serving equipment, catering displays, and hospitality essentials.', dar: 'محطات قهوة ومعدات تقديم وعروض ضيافة.',                     route: 'rental/hospitality-equipment' },
    { id: 'kids',      icon: 'gift',      en: 'Kids & Party Items',      ar: 'مستلزمات الأطفال والحفلات', den: 'Kids furniture, party supplies, themed props, and entertainment items.',              dar: 'أثاث أطفال ومستلزمات حفلات وقطع ترفيهية.',                  route: 'rental/kids-party' },
    { id: 'other',     icon: 'package',   en: 'Other Event Essentials',  ar: 'مستلزمات أخرى',             den: 'Additional event equipment, accessories, and special items on request.',              dar: 'معدات وإكسسوارات إضافية وعناصر خاصة عند الطلب.',           route: 'rental/other-essentials' },
  ];

  const HOW = [
    { icon: 'search',        en: 'Browse Categories',  ar: 'تصفح الفئات',      den: 'Explore rental categories and find items for your event.',           dar: 'استكشف فئات التأجير وابحث عن القطع المناسبة لفعاليتك.' },
    { icon: 'clipboard-list',en: 'Select or Request',  ar: 'اختر أو اطلب',     den: 'Select items and quantities, or submit a full rental request.',       dar: 'اختر المنتجات والكميات أو أرسل طلب تأجير كامل.' },
    { icon: 'check-circle',  en: 'Confirm & Book',     ar: 'تأكيد والحجز',     den: 'Confirm availability, pricing, and delivery details with the vendor.',dar: 'تأكيد التوفر والأسعار وتفاصيل التوصيل مع المورد.' },
    { icon: 'truck',         en: 'Delivery & Setup',   ar: 'التوصيل والتركيب', den: 'Vendor delivers, installs, and collects items after your event.',     dar: 'يقوم المورد بالتوصيل والتركيب والاستلام بعد الفعالية.' },
  ];

  return (
    <main style={{ paddingTop: 72 }}>

      {/* ── HERO ── */}
      <section style={{ background: 'var(--espresso)', color: 'var(--ivory)', paddingBlock: 'clamp(56px,9vw,110px) clamp(44px,7vw,88px)', position: 'relative', overflow: 'hidden' }}>
        <div style={{ position: 'absolute', inset: 0, background: 'radial-gradient(ellipse 80% 60% at 60% 40%, rgba(193,160,70,0.12) 0%, transparent 70%)', pointerEvents: 'none' }} />
        <Container narrow style={{ position: 'relative', textAlign: 'center' }}>
          <Reveal>
            <Eyebrow color="var(--gold-light)">{ar ? 'منصة التأجير' : 'Rental Marketplace'}</Eyebrow>
            <h1 style={{ fontFamily: 'var(--font-display)', fontSize: 'clamp(34px,5.5vw,64px)', lineHeight: 1.06, fontWeight: 500, color: 'var(--ivory)', margin: '16px 0 22px' }}>
              {ar ? 'سوق تأجير فعاليات الإمارات' : 'Event Rentals Marketplace'}
            </h1>
            <p style={{ fontSize: 'clamp(15px,2vw,18px)', lineHeight: 1.7, color: 'rgba(250,246,240,0.78)', maxWidth: 580, marginInline: 'auto' }}>
              {ar
                ? 'استأجر الأثاث والديكور والمعدات ومستلزمات الفعاليات من سرايا للفعاليات والموردين المعتمدين للأعراس والاحتفالات والفعاليات المؤسسية.'
                : 'Rent furniture, décor, equipment, and event essentials from Saraya Events and approved vendors for weddings, celebrations, corporate events, and special occasions.'}
            </p>
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 12, justifyContent: 'center', marginTop: 30 }}>
              <Button variant="gold" size="lg" icon="search" onClick={() => { const el = document.getElementById('rental-categories'); el && el.scrollIntoView({ behavior: 'smooth' }); }}>
                {ar ? 'تصفح منتجات التأجير' : 'Browse Rental Items'}
              </Button>
              <Button variant="onDark" size="lg" icon="pen-line" onClick={() => go('design')}>
                {ar ? 'اطلب عرض سعر' : 'Request Rental Quote'}
              </Button>
              <Button variant="onDark" size="lg" icon="store" onClick={() => go('partner')}>
                {ar ? 'انضم كمورد' : 'Join as Vendor'}
              </Button>
            </div>
          </Reveal>
        </Container>
      </section>

      {/* ── TOP-LEVEL RENTAL CATEGORIES ── */}
      <Section bg="canvas" id="rental-categories">
        <Container wide>
          <Reveal>
            <SectionHead center
              eyebrow={ar ? 'فئات التأجير' : 'Rental Categories'}
              title={ar ? 'تصفح حسب الفئة' : 'Browse by Category'}
              intro={ar
                ? 'تصفح منتجات التأجير من سرايا للفعاليات والموردين المعتمدين. اختر فئة لعرض المنتجات المتاحة.'
                : 'Browse rental items from Saraya Events and approved vendors. Choose a category to view available items.'} />
          </Reveal>
          <div className="saraya-grid-4" style={{ marginTop: 40 }}>
            {TOP_CATS.map((cat, i) => (
              <Reveal key={cat.id} delay={(i % 4) * 40}>
                <button
                  onClick={() => go(cat.route)}
                  className="saraya-lift"
                  style={{ textAlign: 'start', cursor: 'pointer', padding: 0, position: 'relative', background: 'var(--white)', border: '1px solid var(--line)', borderRadius: 'var(--radius-lg)', boxShadow: 'var(--shadow-soft)', overflow: 'hidden', display: 'flex', flexDirection: 'column', height: '100%', width: '100%', font: 'inherit', color: 'inherit' }}>
                  <div style={{ padding: '24px 22px 20px', display: 'flex', flexDirection: 'column', gap: 10, flex: 1 }}>
                    <div style={{ width: 44, height: 44, borderRadius: 12, background: 'var(--gold-tint)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                      <Icon name={cat.icon} size={22} style={{ color: 'var(--gold-deep)' }} />
                    </div>
                    <h3 style={{ fontFamily: 'var(--font-display)', fontSize: 18, fontWeight: 500, lineHeight: 1.25, margin: 0 }}>{ar ? cat.ar : cat.en}</h3>
                    <p style={{ fontSize: 13, lineHeight: 1.55, color: 'var(--fg-secondary)', flex: 1, margin: 0 }}>{ar ? cat.dar : cat.den}</p>
                    <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, color: 'var(--gold-deep)', fontSize: 13, fontWeight: 600, marginTop: 4 }}>
                      {ar ? 'عرض المنتجات' : 'View Items'} <Icon name={ar ? 'arrow-left' : 'arrow-right'} size={14} />
                    </span>
                  </div>
                </button>
              </Reveal>
            ))}
          </div>
        </Container>
      </Section>

      {/* ── FURNITURE RENTAL CATEGORIES (subcategory) ── */}
      <Section bg="muted">
        <Container wide>
          <Reveal>
            <SectionHead center
              eyebrow={ar ? 'أثاث التأجير' : 'Furniture & Table Rentals'}
              title={ar ? 'فئات أثاث التأجير' : 'Furniture & Table Rental Categories'}
              intro={ar
                ? 'تصفح الأرائك والطاولات وقطع الجلوس والكوشة ومستلزمات الأثاث المتوفرة من سرايا للفعاليات والموردين المعتمدين.'
                : 'Browse seating, tables, lounge pieces, bridal seating, and furniture essentials available from Saraya Events and approved marketplace vendors.'} />
          </Reveal>
          <div className="saraya-grid-4" style={{ marginTop: 40 }}>
            {RENTAL_CATEGORIES.map((cat, i) => {
              const c = catWithOvr(cat);
              return (
                <Reveal key={c.id} delay={(i % 4) * 35}>
                  <button
                    onClick={() => go('rental/' + c.id)}
                    className="saraya-lift"
                    style={{ textAlign: 'start', cursor: 'pointer', padding: 0, background: 'var(--white)', border: '1px solid var(--line)', borderRadius: 'var(--radius-lg)', boxShadow: 'var(--shadow-soft)', overflow: 'hidden', display: 'flex', flexDirection: 'column', height: '100%', width: '100%', font: 'inherit', color: 'inherit' }}>
                    <div style={{ aspectRatio: '4 / 3', background: 'var(--gold-tint)', display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'var(--gold-deep)', position: 'relative' }}>
                      <Icon name={c.icon} size={44} stroke={1.2} />
                      <span style={{ position: 'absolute', top: 12, insetInlineStart: 12, fontSize: 10.5, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '.08em', color: 'var(--gold-deep)', background: 'var(--white)', padding: '3px 9px', borderRadius: 999 }}>
                        {ar ? (RENTAL_GROUPS.find((g) => g.id === c.group) || {}).ar : (RENTAL_GROUPS.find((g) => g.id === c.group) || {}).en}
                      </span>
                    </div>
                    <div style={{ padding: '16px 18px 20px', display: 'flex', flexDirection: 'column', gap: 7, flex: 1 }}>
                      <h3 style={{ fontFamily: 'var(--font-display)', fontSize: 19, fontWeight: 500, lineHeight: 1.2, margin: 0 }}>{ar ? c.ar : c.en}</h3>
                      <p style={{ fontSize: 13, lineHeight: 1.55, color: 'var(--fg-secondary)', flex: 1, margin: 0 }}>{ar ? c.dar : c.den}</p>
                      <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, color: 'var(--gold-deep)', fontSize: 13, fontWeight: 600, marginTop: 4 }}>
                        {ar ? 'عرض المنتجات' : 'View Items'} <Icon name={ar ? 'arrow-left' : 'arrow-right'} size={14} />
                      </span>
                    </div>
                  </button>
                </Reveal>
              );
            })}
          </div>
          <Reveal>
            <p style={{ marginTop: 32, textAlign: 'center', fontSize: 13, color: 'var(--fg-muted)', maxWidth: 580, marginInline: 'auto', lineHeight: 1.6 }}>
              {ar
                ? 'يتم عرض المنتجات من سرايا للفعاليات والموردين المعتمدين في المنصة. قد تختلف الأسعار والتوفر والتوصيل والتركيب حسب المورد.'
                : 'Items are listed by Saraya Events and approved marketplace vendors. Availability, delivery, setup, and pricing may vary by vendor.'}
            </p>
          </Reveal>
        </Container>
      </Section>

      {/* ── HOW RENTAL WORKS ── */}
      <Section bg="canvas">
        <Container wide>
          <Reveal>
            <SectionHead center
              eyebrow={ar ? 'كيف يعمل التأجير' : 'How It Works'}
              title={ar ? 'خطوات التأجير' : 'Renting is simple'} />
          </Reveal>
          <div className="saraya-grid-4" style={{ marginTop: 44 }}>
            {HOW.map((step, i) => (
              <Reveal key={i} delay={i * 60}>
                <div style={{ textAlign: 'center', padding: '28px 20px' }}>
                  <div style={{ width: 56, height: 56, borderRadius: '50%', background: 'var(--gold-tint)', display: 'flex', alignItems: 'center', justifyContent: 'center', marginInline: 'auto', marginBottom: 16, position: 'relative' }}>
                    <Icon name={step.icon} size={24} style={{ color: 'var(--gold-deep)' }} />
                    <span style={{ position: 'absolute', top: -6, insetInlineEnd: -6, width: 22, height: 22, borderRadius: '50%', background: 'var(--espresso)', color: 'var(--ivory)', fontSize: 11, fontWeight: 700, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>{i + 1}</span>
                  </div>
                  <div style={{ fontFamily: 'var(--font-display)', fontSize: 17, fontWeight: 500, marginBottom: 8 }}>{ar ? step.ar : step.en}</div>
                  <p style={{ fontSize: 13.5, lineHeight: 1.6, color: 'var(--fg-secondary)', margin: 0 }}>{ar ? step.dar : step.den}</p>
                </div>
              </Reveal>
            ))}
          </div>
        </Container>
      </Section>

      {/* ── RFQ CALLOUT ── */}
      <Section bg="muted">
        <Container wide>
          <div className="saraya-rfq-band" style={{ display: 'grid', gridTemplateColumns: '1fr auto', gap: 32, alignItems: 'center', flexWrap: 'wrap' }}>
            <Reveal>
              <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, padding: '4px 12px', borderRadius: 999, background: 'var(--gold-tint)', color: 'var(--gold-deep)', fontSize: 11.5, fontWeight: 700, letterSpacing: '0.06em', textTransform: 'uppercase', marginBottom: 12 }}>
                <Icon name="layers" size={11} />{ar ? 'قارن عروض الموردين' : 'Compare Vendor Offers'}
              </span>
              <Eyebrow color="var(--gold-deep)">{ar ? 'طلب عروض أسعار' : 'Request for Quotation'}</Eyebrow>
              <h2 style={{ fontFamily: 'var(--font-display)', fontSize: 'clamp(24px,3.5vw,40px)', lineHeight: 1.1, fontWeight: 500, color: 'var(--fg-primary)', margin: '12px 0 12px' }}>
                {ar ? 'تحتاج منتجات تأجير متعددة أو إعداداً كاملاً؟' : 'Need multiple rental items or a full setup?'}
              </h2>
              <p style={{ fontSize: 16, lineHeight: 1.65, color: 'var(--fg-secondary)', maxWidth: 500, margin: 0 }}>
                {ar
                  ? 'أرسل طلباً واحداً واستقبل عروضاً من الموردين المعتمدين — أو اطلب من سرايا تنسيق إعداد كامل لمناسبتك.'
                  : 'Send one request and receive offers from qualified vendors — or ask Saraya Events to help coordinate a full setup for your occasion.'}
              </p>
            </Reveal>
            <Reveal delay={80}>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 12, minWidth: 190 }}>
                <Button variant="primary" size="lg" icon="pen-line" onClick={() => go('design')}>
                  {ar ? 'اطلب عرض سعر' : 'Request a Quote'}
                </Button>
                <Button variant="secondary" icon="wand-sparkles" onClick={() => go('design')}>
                  {ar ? 'اطلب تنسيق سرايا' : 'Ask Saraya to Coordinate'}
                </Button>
              </div>
            </Reveal>
          </div>
        </Container>
      </Section>

      {/* ── VENDOR CTA ── */}
      <Section bg="canvas">
        <Container wide>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 40, alignItems: 'center' }} className="saraya-split">
            <Reveal>
              <Eyebrow color="var(--gold-deep)">{ar ? 'للموردين' : 'For Vendors'}</Eyebrow>
              <h2 style={{ fontFamily: 'var(--font-display)', fontSize: 'clamp(26px,4vw,42px)', lineHeight: 1.1, fontWeight: 500, color: 'var(--fg-primary)', margin: '14px 0 16px' }}>
                {ar ? 'أضف منتجات التأجير الخاصة بك' : 'List Your Rental Items'}
              </h2>
              <p style={{ fontSize: 16, lineHeight: 1.7, color: 'var(--fg-secondary)', maxWidth: 440, margin: '0 0 24px' }}>
                {ar
                  ? 'يمكن للموردين المعتمدين إضافة الأثاث والديكور والمعدات ومستلزمات المناسبات واستقبال طلبات التأجير من العملاء.'
                  : 'Approved vendors can add furniture, décor, equipment, and event essentials to Saraya Events Marketplace and receive rental inquiries from customers.'}
              </p>
              <div style={{ display: 'flex', gap: 12, flexWrap: 'wrap' }}>
                <Button variant="primary" size="lg" icon="store" onClick={() => go('partner')}>
                  {ar ? 'انضم كمورد' : 'Join as Vendor'}
                </Button>
                <Button variant="secondary" size="lg" icon="plus" onClick={() => go('vendor-dashboard')}>
                  {ar ? 'أضف منتج تأجير' : 'Add Rental Item'}
                </Button>
              </div>
            </Reveal>
            <Reveal delay={100}>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
                {[
                  { icon: 'layout-dashboard', en: 'Vendor Dashboard', ar: 'لوحة التحكم', den: 'Manage your rental items, bookings, and inquiries.', dar: 'أدر منتجاتك وحجوزاتك واستفساراتك.' },
                  { icon: 'check-circle', en: 'Admin Approval', ar: 'موافقة الإدارة', den: 'Items are reviewed before going live to customers.', dar: 'تُراجع المنتجات قبل نشرها للعملاء.' },
                  { icon: 'users', en: 'Customer Reach', ar: 'وصول للعملاء', den: 'Reach event planners, hotels, and individuals across the UAE.', dar: 'تواصل مع منظمي الفعاليات والفنادق والأفراد في الإمارات.' },
                  { icon: 'trending-up', en: 'Grow Your Business', ar: 'نمّ نشاطك', den: 'Receive quote requests and bookings directly.', dar: 'استقبل طلبات عروض الأسعار والحجوزات مباشرة.' },
                ].map((feat, i) => (
                  <div key={i} style={{ padding: '18px 16px', borderRadius: 12, background: 'var(--cream)', border: '1px solid var(--line)' }}>
                    <Icon name={feat.icon} size={20} style={{ color: 'var(--gold-deep)', marginBottom: 10 }} />
                    <div style={{ fontFamily: 'var(--font-body)', fontSize: 14, fontWeight: 600, marginBottom: 5 }}>{ar ? feat.ar : feat.en}</div>
                    <p style={{ fontSize: 12.5, color: 'var(--fg-secondary)', lineHeight: 1.5, margin: 0 }}>{ar ? feat.dar : feat.den}</p>
                  </div>
                ))}
              </div>
            </Reveal>
          </div>
        </Container>
      </Section>

      {/* ── TRUST NOTE ── */}
      <div style={{ background: 'var(--line)', height: 1 }} />
      <div style={{ background: 'var(--bg-canvas)', padding: '20px var(--page-gutter)', textAlign: 'center' }}>
        <p style={{ fontSize: 12.5, color: 'var(--fg-muted)', maxWidth: 700, marginInline: 'auto', lineHeight: 1.65 }}>
          {ar
            ? 'تُقدَّم منتجات التأجير من سرايا للفعاليات والموردين المعتمدين. يتحمّل الموردون مسؤولية التوفر والتوصيل والتركيب والاستلام وحالة المنتج ما لم يُنص على غير ذلك.'
            : 'Rental items are provided by Saraya Events and approved marketplace vendors. Vendors are responsible for availability, delivery, installation, collection, and item condition unless otherwise stated.'}
        </p>
      </div>

      <StickyCartBar />
    </main>
  );
}

Object.assign(window, { RentalCategoryGrid, RentalCategoryPage, RentalMainPage });
