<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
<meta name="google-site-verification" content="F8ptQyZ43OI5Bl3jTh9_T2zn4f1KR5TEDsYJ6_8YNr0" />
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover">
  <meta name="description" content="مول الخدمات — منصتك الأولى للخدمات الرقمية الاحترافية في مصر. تصميم مواقع، برمجة، تسويق رقمي، كتابة محتوى وأكثر — مع ضمان استرداد كامل عبر نظام Escrow.">
  <meta name="google-site-verification" content="z2bKviBbmgwGNYsqFn_DVgWrGsdtutjAVzT99_iqexk" />
  <meta name="keywords" content="خدمات رقمية, فريلانسر مصر, تصميم مواقع, برمجة, تسويق رقمي, كتابة محتوى, SEO, مول الخدمات, mall services egypt, خدمات اون لاين">
  <meta name="theme-color" content="#0F172A">
  <!-- ⚠️ ADDED: there was no favicon link anywhere in the project — the
       browser tab showed a generic blank icon. Reuses the same seal glyph
       as the logo/hero, in the new navy/turquoise palette. -->
  <link rel="icon" type="image/png" href="/icons/icon-192.png">
  <meta name="robots" content="index,follow,max-image-preview:large,max-snippet:-1,max-video-preview:-1">
  <meta name="author" content="مول الخدمات">
  <meta name="language" content="Arabic">
  <meta name="geo.region" content="EG">
  <meta name="geo.placename" content="Cairo, Egypt">
  <link rel="canonical" href="https://mall-services.pages.dev/">

  <!-- Open Graph -->
  <meta property="og:title" content="مول الخدمات | منصة الخدمات الرقمية الأولى في مصر">
  <meta property="og:description" content="اطلب أفضل الخدمات من محترفين معتمدين مع ضمان استرداد كامل. تصميم، برمجة، تسويق، كتابة محتوى وأكثر.">
  <meta property="og:type" content="website">
  <meta property="og:url" content="https://mall-services.pages.dev/">
  <meta property="og:image" content="https://mall-services.pages.dev/icons/icon-512.png">
  <meta property="og:image:width" content="512">
  <meta property="og:image:height" content="512">
  <meta property="og:locale" content="ar_EG">
  <meta property="og:site_name" content="مول الخدمات">

  <!-- Twitter Card -->
  <meta name="twitter:card" content="summary_large_image">
  <meta name="twitter:title" content="مول الخدمات | منصة الخدمات الرقمية الأولى في مصر">
  <meta name="twitter:description" content="اطلب أفضل الخدمات من محترفين معتمدين مع ضمان استرداد كامل.">
  <meta name="twitter:image" content="https://mall-services.pages.dev/icons/icon-512.png">

  <title>مول الخدمات | منصة الخدمات الرقمية الاحترافية في مصر</title>

  <!-- Structured Data: Organization -->
  <script type="application/ld+json">
  {
    "@context": "https://schema.org",
    "@type": "Organization",
    "name": "مول الخدمات",
    "alternateName": "Mall Services",
    "url": "https://mall-services.pages.dev",
    "logo": "https://mall-services.pages.dev/icons/icon-512.png",
    "description": "منصة عربية للخدمات الرقمية تربط المحترفين بأصحاب الأعمال",
    "foundingDate": "2023",
    "foundingLocation": {"@type": "Place", "name": "Cairo, Egypt"},
    "areaServed": {"@type": "Place", "name": "Arab World"},
    "contactPoint": {"@type": "ContactPoint", "contactType": "customer service", "availableLanguage": ["Arabic", "English"]},
    "sameAs": ["https://mall-services.pages.dev"]
  }
  </script>
  <!-- Structured Data: WebSite with SearchAction -->
  <script type="application/ld+json">
  {
    "@context": "https://schema.org",
    "@type": "WebSite",
    "name": "مول الخدمات",
    "url": "https://mall-services.pages.dev",
    "inLanguage": "ar",
    "potentialAction": {
      "@type": "SearchAction",
      "target": "https://mall-services.pages.dev/#services?q={search_term_string}",
      "query-input": "required name=search_term_string"
    }
  }
  </script>
  <!-- ⚠️ PERFORMANCE FIX: Google Analytics was loading unconditionally with the
       placeholder ID "G-XXXXXXXXXX" — that's not a real property, so it was
       pure waste: ~144 KB downloaded, ~68 KB of it never even used, plus
       ~257ms of main-thread time, for analytics that literally go nowhere.
       Flagged by both PageSpeed and GTmetrix reports. Every js/*.js caller
       already guards with `if (window.trackEvent)`, so leaving trackEvent
       undefined is completely safe — nothing breaks, it just no-ops.
       TO ENABLE: replace G-XXXXXXXXXX below with your real Measurement ID
       (Google Analytics → Admin → Data Streams → your stream), then remove
       the "if (false)" wrapper. -->
  <script>
  if (false) { // ← change to `if (true)` once you have a real Measurement ID
    const gaScript = document.createElement('script');
    gaScript.async = true;
    gaScript.src = 'https://www.googletagmanager.com/gtag/js?id=G-XXXXXXXXXX'; // ← your real ID here too
    document.head.appendChild(gaScript);
    window.dataLayer = window.dataLayer || [];
    function gtag(){dataLayer.push(arguments);}
    gtag('js', new Date());
    gtag('config', 'G-XXXXXXXXXX', { 'anonymize_ip': true }); // ← and here
    window.trackEvent = function(action, category, label) {
      gtag('event', action, { 'event_category': category, 'event_label': label });
    };
  }
  </script>

  <!-- PWA -->
  <link rel="manifest" href="/manifest.json">
  <meta name="mobile-web-app-capable" content="yes">
  <meta name="apple-mobile-web-app-capable" content="yes">
  <meta name="apple-mobile-web-app-status-bar-style" content="default">
  <meta name="apple-mobile-web-app-title" content="مول الخدمات">
  <link rel="apple-touch-icon" href="/icons/icon-192.png">

  <!-- Preconnect for performance -->
  <link rel="preconnect" href="https://fonts.googleapis.com">
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
  <link rel="preconnect" href="https://cdnjs.cloudflare.com">

  <!-- Fonts -->
  <link href="https://fonts.googleapis.com/css2?family=Amiri:wght@400;700&family=Fraunces:opsz,wght@9..144,500;9..144,600;9..144,700&family=IBM+Plex+Sans+Arabic:wght@300;400;500;600;700&family=IBM+Plex+Sans:wght@400;500;600;700&family=IBM+Plex+Mono:wght@400;500;600;700&display=swap" rel="stylesheet">

  <!-- Font Awesome -->
  <link rel="preload" as="style" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css"
    onload="this.onload=null;this.rel='stylesheet'">
  <noscript><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css"></noscript>

  <!-- Chart.js — real charting library for dashboard/wallet charts (no custom
       AI-generated-looking graphics; standard bar/line charts, Font Awesome
       icons only everywhere else). -->
  <script defer src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/4.4.1/chart.umd.min.js"></script>

  <!-- Firebase SDK (compat - no CSP issues) -->
  <script src="https://www.gstatic.com/firebasejs/10.14.1/firebase-app-compat.js"></script>
  <script src="https://www.gstatic.com/firebasejs/10.14.1/firebase-auth-compat.js"></script>
  <script src="https://www.gstatic.com/firebasejs/10.14.1/firebase-firestore-compat.js"></script>
  <script src="https://www.gstatic.com/firebasejs/10.14.1/firebase-storage-compat.js"></script>
  <script src="https://www.gstatic.com/firebasejs/10.14.1/firebase-database-compat.js"></script>

  <!-- ⚠️ PERFORMANCE FIX: this used to load cdn.tailwindcss.com and compile
       Tailwind live in the browser on every single page view — flagged
       explicitly by both PageSpeed and GTmetrix ("should not be used in
       production"), and was the single longest main-thread task on the page
       (~482ms) plus ~123 KB transferred (37.6 KB of it never even used).
       Now a plain pre-built stylesheet, same as any other CSS file — no JS
       execution needed at all. The theme (colors/fonts) that used to live in
       the inline `window.tailwindConfig` script now lives in
       tailwind.config.js — that file is the source of truth going forward.
       Rebuild after any class/theme change with:
         npx tailwindcss -i ./css/tailwind-input.css -o ./css/tailwind.css --minify
  -->
  <link rel="stylesheet" href="/css/tailwind.css?v=v3">
  <link rel="stylesheet" href="/css/dark-mode.css?v=1">
  <script>
    /* Apply saved theme before paint to avoid a light-mode flash */
    (function(){
      var t = localStorage.getItem('theme');
      if (t === 'dark' || (!t && window.matchMedia('(prefers-color-scheme: dark)').matches)) {
        document.documentElement.classList.add('dark');
      }
    })();
  </script>

  <style>
    /* ── Reset & Base ────────────────────────────── */
    *{margin:0;padding:0;box-sizing:border-box}
    html{scroll-behavior:smooth}
    body{
      font-family:'IBM Plex Sans Arabic','IBM Plex Sans',sans-serif;
      background:#F8FAFC;
      min-height:100vh;
      -webkit-font-smoothing:antialiased;
      color:#0F172A;
    }

    /* ── Page System ──────────────────────────────── */
    .page{display:none;opacity:0;transition:opacity .3s ease-in-out}
    .page.active{display:block;opacity:1;animation:fadeIn .4s ease-out}
    @keyframes fadeIn{from{opacity:0;transform:translateY(8px)}to{opacity:1;transform:translateY(0)}}

    /* ── Typography ─────────────────────────────── */
    [lang=en] body,[lang=en] .en-only{font-family:'IBM Plex Sans',sans-serif}
    .gradient-text{
      background:linear-gradient(135deg,#0F172A 0%,#0D9488 100%);
      -webkit-background-clip:text;-webkit-text-fill-color:transparent;background-clip:text
    }

    /* ── Buttons ─────────────────────────────────── */
    .btn-primary{
      background:#4F46E5;
      color:#fff;padding:12px 24px;border-radius:8px;font-weight:600;
      transition:all .2s ease;box-shadow:0 1px 3px rgba(15,23,42,.1);
      border:none;cursor:pointer;display:inline-flex;align-items:center;justify-content:center;gap:8px
    }
    .btn-primary:hover{background:#4338CA;box-shadow:0 4px 12px rgba(79,70,229,.25)}
    .btn-primary:active{transform:translateY(1px)}
    .btn-primary:disabled{opacity:.6;cursor:not-allowed;transform:none}

    .btn-secondary{
      background:#fff;color:#0F172A;padding:12px 24px;border-radius:8px;font-weight:600;
      transition:all .2s ease;border:1px solid #CBD5E1;cursor:pointer;
      display:inline-flex;align-items:center;justify-content:center;gap:8px
    }
    .btn-secondary:hover{background:#F1F5F9;border-color:#94A3B8}

    /* ── Forms ───────────────────────────────────── */
    .form-input{
      width:100%;padding:12px 16px;background:#fff;
      border:1px solid #CBD5E1;border-radius:8px;transition:all .2s ease;
      font-family:'IBM Plex Sans Arabic','IBM Plex Sans',sans-serif;font-size:15px;color:#0F172A
    }
    .form-input:focus{border-color:#4F46E5;outline:none;box-shadow:0 0 0 3px rgba(79,70,229,.12);background:#fff}
    .form-input::placeholder{color:#94A3B8}

    /* ── Cards ───────────────────────────────────── */
    .card{transition:all .25s ease;border:1px solid #E2E8F0}
    .card:hover{transform:translateY(-3px);box-shadow:0 10px 15px -3px rgba(15,23,42,.08),0 4px 6px -4px rgba(15,23,42,.04)}

    /* ── Glass ───────────────────────────────────── */
    .glass{background:rgba(248,250,252,.92);backdrop-filter:blur(12px);-webkit-backdrop-filter:blur(12px);border:1px solid #E2E8F0}

    /* ── Modal ───────────────────────────────────── */
    .modal{display:none;position:fixed;inset:0;background:rgba(0,0,0,.6);
      backdrop-filter:blur(8px);z-index:10000;align-items:center;justify-content:center;padding:20px;opacity:0;transition:opacity .3s ease}
    .modal.active{display:flex;opacity:1}
    .modal-content{background:#fff;border-radius:16px;max-width:600px;width:100%;max-height:90vh;
      overflow-y:auto;transform:scale(.9) translateY(20px);transition:transform .3s ease}
    .modal.active .modal-content{transform:scale(1) translateY(0)}

    /* ── Toast ───────────────────────────────────── */
    .toast{
      position:fixed;bottom:30px;left:50%;transform:translateX(-50%) translateY(100px);
      background:#0F172A;color:#fff;
      padding:14px 24px;border-radius:8px;z-index:100001;opacity:0;visibility:hidden;
      transition:all .3s cubic-bezier(.4,0,.2,1);box-shadow:0 20px 25px -5px rgba(15,23,42,.15);
      display:flex;align-items:center;gap:12px;min-width:280px;max-width:90vw;font-weight:600
    }
    .toast.show{opacity:1;visibility:visible;transform:translateX(-50%) translateY(0)}
    .toast.success{background:#0F766E}
    .toast.error{background:#EF4444}
    .toast.warning{background:#F59E0B}

    /* ── Status Badges (DESIGN.md state tokens) ──── */
    .status-badge{padding:5px 12px;border-radius:9999px;font-size:12px;font-weight:600;display:inline-block;white-space:nowrap;border:1px solid transparent}
    .status-pending{background:#FFFBEB;color:#B45309;border-color:#FDE68A}
    .status-in-progress{background:#EFF6FF;color:#1D4ED8;border-color:#BFDBFE}
    .status-delivered{background:#ECFDF5;color:#0F766E;border-color:#A7F3D0}
    .status-completed{background:#10B981;color:#fff}
    .status-cancelled{background:#FEF2F2;color:#B91C1C;border-color:#FECACA}
    .status-review{background:#EEF2FF;color:#3730A3;border-color:#C7D2FE}

    /* ── Chat Bubbles ────────────────────────────── */
    .chat-bubble{max-width:75%;padding:12px 16px;border-radius:14px;position:relative;word-break:normal;overflow-wrap:break-word;line-height:1.6}
    .chat-bubble.sent{background:#0F172A;color:#fff;border-bottom-left-radius:4px;box-shadow:0 2px 8px rgba(15,23,42,.2)}
    .chat-bubble.received{background:#F1F5F9;color:#0F172A;border-bottom-right-radius:4px;box-shadow:0 1px 4px rgba(0,0,0,.06)}

    /* ── Skeleton ────────────────────────────────── */
    .skeleton{background:linear-gradient(90deg,#f0f0f0 25%,#e8e8e8 50%,#f0f0f0 75%);background-size:200% 100%;animation:skeleton-loading 1.5s infinite;border-radius:8px}
    @keyframes skeleton-loading{0%{background-position:200% 0}100%{background-position:-200% 0}}

    /* ── Scrollbar ───────────────────────────────── */
    ::-webkit-scrollbar{width:6px;height:6px}
    ::-webkit-scrollbar-track{background:#f1f5f9;border-radius:10px}
    ::-webkit-scrollbar-thumb{background:linear-gradient(135deg,#0F172A,#0B1220);border-radius:10px}

    /* ── Tab System ──────────────────────────────── */
    .tab-btn{padding:10px 20px;border:none;background:none;cursor:pointer;font-family:'Cairo','Inter',sans-serif;font-weight:600;color:#6b7280;border-bottom:2px solid transparent;transition:all .2s ease}
    .tab-btn.active{color:#0F172A;border-bottom-color:#0F172A}

    /* ── Dropdown ────────────────────────────────── */
    .dropdown{display:none;position:absolute;background:#fff;border-radius:16px;box-shadow:0 20px 40px rgba(0,0,0,.15);z-index:1000;min-width:200px;overflow:hidden;border:1px solid #e5e7eb}
    .dropdown.active{display:block;animation:fadeIn .2s ease-out}
    .dropdown a,.dropdown button{display:block;width:100%;padding:12px 18px;text-align:right;color:#374151;text-decoration:none;transition:all .2s ease;border:none;background:none;cursor:pointer;font-family:'Cairo','Inter',sans-serif;font-size:14px}
    .dropdown a:hover,.dropdown button:hover{background:#f3f4f6;color:#0F172A}

    /* ── LTR overrides (English mode) ───────────────*/
    html[dir=ltr] .dropdown a,html[dir=ltr] .dropdown button{text-align:left}
    html[dir=ltr] .chat-bubble.sent{border-bottom-right-radius:4px;border-bottom-left-radius:18px}
    html[dir=ltr] .chat-bubble.received{border-bottom-left-radius:4px;border-bottom-right-radius:18px}

    /* ── Chat Enhancements ─────────────────────────── */
    .chat-messages-area{scroll-behavior:smooth}
    .chat-messages-area::-webkit-scrollbar{width:4px}
    .chat-messages-area::-webkit-scrollbar-track{background:transparent}
    .chat-messages-area::-webkit-scrollbar-thumb{background:#e5e7eb;border-radius:4px}
    .chat-text-input:focus{outline:none;border-color:#0F172A;box-shadow:0 0 0 3px rgba(2,132,199,.1)}
    .chat-send-btn:active{transform:scale(.92)}
    .chat-file-input{display:none !important}
    .emoji-quick{transition:transform .15s}
    .emoji-quick:hover{transform:scale(1.25)}

    /* ── Star Rating ─────────────────────────────── */
    .rating-stars{display:flex;gap:4px}
    .rating-stars i{color:#fbbf24}
    .rating-stars i.empty{color:#d1d5db}

    /* ── Nav ─────────────────────────────────────── */
    .nav-link{position:relative;transition:all .3s ease}
    .nav-link::after{content:'';position:absolute;bottom:-4px;right:0;width:0;height:3px;background:linear-gradient(135deg,#0F172A,#0D9488);border-radius:2px;transition:width .3s ease}
    html[dir=ltr] .nav-link::after{right:auto;left:0}
    .nav-link.active::after{width:100%}

    /* ── Image preview ───────────────────────────── */
    .image-upload-preview{width:100%;height:200px;object-fit:cover;border-radius:16px;margin-top:12px;display:none}
    .image-upload-preview.show{display:block;animation:fadeIn .3s ease-out}

    /* ── Payment Options ─────────────────────────── */
    .payment-option{transition:all .25s ease}
    .payment-option:hover{transform:translateX(-2px)}
    html[dir=ltr] .payment-option:hover{transform:translateX(2px)}

    /* ── Service Card ────────────────────────────── */
    .service-card{background:#fff;border-radius:20px;overflow:hidden;border:1px solid #e5e7eb;transition:all .3s ease}
    .service-card:hover{transform:translateY(-4px);box-shadow:0 16px 32px rgba(0,0,0,.1);border-color:#bae6fd}

    /* ── Order Card ──────────────────────────────── */
    .order-card{transition:all .3s ease}
    .order-card:hover{border-color:#7dd3fc}

    /* ── Notification badge ──────────────────────── */
    [data-cart-count],[data-notif-count]{
      background:#ef4444;color:#fff;border-radius:50%;width:18px;height:18px;
      font-size:11px;font-weight:800;display:flex;align-items:center;justify-content:center;
      position:absolute;top:-6px;right:-6px;animation:fadeIn .3s ease
    }
    html[dir=ltr] [data-cart-count],html[dir=ltr] [data-notif-count]{right:auto;left:-6px}

    /* ── App Loading Screen ──────────────────────── */
    #appLoadingScreen{
      position:fixed;inset:0;z-index:99999;
      background:linear-gradient(135deg,#0F172A 0%,#0B1220 100%);
      display:flex;flex-direction:column;align-items:center;justify-content:center;gap:20px;
      transition:opacity .5s ease;
    }
    #appLoadingScreen.fade-out{opacity:0;pointer-events:none}
    #appLoadingScreen .spinner{
      width:56px;height:56px;border:4px solid rgba(255,255,255,.3);
      border-top-color:#fff;border-radius:50%;animation:spin 1s linear infinite;
    }
    @keyframes spin{to{transform:rotate(360deg)}}

    /* ── Offline Banner ──────────────────────────── */
    #offlineBanner{
      position:fixed;bottom:0;left:0;right:0;z-index:9999;
      background:#ef4444;color:#fff;text-align:center;
      padding:12px;font-weight:700;font-size:14px;
      transform:translateY(100%);transition:transform .3s ease;
    }
    #offlineBanner.show{transform:translateY(0)}

    /* ── Skeleton ────────────────────────────────── */
    /* ⚠️ PERFORMANCE FIX: animating `background-position` forces the browser
       to repaint every frame (not GPU-composited) — flagged by GTmetrix as
       "non-composited animations" across every skeleton on the page. Same
       shimmer look, now done with `transform: translateX()` on an overlay
       pseudo-element instead, which the browser can composite on the GPU. */
    .skeleton{
      position:relative;
      overflow:hidden;
      background:#eef1f5;
      border-radius:8px;
    }
    .skeleton::after{
      content:'';
      position:absolute; inset:0;
      background:linear-gradient(90deg,transparent 0%,rgba(255,255,255,.6) 50%,transparent 100%);
      transform:translateX(-100%);
      animation:shimmer 1.5s infinite;
      will-change:transform;
    }
    @keyframes shimmer{100%{transform:translateX(100%)}}

    /* ── Terms Modal ─────────────────────────────── */
    #termsModal{
      position:fixed;inset:0;z-index:99998;
      background:rgba(0,0,0,.7);display:flex;align-items:center;justify-content:center;padding:16px;
    }
    #termsModal .terms-box{
      background:#fff;border-radius:24px;max-width:600px;width:100%;
      max-height:90vh;overflow-y:auto;box-shadow:0 24px 64px rgba(0,0,0,.3);
    }
  </style>
</head>
<body>

<!-- ── Signature seal glyph — reused everywhere escrow protection is shown ── -->
<svg width="0" height="0" style="position:absolute" aria-hidden="true">
  <symbol id="seal-icon" viewBox="0 0 64 64">
    <circle cx="32" cy="32" r="29" fill="none" stroke="currentColor" stroke-width="2.5"/>
    <circle cx="32" cy="32" r="23" fill="none" stroke="currentColor" stroke-width="1" stroke-dasharray="2 3"/>
    <path d="M20 33.5 L27.5 41 L45 22" fill="none" stroke="currentColor" stroke-width="3.5" stroke-linecap="round" stroke-linejoin="round"/>
  </symbol>
</svg>

<!-- ── App Loading Screen (shown until Firebase auth state resolves) ── -->
<div id="appLoadingScreen">
  <div style="width:110px;height:110px;border-radius:24px;background:rgba(255,255,255,.12);display:flex;align-items:center;justify-content:center;box-shadow:0 12px 40px rgba(0,0,0,.4);margin-bottom:4px;padding:16px">
    <img src="/icons/logo-mark.png" alt="مول الخدمات" style="width:100%;height:100%;object-fit:contain">
  </div>
  <div class="spinner"></div>
  <p style="color:#fff;font-size:18px;font-weight:900;letter-spacing:.5px">Services Mall</p>
  <p style="color:rgba(255,255,255,.7);font-size:13px;font-weight:600">خدماتك أونلاين</p>
</div>

<!-- ── Offline Banner ── -->
<div id="offlineBanner">
  <i class="fa-solid fa-wifi-slash me-2"></i>
  لا يوجد اتصال بالإنترنت — بعض الميزات قد لا تعمل
</div>


<!-- ══════════════════════════════════════════════════════════
     NAVBAR
══════════════════════════════════════════════════════════════ -->
<nav class="glass sticky top-0 z-50 border-b border-white/40 shadow-sm">
  <div class="max-w-7xl mx-auto px-4 py-3 flex items-center justify-between gap-4">

    <!-- Logo — new mark: the same "seal" glyph used for the escrow trust
         story throughout the app, now doubling as the logo (navy/turquoise) -->
    <button onclick="navigateTo('home')" class="flex items-center gap-2 flex-shrink-0">
      <div class="w-9 h-9 bg-navy-800 rounded-lg flex items-center justify-center shadow-sm p-1">
        <img src="/icons/logo-mark.png" alt="مول الخدمات" class="w-full h-full object-contain">
      </div>
      <span class="font-bold text-textprimary text-lg hidden sm:block" id="siteTitle">مول الخدمات</span>
    </button>

    <!-- Desktop Nav Links -->
    <div class="hidden md:flex items-center gap-1">
      <button onclick="navigateTo('home')"     data-nav="home"     class="nav-link px-3 py-2 text-sm font-semibold text-textsecondary hover:text-textprimary rounded-lg hover:bg-navy-50 transition" data-i18n="nav.home">الرئيسية</button>
      <button onclick="navigateTo('services')" data-nav="services" class="nav-link px-3 py-2 text-sm font-semibold text-textsecondary hover:text-textprimary rounded-lg hover:bg-navy-50 transition" data-i18n="nav.services">الخدمات</button>
      <button onclick="navigateTo('orders')"   data-nav="orders"   class="nav-link px-3 py-2 text-sm font-semibold text-textsecondary hover:text-textprimary rounded-lg hover:bg-navy-50 transition" data-i18n="nav.orders">طلباتي</button>
    </div>

    <!-- Right Controls -->
    <div class="flex items-center gap-2">

      <!-- Theme Toggle -->
      <button id="themeToggle" onclick="toggleTheme()" title="الوضع الداكن / الفاتح"
        class="w-11 h-11 flex items-center justify-center rounded-lg hover:bg-navy-50 text-textsecondary hover:text-textprimary transition">
        <i class="fa-solid fa-sun icon-sun"></i>
        <i class="fa-solid fa-moon icon-moon"></i>
      </button>

      <!-- Language Toggle -->
      <button id="langToggle" onclick="toggleLanguage()"
        class="hidden sm:flex items-center gap-1.5 px-3 py-2 text-xs font-semibold text-textsecondary bg-surfacecanvas border border-borderline rounded-lg hover:bg-navy-50 transition">
        🇬🇧 English
      </button>

      <!-- Currency -->
      <div class="relative hidden sm:block">
        <button id="currencyToggle" onclick="toggleCurrencyMenu()"
          class="flex items-center gap-1 px-3 py-2 text-xs font-mono font-semibold text-textsecondary bg-surfacecanvas border border-borderline rounded-lg hover:bg-navy-50 transition">
          EGP ج.م
        </button>
        <div id="currencyMenu" class="dropdown absolute top-full mt-1 end-0" style="min-width:150px">
          <button onclick="setCurrency('EGP');toggleCurrencyMenu()" class="text-start">🇪🇬 EGP — ج.م</button>
          <button onclick="setCurrency('USD');toggleCurrencyMenu()" class="text-start">🇺🇸 USD — $</button>
          <button onclick="setCurrency('EUR');toggleCurrencyMenu()" class="text-start">🇪🇺 EUR — €</button>
          <button onclick="setCurrency('GBP');toggleCurrencyMenu()" class="text-start">🇬🇧 GBP — £</button>
          <button onclick="setCurrency('SAR');toggleCurrencyMenu()" class="text-start">🇸🇦 SAR — ر.س</button>
          <button onclick="setCurrency('AED');toggleCurrencyMenu()" class="text-start">🇦🇪 AED — د.إ</button>
        </div>
      </div>

      <!-- Cart -->
      <button onclick="navigateTo('cart')" class="relative w-11 h-11 flex items-center justify-center rounded-lg hover:bg-navy-50 text-textsecondary hover:text-textprimary transition">
        <i class="fa-solid fa-cart-shopping"></i>
        <span data-cart-count class="hidden absolute top-2 end-2 bg-secondary text-white text-[10px] font-bold w-4 h-4 rounded-full flex items-center justify-center">0</span>
      </button>

      <!-- Notifications -->
      <button id="notifBtn" onclick="toggleNotifDropdown()" class="relative w-11 h-11 flex items-center justify-center rounded-lg hover:bg-navy-50 text-textsecondary hover:text-textprimary transition hidden">
        <i class="fa-solid fa-bell"></i>
        <span data-notif-count class="hidden">0</span>
      </button>

      <!-- User Menu -->
      <div id="guestButtons" class="flex items-center gap-2">
        <button onclick="navigateTo('login')"    class="btn-secondary text-sm px-4 py-2" data-i18n="nav.login">دخول</button>
        <button onclick="navigateTo('register')" class="btn-primary  text-sm px-4 py-2 hidden sm:flex" data-i18n="nav.register">تسجيل</button>
      </div>

      <div id="userMenuWrap" class="relative hidden">
        <button onclick="toggleUserMenu()" class="flex items-center gap-2 bg-navy-50 border border-borderline rounded-lg px-3 py-2 hover:bg-navy-100 transition">
          <img id="navAvatar" src="" class="w-7 h-7 rounded-full object-cover" alt="">
          <span id="navName" class="text-sm font-semibold text-textprimary hidden sm:block max-w-24 truncate"></span>
          <i class="fa-solid fa-chevron-down text-xs text-textmuted"></i>
        </button>
        <div id="userDropdown" class="dropdown absolute top-full mt-1 end-0 z-50" style="min-width:200px">
          <button onclick="navigateTo('dashboard');toggleUserMenu()" data-i18n="nav.dashboard">لوحة التحكم</button>
          <button onclick="navigateTo('profile');toggleUserMenu()"   data-i18n="nav.profile">الملف الشخصي</button>
          <button onclick="navigateTo('wallet');toggleUserMenu()"    data-i18n="nav.wallet">المحفظة</button>
          <button id="adminNavBtn" onclick="navigateTo('admin');toggleUserMenu()" class="hidden" data-i18n="nav.admin">الإدارة</button>
          <hr class="my-1 border-gray-100">
          <button onclick="AuthManager.logout();toggleUserMenu()" class="text-red-500 hover:bg-red-50" data-i18n="nav.logout">تسجيل الخروج</button>
        </div>
      </div>

      <!-- Mobile Menu Toggle -->
      <button onclick="toggleMobileMenu()" class="md:hidden p-2.5 bg-gray-100 rounded-xl text-gray-700">
        <i class="fa-solid fa-bars"></i>
      </button>
    </div>
  </div>

  <!-- Mobile Menu -->
  <div id="mobileMenu" class="hidden md:hidden border-t border-gray-100 px-4 pb-4 bg-white">
    <div class="grid grid-cols-2 gap-2 mt-3">
      <button onclick="navigateTo('home');toggleMobileMenu()"     class="flex items-center gap-2 p-3 bg-gray-50 rounded-xl text-sm font-bold text-gray-700"><i class="fa-solid fa-home text-navy-500"></i><span data-i18n="nav.home">الرئيسية</span></button>
      <button onclick="navigateTo('services');toggleMobileMenu()" class="flex items-center gap-2 p-3 bg-gray-50 rounded-xl text-sm font-bold text-gray-700"><i class="fa-solid fa-grid-2 text-navy-500"></i><span data-i18n="nav.services">الخدمات</span></button>
      <button onclick="navigateTo('orders');toggleMobileMenu()"   class="flex items-center gap-2 p-3 bg-gray-50 rounded-xl text-sm font-bold text-gray-700"><i class="fa-solid fa-bag-shopping text-navy-500"></i><span data-i18n="nav.orders">طلباتي</span></button>
      <button onclick="toggleLanguage()"                           class="flex items-center gap-2 p-3 bg-gray-50 rounded-xl text-sm font-bold text-gray-700"><i class="fa-solid fa-globe text-navy-500"></i><span id="mobileLanguageBtn">English</span></button>
    </div>
  </div>
</nav>

<!-- Notification Dropdown -->
<div id="notifDropdown" class="hidden fixed top-16 end-4 w-80 bg-white rounded-2xl shadow-2xl border border-gray-100 z-[9999] overflow-hidden">
  <div class="flex items-center justify-between px-4 py-3 border-b border-gray-100">
    <h3 class="font-black text-gray-900 text-sm" data-i18n="nav.notifications">الإشعارات</h3>
    <button onclick="markAllNotifsRead()" class="text-xs text-navy-600 font-bold">مقروء الكل</button>
  </div>
  <div id="notifList" class="max-h-80 overflow-y-auto divide-y divide-gray-50">
    <p class="text-center text-gray-400 text-sm py-8">لا توجد إشعارات</p>
  </div>
</div>


<!-- ══════════════════════════════════════════════════════════
     PAGES CONTAINER
══════════════════════════════════════════════════════════════ -->

<!-- ─── HOME ──────────────────────────────────────────────── -->
<div id="page-home" class="page">
  <!-- ══════════════════════════════════════════════════════════════════════
       HERO — dual segmented search (خدمات مخصصة / منتجات جاهزة) + live stats
       ══════════════════════════════════════════════════════════════════════ -->
  <section class="relative overflow-hidden rounded-3xl bg-white shadow-sm mt-6 mb-14 mx-auto max-w-7xl">
    <div class="absolute -top-24 -right-24 w-96 h-96 bg-secondary/10 rounded-full blur-3xl pointer-events-none"></div>
    <div class="absolute top-1/2 -left-20 w-80 h-80 bg-turquoise-500/10 rounded-full blur-3xl pointer-events-none"></div>
    <div class="relative px-6 py-14 md:py-20 grid md:grid-cols-2 gap-10 md:gap-14 items-center">

      <!-- Text + Dual Search -->
      <div class="text-center md:text-start">
        <div class="inline-flex items-center gap-2 bg-turquoise-50 text-turquoise-700 px-4 py-1.5 rounded-full mb-5">
          <i class="fa-solid fa-shield-halved text-sm"></i>
          <span class="text-xs font-bold">حماية 100% لأموالك بنظام الضمان Escrow</span>
        </div>
        <h1 class="font-sans font-black text-4xl md:text-5xl text-navy-900 mb-5 leading-tight" data-i18n="home.hero.title">
          سوق الخدمات الرقمية والمنتجات الجاهزة الموثوق
        </h1>
        <p class="text-lg text-navy-500 mb-8 max-w-xl mx-auto md:mx-0 leading-relaxed" data-i18n="home.hero.subtitle">
          اطلب خدمات مخصصة من خبراء معتمدين، أو حمّل منتجات رقمية جاهزة فورًا — فلوسك محجوزة عندنا لحد ما توافق إنك استلمت
        </p>

        <!-- Segment: Services vs Products -->
        <div class="bg-gray-50 p-1.5 rounded-2xl flex flex-col gap-2 max-w-xl mx-auto md:mx-0">
          <div class="flex items-center gap-1 p-1 bg-white rounded-xl w-fit mx-auto md:mx-0" id="heroTabGroup">
            <button type="button" id="heroTabServices" onclick="switchHeroSearch('services')"
              class="flex items-center gap-1.5 px-4 py-2 rounded-lg bg-navy-900 text-white text-sm font-bold transition">
              <i class="fa-solid fa-handshake text-sm"></i><span>خدمات مخصصة</span>
            </button>
            <button type="button" id="heroTabProducts" onclick="switchHeroSearch('products')"
              class="flex items-center gap-1.5 px-4 py-2 rounded-lg text-gray-500 hover:text-navy-900 text-sm font-bold transition">
              <i class="fa-solid fa-bolt text-sm"></i><span>منتجات جاهزة</span>
            </button>
          </div>

          <div class="bg-white shadow-sm rounded-xl p-1.5 flex items-center gap-1">
            <i class="fa-solid fa-magnifying-glass text-navy-300 ms-3 hidden sm:block"></i>
            <input type="text" id="heroSearchInput" class="flex-1 min-w-0 bg-transparent border-0 outline-none px-3 py-3 text-navy-900 placeholder:text-navy-300 text-sm"
              placeholder="ابحث عن برمجة متجر، تصميم هوية، قوالب Figma..." data-i18n="home.hero.searchPlaceholder"
              onkeypress="if(event.key==='Enter'){event.preventDefault();doHeroSearch();}">
            <button onclick="doHeroSearch()" class="bg-secondary hover:bg-secondary-600 text-white font-bold px-6 py-3 rounded-lg transition flex items-center justify-center gap-2 whitespace-nowrap flex-shrink-0">
              <span data-i18n="home.hero.searchBtn">ابحث الآن</span>
            </button>
          </div>

          <!-- Trending tag chips -->
          <div class="flex flex-wrap items-center gap-2 pt-1 px-1 justify-center md:justify-start">
            <span class="text-xs text-gray-400">الأكثر طلباً:</span>
            <button onclick="filterByCategory('programming')" class="bg-white hover:bg-gray-100 px-3 py-1 rounded-md text-xs font-bold text-navy-600 transition">برمجة تطبيقات</button>
            <button onclick="filterByCategory('design')" class="bg-white hover:bg-gray-100 px-3 py-1 rounded-md text-xs font-bold text-navy-600 transition">هويات بصرية</button>
            <button onclick="filterByType('product')" class="bg-white hover:bg-gray-100 px-3 py-1 rounded-md text-xs font-bold text-navy-600 transition">منتجات جاهزة</button>
            <button onclick="filterByCategory('marketing')" class="bg-white hover:bg-gray-100 px-3 py-1 rounded-md text-xs font-bold text-navy-600 transition">حملات إعلانية</button>
          </div>
        </div>

        <button onclick="navigateTo('register')" class="inline-flex items-center gap-3 bg-turquoise-500 text-white font-black px-7 py-3.5 rounded-2xl hover:bg-turquoise-600 transition mt-8">
          <i class="fa-solid fa-rocket"></i><span data-i18n="home.hero.sell">ابدأ البيع</span>
        </button>

        <!-- Live stats — real counts, loaded by loadHomeStats() -->
        <div class="grid grid-cols-3 gap-4 mt-10 pt-8 border-t border-gray-100 max-w-md mx-auto md:mx-0">
          <div>
            <p class="text-xl md:text-2xl font-black text-navy-900" id="statServices">—</p>
            <p class="text-gray-400 text-xs mt-1" data-i18n="home.stats.services">خدمة نشطة</p>
          </div>
          <div>
            <p class="text-xl md:text-2xl font-black text-turquoise-600" id="statOrders">—</p>
            <p class="text-gray-400 text-xs mt-1" data-i18n="home.stats.orders">طلب مكتمل</p>
          </div>
          <div>
            <p class="text-xl md:text-2xl font-black text-secondary"><span id="statRating">—</span> <i class="fa-solid fa-star text-yellow-400 text-sm align-middle"></i></p>
            <p class="text-gray-400 text-xs mt-1" data-i18n="home.stats.rating">تقييم المستخدمين</p>
          </div>
        </div>
      </div>

      <!-- Visual side panel -->
      <div class="relative hidden md:flex items-center justify-center">
        <div class="w-72 h-72 lg:w-80 lg:h-80 bg-turquoise-50 rounded-full flex items-center justify-center relative">
          <i class="fa-solid fa-shield-halved text-navy-900" style="font-size:88px"></i>
          <div class="absolute top-2 end-6 w-14 h-14 bg-white rounded-2xl shadow-lg border border-gray-100 flex items-center justify-center">
            <i class="fa-solid fa-code text-turquoise-600 text-xl"></i>
          </div>
          <div class="absolute bottom-4 start-2 w-14 h-14 bg-white rounded-2xl shadow-lg border border-gray-100 flex items-center justify-center">
            <i class="fa-solid fa-cloud-arrow-down text-turquoise-600 text-xl"></i>
          </div>
          <div class="absolute top-1/3 -start-6 w-12 h-12 bg-white rounded-2xl shadow-lg border border-gray-100 flex items-center justify-center">
            <i class="fa-solid fa-headset text-navy-800 text-lg"></i>
          </div>
        </div>
        <div class="absolute -bottom-4 -start-6 bg-white rounded-2xl shadow-xl border border-navy-50 p-4 flex items-center gap-3 max-w-[230px]">
          <div class="w-11 h-11 bg-navy-50 rounded-xl flex items-center justify-center flex-shrink-0">
            <svg class="w-6 h-6 text-navy-700"><use href="#seal-icon"/></svg>
          </div>
          <div>
            <p class="font-black text-navy-900 text-sm">فلوسك في أمان</p>
            <p class="text-navy-400 text-xs mt-0.5">محجوزة لحد ما توافق</p>
          </div>
        </div>
        <div class="absolute -top-5 -end-5 bg-white rounded-2xl shadow-xl border border-navy-50 px-4 py-3 flex items-center gap-2">
          <i class="fa-solid fa-bolt text-turquoise-500 text-lg"></i>
          <span class="font-black text-navy-900 text-sm">تسليم فوري</span>
        </div>
      </div>
    </div>
  </section>

  <!-- ══════════════════════════════════════════════════════════════════════
       VALUE PROPS — 4 trust cards
       ══════════════════════════════════════════════════════════════════════ -->
  <section class="py-4 px-4 max-w-7xl mx-auto mb-14">
    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-5">
      <div class="bg-white p-6 rounded-2xl shadow-sm border border-gray-100 flex flex-col gap-3 hover:shadow-md transition">
        <div class="w-12 h-12 rounded-xl bg-turquoise-50 text-turquoise-600 flex items-center justify-center"><i class="fa-solid fa-shield-halved text-xl"></i></div>
        <h3 class="font-black text-navy-900">حماية بنظام Escrow</h3>
        <p class="text-sm text-gray-500 leading-relaxed">نحتفظ بقيمة الطلب في خزينة ضمان آمنة، ولا يتم تحويل المستحقات للبائع إلا بعد استلامك الخدمة وموافقتك.</p>
      </div>
      <div class="bg-white p-6 rounded-2xl shadow-sm border border-gray-100 flex flex-col gap-3 hover:shadow-md transition">
        <div class="w-12 h-12 rounded-xl bg-secondary/10 text-secondary flex items-center justify-center"><i class="fa-solid fa-bolt text-xl"></i></div>
        <h3 class="font-black text-navy-900">تحميل المنتجات فوري</h3>
        <p class="text-sm text-gray-500 leading-relaxed">القوالب والأكواد والأصول الرقمية الجاهزة تصبح متاحة للتحميل المباشر فور تأكيد الدفع.</p>
      </div>
      <div class="bg-white p-6 rounded-2xl shadow-sm border border-gray-100 flex flex-col gap-3 hover:shadow-md transition">
        <div class="w-12 h-12 rounded-xl bg-navy-50 text-navy-700 flex items-center justify-center"><i class="fa-solid fa-id-badge text-xl"></i></div>
        <h3 class="font-black text-navy-900">بائعون حقيقيون</h3>
        <p class="text-sm text-gray-500 leading-relaxed">كل بائع بيسجل حساب موثّق ومربوط بتقييمات حقيقية من عملاء فعليين على المنصة.</p>
      </div>
      <div class="bg-white p-6 rounded-2xl shadow-sm border border-gray-100 flex flex-col gap-3 hover:shadow-md transition">
        <div class="w-12 h-12 rounded-xl bg-amber-50 text-amber-600 flex items-center justify-center"><i class="fa-solid fa-wallet text-xl"></i></div>
        <h3 class="font-black text-navy-900">وسائل دفع آمنة</h3>
        <p class="text-sm text-gray-500 leading-relaxed">ادفع عبر فواتيرك بالبطاقات البنكية، فودافون كاش، وباقي المحافظ الإلكترونية من صفحة واحدة.</p>
      </div>
    </div>
  </section>

  <!-- ══════════════════════════════════════════════════════════════════════
       DUAL CATEGORY BROWSE — services categories | product categories
       ══════════════════════════════════════════════════════════════════════ -->
  <section class="py-4 px-4 max-w-7xl mx-auto mb-14">
    <div class="text-center mb-8">
      <span class="text-secondary text-sm font-bold">مسارات السوق المتكاملة</span>
      <h2 class="font-sans font-black text-3xl text-gray-900 mt-1">استكشف حسب نوع احتياجك</h2>
    </div>
    <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
      <!-- Services categories -->
      <div class="bg-white rounded-2xl p-6 shadow-sm border border-gray-100">
        <div class="flex items-center justify-between mb-5">
          <div class="flex items-center gap-2"><span class="w-2.5 h-2.5 rounded-full bg-secondary"></span><h3 class="font-black text-navy-900">خدمات مخصصة حسب الطلب</h3></div>
          <span class="text-xs font-bold bg-gray-50 text-gray-500 px-2.5 py-1 rounded-md">تنفيذ حسب الطلب</span>
        </div>
        <div class="grid grid-cols-2 sm:grid-cols-3 gap-3">
          <button onclick="filterByCategory('programming')" class="p-3 rounded-xl hover:bg-gray-50 transition flex flex-col items-start gap-1.5 text-start"><i class="fa-solid fa-code text-secondary text-xl"></i><span class="text-sm font-bold text-navy-900">برمجة ومواقع</span></button>
          <button onclick="filterByCategory('design')" class="p-3 rounded-xl hover:bg-gray-50 transition flex flex-col items-start gap-1.5 text-start"><i class="fa-solid fa-palette text-secondary text-xl"></i><span class="text-sm font-bold text-navy-900">تصميم وهوية</span></button>
          <button onclick="filterByCategory('marketing')" class="p-3 rounded-xl hover:bg-gray-50 transition flex flex-col items-start gap-1.5 text-start"><i class="fa-solid fa-bullhorn text-secondary text-xl"></i><span class="text-sm font-bold text-navy-900">تسويق وإعلانات</span></button>
          <button onclick="filterByCategory('writing')" class="p-3 rounded-xl hover:bg-gray-50 transition flex flex-col items-start gap-1.5 text-start"><i class="fa-solid fa-pen-fancy text-secondary text-xl"></i><span class="text-sm font-bold text-navy-900">كتابة وترجمة</span></button>
          <button onclick="filterByCategory('video')" class="p-3 rounded-xl hover:bg-gray-50 transition flex flex-col items-start gap-1.5 text-start"><i class="fa-solid fa-video text-secondary text-xl"></i><span class="text-sm font-bold text-navy-900">فيديو وأنيميشن</span></button>
          <button onclick="filterByCategory('seo')" class="p-3 rounded-xl hover:bg-gray-50 transition flex flex-col items-start gap-1.5 text-start"><i class="fa-solid fa-magnifying-glass-chart text-secondary text-xl"></i><span class="text-sm font-bold text-navy-900">SEO واستشارات</span></button>
        </div>
      </div>
      <!-- Products categories -->
      <div class="bg-white rounded-2xl p-6 shadow-sm border border-gray-100">
        <div class="flex items-center justify-between mb-5">
          <div class="flex items-center gap-2"><span class="w-2.5 h-2.5 rounded-full bg-turquoise-500"></span><h3 class="font-black text-navy-900">منتجات جاهزة (تحميل فوري)</h3></div>
          <span class="text-xs font-bold bg-turquoise-50 text-turquoise-700 px-2.5 py-1 rounded-md">تحميل بنقرة واحدة</span>
        </div>
        <div class="grid grid-cols-2 sm:grid-cols-3 gap-3">
          <button onclick="filterByTypeAndCategory('product','programming')" class="p-3 rounded-xl hover:bg-gray-50 transition flex flex-col items-start gap-1.5 text-start"><i class="fa-solid fa-window-restore text-turquoise-600 text-xl"></i><span class="text-sm font-bold text-navy-900">قوالب SaaS و UI</span></button>
          <button onclick="filterByTypeAndCategory('product','programming')" class="p-3 rounded-xl hover:bg-gray-50 transition flex flex-col items-start gap-1.5 text-start"><i class="fa-solid fa-terminal text-turquoise-600 text-xl"></i><span class="text-sm font-bold text-navy-900">سكريبتات برمجية</span></button>
          <button onclick="filterByType('product')" class="p-3 rounded-xl hover:bg-gray-50 transition flex flex-col items-start gap-1.5 text-start"><i class="fa-solid fa-puzzle-piece text-turquoise-600 text-xl"></i><span class="text-sm font-bold text-navy-900">إضافات متاجر</span></button>
          <button onclick="filterByTypeAndCategory('product','design')" class="p-3 rounded-xl hover:bg-gray-50 transition flex flex-col items-start gap-1.5 text-start"><i class="fa-solid fa-images text-turquoise-600 text-xl"></i><span class="text-sm font-bold text-navy-900">قوالب سوشيال ميديا</span></button>
          <button onclick="filterByType('product')" class="p-3 rounded-xl hover:bg-gray-50 transition flex flex-col items-start gap-1.5 text-start"><i class="fa-solid fa-cube text-turquoise-600 text-xl"></i><span class="text-sm font-bold text-navy-900">ملفات 3D وموك أب</span></button>
          <button onclick="filterByType('product')" class="p-3 rounded-xl hover:bg-gray-50 transition flex flex-col items-start gap-1.5 text-start"><i class="fa-solid fa-robot text-turquoise-600 text-xl"></i><span class="text-sm font-bold text-navy-900">أدوات وبوتات AI</span></button>
        </div>
      </div>
    </div>
  </section>

  <!-- ══════════════════════════════════════════════════════════════════════
       DIGITAL PRODUCTS SPOTLIGHT — real data
       ══════════════════════════════════════════════════════════════════════ -->
  <section class="py-4 px-4 max-w-7xl mx-auto mb-14">
    <div class="flex items-center justify-between mb-6 flex-wrap gap-3">
      <div>
        <span class="inline-flex items-center gap-1.5 bg-turquoise-50 text-turquoise-700 text-xs font-bold px-3 py-1 rounded-full mb-2"><i class="fa-solid fa-bolt"></i> تسليم وتنزيل فوري تلقائي</span>
        <h2 class="font-sans font-black text-2xl md:text-3xl text-gray-900">المنتجات الرقمية الجاهزة الأكثر مبيعاً</h2>
      </div>
      <button onclick="filterByType('product')" class="text-navy-700 font-bold flex items-center gap-2 hover:gap-3 transition-all text-sm">
        <span>عرض كل المنتجات</span><i class="fa-solid fa-arrow-left"></i>
      </button>
    </div>
    <div id="homeProductsGrid" class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-6">
      <div class="service-card"><div class="skeleton h-40 w-full"></div><div class="p-4 space-y-3"><div class="skeleton h-4 w-3/4 rounded"></div><div class="skeleton h-3 w-1/2 rounded"></div><div class="skeleton h-8 w-full rounded-xl"></div></div></div>
      <div class="service-card"><div class="skeleton h-40 w-full"></div><div class="p-4 space-y-3"><div class="skeleton h-4 w-3/4 rounded"></div><div class="skeleton h-3 w-1/2 rounded"></div><div class="skeleton h-8 w-full rounded-xl"></div></div></div>
      <div class="service-card"><div class="skeleton h-40 w-full"></div><div class="p-4 space-y-3"><div class="skeleton h-4 w-3/4 rounded"></div><div class="skeleton h-3 w-1/2 rounded"></div><div class="skeleton h-8 w-full rounded-xl"></div></div></div>
      <div class="service-card"><div class="skeleton h-40 w-full"></div><div class="p-4 space-y-3"><div class="skeleton h-4 w-3/4 rounded"></div><div class="skeleton h-3 w-1/2 rounded"></div><div class="skeleton h-8 w-full rounded-xl"></div></div></div>
    </div>
  </section>

  <!-- ══════════════════════════════════════════════════════════════════════
       CUSTOM SERVICES SPOTLIGHT — real data (reuses loadFeaturedServices)
       ══════════════════════════════════════════════════════════════════════ -->
  <section class="py-4 px-4 max-w-7xl mx-auto mb-14">
    <div class="flex items-center justify-between mb-6 flex-wrap gap-3">
      <div>
        <span class="inline-flex items-center gap-1.5 bg-secondary/10 text-secondary text-xs font-bold px-3 py-1 rounded-full mb-2"><i class="fa-solid fa-gavel"></i> تنفيذ مخصص محمي بنظام Escrow</span>
        <h2 class="font-sans font-black text-2xl md:text-3xl text-gray-900" data-i18n="home.featured">خدمات احترافية حسب متطلبات مشروعك</h2>
      </div>
      <button onclick="navigateTo('services')" class="text-navy-700 font-bold flex items-center gap-2 hover:gap-3 transition-all text-sm">
        <span>عرض كل الخدمات</span><i class="fa-solid fa-arrow-left"></i>
      </button>
    </div>
    <div id="featuredServices" class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6">
      <div class="service-card"><div class="skeleton h-48 w-full"></div><div class="p-4 space-y-3"><div class="skeleton h-4 w-3/4 rounded"></div><div class="skeleton h-3 w-1/2 rounded"></div><div class="skeleton h-8 w-full rounded-xl"></div></div></div>
      <div class="service-card"><div class="skeleton h-48 w-full"></div><div class="p-4 space-y-3"><div class="skeleton h-4 w-3/4 rounded"></div><div class="skeleton h-3 w-1/2 rounded"></div><div class="skeleton h-8 w-full rounded-xl"></div></div></div>
      <div class="service-card"><div class="skeleton h-48 w-full"></div><div class="p-4 space-y-3"><div class="skeleton h-4 w-3/4 rounded"></div><div class="skeleton h-3 w-1/2 rounded"></div><div class="skeleton h-8 w-full rounded-xl"></div></div></div>
    </div>
  </section>

  <!-- ══════════════════════════════════════════════════════════════════════
       HOW IT WORKS — 2-column comparison (escrow flow vs instant delivery)
       ══════════════════════════════════════════════════════════════════════ -->
  <section class="py-4 px-4 max-w-7xl mx-auto mb-14">
    <div class="bg-white rounded-3xl p-6 md:p-10 shadow-sm border border-gray-100">
      <div class="text-center max-w-2xl mx-auto mb-10">
        <span class="inline-block bg-turquoise-50 text-turquoise-700 text-xs font-bold px-3 py-1 rounded-full mb-3">الأمان والشفافية أولاً</span>
        <h2 class="font-sans font-black text-2xl md:text-3xl text-gray-900 mb-3">كيف يضمن مول الخدمات حقك كاملاً؟</h2>
        <p class="text-gray-500 text-sm">مساران ماليان واضحان مصممان لحماية أموالك سواء طلبت عملاً مخصصاً أو اشتريت منتجاً رقمياً فورياً.</p>
      </div>
      <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
        <div class="bg-gray-50 rounded-2xl p-6">
          <div class="flex items-center gap-3 mb-6 pb-4 border-b border-gray-200">
            <div class="w-10 h-10 rounded-xl bg-secondary text-white flex items-center justify-center font-black">1</div>
            <div><h3 class="font-black text-navy-900">الخدمات المخصصة (ضمان Escrow)</h3><p class="text-xs text-gray-400">للأعمال اللي محتاجة وقت تنفيذ وتطوير</p></div>
          </div>
          <div class="space-y-4">
            <div class="flex gap-3"><span class="w-7 h-7 rounded-full bg-white shadow-sm text-secondary flex items-center justify-center font-mono text-xs font-bold flex-shrink-0">1</span><div><p class="font-bold text-navy-900 text-sm">إيداع المبلغ في حساب الضمان</p><p class="text-xs text-gray-500 mt-0.5">تدفع بأمان وفلوسك تفضل محجوزة عندنا، مش عند البائع.</p></div></div>
            <div class="flex gap-3"><span class="w-7 h-7 rounded-full bg-white shadow-sm text-secondary flex items-center justify-center font-mono text-xs font-bold flex-shrink-0">2</span><div><p class="font-bold text-navy-900 text-sm">بدء التنفيذ والمتابعة اللحظية</p><p class="text-xs text-gray-500 mt-0.5">تابع التقدم أول بأول في مساحة عمل فيها شات وملفات موثّقة.</p></div></div>
            <div class="flex gap-3"><span class="w-7 h-7 rounded-full bg-white shadow-sm text-secondary flex items-center justify-center font-mono text-xs font-bold flex-shrink-0">3</span><div><p class="font-bold text-navy-900 text-sm">المعاينة والموافقة على الاستلام</p><p class="text-xs text-gray-500 mt-0.5">تراجع الشغل وتطلب تعديل لو محتاج، وبعد موافقتك بس تتحول الفلوس للبائع.</p></div></div>
          </div>
        </div>
        <div class="bg-gray-50 rounded-2xl p-6">
          <div class="flex items-center gap-3 mb-6 pb-4 border-b border-gray-200">
            <div class="w-10 h-10 rounded-xl bg-turquoise-500 text-white flex items-center justify-center font-black">2</div>
            <div><h3 class="font-black text-navy-900">المنتجات الرقمية (تسليم فوري)</h3><p class="text-xs text-gray-400">للقوالب والأكواد والملفات الجاهزة</p></div>
          </div>
          <div class="space-y-4">
            <div class="flex gap-3"><span class="w-7 h-7 rounded-full bg-white shadow-sm text-turquoise-600 flex items-center justify-center font-mono text-xs font-bold flex-shrink-0">1</span><div><p class="font-bold text-navy-900 text-sm">الدفع الإلكتروني الفوري</p><p class="text-xs text-gray-500 mt-0.5">سداد آمن خلال ثوانٍ عبر البطاقات، المحافظ الإلكترونية، أو فواتيرك.</p></div></div>
            <div class="flex gap-3"><span class="w-7 h-7 rounded-full bg-white shadow-sm text-turquoise-600 flex items-center justify-center font-mono text-xs font-bold flex-shrink-0">2</span><div><p class="font-bold text-navy-900 text-sm">رابط تنزيل مباشر فورًا</p><p class="text-xs text-gray-500 mt-0.5">فور تأكيد الدفع، رابط التحميل بيظهرلك على الشاشة على طول.</p></div></div>
            <div class="flex gap-3"><span class="w-7 h-7 rounded-full bg-white shadow-sm text-turquoise-600 flex items-center justify-center font-mono text-xs font-bold flex-shrink-0">3</span><div><p class="font-bold text-navy-900 text-sm">وصول دائم لملفاتك</p><p class="text-xs text-gray-500 mt-0.5">تلاقي كل مشترياتك محفوظة في حسابك، تقدر تنزلها تاني في أي وقت.</p></div></div>
          </div>
        </div>
      </div>
    </div>
  </section>

  <!-- ── Blog Teaser Section (Dynamic from Firestore) ─────────────────────── -->
  <section class="py-14 px-4 bg-gray-50 -mx-4">
    <div class="max-w-7xl mx-auto">
      <div class="flex items-center justify-between mb-8 flex-wrap gap-4">
        <div>
          <div class="inline-flex items-center gap-2 bg-purple-100 text-purple-700 px-3 py-1 rounded-full text-xs font-bold mb-2">
            <i class="fa-solid fa-robot text-xs"></i> يُنشر تلقائياً بالذكاء الاصطناعي
          </div>
          <h2 class="text-3xl font-black text-gray-900">من مدونتنا</h2>
          <p class="text-gray-500 mt-1 text-sm">مقالات SEO يومية — موضوعات الأعمال الرقمية في مصر</p>
        </div>
        <a href="/blog" class="text-navy-700 font-bold flex items-center gap-2 hover:gap-3 transition-all text-sm border border-navy-200 px-4 py-2 rounded-xl hover:bg-navy-50">
          <span>عرض جميع المقالات</span><i class="fa-solid fa-arrow-left"></i>
        </a>
      </div>
      <div id="home-blog-grid" style="display:grid;grid-template-columns:repeat(auto-fill,minmax(300px,1fr));gap:22px">
        <div class="skeleton" style="border-radius:18px;height:280px"></div>
        <div class="skeleton" style="border-radius:18px;height:280px"></div>
        <div class="skeleton" style="border-radius:18px;height:280px"></div>
      </div>
    </div>
  </section>

  <!-- ── Newsletter Section ─────────────────────────────────────────────── -->
  <section class="py-16 px-4 -mx-4" style="background:linear-gradient(135deg,#131B2E,#0B1220)">
    <div class="max-w-2xl mx-auto text-center">
      <div class="inline-flex items-center gap-2 bg-white/15 text-white px-4 py-2 rounded-full text-sm font-bold mb-6 border border-white/20">
        <i class="fa-solid fa-envelope-open-text text-yellow-300"></i>
        النشرة البريدية
      </div>
      <h2 class="text-3xl font-black text-white mb-4">لا تفوّت أي جديد</h2>
      <p class="text-blue-100 mb-8 text-base">اشترك ليصلك مقال SEO جديد كل يوم — مجاناً</p>
      <div class="flex gap-3 max-w-md mx-auto flex-wrap justify-center">
        <input type="email" id="homeNewsletterEmail" placeholder="بريدك الإلكتروني"
          class="flex-1 min-w-0 px-5 py-3 rounded-xl text-gray-900 font-medium outline-none text-sm"
          style="min-width:200px"
          onkeypress="if(event.key==='Enter')homeSubscribe()">
        <button onclick="homeSubscribe()"
          class="bg-white text-navy-800 font-black px-6 py-3 rounded-xl hover:bg-turquoise-50 transition whitespace-nowrap text-sm flex items-center gap-2">
          <i class="fa-solid fa-paper-plane"></i> اشتراك مجاني
        </button>
      </div>
      <p id="homeNewsletterMsg" class="text-sm mt-4 font-bold text-green-300" style="display:none"></p>
      <p class="text-blue-200 text-xs mt-4">بلا رسائل مزعجة — يمكنك إلغاء الاشتراك في أي وقت</p>
    </div>
  </section>

  <!-- ── Footer ───────────────────────────────────────────────────────────── -->
  <footer style="background:#0B1220" class="py-14 px-4 -mx-4">
    <div class="max-w-6xl mx-auto">
      <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-10 pb-10 border-b border-white/10">
        <div class="lg:col-span-2">
          <p class="text-white font-black text-lg mb-3">مول الخدمات</p>
          <p class="text-navy-200/70 text-sm leading-relaxed max-w-sm mb-4">المنصة الموثوقة للخدمات الرقمية والمنتجات الجاهزة، بنظام ضمان مالي (Escrow) يحمي حقوق البائع والمشتري في كل عملية.</p>
          <div class="inline-flex items-center gap-2 bg-turquoise-500/10 text-turquoise-400 px-3 py-1.5 rounded-lg text-xs font-bold">
            <i class="fa-solid fa-shield-halved"></i> معاملات محمية بالكامل
          </div>
        </div>
        <div>
          <h4 class="text-white font-bold text-sm mb-3">روابط سريعة</h4>
          <ul class="space-y-2 text-sm text-navy-200/70">
            <li><a href="/" class="hover:text-white transition">الرئيسية</a></li>
            <li><a href="/blog" class="hover:text-white transition">المدونة</a></li>
            <li><a href="/about" class="hover:text-white transition">من نحن</a></li>
            <li><a href="/contact" class="hover:text-white transition">تواصل معنا</a></li>
          </ul>
        </div>
        <div>
          <h4 class="text-white font-bold text-sm mb-3">الضمان والدعم</h4>
          <ul class="space-y-2 text-sm text-navy-200/70">
            <li><a href="/terms" target="_blank" class="hover:text-white transition">الشروط والأحكام</a></li>
            <li><a href="/privacy" target="_blank" class="hover:text-white transition">سياسة الخصوصية</a></li>
            <li><a href="/refund-policy.html" target="_blank" class="hover:text-white transition">سياسة الاسترجاع</a></li>
            <li><a href="mailto:support@mall-services.com" class="hover:text-white transition">الدعم الفني</a></li>
          </ul>
        </div>
      </div>
      <div class="pt-6 flex flex-col md:flex-row items-center justify-between gap-4">
        <p class="text-navy-200/60 text-xs">© 2026 مول الخدمات. جميع الحقوق محفوظة</p>
        <div class="flex items-center gap-4 text-xs text-navy-200/60">
          <span class="flex items-center gap-1.5"><i class="fa-solid fa-lock text-turquoise-400"></i> دفع آمن 100%</span>
          <span class="flex items-center gap-1.5"><i class="fa-solid fa-star text-yellow-400"></i> تقييم 4.9/5</span>
        </div>
      </div>
    </div>
  </footer>

</div>

<!-- ─── SERVICES ───────────────────────────────────────────── -->
<div id="page-services" class="page">
  <div class="max-w-7xl mx-auto px-4 py-8">
    <!-- Header & Search -->
    <div class="flex flex-wrap gap-4 items-center justify-between mb-8">
      <h1 class="text-3xl font-black text-gray-900" data-i18n="services.title">الخدمات</h1>
      <div class="flex gap-3 flex-1 max-w-xl">
        <div class="relative flex-1">
          <i class="fa-solid fa-search absolute top-1/2 -translate-y-1/2 start-4 text-gray-400"></i>
          <input type="text" id="servicesSearch" class="form-input ps-11 pe-4"
            placeholder="ابحث عن خدمة..." data-i18n="services.search"
            oninput="ServicesManager.search(this.value)">
        </div>
        <select id="servicesSort" class="form-input w-auto min-w-36" onchange="ServicesManager.sort(this.value)">
          <option value="newest">الأحدث</option>
          <option value="price_asc">السعر: الأقل</option>
          <option value="price_desc">السعر: الأعلى</option>
          <option value="rating">التقييم</option>
          <option value="quality">الأعلى جودة</option>
        </select>
      </div>
    </div>

    <!-- ⚠️ ADDED: services vs products split — the two-section request -->
    <div class="flex gap-2 mb-4 bg-gray-100 p-1.5 rounded-2xl w-fit">
      <button onclick="ServicesManager.filterType('')" data-type="" class="type-tab-btn px-5 py-2 rounded-xl text-sm font-bold transition bg-navy-800 text-white">الكل</button>
      <button onclick="ServicesManager.filterType('service')" data-type="service" class="type-tab-btn px-5 py-2 rounded-xl text-sm font-bold transition bg-gray-100 text-gray-600"><i class="fa-solid fa-toolbox me-1.5"></i>خدمات</button>
      <button onclick="ServicesManager.filterType('product')" data-type="product" class="type-tab-btn px-5 py-2 rounded-xl text-sm font-bold transition bg-gray-100 text-gray-600"><i class="fa-solid fa-box me-1.5"></i>منتجات</button>
    </div>

    <!-- Category Pills -->
    <div class="flex gap-2 overflow-x-auto pb-2 mb-3">
      <button onclick="ServicesManager.filterCategory('')" data-cat="" class="cat-btn flex-shrink-0 px-4 py-2 bg-navy-600 text-white rounded-xl text-sm font-bold transition" data-i18n="general.all">الكل</button>
      <button onclick="ServicesManager.filterCategory('design')"      data-cat="design"      class="cat-btn flex-shrink-0 px-4 py-2 bg-white text-gray-600 border border-gray-200 rounded-xl text-sm font-bold hover:border-navy-400 transition"><i class="fa-solid fa-palette me-1.5"></i>تصميم</button>
      <button onclick="ServicesManager.filterCategory('programming')" data-cat="programming" class="cat-btn flex-shrink-0 px-4 py-2 bg-white text-gray-600 border border-gray-200 rounded-xl text-sm font-bold hover:border-navy-400 transition"><i class="fa-solid fa-laptop-code me-1.5"></i>برمجة</button>
      <button onclick="ServicesManager.filterCategory('marketing')"   data-cat="marketing"   class="cat-btn flex-shrink-0 px-4 py-2 bg-white text-gray-600 border border-gray-200 rounded-xl text-sm font-bold hover:border-navy-400 transition"><i class="fa-solid fa-chart-line me-1.5"></i>تسويق</button>
      <button onclick="ServicesManager.filterCategory('writing')"     data-cat="writing"     class="cat-btn flex-shrink-0 px-4 py-2 bg-white text-gray-600 border border-gray-200 rounded-xl text-sm font-bold hover:border-navy-400 transition"><i class="fa-solid fa-pen-nib me-1.5"></i>كتابة</button>
      <button onclick="ServicesManager.filterCategory('video')"       data-cat="video"       class="cat-btn flex-shrink-0 px-4 py-2 bg-white text-gray-600 border border-gray-200 rounded-xl text-sm font-bold hover:border-navy-400 transition"><i class="fa-solid fa-video me-1.5"></i>فيديو</button>
      <button onclick="ServicesManager.filterCategory('seo')"         data-cat="seo"         class="cat-btn flex-shrink-0 px-4 py-2 bg-white text-gray-600 border border-gray-200 rounded-xl text-sm font-bold hover:border-navy-400 transition"><i class="fa-solid fa-magnifying-glass-chart me-1.5"></i>SEO</button>
    </div>

    <!-- Express Delivery Hub — services delivered in 24h or less -->
    <div class="mb-6">
      <button onclick="ServicesManager.toggleExpress()" id="expressToggleBtn"
        class="flex items-center gap-2 px-4 py-2 bg-orange-50 border border-orange-200 text-orange-700 rounded-xl text-sm font-bold hover:bg-orange-100 transition">
        <i class="fa-solid fa-bolt"></i>
        <span>خدمات سريعة — تسليم خلال 24 ساعة</span>
      </button>
    </div>

    <div id="servicesGrid" class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6"></div>
    <div id="servicesEmpty" class="hidden text-center py-20">
      <i class="fa-solid fa-search text-gray-300 text-5xl mb-4"></i>
      <p class="text-gray-400 font-bold text-xl">لا توجد خدمات</p>
    </div>
  </div>
</div>

<!-- ─── CART (rendered dynamically, hidden until populated) ─── -->
<div id="page-cart" class="page">
  <div class="max-w-5xl mx-auto px-4 py-10">
    <h1 class="text-2xl font-black text-gray-900 mb-8 flex items-center gap-3">
      <i class="fa-solid fa-cart-shopping text-navy-700"></i>
      <span data-i18n="cart.title">سلة الشراء</span>
    </h1>

    <div class="grid md:grid-cols-3 gap-8">
      <!-- Items -->
      <div class="md:col-span-2 space-y-3">
        <div id="cartItems"></div>
        <div id="cartEmpty" class="hidden text-center py-16 bg-white rounded-2xl border border-gray-100">
          <i class="fa-solid fa-cart-shopping text-5xl text-gray-200 mb-4"></i>
          <p class="font-black text-gray-700 text-lg mb-1" data-i18n="cart.empty">سلتك فارغة</p>
          <p class="text-gray-400 text-sm mb-6" data-i18n="cart.empty_sub">أضف خدمات لبدء طلبك</p>
          <button onclick="navigateTo('services')" class="bg-secondary text-white font-bold px-6 py-3 rounded-xl hover:bg-secondary-600 transition">
            <span data-i18n="cart.continue">مواصلة التسوق</span>
          </button>
        </div>
      </div>

      <!-- Summary -->
      <div class="md:col-span-1">
        <div class="bg-white rounded-2xl border border-gray-100 shadow-sm p-6 sticky top-24">
          <h2 class="font-black text-gray-900 mb-4">ملخص الطلب</h2>
          <div id="cartSummary" class="space-y-2"></div>
          <button id="cartCheckoutBtn" onclick="PaymentSystem.openPaymentPage('cart')" disabled
            class="w-full bg-secondary disabled:opacity-40 disabled:cursor-not-allowed text-white font-black py-4 rounded-xl hover:bg-secondary-600 transition mt-5 flex items-center justify-center gap-2">
            <i class="fa-solid fa-lock"></i><span data-i18n="cart.checkout">إتمام الشراء</span>
          </button>
          <p class="text-xs text-gray-400 text-center mt-3 flex items-center justify-center gap-1">
            <i class="fa-solid fa-shield-halved text-turquoise-600"></i>
            فلوسك محجوزة بأمان لحد ما تستلم
          </p>
        </div>
      </div>
    </div>
  </div>
</div>

<!-- ─── PAYMENT (rendered dynamically by PaymentSystem) ──────── -->
<div id="page-payment" class="page"></div>

<!-- ─── ORDERS ──────────────────────────────────────────────── -->
<div id="page-orders" class="page">
  <!-- Rendered dynamically by initOrdersPage() -->
</div>

<!-- ─── WORKSPACE ───────────────────────────────────────────── -->
<div id="page-workspace" class="page">
  <!-- Rendered dynamically by openWorkspace() -->
</div>

<!-- ─── DASHBOARD ───────────────────────────────────────────── -->
<div id="page-dashboard" class="page">
  <div class="max-w-7xl mx-auto px-4 py-8">
    <div id="dashboardContent"></div>
  </div>
</div>

<!-- ─── LOGIN ───────────────────────────────────────────────── -->
<div id="page-login" class="page">
  <div class="min-h-[85vh] flex items-center justify-center px-4 py-12">
    <div class="w-full max-w-md">
      <div class="bg-white rounded-3xl shadow-xl p-8 border border-gray-100">
        <div class="text-center mb-8">
          <div class="w-16 h-16 bg-navy-100 rounded-2xl flex items-center justify-center mx-auto mb-4">
            <i class="fa-solid fa-user-circle text-navy-600 text-2xl"></i>
          </div>
          <h1 class="text-2xl font-black text-gray-900" data-i18n="auth.login">تسجيل الدخول</h1>
        </div>
        <button onclick="AuthManager.loginWithGoogle()" class="w-full flex items-center justify-center gap-3 border-2 border-gray-200 rounded-2xl py-3.5 font-bold text-gray-700 hover:border-navy-400 hover:bg-navy-50 transition mb-6">
          <svg class="w-5 h-5" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z" fill="#4285F4"/><path d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z" fill="#34A853"/><path d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l3.66-2.84z" fill="#FBBC05"/><path d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z" fill="#EA4335"/></svg>
          <span data-i18n="auth.google">متابعة بـ Google</span>
        </button>
        <div class="relative mb-6"><hr class="border-gray-200"><span class="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 bg-white px-3 text-gray-400 text-sm">أو</span></div>
        <div class="space-y-4">
          <input type="email"    id="loginEmail"    class="form-input" placeholder="البريد الإلكتروني" data-i18n="auth.email">
          <input type="password" id="loginPassword" class="form-input" placeholder="كلمة المرور" data-i18n="auth.password">
          <button onclick="AuthManager.loginWithEmail()" class="btn-primary w-full py-4" data-i18n="auth.login">تسجيل الدخول</button>
        </div>
        <div class="flex items-center justify-between mt-4 text-sm">
          <button onclick="AuthManager.forgotPassword()" class="text-navy-600 hover:underline" data-i18n="auth.forgot">نسيت كلمة المرور؟</button>
          <button onclick="navigateTo('register')" class="text-gray-500">
            <span data-i18n="auth.no_account">ليس لديك حساب؟</span> <span class="text-navy-600 font-bold" data-i18n="auth.register">سجّل</span>
          </button>
        </div>
      </div>
    </div>
  </div>
</div>

<!-- ─── REGISTER ─────────────────────────────────────────────── -->
<div id="page-register" class="page">
  <div class="min-h-[85vh] flex items-center justify-center px-4 py-12">
    <div class="w-full max-w-md">
      <div class="bg-white rounded-3xl shadow-xl p-8 border border-gray-100">
        <div class="text-center mb-8">
          <div class="w-16 h-16 bg-green-100 rounded-2xl flex items-center justify-center mx-auto mb-4">
            <i class="fa-solid fa-user-plus text-green-600 text-2xl"></i>
          </div>
          <h1 class="text-2xl font-black text-gray-900" data-i18n="auth.register">إنشاء حساب</h1>
        </div>
        <button onclick="AuthManager.loginWithGoogle()" class="w-full flex items-center justify-center gap-3 border-2 border-gray-200 rounded-2xl py-3.5 font-bold text-gray-700 hover:border-navy-400 hover:bg-navy-50 transition mb-6">
          <svg class="w-5 h-5" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z" fill="#4285F4"/><path d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z" fill="#34A853"/><path d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l3.66-2.84z" fill="#FBBC05"/><path d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z" fill="#EA4335"/></svg>
          <span data-i18n="auth.google">متابعة بـ Google</span>
        </button>
        <div class="relative mb-6"><hr class="border-gray-200"><span class="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 bg-white px-3 text-gray-400 text-sm">أو</span></div>
        <div class="space-y-4">
          <input type="text"     id="registerName"     class="form-input" placeholder="الاسم الكامل" data-i18n="auth.name">
          <input type="email"    id="registerEmail"    class="form-input" placeholder="البريد الإلكتروني" data-i18n="auth.email">
          <input type="tel"      id="registerPhone"    class="form-input" placeholder="رقم الهاتف (اختياري)" data-i18n="auth.phone" dir="ltr">
          <input type="password" id="registerPassword" class="form-input" placeholder="كلمة المرور (8 أحرف+)" data-i18n="auth.password">
          <div class="flex gap-3">
            <label class="flex items-center gap-2 cursor-pointer p-3 border-2 rounded-xl flex-1 hover:border-navy-400 transition" id="roleBuyerLabel">
              <input type="radio" name="role" value="buyer" class="accent-navy-600" checked>
              <span class="text-sm font-bold">مشتري</span>
            </label>
            <label class="flex items-center gap-2 cursor-pointer p-3 border-2 rounded-xl flex-1 hover:border-navy-400 transition" id="roleSellerLabel">
              <input type="radio" name="role" value="seller" class="accent-navy-600">
              <span class="text-sm font-bold">بائع</span>
            </label>
          </div>
          <label class="flex items-start gap-2 text-xs text-gray-500 px-1">
            <input type="checkbox" id="acceptTermsCheckbox" class="mt-0.5 accent-navy-600">
            <span>
              أوافق على
              <a href="/terms" target="_blank" class="text-navy-600 font-bold underline">الشروط والأحكام</a>
              و
              <a href="/privacy" target="_blank" class="text-navy-600 font-bold underline">سياسة الخصوصية</a>
            </span>
          </label>
          <button onclick="AuthManager.register()" class="btn-primary w-full py-4" data-i18n="auth.register">إنشاء الحساب</button>
        </div>
        <p class="text-center mt-4 text-sm text-gray-500">
          <span data-i18n="auth.have_account">لديك حساب؟</span>
          <button onclick="navigateTo('login')" class="text-navy-600 font-bold ms-1" data-i18n="auth.login">تسجيل الدخول</button>
        </p>
      </div>
    </div>
  </div>
</div>

<!-- ─── PROFILE ──────────────────────────────────────────────── -->
<div id="page-profile" class="page">
  <div class="max-w-2xl mx-auto px-4 py-8">
    <div id="profileContent"></div>
  </div>
</div>

<!-- ─── WALLET ───────────────────────────────────────────────── -->
<div id="page-wallet" class="page">
  <div class="max-w-3xl mx-auto px-4 py-8">
    <div id="walletContent"></div>
  </div>
</div>

<!-- ─── ADMIN ────────────────────────────────────────────────── -->
<div id="page-admin" class="page" data-requires-role="admin">
  <div class="max-w-7xl mx-auto px-4 py-8">

    <!-- Header -->
    <div class="flex items-center justify-between mb-8 flex-wrap gap-4">
      <div>
        <h1 class="text-2xl font-black text-gray-900 flex items-center gap-3">
          <div class="w-10 h-10 bg-gradient-to-br from-navy-600 to-purple-600 rounded-xl flex items-center justify-center">
            <i class="fa-solid fa-gauge text-white text-sm"></i>
          </div>
          لوحة التحكم
        </h1>
        <p class="text-gray-500 text-sm mt-1">إدارة المحتوى والـ SEO والذكاء الاصطناعي</p>
      </div>
      <button onclick="AdminAI.generateOne()" id="admin-gen-btn"
        class="btn-primary text-sm flex items-center gap-2 px-5 py-3">
        <i class="fa-solid fa-wand-magic-sparkles"></i>
        توليد مقال AI الآن
      </button>
    </div>

    <!-- Stats Row -->
    <div class="grid grid-cols-2 md:grid-cols-4 gap-4 mb-8" id="admin-stats">
      <div class="bg-white rounded-2xl p-5 border border-gray-100 shadow-card">
        <div class="w-10 h-10 bg-blue-100 rounded-xl flex items-center justify-center mb-3"><i class="fa-solid fa-newspaper text-blue-600"></i></div>
        <p class="text-2xl font-black text-gray-900" id="stat-posts">—</p>
        <p class="text-xs text-gray-500 mt-0.5">إجمالي المقالات</p>
      </div>
      <div class="bg-white rounded-2xl p-5 border border-gray-100 shadow-card">
        <div class="w-10 h-10 bg-purple-100 rounded-xl flex items-center justify-center mb-3"><i class="fa-solid fa-robot text-purple-600"></i></div>
        <p class="text-2xl font-black text-gray-900" id="stat-ai">—</p>
        <p class="text-xs text-gray-500 mt-0.5">مُنشأة بـ AI</p>
      </div>
      <div class="bg-white rounded-2xl p-5 border border-gray-100 shadow-card">
        <div class="w-10 h-10 bg-green-100 rounded-xl flex items-center justify-center mb-3"><i class="fa-solid fa-eye text-green-600"></i></div>
        <p class="text-2xl font-black text-gray-900" id="stat-views">—</p>
        <p class="text-xs text-gray-500 mt-0.5">إجمالي المشاهدات</p>
      </div>
      <div class="bg-white rounded-2xl p-5 border border-gray-100 shadow-card">
        <div class="w-10 h-10 bg-amber-100 rounded-xl flex items-center justify-center mb-3"><i class="fa-solid fa-check-circle text-amber-600"></i></div>
        <p class="text-2xl font-black text-gray-900" id="stat-pub">—</p>
        <p class="text-xs text-gray-500 mt-0.5">منشورة</p>
      </div>
    </div>

    <!-- Tabs -->
    <div class="flex gap-2 mb-6 overflow-x-auto pb-1">
      <button onclick="AdminAI.tab('posts',this)"  id="tab-posts-btn"  class="admin-tab-btn active flex items-center gap-2 px-5 py-2.5 rounded-xl text-sm font-bold whitespace-nowrap bg-navy-600 text-white shadow-glow">
        <i class="fa-solid fa-newspaper"></i> المقالات
      </button>
      <button onclick="AdminAI.tab('ai',this)"     id="tab-ai-btn"     class="admin-tab-btn flex items-center gap-2 px-5 py-2.5 rounded-xl text-sm font-bold whitespace-nowrap bg-white text-gray-600 border border-gray-200 hover:border-navy-400 transition">
        <i class="fa-solid fa-robot"></i> <span class="flex items-center gap-1.5">توليد AI <span class="bg-purple-100 text-purple-700 text-xs px-1.5 py-0.5 rounded-full">Admin</span></span>
      </button>
      <button onclick="AdminAI.tab('seo',this)"    id="tab-seo-btn"    class="admin-tab-btn flex items-center gap-2 px-5 py-2.5 rounded-xl text-sm font-bold whitespace-nowrap bg-white text-gray-600 border border-gray-200 hover:border-navy-400 transition">
        <i class="fa-solid fa-magnifying-glass"></i> SEO
      </button>
    </div>

    <!-- Tab: Posts -->
    <div id="admin-tab-posts">
      <div class="bg-white rounded-2xl border border-gray-100 overflow-hidden shadow-card">
        <div class="p-4 border-b border-gray-100 flex items-center justify-between">
          <h3 class="font-black text-gray-900">المقالات</h3>
          <span class="text-xs text-gray-400" id="posts-count-label">تحميل...</span>
        </div>
        <div class="overflow-x-auto">
          <table class="w-full text-sm" id="admin-posts-table">
            <thead class="bg-gray-50">
              <tr>
                <th class="text-right px-4 py-3 font-bold text-gray-600">العنوان</th>
                <th class="text-right px-4 py-3 font-bold text-gray-600 hidden sm:table-cell">التصنيف</th>
                <th class="text-right px-4 py-3 font-bold text-gray-600">الحالة</th>
                <th class="text-right px-4 py-3 font-bold text-gray-600 hidden md:table-cell">مشاهدات</th>
                <th class="text-right px-4 py-3 font-bold text-gray-600">إجراء</th>
              </tr>
            </thead>
            <tbody id="admin-posts-tbody">
              <tr><td colspan="5" class="text-center py-10 text-gray-400">جاري التحميل...</td></tr>
            </tbody>
          </table>
        </div>
      </div>
    </div>

    <!-- Tab: AI Generator -->
    <div id="admin-tab-ai" class="hidden">
      <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
        <div class="bg-white rounded-2xl border border-gray-100 p-6 shadow-card">
          <h3 class="font-black text-lg text-gray-900 mb-2 flex items-center gap-2">
            <i class="fa-solid fa-wand-magic-sparkles text-purple-600"></i>
            توليد مقال بالذكاء الاصطناعي
          </h3>
          <p class="text-sm text-gray-500 mb-5">يستخدم Gemini Flash أو GPT-4o-mini — مقال SEO كامل 1500-2000 كلمة</p>

          <div class="mb-4">
            <label class="block text-xs font-bold text-gray-600 mb-1.5">موضوع مخصص (اختياري)</label>
            <input type="text" id="ai-topic-input" placeholder="مثال: أفضل أدوات التسويق 2025"
              class="form-input text-sm" />
            <p class="text-xs text-gray-400 mt-1">اتركه فارغاً لاختيار موضوع تلقائي</p>
          </div>

          <div class="mb-5">
            <label class="block text-xs font-bold text-gray-600 mb-1.5">عدد المقالات (للتوليد الجماعي)</label>
            <select id="ai-count-select" class="form-input text-sm">
              <option value="1">مقال واحد</option>
              <option value="2">2 مقالات</option>
              <option value="3">3 مقالات</option>
              <option value="5">5 مقالات</option>
            </select>
          </div>

          <button onclick="AdminAI.generate()" id="ai-gen-btn"
            class="btn-primary w-full py-3.5 text-sm mb-3">
            <i class="fa-solid fa-wand-magic-sparkles"></i>
            <span id="ai-gen-btn-text">ابدأ التوليد</span>
          </button>

          <div id="ai-result" class="hidden rounded-xl p-4 text-sm font-medium"></div>
        </div>

        <div class="bg-white rounded-2xl border border-gray-100 p-6 shadow-card">
          <h3 class="font-black text-lg text-gray-900 mb-4 flex items-center gap-2">
            <i class="fa-solid fa-list text-navy-600"></i>
            بنك المواضيع
          </h3>
          <p class="text-xs text-gray-500 mb-4">انقر على أي موضوع لاستخدامه:</p>
          <div class="flex flex-wrap gap-2" id="topics-bank">
            <div class="text-gray-400 text-sm">جاري التحميل...</div>
          </div>

          <div class="mt-5 p-4 bg-purple-50 border border-purple-100 rounded-xl">
            <p class="text-sm font-bold text-purple-800 flex items-center gap-2 mb-1">
              <i class="fa-solid fa-clock"></i> نشر تلقائي يومي
            </p>
            <p class="text-xs text-purple-600">يتم توليد 2 مقالات تلقائياً كل يوم الساعة 9 صباحاً (القاهرة) ونشرها مباشرة.</p>
          </div>
        </div>
      </div>
    </div>

    <!-- Tab: SEO -->
    <div id="admin-tab-seo" class="hidden">
      <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
        <div class="bg-white rounded-2xl border border-gray-100 p-6 shadow-card">
          <h3 class="font-black text-lg text-gray-900 mb-5 flex items-center gap-2">
            <i class="fa-solid fa-sitemap text-navy-600"></i> أدوات SEO
          </h3>
          <div class="space-y-3">
            <a href="/sitemap.xml" target="_blank"
              class="flex items-center gap-3 p-3 rounded-xl hover:bg-gray-50 transition border border-gray-100">
              <i class="fa-solid fa-sitemap text-navy-500 w-5"></i>
              <span class="text-sm font-medium flex-1">Sitemap XML ثابت</span>
              <i class="fa-solid fa-external-link text-gray-300 text-xs"></i>
            </a>
            <a href="/api/sitemap-dynamic" target="_blank"
              class="flex items-center gap-3 p-3 rounded-xl hover:bg-gray-50 transition border border-gray-100">
              <i class="fa-solid fa-bolt text-purple-500 w-5"></i>
              <span class="text-sm font-medium flex-1">Sitemap ديناميكي (Firestore)</span>
              <i class="fa-solid fa-external-link text-gray-300 text-xs"></i>
            </a>
            <a href="/robots.txt" target="_blank"
              class="flex items-center gap-3 p-3 rounded-xl hover:bg-gray-50 transition border border-gray-100">
              <i class="fa-solid fa-robot text-gray-500 w-5"></i>
              <span class="text-sm font-medium flex-1">robots.txt</span>
              <i class="fa-solid fa-external-link text-gray-300 text-xs"></i>
            </a>
            <a href="https://search.google.com/search-console" target="_blank" rel="noopener"
              class="flex items-center gap-3 p-3 rounded-xl hover:bg-gray-50 transition border border-gray-100">
              <i class="fa-brands fa-google text-red-500 w-5"></i>
              <span class="text-sm font-medium flex-1">Google Search Console</span>
              <i class="fa-solid fa-external-link text-gray-300 text-xs"></i>
            </a>
          </div>
        </div>

        <div class="bg-white rounded-2xl border border-gray-100 p-6 shadow-card">
          <h3 class="font-black text-lg text-gray-900 mb-5 flex items-center gap-2">
            <i class="fa-solid fa-check-circle text-green-500"></i> قائمة تدقيق SEO
          </h3>
          <div class="space-y-2" id="seo-checklist">
            <div class="text-gray-400 text-sm">جاري التحميل...</div>
          </div>
        </div>
      </div>
    </div>

    <div id="adminContent"></div>
  </div>
</div>

<!-- ─── SELLER PANEL ─────────────────────────────────────────── -->
<div id="page-seller" class="page">
  <div class="max-w-6xl mx-auto px-4 py-8">
    <div id="sellerContent">
      <!-- Same as seller dashboard -->
    </div>
  </div>
</div>

<!-- ─── ADD SERVICE ──────────────────────────────────────────── -->
<div id="page-add-service" class="page">
  <div class="max-w-2xl mx-auto px-4 py-8">
    <div id="addServiceContent">
      <div class="text-center py-12">
        <div class="w-16 h-16 bg-navy-100 rounded-2xl flex items-center justify-center mx-auto mb-4 animate-pulse">
          <i class="fa-solid fa-layer-group text-navy-600 text-2xl"></i>
        </div>
        <p class="text-gray-400">جاري التحميل...</p>
      </div>
    </div>
  </div>
</div>


<!-- ══════════════════════════════════════════════════════════
     GLOBAL UI COMPONENTS
══════════════════════════════════════════════════════════════ -->

<!-- Service Detail Modal -->
<div id="serviceModal" class="modal" onclick="if(event.target===this)closeModal('serviceModal')">
  <div class="modal-content max-w-3xl">
    <div id="serviceModalContent"></div>
  </div>
</div>

<!-- ─── REQUEST SERVICE MODAL ────────────────────────────────── -->
<div id="requestServiceModal" class="modal" onclick="if(event.target===this)closeModal('requestServiceModal')">
  <div class="modal-content max-w-lg">
    <div class="p-6">
      <!-- Header -->
      <div class="flex items-center justify-between mb-5">
        <div>
          <h2 id="requestModalTitle" class="text-xl font-black text-gray-900">طلب الخدمة</h2>
          <p id="requestServiceName" class="text-sm text-navy-600 font-bold mt-0.5"></p>
        </div>
        <button onclick="closeModal('requestServiceModal')"
          class="w-9 h-9 bg-gray-100 rounded-xl flex items-center justify-center text-gray-500 hover:bg-gray-200 transition">
          <i class="fa-solid fa-xmark"></i>
        </button>
      </div>

      <!-- Info box -->
      <div class="bg-navy-50 border border-navy-200 rounded-2xl p-4 mb-5 flex gap-3">
        <i class="fa-solid fa-circle-info text-navy-600 text-lg flex-shrink-0 mt-0.5"></i>
        <p id="requestModalInfo" class="text-sm text-navy-800 leading-relaxed">
          اكتب تفاصيل ما تحتاجه وسيصل طلبك مباشرةً لمقدم الخدمة، ثم تنطلق المحادثة بينكما فوراً.
        </p>
      </div>

      <!-- Form -->
      <div class="space-y-4">
        <div>
          <div class="flex items-center justify-between mb-2">
            <label class="block text-sm font-black text-gray-700">تفاصيل الطلب <span class="text-red-500">*</span></label>
            <button type="button" onclick="RequestSystem.openBriefAssistant()"
              class="text-xs font-bold text-navy-600 hover:text-navy-800 flex items-center gap-1">
              <i class="fa-solid fa-wand-magic-sparkles"></i> ساعدني أكتب الطلب بالذكاء الاصطناعي
            </button>
          </div>
          <textarea id="requestDetails" rows="4"
            class="form-input w-full resize-none text-sm"
            placeholder="صف ما تحتاجه بالتفصيل... (الهدف، المخرجات المطلوبة، أي ملاحظات مهمة)"></textarea>
        </div>

        <!-- AI Brief Assistant (collapsible) -->
        <div id="briefAssistantBox" class="hidden bg-purple-50 border border-purple-200 rounded-2xl p-4 space-y-3">
          <p class="text-xs text-purple-800 font-bold flex items-center gap-2">
            <i class="fa-solid fa-wand-magic-sparkles"></i>
            جاوب على شوية أسئلة سريعة وهنكتبلك الطلب بشكل احترافي
          </p>
          <input type="text" id="briefGoal" class="form-input w-full text-sm" placeholder="إيه الهدف من الخدمة دي بالظبط؟">
          <input type="text" id="briefOutcome" class="form-input w-full text-sm" placeholder="عايز تستلم إيه في الآخر؟ (مثال: 5 تصاميم، مقال 800 كلمة)">
          <input type="text" id="briefNotes" class="form-input w-full text-sm" placeholder="أي تفاصيل أو تفضيلات مهمة؟ (اختياري)">
          <button type="button" onclick="RequestSystem.generateBrief()" id="briefGenBtn"
            class="w-full btn-primary py-2.5 text-sm flex items-center justify-center gap-2">
            <i class="fa-solid fa-sparkles"></i> اكتب لي الطلب
          </button>
        </div>

        <div>
          <label class="block text-sm font-black text-gray-700 mb-2">الميعاد المطلوب (اختياري)</label>
          <input type="text" id="requestDeadline"
            class="form-input w-full text-sm"
            placeholder="مثال: خلال أسبوع، بحلول نهاية الشهر...">
        </div>
        <div>
          <label class="block text-sm font-black text-gray-700 mb-2">ميزانيتك المتوقعة (اختياري)</label>
          <input type="text" id="requestBudget"
            class="form-input w-full text-sm"
            placeholder="مثال: 500 جنيه، أو حسب الاتفاق">
        </div>
      </div>

      <!-- Actions -->
      <div class="flex gap-3 mt-6">
        <button onclick="closeModal('requestServiceModal')"
          class="flex-1 btn-secondary py-3">إلغاء</button>
        <button onclick="RequestSystem.submitRequest()"
          id="submitRequestBtn"
          class="flex-1 btn-primary py-3 flex items-center justify-center gap-2">
          <i class="fa-solid fa-paper-plane"></i>
          إرسال الطلب وبدء المحادثة
        </button>
      </div>
    </div>
  </div>
</div>

<!-- Product Order Modal — buyer details + seller rules + platform terms,
     shown before checkout for product (not service) listings. -->
<div id="productOrderModal" class="modal" onclick="if(event.target===this)closeModal('productOrderModal')">
  <div class="modal-content max-w-lg">
    <div class="p-6">
      <!-- Header -->
      <div class="flex items-center justify-between mb-5">
        <div>
          <h2 class="text-xl font-black text-gray-900">إتمام طلب المنتج</h2>
          <p id="productOrderName" class="text-sm text-turquoise-600 font-bold mt-0.5"></p>
        </div>
        <button onclick="closeModal('productOrderModal')"
          class="w-9 h-9 bg-gray-100 rounded-xl flex items-center justify-center text-gray-500 hover:bg-gray-200 transition">
          <i class="fa-solid fa-xmark"></i>
        </button>
      </div>

      <!-- Seller's own rules/requirements (shown only if the seller wrote any) -->
      <div id="productSellerRulesBox" class="hidden bg-amber-50 border border-amber-200 rounded-2xl p-4 mb-5">
        <p class="text-xs font-black text-amber-800 mb-1 flex items-center gap-1.5">
          <i class="fa-solid fa-triangle-exclamation"></i> شروط وملاحظات البائع على هذا المنتج
        </p>
        <p id="productSellerRulesText" class="text-sm text-amber-900 leading-relaxed whitespace-pre-wrap"></p>
      </div>

      <!-- Buyer details form -->
      <div class="space-y-4">
        <div>
          <label class="block text-sm font-black text-gray-700 mb-2">الاسم بالكامل <span class="text-red-500">*</span></label>
          <input type="text" id="productBuyerName" class="form-input w-full text-sm" placeholder="الاسم اللي هيتكتب على الشحنة">
        </div>
        <div>
          <label class="block text-sm font-black text-gray-700 mb-2">رقم الهاتف <span class="text-red-500">*</span></label>
          <input type="tel" id="productBuyerPhone" class="form-input w-full text-sm" dir="ltr" placeholder="01xxxxxxxxx">
        </div>
        <div>
          <label class="block text-sm font-black text-gray-700 mb-2">عنوان التوصيل بالكامل <span class="text-red-500">*</span></label>
          <textarea id="productBuyerAddress" rows="2" class="form-input w-full text-sm resize-none"
            placeholder="المحافظة، المدينة، الشارع، رقم العمارة/الشقة، أقرب علامة مميزة"></textarea>
        </div>
        <div>
          <label class="block text-sm font-black text-gray-700 mb-2">ملاحظات إضافية (اختياري)</label>
          <textarea id="productBuyerNotes" rows="2" class="form-input w-full text-sm resize-none"
            placeholder="أي تفاصيل مهمة عن طلبك (مقاس، لون، توقيت مناسب للتوصيل...)"></textarea>
        </div>

        <!-- Platform rules agreement -->
        <label class="flex items-start gap-2 cursor-pointer select-none">
          <input type="checkbox" id="productAgreeRules" class="mt-1 w-4 h-4 accent-navy-700">
          <span class="text-xs text-gray-600 leading-relaxed">
            أوافق على <a href="/terms" target="_blank" class="underline text-navy-600 font-bold">شروط وأحكام المنصة</a>
            و<a href="/refund-policy.html" target="_blank" class="underline text-navy-600 font-bold">سياسة الاسترجاع</a>
            وشروط البائع الموضحة أعلاه (إن وُجدت)
          </span>
        </label>
      </div>

      <!-- Actions -->
      <div class="flex gap-3 mt-6">
        <button onclick="closeModal('productOrderModal')" class="flex-1 btn-secondary py-3">إلغاء</button>
        <button onclick="RequestSystem.submitProductOrder()" id="submitProductOrderBtn"
          class="flex-1 btn-primary py-3 flex items-center justify-center gap-2">
          <i class="fa-solid fa-lock"></i> تأكيد الطلب والدفع
        </button>
      </div>
    </div>
  </div>
</div>

<!-- Global Toast -->
<div id="globalToast" class="toast"></div>

<!-- Mobile Bottom Nav -->
<nav class="md:hidden fixed bottom-0 inset-x-0 bg-white/95 backdrop-blur-xl border-t border-borderline z-50 pb-safe shadow-[0_-2px_12px_rgba(15,23,42,0.06)]">
  <div class="flex items-center justify-around py-1.5">
    <button onclick="navigateTo('home')"     class="flex flex-col items-center gap-1 py-1.5 px-4 min-h-[44px] justify-center text-textsecondary hover:text-secondary transition" data-mobile-nav="home">
      <i class="fa-solid fa-store text-lg"></i><span class="text-[11px] font-semibold" data-i18n="nav.home">الرئيسية</span>
    </button>
    <button onclick="navigateTo('services')" class="flex flex-col items-center gap-1 py-1.5 px-4 min-h-[44px] justify-center text-textsecondary hover:text-secondary transition" data-mobile-nav="services">
      <i class="fa-solid fa-grid-2 text-lg"></i><span class="text-[11px] font-semibold" data-i18n="nav.services">الخدمات</span>
    </button>
    <button onclick="navigateTo('cart')" class="relative flex flex-col items-center gap-1 py-1.5 px-4 min-h-[44px] justify-center text-textsecondary hover:text-secondary transition" data-mobile-nav="cart">
      <i class="fa-solid fa-cart-shopping text-lg"></i><span class="text-[11px] font-semibold" data-i18n="cart.short">السلة</span>
      <span data-cart-count class="hidden absolute top-0 end-2 bg-secondary text-white text-[9px] font-black w-3.5 h-3.5 rounded-full flex items-center justify-center">0</span>
    </button>
    <button onclick="navigateTo('orders')"   class="flex flex-col items-center gap-1 py-1.5 px-4 min-h-[44px] justify-center text-textsecondary hover:text-secondary transition" data-mobile-nav="orders">
      <i class="fa-solid fa-shield-heart text-lg"></i><span class="text-[11px] font-semibold" data-i18n="nav.orders">طلباتي</span>
    </button>
    <button onclick="AppState.currentUser?navigateTo('dashboard'):navigateTo('login')" class="flex flex-col items-center gap-1 py-1.5 px-4 min-h-[44px] justify-center text-textsecondary hover:text-secondary transition">
      <i class="fa-solid fa-user text-lg"></i><span class="text-[11px] font-semibold">حسابي</span>
    </button>
  </div>
</nav>
<div class="h-20 md:hidden"></div><!-- Spacer for bottom nav -->


<!-- ══════════════════════════════════════════════════════════
     SCRIPTS — Load order matters!
══════════════════════════════════════════════════════════════ -->

<!-- 1. Firebase Config — Single source of truth, multi-domain support -->
<script>
// ══════════════════════════════════════════════════════════════════════════════
//  FIREBASE INIT v4.0
//  • authDomain = project's own .firebaseapp.com
//  • Authorized Domains in Firebase Console must include:
//      mall-services.pages.dev
//      (+ your custom domain here, if you add one later — e.g. mallservices.com)
//  • Google Cloud OAuth must include both domains in origins + redirect URIs:
//      https://mall-services.pages.dev/__/auth/handler
//      (+ https://yourcustomdomain.com/__/auth/handler once you have one)
// ══════════════════════════════════════════════════════════════════════════════
const FIREBASE_CONFIG = {
    apiKey:            "AIzaSyDfWKWN5CTlBA-krEMXsmYmaI8j7fyuw20",
    authDomain:        "services-mall.firebaseapp.com",   // ← الصحيح دائماً
    databaseURL:       "https://services-mall-default-rtdb.firebaseio.com",
    projectId:         "services-mall",
    storageBucket:     "services-mall.firebasestorage.app",
    messagingSenderId: "20174208068",
    appId:             "1:20174208068:web:382ece0ff09fa9be815011",
    measurementId:     "G-20SMHQMQ1G",
};

// Guard: prevent duplicate init if script ever runs twice
if (!firebase.apps.length) {
    firebase.initializeApp(FIREBASE_CONFIG);
} else {
    console.warn('[Firebase] App already initialized — skipping duplicate init');
}

// Resolves once the FIRST auth state (logged in or not) is known — used to
// safely deep-link into auth-dependent pages (like a shared order workspace
// link) without racing Firebase's async session restore on a fresh load.
let _resolveAuthReady;
window._authReadyPromise = new Promise(res => { _resolveAuthReady = res; });

const auth    = firebase.auth();
const db      = firebase.firestore();
const storage = firebase.storage();
// Realtime Database — used ONLY for chat messages (js/chat.js). Firestore's
// per-document read/write pricing gets expensive fast for a live chat feed;
// RTDB bills by bandwidth/storage instead, which fits this pattern much better.
const rtdb    = firebase.database();
window.rtdb   = rtdb;

// Google provider — no hardcoded domain, works on any authorized domain
const googleProvider = new firebase.auth.GoogleAuthProvider();
googleProvider.setCustomParameters({
    prompt: 'select_account',   // always show account picker
    // NOTE: do NOT set client_id here — Firebase manages OAuth internally
    // Setting it forces a specific OAuth client that may not have all domains authorized
});

window.auth           = auth;
window.db             = db;
window.storage        = storage;
window.firebase       = firebase;
window.googleProvider = googleProvider;

// Enable offline persistence
db.enablePersistence({ synchronizeTabs: true })
  .catch(e => { if (!['failed-precondition','unimplemented'].includes(e.code)) console.warn('[Firebase]', e.code); });

console.log('✅ Firebase v4.0 initialized | domain:', location.hostname);
</script>

<!-- 2. Constants & Utilities -->
<script src="js/constants.js"></script>

<script>
// Load live platform settings BEFORE any page renders
// PLATFORM object is defined in constants.js — this merges Firestore values into it
// ⚠️ FIXED (found in audit): this used to run immediately, before Firebase Auth
// had resolved whether anyone was signed in — firestore.rules requires
// isSignedIn() to read settings/platform, so `request.auth` was null every
// time and the read was denied (logged as "Missing or insufficient
// permissions"), silently falling back to hardcoded defaults on every load.
// Now waits for _authReadyPromise (resolved by auth.js's onAuthStateChanged)
// before attempting the read.
(async () => { try { await window._authReadyPromise; await loadPlatformSettings(); } catch(e) {} })();
</script>

<!-- 3. i18n -->
<script src="js/i18n.js"></script>

<!-- 4. Payment System -->
<script src="js/request-system.js"></script>
<script src="js/subscription-system.js"></script>

<!-- 5. Escrow -->
<script src="js/escrow.js"></script>

<!-- 5b. Payment (⚠️ ADDED — this tag was missing entirely, so window.PaymentSystem
     was never defined and every "ادفع الآن" click threw "PaymentSystem is not
     defined" instead of opening the payment gateway. The file itself was
     always complete and correct — it just never got wired into the page.) -->
<script src="js/payment-system.js"></script>

<!-- 6. Orders Manager -->
<script src="js/orders.js"></script>

<!-- 7. Order Workspace (chat + delivery) -->
<script src="js/order-workspace.js"></script>

<!-- 7b. Dedicated Chat Module -->

<!-- 7c. Blog Engine (Firestore-powered blog) -->
<script src="js/blog-engine.js"></script>

<!-- 8. Auth -->
<script src="js/auth.js"></script>

<!-- 9. Services -->
<script src="js/services.js"></script>

<!-- 10. Notifications -->
<script src="js/notifications.js"></script>

<!-- 11. Dashboard -->
<script defer src="js/dashboard.js"></script>

<!-- 11b. Seller Dashboard Module -->
<script defer src="js/seller-dashboard.js"></script>

<!-- 12. App Init -->
<script>
(function() {
    'use strict';

    // ── Cart Renderer ─────────────────────────────────────────────────────────
    function renderCart() {
        const container = document.getElementById('cartItems');
        const empty     = document.getElementById('cartEmpty');
        const summary   = document.getElementById('cartSummary');
        const checkBtn  = document.getElementById('cartCheckoutBtn');
        if (!container) return;

        const cart = AppState.cart || [];

        if (cart.length === 0) {
            container.innerHTML = '';
            if (empty)   empty.classList.remove('hidden');
            if (checkBtn) checkBtn.disabled = true;
            if (summary) summary.innerHTML = '';
            return;
        }
        if (empty) empty.classList.add('hidden');
        if (checkBtn) checkBtn.disabled = false;

        const isAr = AppState.language !== 'en';
        container.innerHTML = cart.map((item, idx) => `
          <div class="bg-white rounded-2xl border border-gray-200 p-5 flex gap-4 hover:border-navy-300 transition cart-item" data-id="${item.id}">
            <img src="${item.image || 'https://images.unsplash.com/photo-1460925895917-afdab827c52f?w=120'}"
              class="w-20 h-20 rounded-xl object-cover flex-shrink-0"
              onerror="this.src='https://images.unsplash.com/photo-1460925895917-afdab827c52f?w=120'">
            <div class="flex-1 min-w-0">
              <h3 class="font-black text-gray-900 truncate">${item.title || '—'}</h3>
              <p class="text-sm text-gray-500 mt-0.5">${item.sellerName || ''}</p>
              <p class="text-navy-700 font-black text-lg mt-2">${formatCurrency(item.price || 0)}</p>
            </div>
            <button onclick="removeFromCart('${item.id}')"
              class="w-9 h-9 bg-red-50 hover:bg-red-100 rounded-xl flex items-center justify-center text-red-500 transition flex-shrink-0 self-start">
              <i class="fa-solid fa-trash text-sm"></i>
            </button>
          </div>
        `).join('');

        // Update summary
        const { subtotal, fees, total } = getCartTotals();
        if (summary) {
            summary.innerHTML = `
              <div class="flex justify-between text-sm text-gray-600">
                <span data-i18n="cart.subtotal">${t('cart.subtotal')}</span>
                <span class="font-bold">${formatCurrency(subtotal)}</span>
              </div>
              <div class="flex justify-between text-sm text-gray-600">
                <span>${t('cart.fees')} (${PLATFORM.FEE_PERCENT}%)</span>
                <span class="font-bold">${formatCurrency(fees)}</span>
              </div>
              <hr class="border-gray-100">
              <div class="flex justify-between text-lg font-black text-navy-700">
                <span data-i18n="cart.total">${t('cart.total')}</span>
                <span>${formatCurrency(total)}</span>
              </div>`;
        }
        updateCartCount();
    }

    // ── UI Event Handlers ─────────────────────────────────────────────────────
    window.toggleUserMenu = function() {
        document.getElementById('userDropdown')?.classList.toggle('active');
    };
    window.toggleMobileMenu = function() {
        document.getElementById('mobileMenu')?.classList.toggle('hidden');
    };
    window.toggleNotifDropdown = function() {
        document.getElementById('notifDropdown')?.classList.toggle('hidden');
    };
    window.markAllNotifsRead = async function() {
        const user = AppState.currentUser;
        if (!user) return;
        try {
            const snap = await db.collection(COLLECTIONS.NOTIFICATIONS)
                .where('userId','==',user.uid).where('read','==',false).get();
            const batch = db.batch();
            snap.docs.forEach(d => batch.update(d.ref, { read: true }));
            await batch.commit();
        } catch (_) {}
    };

    // Close dropdowns on outside click
    document.addEventListener('click', (e) => {
        if (!e.target.closest('#userMenuWrap'))     document.getElementById('userDropdown')?.classList.remove('active');
        if (!e.target.closest('#currencyToggle') && !e.target.closest('#currencyMenu')) document.getElementById('currencyMenu')?.classList.remove('active');
        if (!e.target.closest('#notifBtn') && !e.target.closest('#notifDropdown')) document.getElementById('notifDropdown')?.classList.add('hidden');
        if (!e.target.closest('nav') && !e.target.closest('#mobileMenu')) document.getElementById('mobileMenu')?.classList.add('hidden');
    });

    // ── Hash-based routing ────────────────────────────────────────────────────
    // ⚠️ FIXED: a hard refresh while on the order workspace (#workspace) used
    // to leave the user on a completely blank page. Why: navigateTo('workspace')
    // just marks that page div active — the actual content only ever gets
    // rendered by openWorkspace(orderId), which is called with an order id
    // from a button click, never from routing. The bare "#workspace" hash
    // carries no order id, so there was nothing to render.
    // Now: openWorkspace() rewrites the URL to "#workspace-<orderId>" once a
    // workspace is actually open, so refreshing (or sharing the link) can
    // deep-link straight back into that same order once the user's auth
    // state is known. A bare "#workspace" (no id — e.g. an old bookmark)
    // goes home instead of showing a blank shell.
    function handleHash() {
        const raw = window.location.hash.replace('#','') || 'home';
        const wsMatch = raw.match(/^workspace-(.+)$/);
        if (wsMatch) {
            const orderId = wsMatch[1];
            (window._authReadyPromise || Promise.resolve()).then(() => {
                if (AppState.currentUser && typeof openWorkspace === 'function') {
                    openWorkspace(orderId);
                } else {
                    navigateTo('home');
                }
            });
            return;
        }
        if (raw === 'workspace') { navigateTo('home'); return; }
        const validPages = ['home','services','orders','workspace','dashboard','login','register','profile','wallet','admin','seller','add-service'];
        navigateTo(validPages.includes(raw) ? raw : 'home');
    }
    window.addEventListener('popstate', handleHash);

    // ── Featured Services Loader ──────────────────────────────────────────────
    async function loadFeaturedServices() {
        try {
            const container = document.getElementById('featuredServices');
            if (!container) return;

            const snap = await db.collection(COLLECTIONS.SERVICES)
                .where('active','==',true)
                .where('featured','==',true)
                .limit(12).get();

            // Filter out product listings client-side (no extra composite
            // index needed) — this section is "custom services" only, real
            // digital products get their own dedicated grid (loadHomeProducts).
            let docs = snap.docs.filter(d => (d.data().listingType||'service') !== 'product');

            if (docs.length === 0) {
                const allSnap = await db.collection(COLLECTIONS.SERVICES).where('active','==',true).limit(20).get();
                docs = allSnap.docs.filter(d => (d.data().listingType||'service') !== 'product');
            }

            if (docs.length === 0) { container.innerHTML = `<p class="text-gray-400 col-span-3 text-center py-8">لا توجد خدمات بعد</p>`; return; }
            _renderFeaturedCards(docs.slice(0,6), container);
        } catch (err) {
            console.warn('[Featured] Error:', err.message);
        }
    }

    function _renderFeaturedCards(docs, container) {
        const isAr = AppState.language !== 'en';
        container.innerHTML = docs.map(doc => {
            const s = { id: doc.id, ...doc.data() };
            const stars = Math.round(s.rating || 5);
            const isInstant = s.orderMode === 'instant';
            const requestData = JSON.stringify({id:s.id,title:s.title||'',price:s.price||0,image:s.image||'',sellerId:s.sellerId||'',sellerName:s.sellerName||'',deliveryDays:s.deliveryDays||3}).replace(/"/g,'&quot;');
            return `
            <div class="bg-white rounded-2xl border border-gray-100 shadow-sm hover:shadow-lg transition-all overflow-hidden flex flex-col cursor-pointer" onclick="ServicesManager.openServiceDetail('${s.id}')">
              <div class="relative aspect-video bg-gray-100">
                <img src="${s.image || 'https://images.unsplash.com/photo-1460925895917-afdab827c52f?w=500'}"
                  class="w-full h-full object-cover" loading="lazy"
                  onerror="this.src='https://images.unsplash.com/photo-1460925895917-afdab827c52f?w=500'">
                <span class="absolute top-3 start-3 bg-turquoise-50 text-turquoise-700 text-[11px] font-bold px-2.5 py-1 rounded-full flex items-center gap-1">
                  <i class="fa-solid fa-shield text-[10px]"></i> ضمان مالي Escrow
                </span>
              </div>
              <div class="p-4 flex flex-col gap-3 flex-1">
                <div class="flex items-center justify-between">
                  <div class="flex items-center gap-2">
                    <img src="${s.sellerAvatar || 'https://ui-avatars.com/api/?name=' + encodeURIComponent(s.sellerName||'U')}" class="w-8 h-8 rounded-full object-cover">
                    <span class="text-xs font-bold text-gray-700">${escapeHtml(s.sellerName || '—')}</span>
                  </div>
                  <div class="flex items-center gap-1 text-amber-500 text-xs font-bold">
                    <i class="fa-solid fa-star"></i><span class="text-gray-900">${stars.toFixed ? s.rating||5 : stars}</span><span class="text-gray-400 font-normal">(${s.reviewCount||0})</span>
                  </div>
                </div>
                <h3 class="font-black text-gray-900 text-sm leading-snug line-clamp-2">${escapeHtml(s.title || '—')}</h3>
                <div class="flex flex-wrap gap-2 text-[11px] text-gray-500">
                  <span class="bg-gray-50 px-2 py-1 rounded-md flex items-center gap-1"><i class="fa-regular fa-clock text-gray-400"></i>تسليم ${s.deliveryDays||3} أيام</span>
                  <span class="bg-gray-50 px-2 py-1 rounded-md flex items-center gap-1"><i class="fa-solid ${isInstant?'fa-lock':'fa-paper-plane'} text-gray-400"></i>${isInstant?'دفع مباشر':'طلب ثم موافقة'}</span>
                </div>
              </div>
              <div class="p-4 bg-gray-50/70 flex items-center justify-between border-t border-gray-100">
                <div>
                  <p class="text-[11px] text-gray-400 leading-none mb-1">يبدأ من</p>
                  <p class="font-black text-navy-900" data-price-egp="${s.price||0}">${formatCurrency(s.price||0)}</p>
                </div>
                <button onclick="event.stopPropagation();${isInstant?'RequestSystem.openInstantModal':'RequestSystem.openRequestModal'}(${requestData})"
                  class="bg-secondary text-white text-xs font-bold px-4 py-2.5 rounded-lg hover:bg-secondary-600 transition flex items-center gap-1.5">
                  <i class="fa-solid ${isInstant?'fa-lock':'fa-paper-plane'}"></i>${isInstant?(isAr?'اطلب وادفع':'Pay & Request'):(isAr?'اطلب الآن':'Request now')}
                </button>
              </div>
            </div>`;
        }).join('');
    }

    // ⚠️ ADDED: real "digital products" grid for the homepage spotlight
    // section — same data-loading pattern as loadFeaturedServices() but
    // filtered to listingType === 'product', with a buy-now style card.
    async function loadHomeProducts() {
        try {
            const container = document.getElementById('homeProductsGrid');
            if (!container) return;
            const snap = await db.collection(COLLECTIONS.SERVICES)
                .where('active', '==', true)
                .where('listingType', '==', 'product')
                .limit(8).get();
            if (snap.empty) { container.innerHTML = `<p class="text-gray-400 col-span-4 text-center py-8">لا توجد منتجات بعد</p>`; return; }
            const isAr = AppState.language !== 'en';
            container.innerHTML = snap.docs.map(doc => {
                const s = { id: doc.id, ...doc.data() };
                const cartData = JSON.stringify({id:s.id,title:s.title||'',price:s.price||0,image:s.image||'',sellerId:s.sellerId||'',sellerName:s.sellerName||'',deliveryDays:s.deliveryDays||0,orderRules:s.orderRules||''}).replace(/"/g,'&quot;');
                return `
                <div class="bg-white rounded-2xl border border-gray-100 shadow-sm hover:shadow-lg transition-all overflow-hidden flex flex-col cursor-pointer" onclick="ServicesManager.openServiceDetail('${s.id}')">
                  <div class="relative aspect-video bg-gray-100">
                    <img src="${s.image || 'https://images.unsplash.com/photo-1460925895917-afdab827c52f?w=500'}"
                      class="w-full h-full object-cover" loading="lazy"
                      onerror="this.src='https://images.unsplash.com/photo-1460925895917-afdab827c52f?w=500'">
                    <span class="absolute top-3 start-3 bg-turquoise-500 text-white text-[11px] font-bold px-2.5 py-1 rounded-full flex items-center gap-1">
                      <i class="fa-solid fa-bolt text-[10px]"></i> تسليم فوري
                    </span>
                  </div>
                  <div class="p-4 flex flex-col gap-2 flex-1">
                    <div class="flex items-center justify-between">
                      <span class="text-xs text-gray-400 font-bold">${escapeHtml(s.sellerName||'—')}</span>
                      <div class="flex items-center gap-1 text-amber-500 text-xs font-bold"><i class="fa-solid fa-star"></i><span class="text-gray-900">${s.rating||5}</span><span class="text-gray-400 font-normal">(${s.reviewCount||0})</span></div>
                    </div>
                    <h3 class="font-black text-gray-900 text-sm leading-snug line-clamp-2">${escapeHtml(s.title||'—')}</h3>
                  </div>
                  <div class="p-4 bg-gray-50/70 flex items-center justify-between border-t border-gray-100">
                    <span class="font-black text-navy-900" data-price-egp="${s.price||0}">${formatCurrency(s.price||0)}</span>
                    <button onclick="event.stopPropagation();RequestSystem.openProductOrderModal(${cartData})"
                      class="bg-turquoise-600 text-white text-xs font-bold px-4 py-2.5 rounded-lg hover:bg-turquoise-700 transition flex items-center gap-1.5">
                      <i class="fa-solid fa-cart-shopping"></i>${isAr?'شراء فوري':'Buy now'}
                    </button>
                  </div>
                </div>`;
            }).join('');
        } catch (err) {
            console.warn('[loadHomeProducts] Error:', err.message);
        }
    }

    window.filterByCategory = function(cat) {
        AppState.filterCategory = cat;
        navigateTo('services');
        setTimeout(() => {
            if (typeof ServicesManager?.filterCategory === 'function') ServicesManager.filterCategory(cat);
        }, 100);
    };

    // ⚠️ ADDED: jump straight to the "منتجات" tab on the services page —
    // mirrors filterByCategory's pattern.
    window.filterByType = function(type) {
        AppState.filterType = type;
        navigateTo('services');
        setTimeout(() => {
            if (typeof ServicesManager?.filterType === 'function') ServicesManager.filterType(type);
        }, 100);
    };

    // ⚠️ ADDED: combined type+category filter, used by the homepage's dual
    // category browse section (e.g. "قوالب SaaS و UI" = product + programming).
    window.filterByTypeAndCategory = function(type, cat) {
        AppState.filterType = type;
        AppState.filterCategory = cat;
        navigateTo('services');
        setTimeout(() => {
            if (typeof ServicesManager?.filterType === 'function') ServicesManager.filterType(type);
            if (typeof ServicesManager?.filterCategory === 'function') ServicesManager.filterCategory(cat);
        }, 100);
    };

    // ⚠️ ADDED: toggle the hero's services/products segmented control —
    // purely cosmetic (which tab looks active + placeholder text); the
    // actual search still runs through doHeroSearch() below, now aware of
    // which segment is selected.
    window._heroSearchMode = 'services';
    window.switchHeroSearch = function(mode) {
        window._heroSearchMode = mode;
        const tabServices = document.getElementById('heroTabServices');
        const tabProducts = document.getElementById('heroTabProducts');
        const input = document.getElementById('heroSearchInput');
        const activeCls   = 'flex items-center gap-1.5 px-4 py-2 rounded-lg bg-navy-900 text-white text-sm font-bold transition';
        const inactiveCls = 'flex items-center gap-1.5 px-4 py-2 rounded-lg text-gray-500 hover:text-navy-900 text-sm font-bold transition';
        if (!tabServices || !tabProducts) return;
        if (mode === 'products') {
            tabProducts.className = activeCls; tabServices.className = inactiveCls;
            if (input) input.placeholder = 'ابحث عن قوالب Figma، سكريبتات Laravel، حزم تصميم جاهزة...';
        } else {
            tabServices.className = activeCls; tabProducts.className = inactiveCls;
            if (input) input.placeholder = 'ابحث عن برمجة متجر، تصميم هوية، قوالب Figma...';
        }
    };

    // Hero search bar (home page) — navigates to services and applies the
    // typed query + selected category + selected services/products segment.
    window.doHeroSearch = function() {
        const query = document.getElementById('heroSearchInput')?.value.trim() || '';
        const cat   = document.getElementById('heroSearchCategory')?.value || '';
        const type  = window._heroSearchMode === 'products' ? 'product' : (window._heroSearchMode === 'services' ? 'service' : '');
        AppState.filterCategory = cat;
        AppState.filterType = type;
        navigateTo('services');
        setTimeout(() => {
            if (cat && typeof ServicesManager?.filterCategory === 'function') ServicesManager.filterCategory(cat);
            if (typeof ServicesManager?.filterType === 'function') ServicesManager.filterType(type);
            if (query && typeof ServicesManager?.search === 'function') {
                const input = document.getElementById('servicesSearch');
                if (input) input.value = query;
                ServicesManager.search(query);
            }
        }, 100);
    };

    // ── Home page stats — real counts from Firestore, not hardcoded marketing
    //    numbers. Fetched from /api/home-stats (server-side, service account)
    //    rather than queried directly from the client: `orders` and `users`
    //    reads are locked down by firestore.rules to "your own data only", so
    //    a guest browsing the homepage couldn't run these counts directly —
    //    see functions/api/home-stats.js for why. Runs once per session via
    //    the initHomePage convention (fires on first load + every home visit,
    //    but only actually fetches once). ─────────────────────────────────────
    function _formatStatNumber(n) {
        if (n == null) return '—';
        return '+' + n.toLocaleString('en-US');
    }
    window.initHomePage = function() { loadHomeStats(); loadFeaturedServices(); loadHomeProducts(); };
    window.loadHomeStats = async function() {
        if (window._homeStatsLoaded) return;
        window._homeStatsLoaded = true;
        try {
            const resp = await fetch('/api/home-stats');
            const data = await resp.json();
            if (!data.success) throw new Error(data.error || 'failed');

            const elServices = document.getElementById('statServices');
            const elSellers  = document.getElementById('statSellers');
            const elOrders   = document.getElementById('statOrders');
            const elRating   = document.getElementById('statRating');

            if (elServices) elServices.textContent = _formatStatNumber(data.services);
            if (elSellers)  elSellers.textContent  = _formatStatNumber(data.sellers);
            if (elOrders)   elOrders.textContent   = _formatStatNumber(data.completedOrders);
            if (elRating)   elRating.textContent   = (data.avgRating != null ? data.avgRating.toFixed(1) : '—');
        } catch (err) {
            console.error('[loadHomeStats]', err);
            window._homeStatsLoaded = false; // allow a retry on next visit
        }
    };

    // ⚠️ ADDED: "Trending Offers" horizontal carousel — most recent active
    // listings (services + products mixed), compact card style.
    window.loadTrendingOffers = async function() {
        if (!window.db || window._trendingLoaded) return;
        window._trendingLoaded = true;
        const row = document.getElementById('trendingOffersRow');
        if (!row) return;
        try {
            const snap = await window.db.collection(COLLECTIONS.SERVICES)
                .where('active', '==', true)
                .orderBy('createdAt', 'desc')
                .limit(10)
                .get();
            if (snap.empty) { row.innerHTML = ''; return; }

            row.innerHTML = snap.docs.map(d => {
                const s = { id: d.id, ...d.data() };
                const isProduct = s.listingType === 'product';
                const actionBtn = isProduct
                    ? `<button onclick="addToCart(${JSON.stringify({id:s.id,title:s.title||'',price:s.price||0,image:s.image||'',sellerId:s.sellerId||'',sellerName:s.sellerName||'',deliveryDays:s.deliveryDays||0}).replace(/"/g,'&quot;')})" class="w-full bg-turquoise-600 text-white text-xs font-bold py-2 rounded-xl hover:bg-turquoise-700 transition">أضف للسلة</button>`
                    : `<button onclick="RequestSystem.openRequestModal(${JSON.stringify({id:s.id,title:s.title||'',price:s.price||0,image:s.image||'',sellerId:s.sellerId||'',sellerName:s.sellerName||'',deliveryDays:s.deliveryDays||3}).replace(/"/g,'&quot;')})" class="w-full bg-secondary text-white text-xs font-bold py-2 rounded-xl hover:bg-secondary-600 transition">اطلب الآن</button>`;
                return `
                <div class="flex-shrink-0 bg-white rounded-2xl border border-gray-100 shadow-sm overflow-hidden hover:shadow-lg transition-shadow" style="width:220px">
                  <div class="relative h-32 bg-gray-100">
                    ${s.image ? `<img src="${s.image}" class="w-full h-full object-cover" loading="lazy">` : `<div class="w-full h-full flex items-center justify-center text-gray-300"><i class="fa-solid fa-image text-3xl"></i></div>`}
                    <span class="absolute top-2 start-2 text-[10px] font-black px-2 py-1 rounded-lg ${isProduct ? 'bg-turquoise-500 text-white' : 'bg-navy-800 text-white'}">${isProduct ? '<i class=\'fa-solid fa-box\'></i> منتج' : '<i class=\'fa-solid fa-toolbox\'></i> خدمة'}</span>
                  </div>
                  <div class="p-3">
                    <p class="font-bold text-gray-900 text-sm truncate mb-1">${escapeHtml(s.title||'')}</p>
                    <p class="font-black text-navy-900 text-sm mb-2">${formatCurrency(s.price||0)}</p>
                    ${actionBtn}
                  </div>
                </div>`;
            }).join('');
        } catch (err) {
            console.error('[loadTrendingOffers]', err);
            row.innerHTML = '';
            window._trendingLoaded = false;
        }
    };
    // Track if this is the first auth state change (page load)
    let _authFirstRun = true;

    auth.onAuthStateChanged(async (user) => {
        const isFirstRun = _authFirstRun;
        _authFirstRun = false;
        if (isFirstRun && typeof _resolveAuthReady === 'function') _resolveAuthReady();
        if (user) {
            try {
                // Ensure user doc exists
                if (typeof window._ensureUserDoc === 'function') {
                    await window._ensureUserDoc(user);
                }

                const snap    = await db.collection(COLLECTIONS.USERS).doc(user.uid).get();
                const profile = snap.data() || {};

                AppState.currentUser = {
                    uid:           user.uid,
                    email:         user.email,
                    displayName:   profile.name   || user.displayName || (user.email||'').split('@')[0],
                    photoURL:      profile.avatar  || user.photoURL   || '',
                    phone:         profile.phone   || user.phoneNumber || '',
                    role:          profile.role    || 'buyer',
                    acceptedTerms: profile.acceptedTerms || false,
                };

                // Wallet listener — delayed to avoid permission-denied race condition
                setTimeout(() => {
                    db.collection(COLLECTIONS.WALLET).doc(user.uid).onSnapshot(
                        snap => { if (snap.exists) AppState.wallet = snap.data(); },
                        err  => {
                            if (err.code !== 'permission-denied') {
                                console.warn('[Wallet] listener:', err.code);
                            }
                        }
                    );
                }, 1500);

                _updateNavForUser(AppState.currentUser);
                _startNotifListener(user.uid);
                updateCartCount();

                // Navigate home on first load if no hash in URL
                if (isFirstRun && !window.location.hash) {
                    navigateTo('home');
                }

                // Show Terms modal if not accepted
                if (!AppState.currentUser.acceptedTerms) {
                    setTimeout(_showTermsModal, 500);
                }

            } catch (err) {
                console.warn('[Auth] Profile load error:', err.code || err.message);
                AppState.currentUser = {
                    uid: user.uid, email: user.email,
                    displayName: user.displayName || 'User',
                    photoURL: user.photoURL || '',
                    role: 'buyer', acceptedTerms: false,
                };
                _updateNavForUser(AppState.currentUser);
                if (!window.location.hash) navigateTo('home');
            }
        } else {
            AppState.currentUser = null;
            _updateNavForGuest();
        }

        // ⚠️ ADDED (found in audit): the admin "Maintenance mode" toggle
        // (js/dashboard.js cfg_maintenance) saved PLATFORM.MAINTENANCE to
        // Firestore but nothing ever read it back — a real admin control with
        // zero actual effect on the site. Now enforced here, once we know
        // both the platform config and the visitor's role.
        try { await loadPlatformSettings(); } catch (e) {}
        _enforceMaintenanceGate();

        // ── Hide loading screen ──
        const loadingScreen = document.getElementById('appLoadingScreen');
        if (loadingScreen && !loadingScreen.classList.contains('fade-out')) {
            loadingScreen.classList.add('fade-out');
            setTimeout(() => loadingScreen.remove(), 600);
        }
    });

    // Full-site maintenance gate — admins always pass through so they can
    // still fix things; everyone else sees a blocking notice instead of the app.
    function _enforceMaintenanceGate() {
        const isAr   = AppState.language !== 'en';
        const isAdmin = AppState.currentUser && AppState.currentUser.role === 'admin';
        let gate = document.getElementById('maintenanceGate');
        if (!PLATFORM.MAINTENANCE || isAdmin) {
            if (gate) gate.remove();
            return;
        }
        if (gate) return; // already showing
        gate = document.createElement('div');
        gate.id = 'maintenanceGate';
        gate.style.cssText = 'position:fixed;inset:0;z-index:99999;background:#0f2a4a;color:#fff;display:flex;flex-direction:column;align-items:center;justify-content:center;text-align:center;padding:2rem;';
        gate.innerHTML = `
          <i class="fa-solid fa-screwdriver-wrench" style="font-size:2.5rem;color:#2dd4bf;margin-bottom:1rem"></i>
          <h1 style="font-size:1.5rem;font-weight:900;margin-bottom:.5rem">${isAr ? 'الموقع تحت الصيانة حالياً' : 'Site under maintenance'}</h1>
          <p style="color:#c8d5e6;max-width:420px">${(PLATFORM.MAINTENANCE_MSG && PLATFORM.MAINTENANCE_MSG.trim()) || (isAr ? 'هنرجع قريب، شكراً لصبرك.' : "We'll be back shortly — thanks for your patience.")}</p>`;
        document.body.appendChild(gate);
    }

    function _updateNavForUser(user) {
        document.getElementById('guestButtons')?.classList.add('hidden');
        document.getElementById('userMenuWrap')?.classList.remove('hidden');
        document.getElementById('notifBtn')?.classList.remove('hidden');

        const navName = document.getElementById('navName');
        if (navName) navName.textContent = user.displayName?.split(' ')[0] || '';

        const navAvatar = document.getElementById('navAvatar');
        if (navAvatar) { navAvatar.src = user.photoURL || ''; navAvatar.onerror = () => navAvatar.src = `https://ui-avatars.com/api/?name=${encodeURIComponent(user.displayName||'U')}&background=0284c7&color=fff`; }

        const adminBtn = document.getElementById('adminNavBtn');
        if (adminBtn) adminBtn.classList.toggle('hidden', user.role !== 'admin');
    }

    function _updateNavForGuest() {
        document.getElementById('guestButtons')?.classList.remove('hidden');
        document.getElementById('userMenuWrap')?.classList.add('hidden');
        document.getElementById('notifBtn')?.classList.add('hidden');
    }

    // ── Terms Modal ───────────────────────────────────────────────────────────
    function _showTermsModal() {
        if (document.getElementById('termsModal')) return;
        const isAr = AppState.language !== 'en';
        const modal = document.createElement('div');
        modal.id = 'termsModal';
        modal.innerHTML = `
          <div class="terms-box">
            <div class="sticky top-0 bg-white border-b border-gray-100 p-6 rounded-t-3xl">
              <div class="flex items-center gap-3">
                <div class="w-12 h-12 bg-navy-100 rounded-2xl flex items-center justify-center">
                  <i class="fa-solid fa-shield-check text-navy-600 text-xl"></i>
                </div>
                <div>
                  <h2 class="font-black text-gray-900 text-lg">${isAr ? 'الشروط والأحكام' : 'Terms & Conditions'}</h2>
                  <p class="text-gray-500 text-sm">${isAr ? 'يرجى قراءة الشروط قبل الاستخدام' : 'Please read before using the platform'}</p>
                </div>
              </div>
            </div>
            <div class="p-6 space-y-5 text-sm text-gray-700 leading-relaxed">
              <div class="bg-blue-50 border border-blue-200 rounded-2xl p-4">
                <h3 class="font-black text-blue-800 mb-2 flex items-center gap-2">
                  <i class="fa-solid fa-store"></i> ${isAr ? 'دور المنصة' : 'Platform Role'}
                </h3>
                <p>${isAr
                  ? 'مول الخدمات وسيط بين البائعين والمشترين فقط. المنصة ليست طرفاً في أي اتفاقية خدمة بين المستخدمين.'
                  : 'Mall Services acts as an intermediary between buyers and sellers only. The platform is not a party to any service agreement between users.'
                }</p>
              </div>
              <div class="bg-orange-50 border border-orange-200 rounded-2xl p-4">
                <h3 class="font-black text-orange-800 mb-2 flex items-center gap-2">
                  <i class="fa-solid fa-credit-card"></i> ${isAr ? 'سياسة الدفع والاسترداد' : 'Payment & Refund Policy'}
                </h3>
                <ul class="space-y-2 list-none">
                  <li class="flex items-start gap-2"><i class="fa-solid fa-circle-check text-green-500 mt-0.5 flex-shrink-0"></i><span>${isAr ? 'يتم تحويل المبلغ لحساب الضمان (Escrow) فور الدفع.' : 'Payment is transferred to escrow immediately upon checkout.'}</span></li>
                  <li class="flex items-start gap-2"><i class="fa-solid fa-circle-check text-green-500 mt-0.5 flex-shrink-0"></i><span>${isAr ? 'يمكن طلب الاسترداد قبل بدء تنفيذ الخدمة.' : 'Refunds can be requested before service delivery begins.'}</span></li>
                  <li class="flex items-start gap-2"><i class="fa-solid fa-circle-xmark text-red-500 mt-0.5 flex-shrink-0"></i><span>${isAr ? 'لا يمكن الاسترداد بعد تسليم الخدمة واعتماد المشتري للتسليم.' : 'No refunds after service delivery is confirmed by the buyer.'}</span></li>
                  <li class="flex items-start gap-2"><i class="fa-solid fa-circle-check text-green-500 mt-0.5 flex-shrink-0"></i><span>${isAr ? 'يحق للمشتري رفع نزاع خلال 7 أيام من التسليم.' : 'Buyers may raise a dispute within 7 days of delivery.'}</span></li>
                </ul>
              </div>
              <div class="bg-purple-50 border border-purple-200 rounded-2xl p-4">
                <h3 class="font-black text-purple-800 mb-2 flex items-center gap-2">
                  <i class="fa-solid fa-user-shield"></i> ${isAr ? 'مسؤولية المستخدم' : 'User Responsibility'}
                </h3>
                <p>${isAr
                  ? 'المستخدم مسؤول عن دقة المعلومات المقدمة واحترام شروط الخدمة. يُحظر نشر محتوى غير قانوني أو مضلل.'
                  : 'Users are responsible for the accuracy of information provided and compliance with service terms. Illegal or misleading content is prohibited.'
                }</p>
              </div>
              <div class="bg-green-50 border border-green-200 rounded-2xl p-4">
                <h3 class="font-black text-green-800 mb-2 flex items-center gap-2">
                  <i class="fa-solid fa-lock"></i> ${isAr ? 'الخصوصية والأمان' : 'Privacy & Security'}
                </h3>
                <p>${isAr
                  ? 'نحن نحمي بياناتك وفقاً لأعلى معايير الأمان. لن يتم مشاركة بياناتك مع أطراف ثالثة بدون موافقتك.'
                  : 'We protect your data according to the highest security standards. Your data will not be shared with third parties without your consent.'
                }</p>
              </div>
            </div>
            <div class="sticky bottom-0 bg-white border-t border-gray-100 p-6 rounded-b-3xl space-y-3">
              <button onclick="if(window.AuthManager&&AuthManager.acceptTerms){AuthManager.acceptTerms()}else{document.getElementById('termsModal').remove()}"
                class="w-full py-4 bg-gradient-to-r from-navy-600 to-navy-800 text-white rounded-2xl font-black text-base shadow-lg hover:shadow-xl transition flex items-center justify-center gap-2">
                <i class="fa-solid fa-check-circle"></i>
                ${isAr ? 'أوافق على الشروط والأحكام' : 'I Accept the Terms & Conditions'}
              </button>
              <button onclick="AuthManager.logout()"
                class="w-full py-3 text-gray-500 font-bold border-2 border-gray-200 rounded-2xl hover:bg-gray-50 transition text-sm">
                ${isAr ? 'تسجيل الخروج' : 'Sign Out'}
              </button>
            </div>
          </div>`;
        document.body.appendChild(modal);
    }

    function _startNotifListener(uid) {
        if (typeof NotificationsManager !== 'undefined') {
            NotificationsManager.startListener(uid);
            return;
        }
        // Fallback if notifications.js not loaded yet
        db.collection(COLLECTIONS.NOTIFICATIONS)
            .where('userId','==',uid).where('read','==',false)
            .orderBy('createdAt','desc').limit(20)
            .onSnapshot(snap => {
                const count = snap.size;
                document.querySelectorAll('[data-notif-count]').forEach(el => {
                    el.textContent = count;
                    el.classList.toggle('hidden', count === 0);
                });

                const list = document.getElementById('notifList');
                if (!list) return;
                if (snap.empty) { list.innerHTML = '<p class="text-center text-gray-400 text-sm py-8">لا توجد إشعارات</p>'; return; }

                list.innerHTML = snap.docs.map(doc => {
                    const n = doc.data();
                    return `
                    <div class="px-4 py-3 hover:bg-gray-50 transition cursor-pointer" onclick="if('${n.orderId}')openWorkspace('${n.orderId}');toggleNotifDropdown()">
                      <p class="text-sm font-bold text-gray-900">${n.title || ''}</p>
                      <p class="text-xs text-gray-500 mt-0.5">${n.message || ''}</p>
                      <p class="text-xs text-gray-400 mt-1">${formatTimeAgo(n.createdAt)}</p>
                    </div>`;
                }).join('');
            }, err => { if (err.code !== 'failed-precondition') console.warn('[Notif]', err.code); });
    }

    // ── App Start ─────────────────────────────────────────────────────────────
    document.addEventListener('DOMContentLoaded', () => {
        // Expose renderCart globally
        window.renderCart = renderCart;
        window.initCartPage = renderCart; // called automatically by navigateTo('cart')

        // Handle Google sign-in redirect result (fires after returning from Google)
        if (window.AuthManager && typeof AuthManager.handleGoogleRedirectResult === 'function') {
            AuthManager.handleGoogleRedirectResult();
        }

        // Start on home
        handleHash();
        if (!window.location.hash) navigateTo('home');

        // Load featured services, products, and stats after short delay
        // (initHomePage was defined but never invoked — homeProductsGrid and
        // the header stats stayed stuck on skeletons/"—" forever)
        setTimeout(() => window.initHomePage(), 500);

        // Initial cart render
        renderCart();
        updateCartCount();

        console.log('✅ Mall Services v3.0 ready — Chat | Firebase | Fawaterak | Google Auth');

        // ── Newsletter subscription ──────────────────────────────────────────
        window.homeSubscribe = function() {
          const email = document.getElementById('homeNewsletterEmail')?.value?.trim();
          const msg   = document.getElementById('homeNewsletterMsg');
          if (!email || !email.includes('@')) {
            if(msg){msg.style.color='#fca5a5';msg.textContent='يرجى إدخال بريد صحيح';msg.style.display='block';}
            return;
          }
          if(msg){msg.style.color='#86efac';msg.textContent='✅ تم الاشتراك بنجاح! شكراً';msg.style.display='block';}
          document.getElementById('homeNewsletterEmail').value='';
          // Save subscriber to Firestore
          if(window.db){
            window.db.collection('newsletter_subscribers').add({
              email, createdAt: firebase.firestore.FieldValue.serverTimestamp(), source:'homepage'
            }).catch(()=>{});
          }
          if(window.trackEvent) trackEvent('newsletter_subscribe','engagement','homepage');
        };

        // ── Load blog posts on homepage ──────────────────────────────────────
        // Called when page-home becomes visible
        const _origNavigateHome = window.navigateTo;
        // Load homepage blog on first render
        document.addEventListener('DOMContentLoaded', () => {
          setTimeout(() => {
            if (window.BlogEngine && window.db && document.getElementById('home-blog-grid')) {
              BlogEngine.renderBlogList('home-blog-grid', { limit: 3 });
            }
          }, 800);
        });

        window.navigateTo = function(page) {
          // ── Guard: admin page is admin-only ──────────────────────────────
          if (page === 'admin') {
            if (!AppState.currentUser || AppState.currentUser.role !== 'admin') {
              var isAr = AppState.language !== 'en';
              showToast(isAr ? '🚫 هذه الصفحة للمسؤولين فقط' : '🚫 Admin access only', 'error');
              return; // block navigation entirely
            }
          }
          _origNavigateHome(page);
          if (page === 'home' && window.BlogEngine && window.db) {
            setTimeout(() => BlogEngine.renderBlogList('home-blog-grid', { limit: 3 }), 300);
          }
          if (page === 'admin' && AppState.currentUser && AppState.currentUser.role === 'admin') {
            setTimeout(() => { if(window.AdminAI) AdminAI.loadPosts(); }, 200);
          }
        };

        // ── Admin AI Module ──────────────────────────────────────────────────
        window.AdminAI = (function() {
          var self = {
            _activeTab: 'posts',

            // ── Admin token fetch helper ────────────────────────────────────
            _fetchAI: async function(body) {
              // The ADMIN_SECRET header is optional — Function skips the check if ADMIN_SECRET env is not set
              var headers = { 'Content-Type': 'application/json' };
              // Pass uid as a lightweight token so the function can log admin identity
              if (window.AppState && window.AppState.currentUser) {
                headers['X-Admin-Token'] = window.AppState.currentUser.uid;
              }
              var res = await fetch('/api/ai-generate', {
                method: 'POST',
                headers: headers,
                body: JSON.stringify(body),
              });
              return res.json();
            },

            tab: function(name, btn) {
              ['posts','ai','seo'].forEach(function(t) {
                var panel = document.getElementById('admin-tab-'+t);
                var b     = document.getElementById('tab-'+t+'-btn');
                if (panel) panel.classList.toggle('hidden', t !== name);
                if (b) {
                  b.classList.toggle('bg-navy-600',   t === name);
                  b.classList.toggle('text-white',     t === name);
                  b.classList.toggle('shadow-glow',    t === name);
                  b.classList.toggle('bg-white',       t !== name);
                  b.classList.toggle('text-gray-600',  t !== name);
                  b.classList.toggle('border',         t !== name);
                  b.classList.toggle('border-gray-200',t !== name);
                }
              });
              self._activeTab = name;
              if (name === 'posts') self.loadPosts();
              if (name === 'ai')    self.loadTopics();
              if (name === 'seo')   self.renderSEOChecklist();
            },

            loadPosts: async function() {
              if (!window.db) return;
              var tbody = document.getElementById('admin-posts-tbody');
              var label = document.getElementById('posts-count-label');
              if (tbody) tbody.innerHTML = '<tr><td colspan="5" class="text-center py-8 text-gray-400"><i class="fa-solid fa-spinner fa-spin"></i> جاري التحميل...</td></tr>';
              try {
                var snap = await window.db.collection('blog_posts').orderBy('createdAt','desc').limit(60).get();
                var all  = snap.docs.map(function(d){ return Object.assign({id:d.id}, d.data()); });
                var statPosts = document.getElementById('stat-posts');
                var statAi    = document.getElementById('stat-ai');
                var statViews = document.getElementById('stat-views');
                var statPub   = document.getElementById('stat-pub');
                if (statPosts) statPosts.textContent = all.length;
                if (statAi)    statAi.textContent    = all.filter(function(p){ return p.aiGenerated; }).length;
                if (statViews) statViews.textContent = all.reduce(function(s,p){ return s+(p.views||0); },0).toLocaleString('ar-EG');
                if (statPub)   statPub.textContent   = all.filter(function(p){ return p.published; }).length;
                if (label) label.textContent = all.length + ' مقال';
                if (!tbody) return;
                if (all.length === 0) {
                  tbody.innerHTML = '<tr><td colspan="5" class="text-center py-12 text-gray-400">لا توجد مقالات — ولّد أول مقال من تبويب AI</td></tr>';
                  return;
                }
                // rows built via DOM
                all.forEach(function(p) {
                  var pubClass = p.published
                    ? 'bg-green-100 text-green-700 hover:bg-red-100 hover:text-red-600'
                    : 'bg-gray-100 text-gray-600 hover:bg-green-100 hover:text-green-700';
                  var pubLabel = p.published ? '✅ منشور' : '⏸ موقوف';
                  var safeTitle = (p.title||'').slice(0,20).replace(/'/g,'');
                  // Use data attributes to avoid quote nesting issues
                  var tr = document.createElement('tr');
                  tr.className = 'hover:bg-gray-50 transition border-b border-gray-50';
                  tr.innerHTML = '<td class="px-4 py-3 max-w-xs"><p class="font-bold text-gray-900 text-sm truncate">' + (p.title||'') + '</p><p class="text-xs text-gray-400 font-mono">' + (p.slug||'').slice(0,28) + '</p></td>'
                    + '<td class="px-4 py-3 hidden sm:table-cell"><span class="bg-navy-100 text-navy-700 text-xs font-bold px-2 py-0.5 rounded-full">' + (p.category||'').replace(/-/g,' ') + '</span></td>'
                    + '<td class="px-4 py-3"><button data-id="' + p.id + '" data-pub="' + (!p.published) + '" data-title="' + safeTitle + '" class="admin-toggle-pub text-xs font-bold px-3 py-1 rounded-full transition ' + pubClass + '">' + pubLabel + '</button></td>'
                    + '<td class="px-4 py-3 hidden md:table-cell text-gray-500 font-mono text-sm">' + ((p.views||0).toLocaleString()) + '</td>'
                    + '<td class="px-4 py-3"><div class="flex gap-2"><a href="/blog/' + p.slug + '" target="_blank" class="w-8 h-8 bg-blue-50 text-blue-600 rounded-lg flex items-center justify-center hover:bg-blue-100 transition" title="عرض"><i class="fa-solid fa-eye text-xs"></i></a>'
                    + '<button data-del-id="' + p.id + '" class="admin-del-post w-8 h-8 bg-red-50 text-red-500 rounded-lg flex items-center justify-center hover:bg-red-100 transition" title="حذف"><i class="fa-solid fa-trash text-xs"></i></button></div></td>';
                  tbody.appendChild(tr);
                });
                // Event delegation for toggle/delete buttons
                tbody.addEventListener('click', function(e) {
                  var toggleBtn = e.target.closest('.admin-toggle-pub');
                  var deleteBtn = e.target.closest('.admin-del-post');
                  if (toggleBtn) {
                    window.AdminAI.togglePublish(toggleBtn.dataset.id, toggleBtn.dataset.pub === 'true', toggleBtn.dataset.title);
                  }
                  if (deleteBtn) {
                    window.AdminAI.deletePost(deleteBtn.dataset.delId);
                  }
                });
              } catch(err) {
                if (tbody) tbody.innerHTML = '<tr><td colspan="5" class="text-center py-8 text-red-400">خطأ: '+err.message+'</td></tr>';
              }
            },

            togglePublish: async function(id, newVal, title) {
              try {
                await window.db.collection('blog_posts').doc(id).update({
                  published: newVal,
                  updatedAt: firebase.firestore.FieldValue.serverTimestamp()
                });
                showToast((newVal ? '✅ تم نشر ' : '⏸ تم إيقاف ') + '"' + title + '"', newVal ? 'success' : 'info');
                self.loadPosts();
              } catch(e) { showToast('خطأ: ' + e.message, 'error'); }
            },

            deletePost: async function(id) {
              if (!confirm('حذف هذا المقال نهائياً؟')) return;
              try {
                await window.db.collection('blog_posts').doc(id).delete();
                showToast('🗑️ تم حذف المقال', 'success');
                self.loadPosts();
              } catch(e) { showToast('خطأ: ' + e.message, 'error'); }
            },

            loadTopics: async function() {
              var container = document.getElementById('topics-bank');
              if (!container) return;
              try {
                var data   = await self._fetchAI({action:'topics'});
                var topics = data.topics || [];
                var frag = document.createDocumentFragment();
                topics.forEach(function(t) {
                  var btn = document.createElement('button');
                  btn.className = 'text-xs bg-gray-100 hover:bg-navy-100 hover:text-navy-700 text-gray-600 px-3 py-1.5 rounded-full font-medium transition cursor-pointer border border-transparent hover:border-navy-300';
                  btn.textContent = t;
                  btn.addEventListener('click', function() {
                    var inp = document.getElementById('ai-topic-input');
                    if (inp) inp.value = t;
                  });
                  frag.appendChild(btn);
                });
                container.innerHTML = '';
                container.appendChild(frag);
              } catch(e) {
                container.innerHTML = '<p class="text-xs text-gray-400">أضف GEMINI_API_KEY في Cloudflare Pages Environment Variables</p>';
              }
            },

            generate: async function() {
              // ── Admin-only guard ──────────────────────────────────────────
              if (!AppState.currentUser || AppState.currentUser.role !== 'admin') {
                showToast('🚫 ' + (AppState.language !== 'en' ? 'توليد المقالات للمسؤولين فقط' : 'Article generation is admin-only'), 'error');
                return;
              }
              var btn     = document.getElementById('ai-gen-btn');
              var btnText = document.getElementById('ai-gen-btn-text');
              var result  = document.getElementById('ai-result');
              var topicEl = document.getElementById('ai-topic-input');
              var countEl = document.getElementById('ai-count-select');
              var topic   = topicEl ? topicEl.value.trim() : '';
              var count   = countEl ? parseInt(countEl.value) || 1 : 1;
              if (btn) btn.disabled = true;
              if (btnText) btnText.textContent = 'جاري التوليد...';
              if (result) {
                result.classList.remove('hidden');
                result.className = 'rounded-xl p-4 text-sm font-medium bg-yellow-50 border border-yellow-200 text-yellow-800';
                result.innerHTML = '<i class="fa-solid fa-spinner fa-spin mr-2"></i>يتم توليد المقال... قد يستغرق 20-40 ثانية';
              }
              try {
                var body = topic ? {action:'generate', topic:topic} : {action:'bulk', count:count};
                var data = await self._fetchAI(body);
                if (data.success) {
                  var n = (data.results && data.results.length) || 1;
                  if (result) {
                    result.className = 'rounded-xl p-4 text-sm font-medium bg-green-50 border border-green-200 text-green-800';
                    result.innerHTML = '✅ تم توليد ' + n + ' مقال بنجاح! سيظهر في قائمة المقالات.';
                  }
                  self.loadPosts();
                  if (window.trackEvent) trackEvent('ai_generate', 'admin', 'count_' + n);
                } else {
                  if (result) {
                    result.className = 'rounded-xl p-4 text-sm font-medium bg-red-50 border border-red-200 text-red-700';
                    result.innerHTML = '❌ خطأ: ' + (data.error || 'مجهول') + '<br><small>تأكد من إضافة GEMINI_API_KEY في Cloudflare Pages Environment Variables</small>';
                  }
                }
              } catch(e) {
                if (result) {
                  result.className = 'rounded-xl p-4 text-sm font-medium bg-red-50 border border-red-200 text-red-700';
                  result.innerHTML = '❌ ' + e.message;
                }
              } finally {
                if (btn) btn.disabled = false;
                if (btnText) btnText.textContent = 'ابدأ التوليد';
              }
            },

            generateOne: async function() {
              // ── Admin-only guard ──────────────────────────────────────────
              if (!AppState.currentUser || AppState.currentUser.role !== 'admin') {
                showToast('🚫 ' + (AppState.language !== 'en' ? 'توليد المقالات للمسؤولين فقط' : 'Article generation is admin-only'), 'error');
                return;
              }
              var btn = document.getElementById('admin-gen-btn');
              if (btn) { btn.disabled = true; btn.innerHTML = '<i class="fa-solid fa-spinner fa-spin"></i> جاري التوليد...'; }
              try {
                var data = await self._fetchAI({action:'generate'});
                if (data.success) {
                  showToast('✅ تم توليد: ' + (data.title||'').slice(0,40) + '…', 'success');
                  self.loadPosts();
                } else {
                  showToast('❌ ' + (data.error||'خطأ'), 'error');
                }
              } catch(e) {
                showToast('❌ ' + e.message, 'error');
              } finally {
                if (btn) { btn.disabled = false; btn.innerHTML = '<i class="fa-solid fa-wand-magic-sparkles"></i> توليد مقال AI الآن'; }
              }
            },

            renderSEOChecklist: function() {
              var el = document.getElementById('seo-checklist');
              if (!el) return;
              var checks = [
                {done:true,  label:'Google Site Verification مضاف'},
                {done:true,  label:'Sitemap.xml ثابت موجود'},
                {done:true,  label:'Sitemap ديناميكي من Firestore'},
                {done:true,  label:'robots.txt محسن'},
                {done:true,  label:'Meta tags ديناميكية لكل مقال'},
                {done:true,  label:'Open Graph + Twitter Cards'},
                {done:true,  label:'JSON-LD Structured Data'},
                {done:true,  label:'توليد محتوى تلقائي يومي'},
                {done:true,  label:'نظام مدونة ديناميكي من Firestore'},
                {done:false, label:'أضف GEMINI_API_KEY في Cloudflare Env Vars'},
                {done:false, label:'أضف UNSPLASH_ACCESS_KEY للصور'},
                {done:false, label:'ربط Google Analytics'},
                {done:false, label:'تقديم طلب Google AdSense'}
              ];
              var html = '';
              checks.forEach(function(c) {
                var iconClass = c.done ? 'fa-circle-check text-green-500' : 'fa-circle-xmark text-red-400';
                var textClass = c.done ? 'text-gray-700' : 'text-gray-400';
                html += '<div class="flex items-start gap-3 py-2 border-b border-gray-50 last:border-0">'
                  + '<i class="fa-solid '+iconClass+' mt-0.5 flex-shrink-0"></i>'
                  + '<span class="text-sm '+textClass+'">'+c.label+'</span></div>';
              });
              el.innerHTML = html;
            }
          };
          return self;
        })();
        // Init admin when navigating to admin page (handled above)
        

        // ── Network status ────────────────────────────────────────────────────
        const offlineBanner = document.getElementById('offlineBanner');
        function _handleOnline()  { offlineBanner && offlineBanner.classList.remove('show'); }
        function _handleOffline() { offlineBanner && offlineBanner.classList.add('show'); }
        window.addEventListener('online',  _handleOnline);
        window.addEventListener('offline', _handleOffline);
        if (!navigator.onLine) _handleOffline();

        // Register Service Worker
        if ('serviceWorker' in navigator) {
            navigator.serviceWorker.register('/sw.js')
                .then(reg => console.log('[SW] Registered:', reg.scope))
                .catch(err => console.warn('[SW] Registration failed:', err));
        }
    });

})();
</script>
</body>
</html>
