// Saraya Events — app shell: providers, router, tweaks.

const { useState: useStateA, useEffect: useEffectA, useCallback } = React;

/* ====== SEO: per-route meta data ====== */
const _SITE_URL = (typeof window !== 'undefined' && window.SARAYA_SITE_URL) || 'https://app.sarayaevents.com';
const _OG_IMAGE = _SITE_URL + '/assets/logo-primary.png';
const SEO_META = {
  home:     { title: 'Saraya Events Marketplace UAE | Event Rentals, Services & Packages', desc: 'Discover Saraya Events Marketplace for event rentals, services, flowers, gifts, packages, and verified vendors across Abu Dhabi and the UAE.', index: true },
  about:    { title: 'About Saraya Events | Luxury Event Design in Abu Dhabi UAE', desc: 'Saraya Events is an Abu Dhabi event design house specialising in weddings, corporate events, flowers, décor, furniture rental, and hospitality services.', index: true },
  services: { title: 'Event Services UAE | Weddings, Corporate Events & Hospitality', desc: 'Explore event services from Saraya Events including weddings, corporate events, décor, flowers, photography, catering, and full event management across the UAE.', index: true },
  store:    { title: 'Flowers, Gifts & Event Supplies UAE | Saraya Events Store', desc: 'Shop flowers, gifts, décor, and event essentials online from Saraya Events. Delivered across Abu Dhabi and the UAE.', index: true },
  rental:   { title: 'Event Rentals UAE | Furniture, Décor, AV & Party Equipment', desc: 'Rent event furniture, décor, AV equipment, lighting, and party essentials from Saraya Events and approved vendors across the UAE.', index: true },
  packages: { title: 'Saraya Event Packages UAE | Weddings, Engagements & Custom Events', desc: 'Choose curated Saraya Events packages for weddings, engagements, birthdays, and corporate events — or request a fully custom event package.', index: true },
  showroom: { title: 'Virtual Showroom UAE | Display Your Event Business Online', desc: 'Join Saraya Events Virtual Showroom to display your products, rentals, services, and business profile to customers across the UAE.', index: true },
  'vendor-packages': { title: 'Vendor Packages UAE | Sell & Promote Your Event Business Online', desc: 'Choose a Saraya Events vendor package to list products, rental items, and services, respond to RFQs, and grow your event business in the UAE.', index: true },
  partner:  { title: 'Join Saraya Events as Vendor | List Products, Rentals & Services', desc: 'Register as a vendor with Saraya Events Marketplace to list products, rentals, and services and receive customer inquiries across Abu Dhabi and UAE.', index: true },
  contact:  { title: 'Contact Saraya Events UAE | Event Planning, Rentals & Vendor Support', desc: 'Contact Saraya Events for event planning, rentals, packages, vendor support, custom event requests, and marketplace inquiries across the UAE.', index: true },
  gallery:  { title: 'Event Gallery | Saraya Events Portfolio Abu Dhabi', desc: 'Browse Saraya Events portfolio — weddings, corporate events, décor, flowers, and hospitality setups across Abu Dhabi and the UAE.', index: true },
  terms:    { title: 'Terms & Conditions | Saraya Events Marketplace', desc: 'Read the Saraya Events Marketplace terms and conditions governing platform use, purchases, rentals, and vendor services.', index: true },
  privacy:  { title: 'Privacy Policy | Saraya Events Marketplace', desc: 'Learn how Saraya Events collects, uses, and protects your personal data in compliance with UAE data protection regulations.', index: true },
  'cancellation-refund': { title: 'Cancellation & Refund Policy | Saraya Events', desc: 'Understand the Saraya Events cancellation and refund policy for products, rentals, services, and event packages in the UAE.', index: true },
  complaints: { title: 'Complaints & Disputes | Saraya Events Marketplace', desc: 'Submit a complaint or dispute through the Saraya Events Marketplace formal resolution process. We respond within 3 business days.', index: true },
  'vendor-agreement': { title: 'Vendor Agreement | Saraya Events Marketplace', desc: 'Read the Saraya Events vendor agreement covering listing terms, commissions, payouts, and vendor responsibilities.', index: true },
  'vendor-terms':    { title: 'Vendor Terms & Conditions | Saraya Events', desc: 'Full terms and conditions for vendors on the Saraya Events Marketplace: subscriptions, listing standards, commissions, and responsibilities.', index: true },
  'customer-terms':  { title: 'Customer Terms & Conditions | Saraya Events', desc: 'Customer terms for shopping on the Saraya Events Marketplace: payments, privacy, complaints, and cancellation policy.', index: true },
  campaigns: { title: 'Event Planning Services UAE | Saraya Events', desc: 'Explore Saraya Events campaigns for wedding planning, event rentals, corporate events, flowers, and more in Abu Dhabi and the UAE.', index: true },
  'campaigns/wedding-planning': { title: 'Wedding Planning UAE | Packages, Vendors & Décor | Saraya Events', desc: 'Plan your perfect wedding in Abu Dhabi. Browse wedding décor, flowers, catering, photography, and verified vendors through Saraya Events Marketplace.', index: true },
  'campaigns/rental-furniture': { title: 'Event Furniture Rental UAE | Chairs, Tables, Sofas & Tents', desc: 'Rent banquet chairs, tables, sofas, tents, and AV equipment for events in Abu Dhabi and UAE. Flexible daily and per-event pricing from verified suppliers.', index: true },
  'campaigns/corporate-events': { title: 'Corporate Event Services UAE | AV, Catering & Full Production', desc: 'Source AV equipment, conference furniture, catering, and full event production from verified UAE vendors for your corporate event.', index: true },
  'campaigns/flowers-gifts':    { title: 'Flowers & Gifts Delivery Abu Dhabi | Saraya Events Store', desc: 'Order fresh flowers, gift boxes, wedding bouquets, and event décor online. Same-day delivery available in Abu Dhabi from Saraya Events.', index: true },
  'campaigns/party-rentals':    { title: 'Party Rentals Abu Dhabi | Tables, Chairs, Décor & Balloons', desc: 'Rent party tables, chairs, backdrops, lighting, balloon arches, and props for birthday parties and events in Abu Dhabi and UAE.', index: true },
  'campaigns/vendor-join':      { title: 'Join Saraya Events Marketplace | Grow Your Event Business UAE', desc: 'Register as a vendor on Saraya Events Marketplace to list products, rentals, and services and reach event customers across Abu Dhabi and UAE.', index: true },
  vendors:  { title: 'Grow Your Event Business in UAE | Saraya Events', desc: 'Partner with Saraya Events to reach thousands of event customers across Abu Dhabi and the UAE.', index: true },
  // Service detail pages
  'service-weddings':   { title: 'Wedding Services Abu Dhabi UAE | Saraya Events', desc: 'Full-service wedding planning and design in Abu Dhabi — décor, flowers, catering, photography, and complete event coordination.', index: true },
  'service-corporate':  { title: 'Corporate Event Services UAE | Saraya Events', desc: 'Professional corporate event services across the UAE — conferences, product launches, gala dinners, and brand activations.', index: true },
  'service-catering':   { title: 'Event Catering UAE | Saraya Events Hospitality', desc: 'Premium event catering and hospitality services for weddings, corporate events, and private occasions across Abu Dhabi and UAE.', index: true },
  'service-flowers':    { title: 'Flowers & Floral Design UAE | Saraya Events', desc: 'Beautiful floral arrangements, wedding bouquets, and event flower décor delivered across Abu Dhabi and the UAE.', index: true },
  'service-decor':      { title: 'Event Décor & Styling UAE | Saraya Events', desc: 'Premium event décor, backdrops, stage builds, draping, and lighting for weddings and events across the UAE.', index: true },
  'service-balloons':   { title: 'Balloon Décor & Installations UAE | Saraya Events', desc: 'Organic balloon arches, garlands, ceilings and custom balloon installations for events across Abu Dhabi and UAE.', index: true },
  'service-majlis':     { title: 'Majlis Setup & Styling UAE | Saraya Events', desc: 'Traditional majlis styling with floor seating, florals, fragrance, and catering setup across Abu Dhabi and UAE.', index: true },
  'service-graduation': { title: 'Graduation Event Services UAE | Saraya Events', desc: 'Celebrate graduations with custom décor, flowers, catering, and full event design across Abu Dhabi and UAE.', index: true },
  'service-birthdays':  { title: 'Birthday Party Planning UAE | Saraya Events', desc: 'Bespoke birthday party planning and décor for all ages across Abu Dhabi and the UAE.', index: true },
  // Private routes — noindex
  'vendor-dashboard': { title: 'Vendor Dashboard | Saraya Events', desc: '', index: false },
  'admin-dashboard':  { title: 'Admin | Saraya Events', desc: '', index: false },
  checkout:           { title: 'Checkout | Saraya Events', desc: '', index: false },
  'my-orders':        { title: 'My Orders | Saraya Events', desc: '', index: false },
  confirmation:       { title: 'Order Confirmed | Saraya Events', desc: '', index: false },
  design:             { title: 'Request a Quote | Saraya Events', desc: '', index: false },
  product:            { title: 'Product | Saraya Events', desc: '', index: false },
};

function _setMeta(route) {
  const [base, param] = route.split('/');
  const key = param ? (base + '/' + param) : base;
  const seo = SEO_META[key] || SEO_META.home;
  const url = _SITE_URL + '/#' + route;

  document.title = seo.title;

  const setAttr = (sel, attr, val) => {
    let el = document.querySelector(sel);
    if (!el) { const [tag, ...rest] = sel.split('['); el = document.createElement(tag); rest.forEach(a => { const [k,v] = a.replace(/[\[\]"]/g,'').split('='); el.setAttribute(k, v||''); }); document.head.appendChild(el); }
    el.setAttribute(attr, val);
  };

  if (seo.desc) setAttr('meta[name="description"]', 'content', seo.desc);
  setAttr('link[rel="canonical"]', 'href', url);
  setAttr('meta[name="robots"]', 'content', seo.index ? 'index, follow' : 'noindex, nofollow');
  setAttr('meta[property="og:title"]', 'content', seo.title);
  if (seo.desc) setAttr('meta[property="og:description"]', 'content', seo.desc);
  setAttr('meta[property="og:url"]', 'content', url);
  setAttr('meta[property="og:image"]', 'content', _OG_IMAGE);
  setAttr('meta[name="twitter:title"]', 'content', seo.title);
  if (seo.desc) setAttr('meta[name="twitter:description"]', 'content', seo.desc);
}

/* Hero headline options (tweakable, bilingual) */
const HERO_OPTIONS = {
  brief:   { en: 'Elegant Events, Beautifully Designed', ar: 'فعاليات أنيقة، بتصميمٍ بديع' },
  care:    { en: 'Every Occasion, Composed With Care',   ar: 'كل مناسبة، بعنايةٍ فائقة' },
  remember:{ en: 'The Days You’ll Always Remember',       ar: 'أيامٌ لا تُنسى أبدًا' },
  life:    { en: 'Luxury Events, Brought to Life',        ar: 'فعاليات فاخرة، نُحييها بإتقان' },
};

const ACCENTS = {
  gold: { '--accent': '#C9A961', '--accent-deep': '#A8884A' },
  rose: { '--accent': '#C98F8F', '--accent-deep': '#B07878' },
};

function App() {
  const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
    "heroHeadline": "brief",
    "accent": "gold"
  }/*EDITMODE-END*/;
  const [tw, setTweak] = useTweaks(TWEAK_DEFAULTS);

  /* ----- language ----- */
  const [lang, setLangState] = useStateA(() => localStorage.getItem('saraya_lang') || 'en');
  const t = useCallback((key) => {
    const I = window.SARAYA.I18N;
    return (I[lang] && I[lang][key]) || I.en[key] || key;
  }, [lang]);
  const setLang = useCallback((l) => { setLangState(l); localStorage.setItem('saraya_lang', l); }, []);
  useEffectA(() => {
    document.documentElement.lang = lang;
    document.documentElement.dir = window.SARAYA.I18N[lang].dir;
  }, [lang]);

  /* ----- routing ----- */
  const [route, setRoute] = useStateA(() => (location.hash || '#home').slice(1) || 'home');
  const go = useCallback((r) => {
    // Intercept design route — open modal instead of navigating to a page
    if (r === 'design') {
      if (window.openRequestQuoteModal) { window.openRequestQuoteModal(); return; }
    }
    location.hash = '#' + r;
  }, []);
  useEffectA(() => {
    const onHash = () => {
      const newRoute = (location.hash || '#home').slice(1) || 'home';
      // Handle direct URL navigation to #design
      if (newRoute === 'design') {
        if (window.openRequestQuoteModal) {
          window.openRequestQuoteModal();
          history.replaceState(null, '', location.href.replace('#design', '#home'));
          return;
        }
      }
      setRoute(newRoute);
      window.scrollTo(0, 0);
    };
    window.addEventListener('hashchange', onHash); onHash();
    return () => window.removeEventListener('hashchange', onHash);
  }, []);

  /* ----- inquiry tray ----- */
  const [items, setItems] = useStateA(() => { try { return JSON.parse(localStorage.getItem('saraya_inquiry') || '[]'); } catch (e) { return []; } });
  const [trayOpen, setTrayOpen] = useStateA(false);
  useEffectA(() => { localStorage.setItem('saraya_inquiry', JSON.stringify(items)); }, [items]);
  const inquiry = {
    items, count: items.length, isOpen: trayOpen,
    add: (it) => setItems((p) => p.some((x) => x.id === it.id) ? p : [...p, it]),
    remove: (id) => setItems((p) => p.filter((x) => x.id !== id)),
    clear: () => { setItems([]); setTrayOpen(false); },
    has: (id) => items.some((x) => x.id === id),
    openTray: () => setTrayOpen(true), closeTray: () => setTrayOpen(false),
  };

  /* ----- accent tweak ----- */
  useEffectA(() => {
    const a = ACCENTS[tw.accent] || ACCENTS.gold;
    Object.entries(a).forEach(([k, v]) => document.documentElement.style.setProperty(k, v));
  }, [tw.accent]);

  const heroHeadline = (HERO_OPTIONS[tw.heroHeadline] || HERO_OPTIONS.brief)[lang];

  /* ----- SEO: update meta tags on every route change ----- */
  useEffectA(() => {
    _setMeta(route);
    // SPA page view — fires on every hash navigation after the initial load
    const url = _SITE_URL + '/#' + route;
    if (typeof gtag === 'function') {
      gtag('event', 'page_view', {
        page_title:    document.title,
        page_location: url,
        page_path:     '/#' + route,
      });
    }
    if (typeof fbq === 'function') {
      fbq('track', 'PageView');
    }
  }, [route]);

  /* ----- auth guard helper ----- */
  // NOTE: auth is read here for requireAuth — BUT this component is the parent of AuthProvider,
  // so window.useAuth() returns the default context (user:null). requireAuth is therefore only
  // used for non-dashboard pages (my-orders, wishlist, notifications) where a simple gate is OK.
  // Dashboard pages (vendor-dashboard, admin-dashboard) handle their own auth inside AuthProvider.
  const auth = window.useAuth ? window.useAuth() : null;
  const requireAuth = (page, requireAdmin = false) => {
    // If auth hasn't resolved yet (context default has loading:false but user:null),
    // show a loading spinner rather than immediately gating.
    if (!auth?.user) return (
      <main style={{ paddingTop: 160, paddingBottom: 80, minHeight: '70vh', display: 'flex', alignItems: 'center', justifyContent: 'center', flexDirection: 'column', gap: 16 }}>
        <p style={{ fontSize: 16, color: 'var(--fg-muted)', textAlign: 'center' }}>Please sign in to access this page.</p>
        <button onClick={() => auth?.openAuthModal?.('login')} style={{ padding: '10px 24px', borderRadius: 8, background: 'var(--gold)', color: '#fff', border: 'none', fontWeight: 600, cursor: 'pointer', fontSize: 14 }}>Sign In</button>
      </main>
    );
    if (requireAdmin && !auth?.isAdmin) return (
      <main style={{ paddingTop: 160, paddingBottom: 80, minHeight: '70vh', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
        <p style={{ fontSize: 16, color: 'var(--fg-muted)' }}>You do not have permission to access this page.</p>
      </main>
    );
    return page;
  };

  /* ----- page switch ----- */
  const [base, param] = route.split('/');
  const renderPage = () => {
    switch (base) {
      case 'home': return <HomePage heroHeadline={heroHeadline} />;
      case 'about': return <AboutPage />;
      case 'services': return <ServicesPage />;
      case 'service-weddings':    return <ServiceDetailPage serviceId="weddings" />;
      case 'service-corporate':   return <ServiceDetailPage serviceId="corporate" />;
      case 'service-catering':    return <ServiceDetailPage serviceId="catering" />;
      case 'service-flowers':     return <ServiceDetailPage serviceId="flowers" />;
      case 'service-graduation':  return <ServiceDetailPage serviceId="graduation" />;
      case 'service-birthdays':   return <ServiceDetailPage serviceId="birthdays" />;
      case 'service-decor':       return <ServiceDetailPage serviceId="decor" />;
      case 'service-balloons':    return <ServiceDetailPage serviceId="balloons" />;
      case 'service-majlis':      return <ServiceDetailPage serviceId="majlis" />;
      case 'service-partners':    return <ServiceDetailPage serviceId="partners" />;
      case 'store': return <StorePage />;
      case 'rental': return param ? <RentalCategoryPage categoryId={param} /> : <RentalMainPage />;
      case 'showroom': return <ShowroomPage />;
      case 'product': return <ProductDetailPage productId={param} />;
      case 'checkout': return <CheckoutPage />;
      case 'confirmation': return <ConfirmationPage orderId={param} />;
      case 'packages': return <PackagesPage />;
      case 'gallery': return <GalleryPage />;
      case 'partner': return <PartnerPage />;
      case 'design': return <DesignBuilder />;
      case 'contact': return <ContactPage />;
      case 'my-orders':        return requireAuth(<MyOrdersPage />);
      case 'my-wishlist':      return requireAuth(window.MyWishlistPage ? <window.MyWishlistPage /> : null);
      case 'notifications':    return requireAuth(window.NotificationsPage ? <window.NotificationsPage /> : null);
      case 'vendor-dashboard': return <VendorDashboardPage />;
      case 'admin-dashboard':  return <AdminDashboardPage />;
      case 'vendor-packages':   return <VendorPackagesPage />;
      case 'vendor-agreement':  return <VendorAgreementPage />;
      case 'terms':             return <TermsPage />;
      case 'privacy':           return <PrivacyPage />;
      case 'cancellation-refund': return <CancellationPage />;
      case 'complaints':        return <ComplaintsPage />;
      case 'vendor-terms':      return <VendorTermsPage />;
      case 'customer-terms':    return <CustomerTermsPage />;
      case 'vendors':           return param === 'grow' ? <VendorGrowPage /> : <PartnerPage />;
      case 'campaigns':         return <CampaignPage campaignId={param || 'wedding-planning'} />;
      default: return <HomePage heroHeadline={heroHeadline} />;
    }
  };
  const hideFooter = base === 'design';

  return (
    <AuthProvider>
    <AdminProvider>
    <window.LangContext.Provider value={{ lang, setLang, t }}>
      <window.NavContext.Provider value={{ route, go }}>
        <window.InquiryContext.Provider value={inquiry}>
          <CartProvider>
          <WishlistWrapper>
          <Header />
          {renderPage()}
          {!hideFooter && <Footer />}
          <FloatingWhatsApp />
          <SarayaAssistant />
          <InquiryTray />
          <JoinVendorModal />
          {window.RequestQuoteModal && React.createElement(window.RequestQuoteModal)}
            {window.ItemRFQModal && React.createElement(window.ItemRFQModal)}

          <TweaksPanel title="Tweaks">
            <TweakSection label="Hero" />
            <TweakSelect label="Headline" value={tw.heroHeadline}
              options={[
                { value: 'brief',    label: 'Elegant Events, Beautifully Designed' },
                { value: 'care',     label: 'Every Occasion, Composed With Care' },
                { value: 'remember', label: 'The Days You’ll Always Remember' },
                { value: 'life',     label: 'Luxury Events, Brought to Life' },
              ]}
              onChange={(v) => setTweak('heroHeadline', v)} />
            <TweakSection label="Accent" />
            <TweakRadio label="Accent colour" value={tw.accent}
              options={[{ value: 'gold', label: 'Gold' }, { value: 'rose', label: 'Rose' }]}
              onChange={(v) => setTweak('accent', v)} />
          </TweaksPanel>
          </WishlistWrapper>
          </CartProvider>
        </window.InquiryContext.Provider>
      </window.NavContext.Provider>
    </window.LangContext.Provider>
    </AdminProvider>
    </AuthProvider>
  );
}

/* Wrap the entire app in WishlistProvider if available (loaded after app.jsx) */
function WishlistWrapper({ children }) {
  const P = window.WishlistProvider;
  return P ? React.createElement(P, null, children) : React.createElement(React.Fragment, null, children);
}

const APP_ORDER_LABELS = {
  pending:    { en: 'Pending',    ar: 'قيد الانتظار', icon: '⏳', color: '#E8A838' },
  confirmed:  { en: 'Confirmed', ar: 'مؤكد',          icon: '✅', color: '#3AB86C' },
  processing: { en: 'Processing', ar: 'قيد التنفيذ',  icon: '⚙️', color: '#4A90D9' },
  shipped:    { en: 'Shipped',   ar: 'تم الشحن',       icon: '🚚', color: '#7B68EE' },
  delivered:  { en: 'Delivered', ar: 'تم التسليم',     icon: '📦', color: '#3AB86C' },
  cancelled:  { en: 'Cancelled', ar: 'ملغى',           icon: '✖',  color: '#E05454' },
  refunded:   { en: 'Refunded',  ar: 'مُسترد',         icon: '↩',  color: '#888'    },
};

function MyOrdersPage() {
  const { lang } = useLang();
  const { go }   = useNav();
  const auth     = window.useAuth ? window.useAuth() : null;
  const db       = window.SarayaDB;
  const ar       = lang === 'ar';

  const [orders,  setOrders]  = useStateA([]);
  const [loading, setLoading] = useStateA(true);
  const [expanded, setExpanded] = useStateA(null);

  useEffectA(() => {
    if (!auth?.user || !db) { setLoading(false); return; }
    db.from('orders')
      .select('*, order_items(*)')
      .eq('customer_id', auth.user.id)
      .order('created_at', { ascending: false })
      .then(({ data }) => { setOrders(data || []); setLoading(false); });
  }, [auth?.user?.id, db]);

  if (!auth?.user) return (
    <main style={{ paddingTop: 140, paddingBottom: 80, minHeight: '70vh', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
      <div style={{ textAlign: 'center' }}>
        <p style={{ fontSize: 16, color: 'var(--fg-muted)' }}>{ar ? 'يجب تسجيل الدخول لعرض طلباتك.' : 'Please sign in to view your orders.'}</p>
        <Button variant="primary" onClick={() => auth?.openAuthModal('login')} style={{ marginTop: 20 }}>{ar ? 'تسجيل الدخول' : 'Sign In'}</Button>
      </div>
    </main>
  );

  return (
    <main>
      <section style={{ background: 'var(--cream)', paddingTop: 140, paddingBottom: 56, borderBottom: '1px solid var(--line)' }}>
        <Container wide>
          <Eyebrow>{ar ? 'حسابي' : 'My Account'}</Eyebrow>
          <h1 style={{ fontFamily: 'var(--font-display)', fontSize: 'clamp(34px,5.5vw,60px)', fontWeight: 500, margin: '16px 0 0' }}>
            {ar ? 'طلباتي' : 'My Orders'}
          </h1>
          <p style={{ marginTop: 10, fontSize: 15, color: 'var(--fg-secondary)' }}>{auth.user.email}</p>
        </Container>
      </section>

      <Section bg="canvas">
        <Container style={{ maxWidth: 780, margin: '0 auto' }}>
          {loading && <p style={{ textAlign: 'center', color: 'var(--fg-muted)' }}>{ar ? 'جارٍ التحميل...' : 'Loading...'}</p>}

          {!loading && orders.length === 0 && (
            <div style={{ textAlign: 'center', padding: '60px 24px' }}>
              <Icon name="package" size={48} style={{ color: 'var(--gold-deep)', opacity: 0.4, marginBottom: 20 }} />
              <h2 style={{ fontFamily: 'var(--font-display)', fontSize: 24, fontWeight: 500, marginBottom: 12 }}>
                {ar ? 'لا توجد طلبات بعد' : 'No orders yet'}
              </h2>
              <p style={{ fontSize: 14, color: 'var(--fg-muted)', marginBottom: 28 }}>
                {ar ? 'ابدأ التسوق وستظهر طلباتك هنا.' : 'Place an order and it will appear here.'}
              </p>
              <div style={{ display: 'flex', gap: 12, justifyContent: 'center', flexWrap: 'wrap' }}>
                <Button variant="primary" onClick={() => go('store')}>{ar ? 'تصفح المتجر' : 'Browse Store'}</Button>
                <Button variant="whatsapp" icon="message-circle" href={window.SARAYA.waLink('Hello Saraya Events, I would like to follow up on my order.')}>
                  {ar ? 'تواصل عبر واتساب' : 'Contact via WhatsApp'}
                </Button>
              </div>
            </div>
          )}

          {!loading && orders.map((order) => {
            const st = APP_ORDER_LABELS[order.status] || APP_ORDER_LABELS.pending;
            const isOpen = expanded === order.id;
            const date = new Date(order.created_at).toLocaleDateString(ar ? 'ar-AE' : 'en-AE', { year: 'numeric', month: 'short', day: 'numeric' });
            const items = order.order_items || [];
            return (
              <div key={order.id} style={{ marginBottom: 16, borderRadius: 14, border: '1px solid var(--line)', background: 'var(--white)', overflow: 'hidden' }}>
                {/* Order header row */}
                <button
                  onClick={() => setExpanded(isOpen ? null : order.id)}
                  style={{ width: '100%', display: 'flex', alignItems: 'center', gap: 16, padding: '18px 22px', background: 'none', border: 'none', cursor: 'pointer', textAlign: 'start' }}
                >
                  <span style={{ fontSize: 24 }}>{st.icon}</span>
                  <div style={{ flex: 1 }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 10, flexWrap: 'wrap' }}>
                      <span style={{ fontSize: 14, fontWeight: 700, color: 'var(--fg-primary)' }}>
                        {ar ? 'طلب' : 'Order'} #{(order.reference || order.id.slice(0,8)).toUpperCase()}
                      </span>
                      <span style={{ padding: '3px 10px', borderRadius: 20, background: st.color + '22', color: st.color, fontSize: 12, fontWeight: 600 }}>
                        {ar ? st.ar : st.en}
                      </span>
                    </div>
                    <div style={{ fontSize: 12.5, color: 'var(--fg-muted)', marginTop: 3 }}>
                      {date} · {items.length} {ar ? 'عنصر' : 'item(s)'} · AED {Number(order.total || 0).toFixed(2)}
                    </div>
                  </div>
                  <Icon name={isOpen ? 'chevron-up' : 'chevron-down'} size={18} style={{ color: 'var(--fg-muted)', flexShrink: 0 }} />
                </button>

                {/* Expanded: timeline + items */}
                {isOpen && (
                  <div style={{ padding: '0 22px 22px', borderTop: '1px solid var(--line)' }}>
                    {/* Status timeline */}
                    <div style={{ display: 'flex', gap: 0, marginTop: 20, marginBottom: 24, overflowX: 'auto' }}>
                      {['pending','confirmed','processing','shipped','delivered'].map((s, i, arr) => {
                        const idx = arr.indexOf(order.status);
                        const done = i <= idx;
                        const curr = s === order.status;
                        return (
                          <React.Fragment key={s}>
                            <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', minWidth: 72 }}>
                              <div style={{ width: 28, height: 28, borderRadius: '50%', background: done ? 'var(--gold)' : 'var(--line)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 13, fontWeight: 700, color: done ? 'var(--ink)' : 'var(--fg-muted)', border: curr ? '2.5px solid var(--gold-deep)' : 'none', transition: 'all 200ms' }}>
                                {done ? '✓' : (i + 1)}
                              </div>
                              <div style={{ fontSize: 10, color: done ? 'var(--gold-deep)' : 'var(--fg-muted)', marginTop: 5, textAlign: 'center', fontWeight: curr ? 700 : 400 }}>
                                {ar ? APP_ORDER_LABELS[s].ar : APP_ORDER_LABELS[s].en}
                              </div>
                            </div>
                            {i < arr.length - 1 && (
                              <div style={{ flex: 1, height: 2, background: i < idx ? 'var(--gold)' : 'var(--line)', alignSelf: 'flex-start', marginTop: 13, transition: 'background 300ms' }} />
                            )}
                          </React.Fragment>
                        );
                      })}
                    </div>

                    {/* Line items */}
                    {items.length > 0 && (
                      <div style={{ display: 'grid', gap: 10 }}>
                        {items.map((item, j) => (
                          <div key={j} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '10px 14px', borderRadius: 10, background: 'var(--cream)' }}>
                            <div style={{ flex: 1 }}>
                              <div style={{ fontSize: 13.5, fontWeight: 600, color: 'var(--fg-primary)' }}>{item.name || (ar ? 'منتج' : 'Item')}</div>
                              <div style={{ fontSize: 12, color: 'var(--fg-muted)' }}>× {item.quantity || 1}</div>
                            </div>
                            <div style={{ fontSize: 13.5, fontWeight: 700, color: 'var(--gold-deep)' }}>AED {Number((item.unit_price || 0) * (item.quantity || 1)).toFixed(2)}</div>
                          </div>
                        ))}
                        <div style={{ display: 'flex', justifyContent: 'flex-end', paddingTop: 10, borderTop: '1px solid var(--line)', fontSize: 14, fontWeight: 700, color: 'var(--fg-primary)' }}>
                          {ar ? 'الإجمالي: ' : 'Total: '}<span style={{ color: 'var(--gold-deep)', marginInlineStart: 8 }}>AED {Number(order.total || 0).toFixed(2)}</span>
                        </div>
                      </div>
                    )}

                    <div style={{ marginTop: 16 }}>
                      <a href={window.SARAYA.waLink(`Hello Saraya Events, I'd like to follow up on order #${(order.reference || order.id.slice(0,8)).toUpperCase()}`)} target="_blank" rel="noopener" style={{ display: 'inline-flex', alignItems: 'center', gap: 8, padding: '9px 18px', borderRadius: 8, background: '#1FA855', color: '#fff', fontSize: 13, fontWeight: 600, textDecoration: 'none' }}>
                        <Icon name="message-circle" size={15} /> {ar ? 'تابع الطلب عبر واتساب' : 'Follow up on WhatsApp'}
                      </a>
                    </div>
                  </div>
                )}
              </div>
            );
          })}
        </Container>
      </Section>
    </main>
  );
}

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