<!DOCTYPE html>
<html lang="en">
<head>
<!-- Google tag (gtag.js) -->
<script async src="https://www.googletagmanager.com/gtag/js?id=G-FGRX6QS715"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());

  gtag('config', 'G-FGRX6QS715');
</script>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<title>OrderDrop.pk - Chichawatni Ki Fast Delivery | 30 Min Groceries & Fast Food</title>
<meta name="description" content="OrderDrop.pk is Chichawatni's fastest 30-minute delivery service. Order groceries, fresh vegetables, fast food, and more with Cash on Delivery.">
<meta name="keywords" content="OrderDrop, Chichawatni delivery, fast food Chichawatni, grocery delivery Pakistan, online store Chichawatni, 30 min delivery">
<meta name="robots" content="index, follow">
<meta name="author" content="OrderDrop.pk">
<link rel="canonical" href="https://orderdrop.pk/">

<meta property="og:type" content="website">
<meta property="og:url" content="https://orderdrop.pk/">
<meta property="og:title" content="OrderDrop.pk - Chichawatni Ki Fast Delivery">
<meta property="og:description" content="Chichawatni mein 30 min delivery. Groceries, Fast Food, Fresh items order karein. Cash on Delivery available.">
<meta property="og:image" content="https://i.ibb.co/DfWY3Y6H/1792259832609.jpg">

<meta property="twitter:card" content="summary_large_image">
<meta property="twitter:url" content="https://orderdrop.pk/">
<meta property="twitter:title" content="OrderDrop.pk - Chichawatni Ki Fast Delivery">
<meta property="twitter:description" content="Chichawatni mein 30 min delivery. Groceries, Fast Food, Fresh items order karein. Cash on Delivery available.">
<meta property="twitter:image" content="https://i.ibb.co/DfWY3Y6H/1792259832609.jpg">

<script type="application/ld+json">
{
  "@context": "https://schema.org",
  "@type": "GroceryStore",
  "name": "OrderDrop.pk",
  "image": "https://i.ibb.co/DfWY3Y6H/1792259832609.jpg",
  "description": "Chichawatni ki sab se tez tareen delivery service. Groceries, fast food, aur fresh items.",
  "url": "https://orderdrop.pk/",
  "telephone": "+923153367920",
  "address": {
    "@type": "PostalAddress",
    "addressLocality": "Chichawatni",
    "addressRegion": "Punjab",
    "addressCountry": "PK"
  }
}
</script>

<link rel="icon" type="image/png" href="/logo.png">
<link rel="apple-touch-icon" href="/logo.png">
<link rel="icon" type="image/png" sizes="512x512" href="/logo.png">
<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">

<script src="https://cdn.tailwindcss.com"></script>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800;900&display=swap" rel="stylesheet">
<style>
  * { font-family: 'Inter', sans-serif; -webkit-tap-highlight-color: transparent; }
  body { overscroll-behavior-y: none; background: #F5F7FA; }
  .no-scrollbar::-webkit-scrollbar { display: none; }
  .no-scrollbar { -ms-overflow-style: none; scrollbar-width: none; }
  .page { display: none; }
  .page.active { display: block; }
  @keyframes slideUp { from { transform: translateY(100%); opacity: 0; } to { transform: translateY(0); opacity: 1; } }
  .slide-up { animation: slideUp 0.3s ease-out; }
  @keyframes fadeIn { from { opacity: 0; transform: translateY(10px); } to { opacity: 1; transform: translateY(0); } }
  .fade-in { animation: fadeIn 0.3s ease-out; }
  .line-clamp-2 { display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; }
  .safe-bottom { padding-bottom: env(safe-area-inset-bottom, 0); }

  .brand-navy { color: #0B1B33; }
  .brand-orange { color: #FF6B00; }
  .bg-brand-navy { background-color: #0B1B33; }
  .bg-brand-orange { background-color: #FF6B00; }
  .border-brand-orange { border-color: #FF6B00; }

  .product-card { background: #fff; border-radius: 16px; overflow: hidden; transition: all 0.2s ease; border: 1px solid #EEF1F5; }
  .product-card:hover { box-shadow: 0 8px 24px rgba(11, 27, 51, 0.08); transform: translateY(-2px); }

  .btn-primary { background: linear-gradient(135deg, #FF6B00 0%, #FF8A33 100%); color: #fff; font-weight: 700; border-radius: 12px; transition: all 0.2s ease; }
  .btn-primary:hover { box-shadow: 0 6px 20px rgba(255, 107, 0, 0.35); transform: translateY(-1px); }
  .btn-primary:active { transform: scale(0.98); }

  .btn-navy { background: #0B1B33; color: #fff; font-weight: 700; border-radius: 12px; transition: all 0.2s ease; }
  .btn-navy:hover { background: #1a2f4d; }

  .daily-deals-grid { display: grid; grid-template-columns: 1fr; gap: 16px; }
  @media (min-width: 768px) { .daily-deals-grid { grid-template-columns: repeat(2, 1fr); gap: 20px; } }
  @media (min-width: 1024px) { .daily-deals-grid { grid-template-columns: repeat(3, 1fr); gap: 24px; } }

  .combo-card { background: #fff; border-radius: 20px; overflow: hidden; border: 1px solid #EEF1F5; box-shadow: 0 4px 15px rgba(0,0,0,0.03); display: flex; flex-direction: column; transition: all 0.2s ease; }
  .combo-card:hover { box-shadow: 0 8px 25px rgba(0,0,0,0.08); transform: translateY(-2px); }
  .combo-img-wrap { position: relative; width: 100%; height: 160px; background: #f9fafb; }
  .combo-img-wrap img { width: 100%; height: 100%; object-fit: cover; }
  .combo-title-overlay { position: absolute; bottom: 0; left: 0; right: 0; padding: 30px 16px 12px 16px; background: linear-gradient(to top, rgba(0,0,0,0.85) 0%, rgba(0,0,0,0) 100%); color: #fff; font-size: 18px; font-weight: 800; line-height: 1.2; }
  .combo-body { padding: 16px; display: flex; flex-direction: column; flex: 1; }
  .combo-name { font-size: 15px; font-weight: 600; color: #374151; margin-bottom: 4px; line-clamp: 2; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; }
  .combo-vendor { font-size: 12px; color: #9CA3AF; display: flex; align-items: center; gap: 4px; margin-bottom: 16px; }
  .combo-footer { display: flex; align-items: center; justify-content: space-between; margin-top: auto; padding-top: 14px; border-top: 1px solid #F3F4F6; }
  .combo-price { font-size: 20px; font-weight: 800; color: #0B1B33; }


.btn-pro-order {
  background: linear-gradient(135deg, #FF6B00 0%, #FF8A33 100%);
  color: #fff;
  padding: 10px 20px;
  border-radius: 10px;
  font-size: 13px;
  font-weight: 800;
  transition: all 0.3s ease;
  box-shadow: 0 4px 15px rgba(255, 107, 0, 0.3);
  display: inline-flex;
  align-items: center;
  gap: 6px;
  border: none;
  cursor: pointer;
}
.btn-pro-order:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(255, 107, 0, 0.5);
}
.btn-pro-order:active {
  transform: scale(0.96);
}

  .deal-banner { position: relative; overflow: hidden; border-radius: 18px; box-shadow: 0 6px 20px rgba(11, 27, 51, 0.1); display: flex; flex-direction: column; justify-content: flex-end; padding: 22px; }

  .section-header { display: flex; align-items: center; justify-content: space-between; margin-bottom: 14px; }
  .section-title { font-size: 17px; font-weight: 800; color: #0B1B33; letter-spacing: -0.3px; }

  .bottom-nav-item { display: flex; flex-direction: column; align-items: center; gap: 3px; padding: 8px 0; font-size: 10px; font-weight: 600; transition: all 0.2s ease; position: relative; }
  .bottom-nav-item.active { color: #FF6B00; }
  .bottom-nav-item.active::before { content: ''; position: absolute; top: 0; left: 50%; transform: translateX(-50%); width: 24px; height: 3px; background: #FF6B00; border-radius: 0 0 4px 4px; }

  .badge-discount { position: absolute; top: 8px; left: 8px; background: #FF3B30; color: #fff; font-size: 10px; font-weight: 800; padding: 3px 7px; border-radius: 6px; z-index: 2; }

  .rating-stars { display: flex; align-items: center; gap: 2px; font-size: 10px; color: #FFB800; }

  .price-current { font-weight: 800; color: #FF6B00; font-size: 15px; }
  .price-old { font-size: 11px; color: #9CA3AF; text-decoration: line-through; }

  .header-search { background: #F5F7FA; border-radius: 12px; transition: all 0.2s ease; }
  .header-search:focus-within { background: #fff; box-shadow: 0 0 0 2px #FF6B00; }

  .toast-pro { background: #0B1B33; color: #fff; border-radius: 14px; padding: 12px 20px; font-size: 13px; font-weight: 600; box-shadow: 0 10px 30px rgba(11, 27, 51, 0.3); }

  .modal-pro { border-radius: 24px; box-shadow: 0 20px 60px rgba(11, 27, 51, 0.25); }

  input, textarea, select { transition: all 0.2s ease; }
  input:focus, textarea:focus { border-color: #FF6B00 !important; box-shadow: 0 0 0 3px rgba(255, 107, 0, 0.1) !important; outline: none; }

  .qty-btn { width: 32px; height: 32px; border-radius: 10px; display: flex; align-items: center; justify-content: center; font-weight: 800; transition: all 0.15s ease; }
  .qty-btn:active { transform: scale(0.9); }

  .order-status-badge { font-size: 11px; font-weight: 700; padding: 4px 12px; border-radius: 20px; text-transform: capitalize; }

  .deal-banner h3 { font-size: 22px; line-height: 1.2; font-weight: 800; margin-bottom: 4px; word-break: break-word; }
  .deal-banner p { font-size: 12px; font-weight: 500; opacity: 0.9; }
  @media (min-width: 768px) {
    .deal-banner h3 { font-size: 28px; }
    .deal-banner p { font-size: 14px; }
  }

  #backBtn { transition: all 0.2s ease; }
  #backBtn:hover { background: #F5F7FA; transform: translateX(-2px); }

  .logo-img { object-fit: contain; }

  .rating-stars svg { width: 10px; height: 10px; }
  .rating-stars-lg svg { width: 16px; height: 16px; }

  .loading-spinner { display: inline-block; width: 32px; height: 32px; border: 3px solid #FF6B00; border-top-color: transparent; border-radius: 50%; animation: spin 0.8s linear infinite; }
  @keyframes spin { to { transform: rotate(360deg); } }

  .live-dot { display: inline-block; width: 6px; height: 6px; border-radius: 50%; background: #10B981; margin-right: 4px; animation: pulse 2s infinite; }
  @keyframes pulse { 0%, 100% { opacity: 1; } 50% { opacity: 0.4; } }

  .feature-box { background: #fff; border-radius: 12px; padding: 8px 4px; text-align: center; border: 1px solid #EEF1F5; transition: all 0.2s ease; }
  .feature-box:hover { box-shadow: 0 4px 12px rgba(11, 27, 51, 0.08); transform: translateY(-2px); }
  @media (min-width: 640px) { .feature-box { border-radius: 16px; padding: 16px; } }

  .copy-btn { display: inline-flex; align-items: center; gap: 4px; padding: 4px 8px; border-radius: 8px; font-size: 10px; font-weight: 700; background: #F5F7FA; color: #0B1B33; transition: all 0.2s ease; cursor: pointer; border: 1px solid #EEF1F5; }
  .copy-btn:hover { background: #FFF4EC; border-color: #FF6B00; color: #FF6B00; }
  .copy-btn:active { transform: scale(0.95); }
  /* Floating WhatsApp Button */
.whatsapp-float {
  position: fixed;
  bottom: 85px; /* Mobile par bottom nav se upar */
  right: 20px;
  background-color: #25d366;
  color: #FFF;
  border-radius: 50px;
  text-align: center;
  font-size: 30px;
  box-shadow: 2px 2px 10px rgba(0,0,0,0.2);
  z-index: 100;
  width: 55px;
  height: 55px;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
}
.whatsapp-float:hover {
  background-color: #128C7E;
  transform: scale(1.1);
}
@media (min-width: 768px) {
  .whatsapp-float { bottom: 30px; } /* Desktop par thora neechay */
}
</style>
</head>
<body class="text-gray-950">

<header id="mainHeader" class="bg-white sticky top-0 z-40 shadow-sm">
  <div class="bg-brand-navy text-white text-[11px] py-1.5 px-4 text-center font-semibold tracking-wide">
    <span class="inline-flex items-center gap-1">
      <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M4.5 16.5c-1.5 1.26-2 5-2 5s3.74-.5 5-2c.71-.84.7-2.13-.09-2.91a2.18 2.18 0 0 0-2.91-.09z"/><path d="m12 15-3-3a22 22 0 0 1 2-3.95A12.88 12.88 0 0 1 22 2c0 2.72-.78 7.5-6 11a22.35 22.35 0 0 1-4 2z"/><path d="M9 12H4s.55-3.03 2-4c1.62-1.08 5 0 5 0"/><path d="M12 15v5s3.03-.55 4-2c1.08-1.62 0-5 0-5"/></svg>
      Chichawatni mein 30 min delivery | Cash on Delivery
    </span>
  </div>

  <div class="max-w-6xl mx-auto px-4 py-3 flex items-center gap-2">
    <button id="backBtn" onclick="goBack()" class="hidden p-2 -ml-1 rounded-xl">
      <svg class="w-5 h-5 text-gray-700" fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5" d="M15 19l-7-7 7-7"/>
      </svg>
    </button>

    <button id="menuBtn" onclick="toggleMenu()" class="md:hidden p-1.5 -ml-1.5">
      <svg class="w-6 h-6 text-gray-700" fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6h16M4 12h16M4 18h16"/>
      </svg>
    </button>

    <a href="/" onclick="event.preventDefault(); navigateTo('home');" class="cursor-pointer flex items-center gap-2 shrink-0">
      <img src="https://i.ibb.co/DfWY3Y6H/1792259832609.jpg" alt="OrderDrop.pk Logo" class="w-11 h-11 logo-img rounded-xl object-cover">
      <div>
        <h1 class="text-base font-extrabold brand-navy leading-none">OrderDrop.pk</h1>
        <p class="text-[10px] text-gray-500 font-medium">Chichawatni</p>
      </div>
    </a>

    <div class="hidden md:block flex-1 mx-6">
      <div class="header-search relative">
        <input type="text" id="searchDesktop" oninput="searchProducts(this.value)" placeholder="Search groceries, vegetables, food..." class="w-full bg-transparent rounded-xl pl-11 pr-4 py-2.5 text-sm focus:outline-none">
        <svg class="w-5 h-5 text-gray-400 absolute left-3.5 top-1/2 -translate-y-1/2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"/>
        </svg>
      </div>
    </div>

    <div class="ml-auto flex items-center gap-1.5">
      <span class="hidden md:inline-flex items-center text-[10px] font-bold text-emerald-600 bg-emerald-50 px-2 py-1 rounded-full"><span class="live-dot"></span>LIVE</span>
    <button onclick="openAuthModal()" id="authHeaderBtn" class="text-xs font-extrabold bg-orange-50 text-brand-orange px-4 py-2.5 rounded-xl border border-orange-200 shadow-sm hover:bg-brand-orange hover:text-white transition-all duration-300">
        Login
      </button>
      <a href="/track-order" onclick="event.preventDefault(); navigateTo('track');" class="hidden md:block cursor-pointer text-sm font-semibold text-gray-700 px-3 py-2 hover:text-brand-orange transition">Track Order</a>
      <a href="/cart" onclick="event.preventDefault(); navigateTo('cart');" class="cursor-pointer relative bg-brand-orange text-white p-2.5 rounded-xl shadow-md hover:shadow-lg transition">
        <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 3h2l.4 2M7 13h10l4-8H5.4M7 13L5.4 5M7 13l-2.293 2.293c-.63.63-.184 1.707.707 1.707H17m0 0a2 2 0 100 4 2 2 0 000-4zm-8 2a2 2 0 11-4 0 2 2 0 014 0z"/>
        </svg>
        <span id="cartBadge" class="hidden absolute -top-1 -right-1 bg-red-500 text-white text-[10px] font-bold w-5 h-5 rounded-full flex items-center justify-center border-2 border-white">0</span>
      </a>
    </div>
  </div>

  <div id="mobileSearch" class="md:hidden px-4 pb-3">
    <div class="header-search relative">
      <input type="text" id="searchMobile" oninput="searchProducts(this.value)" placeholder="Search products..." class="w-full bg-transparent rounded-xl pl-11 pr-4 py-2.5 text-sm focus:outline-none">
      <svg class="w-5 h-5 text-gray-400 absolute left-3.5 top-1/2 -translate-y-1/2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"/>
      </svg>
    </div>
  </div>
</header>

<div id="mobileMenu" class="hidden fixed inset-0 bg-black/50 z-50 md:hidden" onclick="toggleMenu()">
  <div class="bg-white w-72 h-full p-5 slide-up overflow-y-auto" onclick="event.stopPropagation()">
    <div class="flex items-center gap-3 mb-6 pb-5 border-b">
      <img src="https://i.ibb.co/DfWY3Y6H/1792259832609.jpg" alt="OrderDrop.pk Logo" class="w-12 h-12 logo-img rounded-xl object-cover">
      <div>
        <h2 class="font-extrabold brand-navy text-lg">OrderDrop.pk</h2>
        <p class="text-xs text-gray-500 font-medium">Chichawatni</p>
      </div>
    </div>
    <nav class="space-y-1">
      <button onclick="toggleMenu(); installApp();" class="w-full flex items-center gap-3 px-3 py-3 rounded-xl bg-orange-50 hover:bg-orange-100 transition mb-2 border border-orange-200">
        <span class="w-8 h-8 flex items-center justify-center bg-brand-orange text-white rounded-lg">
          <svg width="18" height="18" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4"/></svg>
        </span>
        <span class="font-bold text-sm text-brand-orange">App Download Karein</span>
      </button>
      
      <!-- Top Menu -->
      <a href="/" onclick="event.preventDefault(); toggleMenu(); navigateTo('home');" class="cursor-pointer flex items-center gap-3 px-3 py-2.5 rounded-xl hover:bg-orange-50 transition group">
        <span class="w-9 h-9 flex items-center justify-center bg-gray-50 group-hover:bg-orange-100 rounded-xl transition-colors">
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="text-[#0B1B33] group-hover:text-brand-orange transition-colors"><path d="M3 12l2-2m0 0l7-7 7 7M5 10v10a1 1 0 001 1h3m10-11l2 2m-2-2v10a1 1 0 01-1 1h-3m-6 0a1 1 0 001-1v-4a1 1 0 011-1h2a1 1 0 011 1v4a1 1 0 001 1m-6 0h6"/></svg>
        </span>
        <span class="font-bold text-[14px] text-[#0B1B33] group-hover:text-brand-orange transition-colors">Home</span>
      </a>

      <a href="/categories" onclick="event.preventDefault(); toggleMenu(); navigateTo('category');" class="cursor-pointer flex items-center gap-3 px-3 py-2.5 rounded-xl hover:bg-orange-50 transition group">
        <span class="w-9 h-9 flex items-center justify-center bg-gray-50 group-hover:bg-orange-100 rounded-xl transition-colors">
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="text-[#0B1B33] group-hover:text-brand-orange transition-colors"><rect x="3" y="3" width="7" height="7" rx="1"/><rect x="14" y="3" width="7" height="7" rx="1"/><rect x="3" y="14" width="7" height="7" rx="1"/><rect x="14" y="14" width="7" height="7" rx="1"/></svg>
        </span>
        <span class="font-bold text-[14px] text-[#0B1B33] group-hover:text-brand-orange transition-colors">Categories</span>
      </a>

      <a href="/track-order" onclick="event.preventDefault(); toggleMenu(); navigateTo('track');" class="cursor-pointer flex items-center gap-3 px-3 py-2.5 rounded-xl hover:bg-orange-50 transition group">
        <span class="w-9 h-9 flex items-center justify-center bg-gray-50 group-hover:bg-orange-100 rounded-xl transition-colors">
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="text-[#0B1B33] group-hover:text-brand-orange transition-colors"><rect x="1" y="3" width="15" height="13" rx="1"/><polygon points="16 8 20 8 23 11 23 16 16 16 16 8"/><circle cx="5.5" cy="18.5" r="2.5"/><circle cx="18.5" cy="18.5" r="2.5"/></svg>
        </span>
        <span class="font-bold text-[14px] text-[#0B1B33] group-hover:text-brand-orange transition-colors">Track Order</span>
      </a>

      <a href="/cart" onclick="event.preventDefault(); toggleMenu(); navigateTo('cart');" class="cursor-pointer flex items-center gap-3 px-3 py-2.5 rounded-xl hover:bg-orange-50 transition group">
        <span class="w-9 h-9 flex items-center justify-center bg-gray-50 group-hover:bg-orange-100 rounded-xl transition-colors">
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="text-[#0B1B33] group-hover:text-brand-orange transition-colors"><circle cx="9" cy="21" r="1"/><circle cx="20" cy="21" r="1"/><path d="M1 1h4l2.68 13.39a2 2 0 0 0 2 1.61h9.72a2 2 0 0 0 2-1.61L23 6H6"/></svg>
        </span>
        <span class="font-bold text-[14px] text-[#0B1B33] group-hover:text-brand-orange transition-colors">Cart</span>
      </a>

      <a href="/my-orders" onclick="event.preventDefault(); toggleMenu(); checkAccountNav();" class="cursor-pointer flex items-center gap-3 px-3 py-2.5 rounded-xl hover:bg-orange-50 transition group">
        <span class="w-9 h-9 flex items-center justify-center bg-gray-50 group-hover:bg-orange-100 rounded-xl transition-colors">
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="text-[#0B1B33] group-hover:text-brand-orange transition-colors"><path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/></svg>
        </span>
        <span class="font-bold text-[14px] text-[#0B1B33] group-hover:text-brand-orange transition-colors" id="mobileAccountLabel">My Orders</span>
      </a>

      <div class="border-t my-2 pt-2"></div>

      <!-- Bottom Menu -->
      <a href="/about" class="flex items-center gap-3 px-3 py-2.5 rounded-xl hover:bg-orange-50 transition group">
        <span class="w-9 h-9 flex items-center justify-center bg-gray-50 group-hover:bg-orange-100 rounded-xl transition-colors">
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="text-[#0B1B33] group-hover:text-brand-orange transition-colors"><circle cx="12" cy="12" r="10"/><line x1="12" y1="16" x2="12" y2="12"/><line x1="12" y1="8" x2="12.01" y2="8"/></svg>
        </span>
        <span class="font-bold text-[14px] text-[#0B1B33] group-hover:text-brand-orange transition-colors">About Us</span>
      </a>

      <a href="/contact" class="flex items-center gap-3 px-3 py-2.5 rounded-xl hover:bg-orange-50 transition group">
        <span class="w-9 h-9 flex items-center justify-center bg-gray-50 group-hover:bg-orange-100 rounded-xl transition-colors">
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="text-[#0B1B33] group-hover:text-brand-orange transition-colors"><path d="M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72 12.84 12.84 0 0 0 .7 2.81 2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45 12.84 12.84 0 0 0 2.81.7A2 2 0 0 1 22 16.92z"/></svg>
        </span>
        <span class="font-bold text-[14px] text-[#0B1B33] group-hover:text-brand-orange transition-colors">Contact Us</span>
      </a>

      <a href="/faq" class="flex items-center gap-3 px-3 py-2.5 rounded-xl hover:bg-orange-50 transition group">
        <span class="w-9 h-9 flex items-center justify-center bg-gray-50 group-hover:bg-orange-100 rounded-xl transition-colors">
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="text-[#0B1B33] group-hover:text-brand-orange transition-colors"><circle cx="12" cy="12" r="10"/><path d="M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3"/><line x1="12" y1="17" x2="12.01" y2="17"/></svg>
        </span>
        <span class="font-bold text-[14px] text-[#0B1B33] group-hover:text-brand-orange transition-colors">FAQs</span>
      </a>

      <a href="/terms" class="flex items-center gap-3 px-3 py-2.5 rounded-xl hover:bg-orange-50 transition group">
        <span class="w-9 h-9 flex items-center justify-center bg-gray-50 group-hover:bg-orange-100 rounded-xl transition-colors">
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="text-[#0B1B33] group-hover:text-brand-orange transition-colors"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/><line x1="16" y1="13" x2="8" y2="13"/><line x1="16" y1="17" x2="8" y2="17"/><polyline points="10 9 9 9 8 9"/></svg>
        </span>
        <span class="font-bold text-[14px] text-[#0B1B33] group-hover:text-brand-orange transition-colors">Terms & Conditions</span>
      </a>

      <a href="/refund-policy" class="flex items-center gap-3 px-3 py-2.5 rounded-xl hover:bg-orange-50 transition group">
        <span class="w-9 h-9 flex items-center justify-center bg-gray-50 group-hover:bg-orange-100 rounded-xl transition-colors">
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="text-[#0B1B33] group-hover:text-brand-orange transition-colors"><path d="M3 9l9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"/><polyline points="9 22 9 12 15 12 15 22"/></svg>
        </span>
        <span class="font-bold text-[14px] text-[#0B1B33] group-hover:text-brand-orange transition-colors">Refund & Return</span>
      </a>

      <a href="/delivery-policy" class="flex items-center gap-3 px-3 py-2.5 rounded-xl hover:bg-orange-50 transition group">
        <span class="w-9 h-9 flex items-center justify-center bg-gray-50 group-hover:bg-orange-100 rounded-xl transition-colors">
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="text-[#0B1B33] group-hover:text-brand-orange transition-colors"><rect x="1" y="3" width="15" height="13"/><polygon points="16 8 20 8 23 11 23 16 16 16 16 8"/><circle cx="5.5" cy="18.5" r="2.5"/><circle cx="18.5" cy="18.5" r="2.5"/></svg>
        </span>
        <span class="font-bold text-[14px] text-[#0B1B33] group-hover:text-brand-orange transition-colors">Delivery Policy</span>
      </a>

      <a href="/privacy-policy" class="flex items-center gap-3 px-3 py-2.5 rounded-xl hover:bg-orange-50 transition group">
        <span class="w-9 h-9 flex items-center justify-center bg-gray-50 group-hover:bg-orange-100 rounded-xl transition-colors">
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="text-[#0B1B33] group-hover:text-brand-orange transition-colors"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/></svg>
        </span>
        <span class="font-bold text-[14px] text-[#0B1B33] group-hover:text-brand-orange transition-colors">Privacy Policy</span>
      </a>

      <a href="/disclaimer" class="flex items-center gap-3 px-3 py-2.5 rounded-xl hover:bg-orange-50 transition group">
        <span class="w-9 h-9 flex items-center justify-center bg-gray-50 group-hover:bg-orange-100 rounded-xl transition-colors">
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="text-[#0B1B33] group-hover:text-brand-orange transition-colors"><path d="M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"/><line x1="12" y1="9" x2="12" y2="13"/><line x1="12" y1="17" x2="12.01" y2="17"/></svg>
        </span>
        <span class="font-bold text-[14px] text-[#0B1B33] group-hover:text-brand-orange transition-colors">Disclaimer</span>
      </a>

      <a href="/whatsapp" class="flex items-center gap-3 px-3 py-2.5 rounded-xl hover:bg-orange-50 transition group">
        <span class="w-9 h-9 flex items-center justify-center bg-gray-50 group-hover:bg-orange-100 rounded-xl transition-colors">
          <svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor" class="text-emerald-500"><path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 01-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 01-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 012.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0012.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 005.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 00-3.48-8.413z"/></svg>
        </span>
        <span class="font-bold text-[14px] text-[#0B1B33] group-hover:text-brand-orange transition-colors">WhatsApp Support</span>
      </a>
    </nav>
  </div>
</div>

<div id="page-home" class="page active pb-24">

<section class="max-w-6xl mx-auto px-4 mt-4">
<div id="dealBoxes" class="flex flex-col gap-3 pb-1">
    <div class="w-full h-48 md:h-60 deal-banner bg-gradient-to-br from-[#0B1B33] to-[#1a2f4d] text-white flex items-center justify-center">
      <div class="loading-spinner" style="border-color:#fff;border-top-color:transparent;"></div>
    </div>
</div>
</section>

<section class="max-w-6xl mx-auto px-4 mt-8">
  <!-- Professional Deals & Combos Header Box -->
  <div class="flex items-center justify-between bg-white p-3.5 rounded-2xl border border-gray-100 shadow-sm mb-4">
    <div class="flex items-center gap-3 min-w-0">
      <div class="w-10 h-10 bg-orange-50 rounded-xl flex items-center justify-center text-brand-orange shrink-0 border border-orange-100">
         <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M20.59 13.41l-7.17 7.17a2 2 0 0 1-2.83 0L2 12V2h10l8.59 8.59a2 2 0 0 1 0 2.82z"/><line x1="7" y1="7" x2="7.01" y2="7"/></svg>
      </div>
      <div class="min-w-0">
        <h2 class="text-base font-extrabold text-[#0B1B33] truncate tracking-tight">Deals & Combos</h2>
        <p class="text-[11px] text-gray-500 font-medium truncate mt-0.5">Din ki behtareen deals aur combo offers</p>
      </div>
    </div>
    <a href="/deals" onclick="event.preventDefault(); navigateTo('all-deals');" class="inline-flex items-center justify-center gap-1 bg-brand-orange text-white px-3.5 py-2 rounded-lg text-[11px] font-extrabold shadow-sm hover:bg-[#e66000] transition-all duration-300 shrink-0">View all <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"><path d="M5 12h14M12 5l7 7-7 7"/></svg></a>
  </div>
  
  <!-- Grid Container -->
  <div id="dailyDealsContainer" class="daily-deals-grid">
    <div class="col-span-full flex justify-center py-8"><div class="loading-spinner"></div></div>
  </div>
</section>

  <div id="homeCategorySections">
    <div class="max-w-6xl mx-auto px-4 mt-8 flex justify-center py-12"><div class="loading-spinner"></div></div>
  </div>

<section class="max-w-6xl mx-auto px-4 mt-10">
  <div class="grid grid-cols-5 gap-1.5 md:gap-3">
    <div class="feature-box">
      <div class="w-7 h-7 md:w-10 md:h-10 mx-auto mb-1 md:mb-2 bg-orange-50 rounded-lg md:rounded-xl flex items-center justify-center">
        <svg class="w-4 h-4 md:w-5 md:h-5" viewBox="0 0 24 24" fill="none" stroke="#FF6B00" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4.5 16.5c-1.5 1.26-2 5-2 5s3.74-.5 5-2c.71-.84.7-2.13-.09-2.91a2.18 2.18 0 0 0-2.91-.09z"/><path d="m12 15-3-3a22 22 0 0 1 2-3.95A12.88 12.88 0 0 1 22 2c0 2.72-.78 7.5-6 11a22.35 22.35 0 0 1-4 2z"/><path d="M9 12H4s.55-3.03 2-4c1.62-1.08 5 0 5 0"/><path d="M12 15v5s3.03-.55 4-2c1.08-1.62 0-5 0-5"/></svg>
      </div>
      <p class="text-[9px] md:text-[11px] font-bold brand-navy leading-tight">30 Min Delivery</p>
    </div>
    <div class="feature-box">
      <div class="w-7 h-7 md:w-10 md:h-10 mx-auto mb-1 md:mb-2 bg-green-50 rounded-lg md:rounded-xl flex items-center justify-center">
        <svg class="w-4 h-4 md:w-5 md:h-5" viewBox="0 0 24 24" fill="none" stroke="#2E7D32" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="2" y="6" width="20" height="12" rx="2"/><circle cx="12" cy="12" r="2"/><path d="M6 12h.01M18 12h.01"/></svg>
      </div>
      <p class="text-[9px] md:text-[11px] font-bold brand-navy leading-tight">Cash on Delivery</p>
    </div>
    <div class="feature-box">
      <div class="w-7 h-7 md:w-10 md:h-10 mx-auto mb-1 md:mb-2 bg-blue-50 rounded-lg md:rounded-xl flex items-center justify-center">
        <svg class="w-4 h-4 md:w-5 md:h-5" viewBox="0 0 24 24" fill="none" stroke="#1976D2" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></svg>
      </div>
      <p class="text-[9px] md:text-[11px] font-bold brand-navy leading-tight">Fresh Products</p>
    </div>
    <div class="feature-box">
      <div class="w-7 h-7 md:w-10 md:h-10 mx-auto mb-1 md:mb-2 bg-purple-50 rounded-lg md:rounded-xl flex items-center justify-center">
        <svg class="w-4 h-4 md:w-5 md:h-5" viewBox="0 0 24 24" fill="none" stroke="#7B1FA2" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72 12.84 12.84 0 0 0 .7 2.81 2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45 12.84 12.84 0 0 0 2.81.7A2 2 0 0 1 22 16.92z"/></svg>
      </div>
      <p class="text-[9px] md:text-[11px] font-bold brand-navy leading-tight">24/7 Support</p>
    </div>
    <a href="/whatsapp" class="feature-box cursor-pointer">
      <div class="w-7 h-7 md:w-10 md:h-10 mx-auto mb-1 md:mb-2 bg-emerald-50 rounded-lg md:rounded-xl flex items-center justify-center">
        <svg class="w-4 h-4 md:w-5 md:h-5" fill="#25D366" viewBox="0 0 24 24"><path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 01-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 01-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 012.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0012.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 005.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 00-3.48-8.413z"/></svg>
      </div>
      <p class="text-[9px] md:text-[11px] font-bold text-emerald-600 leading-tight">WhatsApp</p>
    </a>
  </div>
</section>

  <footer class="mt-12 bg-brand-navy text-gray-300 pt-10 pb-4">
    <div class="max-w-6xl mx-auto px-4 grid grid-cols-1 md:grid-cols-4 gap-8">
      <div>
        <div class="flex items-center gap-2 mb-4">
          <img src="https://i.ibb.co/DfWY3Y6H/1792259832609.jpg" alt="OrderDrop.pk Logo" class="w-12 h-12 logo-img bg-white rounded-xl p-1 object-cover">
          <h3 class="text-white font-extrabold text-xl">OrderDrop.pk</h3>
        </div>
        <p class="text-xs leading-relaxed text-gray-400">Chichawatni ki tez tareen delivery service. Ghar baithe groceries, fast food aur fresh items order karein.</p>
      </div>
      <div>
        <h4 class="text-white font-bold text-sm mb-4">Quick Links</h4>
        <ul class="space-y-2.5 text-xs">
          <li><a href="/" onclick="event.preventDefault(); navigateTo('home');" class="cursor-pointer hover:text-brand-orange transition">Home</a></li>
          <li><a href="/track-order" onclick="event.preventDefault(); navigateTo('track');" class="cursor-pointer hover:text-brand-orange transition">Track Order</a></li>
          <li><a href="/my-orders" onclick="event.preventDefault(); navigateTo('account');" class="cursor-pointer hover:text-brand-orange transition">My Orders</a></li>
          <li><a href="/about" class="hover:text-brand-orange transition">About Us</a></li>
          <li><a href="/faq" class="hover:text-brand-orange transition">FAQs</a></li>
        </ul>
      </div>
      <div>
        <h4 class="text-white font-bold text-sm mb-4">Policies</h4>
        <ul class="space-y-2.5 text-xs">
          <li><a href="/terms" class="hover:text-brand-orange transition">Terms & Conditions</a></li>
          <li><a href="/refund-policy" class="hover:text-brand-orange transition">Refund & Return</a></li>
          <li><a href="/delivery-policy" class="hover:text-brand-orange transition">Delivery Policy</a></li>
          <li><a href="/privacy-policy" class="hover:text-brand-orange transition">Privacy Policy</a></li>
          <li><a href="/disclaimer" class="hover:text-brand-orange transition">Disclaimer</a></li>
          <li><a href="/contact" class="hover:text-brand-orange transition">Contact Us</a></li>
        </ul>
      </div>
      <div>
        <h4 class="text-white font-bold text-sm mb-4">Contact Us</h4>
        <p class="text-xs text-gray-400 mb-2">Chichawatni, Punjab, Pakistan</p>
        <p class="text-xs text-gray-400 mb-1">Helpline: 0315-3367920</p>
       <p class="text-xs text-gray-400 mb-2">Email: admin@orderdrop.pk</p>
<div class="flex items-center gap-3 mb-2">
  <!-- WhatsApp Button -->
  <a href="https://wa.me/923153367920" target="_blank" class="inline-flex items-center gap-1.5 bg-emerald-600 hover:bg-emerald-500 text-white text-[10px] font-bold px-3 py-2 rounded-lg transition shadow-sm">
    <svg class="w-3.5 h-3.5" fill="currentColor" viewBox="0 0 24 24"><path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 01-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 01-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 012.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0012.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 005.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 00-3.48-8.413z"/></svg>
    0315-3367920
  </a>
  <!-- Facebook Icon -->
  <a href="https://www.facebook.com/share/19bNUoEzyN/" target="_blank" class="w-7 h-7 bg-blue-600/20 hover:bg-blue-600 text-blue-400 hover:text-white rounded-lg flex items-center justify-center transition border border-blue-600/30">
    <svg class="w-3.5 h-3.5" fill="currentColor" viewBox="0 0 24 24"><path d="M24 12.073c0-6.627-5.373-12-12-12s-12 5.373-12 12c0 5.99 4.388 10.954 10.125 11.854v-8.385H7.078v-3.47h3.047V9.43c0-3.007 1.792-4.669 4.533-4.669 1.312 0 2.686.235 2.686.235v2.953H15.83c-1.491 0-1.956.925-1.956 1.874v2.25h3.328l-.532 3.47h-2.796v8.385C19.612 23.027 24 18.062 24 12.073z"/></svg>
  </a>
  <!-- TikTok Icon -->
  <a href="https://tiktok.com/@orderdrop.pk" target="_blank" class="w-7 h-7 bg-white/10 hover:bg-white text-white hover:text-black rounded-lg flex items-center justify-center transition border border-white/20">
    <svg class="w-3.5 h-3.5" fill="currentColor" viewBox="0 0 24 24"><path d="M12.525.02c1.31-.02 2.61-.01 3.91-.02.08 1.53.63 3.09 1.75 4.17 1.12 1.11 2.7 1.62 4.24 1.79v4.03c-1.44-.05-2.89-.35-4.2-.97-.57-.26-1.1-.59-1.62-.93-.01 2.92.01 5.84-.02 8.75-.08 1.4-.54 2.79-1.35 3.94-1.31 1.92-3.58 3.17-5.91 3.21-1.43.08-2.86-.31-4.08-1.03-2.02-1.19-3.44-3.37-3.65-5.71-.02-.5-.03-1-.01-1.49.18-1.9 1.12-3.72 2.58-4.96 1.66-1.44 3.98-2.13 6.15-1.72.02 1.48-.04 2.96-.04 4.44-.99-.32-2.15-.23-3.02.37-.63.41-1.11 1.04-1.36 1.75-.21.51-.15 1.07-.14 1.61.24 1.64 1.82 3.02 3.5 2.87 1.12-.01 2.19-.66 2.77-1.61.19-.33.4-.67.41-1.06.1-1.79.06-3.57.07-5.36.01-4.03-.01-8.05.02-12.07z"/></svg>
  </a>
</div>
      </div>
    </div>
    <div class="max-w-6xl mx-auto px-4 mt-8 pt-5 border-t border-white/10 text-center text-xs text-gray-500">
      © 2025 OrderDrop.pk Chichawatni. All rights reserved.
    </div>
  </footer>
</div>

<div id="page-all-deals" class="page pb-24">
  <div class="max-w-6xl mx-auto px-4 py-4">
    <div class="text-xs text-gray-500 mb-3 font-medium">
      <a href="/" onclick="event.preventDefault(); navigateTo('home');" class="cursor-pointer hover:text-brand-orange">Home</a> / 
      <span class="text-gray-800 font-semibold">Deals & Combos</span>
    </div>
    <div class="flex items-center justify-between mb-4">
      <h1 class="text-xl font-extrabold brand-navy">All Deals & Combos</h1>
    </div>
    <div id="allDealsContainer" class="daily-deals-grid"></div>
  </div>
</div>

<div id="page-category" class="page pb-24">
<div class="fixed top-[140px] md:top-[125px] left-0 right-0 z-30 bg-white border-b border-gray-100 shadow-sm">
    <div id="filterBar" class="max-w-6xl mx-auto px-4 py-3 flex gap-2 overflow-x-auto no-scrollbar"></div>
  </div>
<div class="max-w-6xl mx-auto px-4 pt-[20px] pb-4">
    <div class="text-xs text-gray-500 mb-3 font-medium">
      <a href="/" onclick="event.preventDefault(); navigateTo('home');" class="cursor-pointer hover:text-brand-orange">Home</a> / 
      <span id="categoryTitle" class="text-gray-800 font-semibold">All Products</span>
    </div>
    <p id="productCount" class="text-xs text-gray-500 mb-4 font-medium">Loading...</p>
    <div id="categoryProducts" class="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-3"></div>
  </div>
</div>

<div id="page-product" class="page pb-32">
  <div id="productDetail"></div>
</div>

<div id="page-account" class="page pb-24">
  <div class="max-w-3xl mx-auto px-4 py-6">
    <div class="bg-white rounded-2xl p-6 shadow-sm border mb-6 flex items-center justify-between">
      <div class="flex items-center gap-3">
        <div class="w-12 h-12 bg-brand-orange/10 rounded-2xl flex items-center justify-center">
          <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="#FF6B00" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/></svg>
        </div>
        <div>
          <h1 class="text-lg font-extrabold brand-navy" id="accountNameDisplay">Customer Account</h1>
          <p id="accountPhoneDisplay" class="text-sm text-gray-500 font-medium">03XXXXXXXXX</p>
        </div>
      </div>
      <button onclick="handleLogout()" class="bg-red-50 text-red-600 hover:bg-red-100 px-4 py-2 rounded-xl text-xs font-bold transition">Logout</button>
    </div>

    <h2 class="font-extrabold brand-navy mb-3 text-lg">Aapke Purane Orders</h2>
    <div id="accountOrdersList" class="space-y-3">
      <div class="flex justify-center py-8"><div class="loading-spinner"></div></div>
    </div>

    <div class="mt-6 bg-white rounded-2xl p-5 border border-gray-100 text-center">
      <p class="text-sm font-bold brand-navy mb-2">App Download Karein</p>
      <p class="text-xs text-gray-500 mb-3">OrderDrop.pk App install karein taake aur bhi tez shopping kar sakein</p>
<button onclick="installApp()" class="w-full bg-gradient-to-br from-[#FF6B00] to-[#FF8A33] text-white font-bold py-3 rounded-xl text-sm flex items-center justify-center gap-2 hover:shadow-lg transition">
        <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4"/></svg>
        App Download Karein
      </button>
    </div>
  </div>
</div>

<div id="page-cart" class="page">
  <main class="max-w-6xl mx-auto px-4 mt-4 pb-44">
    <h1 class="text-xl font-extrabold brand-navy mb-4">Shopping Cart</h1>
    <div id="cartItems" class="space-y-3"></div>
    <div id="cartEmpty" class="hidden bg-white rounded-2xl p-10 text-center mt-4 border border-gray-100">
      <div class="w-16 h-16 mx-auto mb-3 bg-gray-50 rounded-2xl flex items-center justify-center">
        <svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="#9CA3AF" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="9" cy="21" r="1"/><circle cx="20" cy="21" r="1"/><path d="M1 1h4l2.68 13.39a2 2 0 0 0 2 1.61h9.72a2 2 0 0 0 2-1.61L23 6H6"/></svg>
      </div>
      <h3 class="font-extrabold brand-navy mb-1 text-lg">Cart khali hai</h3>
      <p class="text-xs text-gray-500 mb-4">Kuch products add karein aur shopping shuru karein</p>
      <button onclick="navigateTo('category')" class="btn-primary px-6 py-3 rounded-xl text-sm">Shopping Shuru Karein</button>
    </div>
  </main>

  <div id="cartSummary" class="fixed bottom-0 left-0 right-0 bg-white border-t z-40 safe-bottom shadow-lg">
    <div class="max-w-6xl mx-auto px-4 py-3">
      <div class="flex justify-between items-center mb-3">
        <span class="text-sm text-gray-600 font-medium">Subtotal</span>
        <span id="cartTotal" class="font-extrabold brand-orange text-xl">Rs. 0</span>
      </div>
      <button onclick="goToCheckout()" class="w-full btn-primary py-3.5 rounded-xl text-center text-sm">Proceed to Checkout</button>
    </div>
  </div>
</div>

<div id="page-checkout" class="page pb-40">
  <main class="max-w-6xl mx-auto px-4 mt-4 space-y-3">
    <h1 class="text-xl font-extrabold brand-navy mb-2">Checkout</h1>
    <div class="bg-white rounded-2xl p-5 border border-gray-100">
      <h2 class="font-extrabold brand-navy mb-4 text-sm">Delivery Details</h2>
      <form id="checkoutForm" class="space-y-3" onsubmit="submitOrder(event)">
        <div>
          <label class="text-xs font-bold text-gray-700 mb-1.5 block">Full Name *</label>
          <input type="text" required placeholder="Full Name" id="custName" class="w-full border border-gray-200 rounded-xl px-4 py-3 text-sm">
        </div>
        <div>
          <label class="text-xs font-bold text-gray-700 mb-1.5 block">11-Digit Phone Number *</label>
          <input type="tel" required maxlength="11" placeholder="03001234567" id="custPhone" class="w-full border border-gray-200 rounded-xl px-4 py-3 text-sm">
        </div>
        <div>
          <label class="text-xs font-bold text-gray-700 mb-1.5 block">Delivery Address *</label>
          <textarea required rows="3" placeholder="Full Address in Chichawatni..." id="custAddress" class="w-full border border-gray-200 rounded-xl px-4 py-3 text-sm"></textarea>
        </div>
      </form>
    </div>

    <div class="bg-white rounded-2xl p-5 border border-gray-100">
      <h2 class="font-extrabold brand-navy mb-3 text-sm">Order Summary</h2>
      <div id="checkoutItems" class="space-y-2 pb-3 border-b"></div>
      <div class="flex justify-between pt-3">
        <span class="font-bold text-gray-800">Total</span>
        <span id="checkoutTotal" class="font-extrabold brand-orange text-lg">Rs. 0</span>
      </div>
    </div>
  </main>
  <div class="fixed bottom-0 left-0 right-0 bg-white border-t p-4 z-40 safe-bottom shadow-lg">
    <button onclick="submitOrder()" id="placeOrderBtn" class="w-full btn-primary py-3.5 rounded-xl text-sm">Place Order</button>
  </div>
</div>

<div id="page-confirmation" class="page pb-24">
  <main class="max-w-xl mx-auto px-4 py-10 text-center">
    <div class="w-20 h-20 bg-green-100 rounded-full flex items-center justify-center mx-auto mb-4">
      <svg class="w-10 h-10 text-green-600" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="3" d="M5 13l4 4L19 7"/></svg>
    </div>
    <h1 class="text-2xl font-extrabold brand-navy mb-2">Order Confirmed!</h1>
    <p class="text-sm text-gray-500 mb-6">Aapka order successfully place ho gaya hai</p>
    <div class="bg-white rounded-2xl p-6 mb-4 border border-gray-100 shadow-sm">
      <p class="text-xs text-gray-500 mb-1 font-medium">Order Number</p>
      <div class="flex items-center justify-center gap-2 mb-4">
        <p id="orderNumber" class="text-2xl font-extrabold brand-orange">CD-000000</p>
        <button onclick="copyOrderId('orderNumber')" class="copy-btn" title="Copy Order ID">
          <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z"/></svg>
          Copy
        </button>
      </div>
      <div class="flex items-center justify-center gap-2 text-xs text-gray-500">
        <span class="w-2 h-2 bg-green-500 rounded-full animate-pulse"></span>
        Delivery in 30-45 minutes
      </div>
    </div>
    <button onclick="navigateTo('track')" class="w-full btn-primary py-3.5 rounded-xl mb-2 text-sm">Track Order</button>
    <button onclick="navigateTo('home')" class="w-full bg-gray-100 text-gray-900 font-bold py-3.5 rounded-xl text-sm hover:bg-gray-200 transition">Back to Home</button>
  </main>
</div>

<div id="page-track" class="page pb-24">
  <main class="max-w-md mx-auto px-4 py-6">
    <div class="text-center mb-6">
      <div class="w-16 h-16 bg-brand-orange/10 rounded-2xl flex items-center justify-center mx-auto mb-3">
        <svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="#FF6B00" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="1" y="3" width="15" height="13"/><polygon points="16 8 20 8 23 11 23 16 16 16 16 8"/><circle cx="5.5" cy="18.5" r="2.5"/><circle cx="18.5" cy="18.5" r="2.5"/></svg>
      </div>
      <h1 class="text-xl font-extrabold brand-navy mb-1">Track Your Order</h1>
      <p class="text-sm text-gray-500">Order number aur 11-digit phone number daalein</p>
    </div>

    <form onsubmit="trackOrder(event)" class="space-y-3 mb-6">
      <input type="text" required id="trackNum" placeholder="CD-XXXXXX" class="w-full border border-gray-200 rounded-xl px-4 py-3.5 text-sm">
      <input type="tel" required maxlength="11" id="trackPhone" placeholder="03001234567" class="w-full border border-gray-200 rounded-xl px-4 py-3.5 text-sm">
      <button type="submit" class="w-full btn-primary py-3.5 rounded-xl text-sm">Track Order</button>
    </form>

    <div id="trackResult" class="hidden"></div>
    <div id="trackError" class="hidden bg-red-50 text-red-700 p-4 rounded-xl text-sm font-medium"></div>
  </main>
</div>

<nav id="bottomNav" class="fixed bottom-0 left-0 right-0 bg-white border-t border-gray-200 md:hidden z-30 safe-bottom shadow-lg">
  <div class="grid grid-cols-5 text-center">
    <!-- Home -->
    <a href="/" onclick="event.preventDefault(); navigateTo('home');" id="nav-home" class="bottom-nav-item active text-brand-orange">
      <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 12l2-2m0 0l7-7 7 7M5 10v10a1 1 0 001 1h3m10-11l2 2m-2-2v10a1 1 0 01-1 1h-3m-6 0a1 1 0 001-1v-4a1 1 0 011-1h2a1 1 0 011 1v4a1 1 0 001 1m-6 0h6"/></svg>
      <span>Home</span>
    </a>
    
    <!-- Category -->
    <a href="/categories" onclick="event.preventDefault(); navigateTo('category');" id="nav-category" class="bottom-nav-item text-[#0B1B33]">
      <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6a2 2 0 012-2h2a2 2 0 012 2v2a2 2 0 01-2 2H6a2 2 0 01-2-2V6zM14 6a2 2 0 012-2h2a2 2 0 012 2v2a2 2 0 01-2 2h-2a2 2 0 01-2-2V6zM4 16a2 2 0 012-2h2a2 2 0 012 2v2a2 2 0 01-2 2H6a2 2 0 01-2-2v-2zM14 16a2 2 0 012-2h2a2 2 0 012 2v2a2 2 0 01-2 2h-2a2 2 0 01-2-2v-2z"/></svg>
      <span>Category</span>
    </a>
    
    <!-- Track -->
    <a href="/track-order" onclick="event.preventDefault(); navigateTo('track');" id="nav-track" class="bottom-nav-item text-[#0B1B33]">
      <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"/></svg>
      <span>Track</span>
    </a>
    
    <!-- Cart -->
    <a href="/cart" onclick="event.preventDefault(); navigateTo('cart');" id="nav-cart" class="bottom-nav-item text-[#0B1B33] relative">
      <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 3h2l.4 2M7 13h10l4-8H5.4M7 13L5.4 5M7 13l-2.293 2.293c-.63.63-.184 1.707.707 1.707H17m0 0a2 2 0 100 4 2 2 0 000-4zm-8 2a2 2 0 11-4 0 2 2 0 014 0z"/></svg>
      <span>Cart</span>
      <span id="navCartBadge" class="hidden absolute top-1 right-1/4 bg-red-500 text-white text-[9px] w-4 h-4 rounded-full flex items-center justify-center font-bold">0</span>
    </a>
    
    <!-- WhatsApp (Solid Fill & Professional) -->
    <a href="/whatsapp" id="nav-whatsapp" class="bottom-nav-item text-[#0B1B33]">
      <svg class="w-5 h-5" fill="currentColor" viewBox="0 0 24 24"><path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 01-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 01-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 012.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0012.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 005.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 00-3.48-8.413z"/></svg>
      <span>WhatsApp</span>
    </a>
  </div>
</nav>
<!-- Professional Login Modal (Center + App Download) -->
<div id="authModal" class="hidden fixed inset-0 bg-black/60 z-[90] flex items-center justify-center p-4">
  <div class="bg-white w-full max-w-sm rounded-[32px] p-6 shadow-2xl relative fade-in">
    
    <!-- Close Button -->
    <button onclick="closeAuthModal()" class="absolute top-5 right-5 text-gray-400 hover:text-gray-600 text-2xl font-bold leading-none">&times;</button>

    <!-- Top Orange User Icon -->
    <div class="mb-5">
      <svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="#FF6B00" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/></svg>
    </div>

    <!-- Heading -->
    <h2 class="text-[26px] font-extrabold text-[#0B1B33] mb-2 tracking-tight">Customer Login</h2>
    <p class="text-[13px] text-gray-500 mb-6 font-medium leading-relaxed">Apna Name aur 11-digit number daal kar login karein</p>
    
    <!-- Login Form -->
    <form onsubmit="handlePhoneLogin(event)" class="space-y-4">
      <div>
        <label class="text-[13px] font-bold text-[#0B1B33] block mb-2">Full Name *</label>
        <input type="text" id="loginNameInput" required placeholder="Muhammad Qammar Aseem" class="w-full border border-gray-200 rounded-2xl px-4 py-3.5 text-sm focus:outline-none focus:border-[#FF6B00] focus:ring-1 focus:ring-[#FF6B00] placeholder-gray-400">
      </div>
      <div>
        <label class="text-[13px] font-bold text-[#0B1B33] block mb-2">11-Digit Phone Number *</label>
        <input type="tel" id="loginPhoneInput" required maxlength="11" placeholder="03153367920" class="w-full border border-gray-200 rounded-2xl px-4 py-3.5 text-sm focus:outline-none focus:border-[#FF6B00] focus:ring-1 focus:ring-[#FF6B00] placeholder-gray-400">
      </div>
      
      <button type="submit" class="w-full bg-[#FF6B00] text-white py-4 rounded-2xl font-bold text-[15px] shadow-md hover:bg-[#e66000] transition mt-2">Login / View Orders</button>
    </form>

    <!-- Divider -->
    <div class="flex items-center gap-3 my-4">
      <div class="h-px bg-gray-200 flex-1"></div>
      <span class="text-[10px] text-gray-400 font-bold uppercase tracking-wider">OR</span>
      <div class="h-px bg-gray-200 flex-1"></div>
    </div>

    <!-- App Download Button -->
    <button onclick="closeAuthModal(); installApp();" class="w-full bg-gray-50 border border-gray-200 text-gray-800 py-3.5 rounded-2xl font-bold text-sm flex items-center justify-center gap-2 hover:bg-gray-100 transition">
      <svg class="w-4 h-4 text-[#FF6B00]" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4"/></svg>
      Download App
    </button>

  </div>
</div>
<div id="toast" class="hidden fixed bottom-24 left-1/2 -translate-x-1/2 toast-pro z-[60]">
  <span id="toastMsg"></span>
</div>
<!-- Floating WhatsApp Button -->
<a href="https://wa.me/923153367920?text=Assalam%20o%20Alaikum%20OrderDrop.pk%2C%20mujhe%20order%20krna%20ha" target="_blank" class="whatsapp-float" aria-label="Chat on WhatsApp">
  <svg width="32" height="32" fill="currentColor" viewBox="0 0 24 24">
    <path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 01-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 01-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 012.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0012.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 005.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 00-3.48-8.413z"/>
  </svg>
</a>
<script type="module">
import { initializeApp } from "https://www.gstatic.com/firebasejs/10.12.2/firebase-app.js";
import { 
  getFirestore, collection, doc, getDocs, addDoc, updateDoc, deleteDoc, 
  query, where, orderBy, onSnapshot, serverTimestamp, getDoc
} from "https://www.gstatic.com/firebasejs/10.12.2/firebase-firestore.js";
import { getAnalytics } from "https://www.gstatic.com/firebasejs/10.12.2/firebase-analytics.js";

const firebaseConfig = {
  apiKey: "AIzaSyDFTSeRfldX_U7OXiV1JLenFe7Lufvylo",
  authDomain: "citydrop-store.firebaseapp.com",
  projectId: "citydrop-store",
  storageBucket: "citydrop-store.firebasestorage.app",
  messagingSenderId: "747995786783",
  appId: "1:747995786783:web:ba964c3e806b0ccabdf2a",
  measurementId: "G-FGRX6QS715"
};

const fbApp = initializeApp(firebaseConfig);
const db = getFirestore(fbApp);
const analytics = getAnalytics(fbApp);
// Service Worker Register Karein (Yeh line add karein)
if ('serviceWorker' in navigator) {
  navigator.serviceWorker.register('/sw.js');
}
let PRODUCTS = [];
let CATEGORIES = [];
let DEALS = [];
let DAILY_DEALS = [];
let ORDERS_LIVE = [];
let PRODUCT_REVIEWS = {};
let reviewsUnsubscribers = {};
let currentPage = 'home';
let cart = JSON.parse(localStorage.getItem('orderdrop_cart') || '{}');
let currentProductId = null;
let currentCategory = 'all';
let searchQuery = '';
let currentLoginPhone = localStorage.getItem('citydrop_login_phone') || null;
let currentLoginName = localStorage.getItem('citydrop_login_name') || 'Customer';
let pageScrollPositions = { home: 0 };
let productsLoaded = false;
let categoriesLoaded = false;
let dealsLoaded = false;
let dailyDealsLoaded = false;
let lastTrackedOrderNumber = null;
let liveUnsubscribers = [];
let deferredPrompt;
let pendingInstallTrigger = false;

const STAR_SVG = '<svg viewBox="0 0 24 24" fill="#FFB800" stroke="none"><polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"/></svg>';

const SVG_ICONS = {
  grocery: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="9" cy="21" r="1"/><circle cx="20" cy="21" r="1"/><path d="M1 1h4l2.68 13.39a2 2 0 002 1.61h9.72a2 2 0 002-1.61L23 6H6"/></svg>',
  vegetables: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M11 20A7 7 0 019.8 6.1C15.5 5 17 4.48 19 2c1 2 2 4.18 2 8 0 5.5-4.78 10-10 10z"/><path d="M2 21c0-3 1.85-5.36 5.08-6C9.5 14.52 12 13 13 12"/></svg>',
  fruits: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 20.94c1.5 0 2.75 1.06 4 1.06 3 0 6-8 6-12.22A4.91 4.91 0 0017 5c-2.22 0-4 1.44-5 2-1-.56-2.78-2-5-2a4.9 4.9 0 00-5 4.78C2 14 5 22 8 22c1.25 0 2.5-1.06 4-1.06z"/><path d="M10 2c1 .5 2 2 2 5"/></svg>',
  dairy: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M8 2h8v3H8zM7 5h10l-1 4v11a2 2 0 01-2 2H10a2 2 0 01-2-2V9z"/><path d="M9 12h6"/></svg>',
  meat: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M15.5 2a5.5 5.5 0 00-5.5 5.5c0 1.5.5 3 1.5 4l-8 8c-.5.5-.5 1.5 0 2l2 2c.5.5 1.5.5 2 0l8-8c1 1 2.5 1.5 4 1.5A5.5 5.5 0 0015.5 2z"/></svg>',
  fastfood: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4 12h16a1 1 0 011 1v1a1 1 0 01-1 1H4a1 1 0 01-1-1v-1a1 1 0 011-1z"/><path d="M4 16h16a1 1 0 011 1v1a1 1 0 01-1 1H4a1 1 0 01-1-1v-1a1 1 0 011-1z"/><path d="M6 10c0-2 1-4 3-5 1-.5 2-.5 3 0 2 1 3 3 3 5"/></svg>',
  bakery: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 11a9 9 0 0118 0v8a1 1 0 01-1 1H4a1 1 0 01-1-1v-8z"/><path d="M8 11V7a4 4 0 018 0v4"/><path d="M8 15h8"/></svg>',
  beverages: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M5 3h14l-1.5 16a2 2 0 01-2 2h-7a2 2 0 01-2-2L5 3z"/><path d="M6 8h12"/></svg>',
  snacks: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 8l4 4-4 4M21 8l-4 4 4 4M7 6h10M7 18h10"/></svg>',
  default: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4"/></svg>'
};

function getCategoryIcon(catId) { return SVG_ICONS[catId] || SVG_ICONS.default; }
function formatPrice(n) { return 'Rs. ' + (n||0).toLocaleString('en-PK'); }

function showToast(msg, type = 'success') {
  const toast = document.getElementById('toast');
  document.getElementById('toastMsg').textContent = msg;
  toast.classList.remove('hidden');
  toast.style.background = type === 'error' ? '#DC2626' : '#0B1B33';
  setTimeout(() => toast.classList.add('hidden'), 2200);
}

function getProduct(id) { 
  const p = PRODUCTS.find(p => String(p.id) === String(id) || String(p._fsId) === String(id));
  if (p) return p;
  const dd = DAILY_DEALS.find(d => String(d._fsId) === String(id));
  if (dd) {
    return { ...dd, id: dd._fsId, _fsId: dd._fsId, name: dd.name, price: dd.price, img: dd.img, unit: 'Deal' };
  }
  return null;
}

function isValidPakPhone(phone) { return /^03\d{9}$/.test(phone.trim()); }

window.openAuthModal = function() { document.getElementById('authModal').classList.remove('hidden'); };
window.closeAuthModal = function() { document.getElementById('authModal').classList.add('hidden'); };

window.addEventListener('beforeinstallprompt', (e) => {
  e.preventDefault();
  deferredPrompt = e;
});

window.installApp = async function() {
  if (deferredPrompt) {
    // Agar prompt ready hai, toh direct install ka card kholo
    deferredPrompt.prompt();
    const { outcome } = await deferredPrompt.userChoice;
    if (outcome === 'accepted') {
      showToast('App install ho rahi hai...');
    }
    deferredPrompt = null;
  } else {
    // Agar prompt ready nahi hai (ya user pehle cancel kar chuka hai)
    // Toh user ko guide karein ke browser menu se kaise install karein
    showToast('Install karne ke liye Chrome ke 3 dots (⋮) par click karein aur "Install App" ya "Add to Home Screen" choose karein.', 'error');
  }
};

window.closeInstallPopup = function() {
  document.getElementById('installPopup').classList.add('hidden');
  localStorage.setItem('installPopupDismissed', 'true');
};

window.showInstallManual = function() {
  document.getElementById('installPopup').classList.remove('hidden');
  const cancelBtn = document.querySelector('#installPopup button:last-child');
  if (cancelBtn) cancelBtn.textContent = 'Band Karein';
};

window.copyOrderId = function(elementId) {
  const el = document.getElementById(elementId);
  if (!el) return;
  const text = el.textContent.trim();
  if (!text || text === 'CD-000000') return;
  navigator.clipboard.writeText(text).then(() => {
    showToast('Order ID copy ho gayi: ' + text);
  }).catch(() => {
    const ta = document.createElement('textarea');
    ta.value = text;
    document.body.appendChild(ta);
    ta.select();
    try { document.execCommand('copy'); showToast('Order ID copy ho gayi: ' + text); } catch(e) { showToast('Copy nahi ho saki', 'error'); }
    document.body.removeChild(ta);
  });
};

function startLiveListeners() {
  liveUnsubscribers.push(onSnapshot(collection(db, 'categories'), (snap) => {
    CATEGORIES = snap.docs.map(d => ({ _fsId: d.id, ...d.data() }));
    CATEGORIES.sort((a, b) => (a.order || 0) - (b.order || 0));
    categoriesLoaded = true;
    if (currentPage === 'home') renderHomeSections();
    if (currentPage === 'category') { renderFilterBar(); renderCategoryPage(); }
    if (currentPage === 'product') renderProductDetail();
  }, (err) => console.error('Categories live error:', err)));

  liveUnsubscribers.push(onSnapshot(collection(db, 'products'), (snap) => {
    PRODUCTS = snap.docs.map(d => ({ _fsId: d.id, ...d.data(), id: d.id }));
    productsLoaded = true;
    if (currentPage === 'home') renderHomeSections();
    if (currentPage === 'category') renderCategoryPage();
    if (currentPage === 'product') renderProductDetail();
    if (currentPage === 'cart') renderCart();
  }, (err) => console.error('Products live error:', err)));

  liveUnsubscribers.push(onSnapshot(collection(db, 'deals'), (snap) => {
    DEALS = snap.docs.map(d => ({ _fsId: d.id, ...d.data() }));
    DEALS.sort((a,b) => (a.order||0) - (b.order||0));
    dealsLoaded = true;
    if (currentPage === 'home') renderDealBoxes();
  }, (err) => console.error('Deals live error:', err)));

  liveUnsubscribers.push(onSnapshot(collection(db, 'daily_deals'), (snap) => {
    DAILY_DEALS = snap.docs.map(d => ({ _fsId: d.id, ...d.data() }));
    DAILY_DEALS.sort((a,b) => (a.order||0) - (b.order||0));
    dailyDealsLoaded = true;
    if (currentPage === 'home') renderDailyDeals();
    if (currentPage === 'all-deals') renderAllDealsPage();
    if (currentPage === 'cart') renderCart();
  }, (err) => console.error('Daily deals live error:', err)));

  liveUnsubscribers.push(onSnapshot(collection(db, 'orders'), (snap) => {
    ORDERS_LIVE = snap.docs.map(d => ({ _fsId: d.id, ...d.data() }));
    if (currentPage === 'track' && lastTrackedOrderNumber) {
      const order = ORDERS_LIVE.find(o => o.number === lastTrackedOrderNumber);
      if (order) renderTrackResult(order);
      else {
        const resultEl = document.getElementById('trackResult');
        const errorEl = document.getElementById('trackError');
        if (resultEl) resultEl.classList.add('hidden');
        if (errorEl) { errorEl.textContent = 'Koi bhi sawal, order, ya complaint ke liye Whatsapp Par Rabta Kre. Whatsapp : 0315-3367920'; errorEl.classList.remove('hidden'); }
        lastTrackedOrderNumber = null;
      }
    }
    if (currentPage === 'account' && currentLoginPhone) renderAccountOrdersFromLive();
  }, (err) => console.error('Orders live error:', err)));
}

function renderDealBoxes() {
  const el = document.getElementById('dealBoxes');
  if (!el) return;
  if (!dealsLoaded || DEALS.length === 0) { el.innerHTML = ''; return; }
  el.innerHTML = DEALS.map(d => {
    const hasImage = d.image && d.image.trim() !== '';
    let bgStyle = '';
    if (hasImage) bgStyle = `background-image: url('${d.image}'); background-size: cover; background-position: center;`;
    else bgStyle = `background: linear-gradient(135deg, ${d.gradientFrom||'#0B1B33'}, ${d.gradientTo||'#1a2f4d'}); color: ${d.textColor||'#FFFFFF'};`;
    return `
<div class="w-full h-48 md:h-60 deal-banner text-white relative cursor-pointer overflow-hidden rounded-xl" style="${bgStyle}" onclick="openCategory('${d.link||'all'}')">
  ${hasImage && (d.title || d.subtitle) ? `<div class="absolute inset-0" style="background: linear-gradient(to top, rgba(0,0,0,0.85) 0%, rgba(0,0,0,0) 100%);"></div>` : ''}
  <div class="relative z-10 w-full h-full flex flex-col justify-start items-start p-4 md:p-5 text-left pointer-events-none">
    ${d.title ? `<h3 class="mb-1 text-lg md:text-xl font-extrabold leading-tight drop-shadow-md">${d.title}</h3>` : ''}
    ${d.subtitle ? `<p class="text-xs md:text-sm font-medium text-gray-200 mb-3 drop-shadow-md">${d.subtitle}</p>` : ''}
  </div>
${d.button ? `<div class="absolute bottom-3 left-3 z-20"><button class="bg-[#FF6B00] text-white font-bold text-xs px-4 py-2 rounded-full inline-flex items-center gap-1.5 hover:bg-[#e66000] transition shadow-lg">${d.button}<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"><path d="M5 12h14M12 5l7 7-7 7"/></svg></button></div>` : ''}
</div>`;
  }).join('');
}

function renderDailyDeals() {
  const el = document.getElementById('dailyDealsContainer');
  if (!el || !dailyDealsLoaded) return;
  const activeDeals = DAILY_DEALS.filter(d => d.active !== false);
  if (activeDeals.length === 0) { el.innerHTML = '<div class="col-span-full text-center py-6 text-xs text-gray-400">Abhi koi daily deal available nahi hai</div>'; return; }
  el.innerHTML = activeDeals.map(d => {
    const vendorText = d.unit || d.description || 'OrderDrop.pk Exclusive';
    return `
      <div class="combo-card relative">
        <div class="combo-img-wrap cursor-pointer" onclick="openProduct('${d._fsId}')">
          <img src="${d.img || ''}" alt="${d.name || 'Deal Image'}" onerror="this.src='https://via.placeholder.com/400x200?text=No+Image'">
          <div class="combo-title-overlay">${d.name || 'Deal'}</div>
        </div>
        <div class="combo-body">
          <h3 onclick="openProduct('${d._fsId}')" class="combo-name cursor-pointer hover:text-brand-orange transition">${d.name || 'Deal'}</h3>
          <div class="combo-vendor">
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg>
            ${vendorText}
          </div>
          <div class="combo-footer">
            <div class="combo-price">
              ${d.old && d.old > d.price ? `<span class="text-sm text-gray-400 line-through mr-2 font-medium">Rs. ${(+d.old).toLocaleString()}</span>` : ''}
              Rs. ${(+d.price || 0).toLocaleString()}
            </div>
      <button onclick="addToCart('${d._fsId}')" class="btn-pro-order">Order Now</button>
          </div>
        </div>
      </div>`;
  }).join('');
}

function renderAllDealsPage() {
  const el = document.getElementById('allDealsContainer');
  if (!el) return;
  const activeDeals = DAILY_DEALS.filter(d => d.active !== false);
  if (activeDeals.length === 0) { el.innerHTML = '<div class="col-span-full text-center py-16"><p class="font-bold text-gray-700">Koi deal available nahi hai</p></div>'; return; }
  el.innerHTML = activeDeals.map(d => {
    const vendorText = d.unit || d.description || 'OrderDrop.pk Exclusive';
    return `
      <div class="combo-card relative">
        <div class="combo-img-wrap cursor-pointer" onclick="openProduct('${d._fsId}')">
<img src="${d.img || ''}" alt="${d.name || 'Deal Image'}" onerror="this.src='https://via.placeholder.com/400x200?text=No+Image'">
          <div class="combo-title-overlay">${d.name || 'Deal'}</div>
        </div>
        <div class="combo-body">
          <h3 onclick="openProduct('${d._fsId}')" class="combo-name cursor-pointer hover:text-brand-orange transition">${d.name || 'Deal'}</h3>
          <div class="combo-vendor">
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg>
            ${vendorText}
          </div>
          <div class="combo-footer">
            <div class="combo-price">
              ${d.old && d.old > d.price ? `<span class="text-sm text-gray-400 line-through mr-2 font-medium">Rs. ${(+d.old).toLocaleString()}</span>` : ''}
              Rs. ${(+d.price || 0).toLocaleString()}
            </div>
       <button onclick="addToCart('${d._fsId}')" class="btn-pro-order">Order Now</button>
          </div>
        </div>
      </div>`;
  }).join('');
}

function productCardHTML(p) {
  const pid = p._fsId || p.id;
  const oldPrice = p.old || p.price;
  const discount = oldPrice > p.price ? Math.round(((oldPrice - p.price) / oldPrice) * 100) : 0;
  const manualReviews = p.reviews || 0;
  const realReviews = PRODUCT_REVIEWS[pid] || [];
  const totalCount = manualReviews + realReviews.length;
  const avgRating = realReviews.length > 0 ? (realReviews.reduce((s, r) => s + (r.rating || 0), 0) / realReviews.length).toFixed(1) : null;
  return `
    <div class="product-card p-2.5 flex flex-col justify-between relative" data-product-id="${pid}">
      <div class="relative">
        ${discount > 0 ? `<span class="badge-discount">-${discount}%</span>` : ''}
        <div onclick="openProduct('${pid}')" class="cursor-pointer aspect-square bg-gray-50 rounded-xl overflow-hidden mb-2">
       <img src="${p.img || ''}" alt="${p.name || 'Product Image'}" class="w-full h-full object-cover" onerror="this.style.display='none'">
        </div>
      </div>
      <div class="flex-1 flex flex-col">
        <h3 onclick="openProduct('${pid}')" class="cursor-pointer font-bold text-[13px] line-clamp-2 leading-snug text-gray-800 mb-1">${p.name || ''}</h3>
        <p class="text-[10px] text-gray-400 font-medium mb-1">${p.unit || ''}</p>
        <div class="rating-stars mb-2">
          ${STAR_SVG}${STAR_SVG}${STAR_SVG}${STAR_SVG}${STAR_SVG}
          ${totalCount > 0 ? `<span class="text-gray-400 font-medium ml-1">(${totalCount}${avgRating ? ' · ' + avgRating + '★' : ''})</span>` : ''}
        </div>
        <div class="flex items-center gap-1.5 mb-2">
          <span class="price-current">${formatPrice(p.price)}</span>
          ${oldPrice > p.price ? `<span class="price-old">${formatPrice(oldPrice)}</span>` : ''}
        </div>
        <button onclick="addToCart('${pid}')" class="w-full btn-primary text-[11px] font-bold py-2 rounded-xl mt-auto">Add to Cart</button>
      </div>
    </div>`;
}

// Ye variable shuffle hue products ko yaad rakhega
window._shuffledHomeProducts = window._shuffledHomeProducts || {};

function renderHomeSections() {
  const container = document.getElementById('homeCategorySections');
  if (!container) return;
  
  // Agar data load nahi hua to spinner dikhao
  if (!productsLoaded || !categoriesLoaded) { 
    container.innerHTML = '<div class="max-w-6xl mx-auto px-4 mt-8 flex justify-center py-12"><div class="loading-spinner"></div></div>'; 
    return; 
  }
  
  if (CATEGORIES.length === 0 || PRODUCTS.length === 0) { 
    container.innerHTML = '<div class="max-w-6xl mx-auto px-4 mt-8 text-center py-12 text-gray-400"><p class="font-bold">Koi product nahi mila</p></div>'; 
    return; 
  }

  const allCats = CATEGORIES;
  const html = allCats.map(cat => {
    let catProducts = PRODUCTS.filter(p => p.cat === cat.id && p.active !== false);
const limit = 4;

    // --- SHUFFLE LOGIC (FIXED) ---
    // Agar is category ke products pehle shuffle ho chuke hain, to wahi purane uthao
    if (catProducts.length > limit) {
      if (!window._shuffledHomeProducts[cat.id]) {
        // Pehli dafa shuffle karo aur yaad rakho
        let shuffled = [...catProducts].sort(() => 0.5 - Math.random());
        window._shuffledHomeProducts[cat.id] = shuffled.slice(0, limit).map(p => p._fsId || p.id);
      }
      
      // Jo pehle select hue the, unhi ko wapis list mein lao
      let savedIds = window._shuffledHomeProducts[cat.id];
      let reordered = [];
      savedIds.forEach(id => {
        const found = catProducts.find(p => String(p._fsId || p.id) === String(id));
        if (found) reordered.push(found);
      });
      // Agar koi naya product add hua ho database mein to usko shamil kar lo
      catProducts.forEach(p => {
        if (!reordered.find(r => String(r._fsId || r.id) === String(p._fsId || p.id)) && reordered.length < limit) {
           reordered.push(p);
        }
      });
      catProducts = reordered;
    } else {
      // Agar limit se kam products hain to jaisa hai waisa hi rakho
      catProducts = catProducts.slice(0, limit);
    }
    // -----------------------------

    const selectedProducts = catProducts;
    if (selectedProducts.length === 0) return '';
    
      return `
<section class="max-w-6xl mx-auto px-4 mt-8">
<!-- Professional Category Box Header -->
<div class="flex items-center justify-between bg-white p-3.5 rounded-2xl border border-gray-100 shadow-sm mb-4">
    <div class="flex items-center gap-3 min-w-0">
   <div class="w-10 h-10 ${cat.color || 'bg-orange-50'} rounded-xl flex items-center justify-center text-[#FF6B00] shrink-0 border border-orange-100">
        <span style="width:22px;height:22px;display:inline-block;">${getCategoryIcon(cat.id)}</span>
      </div>
    <div class="min-w-0">
  <h2 class="text-base font-extrabold text-[#0B1B33] truncate tracking-tight">${cat.name}</h2>
  <p class="text-[11px] text-gray-500 font-medium truncate mt-0.5">${cat.name} ke best products</p>
</div>
    </div>
    <a href="/category/${cat.id}" onclick="event.preventDefault(); openCategory('${cat.id}');" class="inline-flex items-center justify-center gap-1 bg-brand-orange text-white px-3.5 py-2 rounded-lg text-[11px] font-extrabold shadow-sm hover:bg-[#e66000] transition-all duration-300 shrink-0">View all <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"><path d="M5 12h14M12 5l7 7-7 7"/></svg></a>
  </div>
  
  <div class="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-3">
    ${selectedProducts.map(productCardHTML).join('')}
  </div>
</section>`;
  }).join('');

  
  if (!html) container.innerHTML = '<div class="max-w-6xl mx-auto px-4 mt-8 text-center py-12 text-gray-400"><p class="font-bold">Koi product nahi mila</p></div>';
  else container.innerHTML = html;
}

window.openCategory = function(catId) {
  currentCategory = catId;
  searchQuery = '';
  navigateTo('category', true);
  setTimeout(() => { renderFilterBar(); renderCategoryPage(); }, 50);
};

window.navigateTo = function(page, isBack = false) {
  sessionStorage.setItem('orderdrop_internal_nav', 'true');
  if (currentPage && currentPage !== page) {
    pageScrollPositions[currentPage] = window.scrollY || window.pageYOffset || 0;
  }
  document.querySelectorAll('.page').forEach(p => p.classList.remove('active'));
  const target = document.getElementById('page-' + page);
 
  if (target) target.classList.add('active');
  currentPage = page;
  if (page === 'cart') renderCart();
  if (page === 'account') renderAccountOrders();
  if (page === 'category') { renderFilterBar(); renderCategoryPage(); }
  if (page === 'all-deals') renderAllDealsPage();
  if (page !== 'track') lastTrackedOrderNumber = null;

  let pageTitle = "OrderDrop.pk - Chichawatni Ki Fast Delivery";
  let pageDesc = "Chichawatni mein 30 min delivery. Groceries, Fast Food, Fresh items order karein. Cash on Delivery available.";
  let newUrl = "/";

  if (page === 'category') {
    const catName = currentCategory !== 'all' ? currentCategory : 'All Products';
    pageTitle = catName.charAt(0).toUpperCase() + catName.slice(1) + " - OrderDrop.pk Chichawatni";
    pageDesc = "Chichawatni mein best " + catName + " order karein. 30 minute fast delivery with Cash on Delivery.";
    newUrl = "/category/" + currentCategory;
  } else if (page === 'cart') { pageTitle = "Shopping Cart - OrderDrop.pk"; newUrl = "/cart"; }
  else if (page === 'checkout') { pageTitle = "Checkout - OrderDrop.pk"; newUrl = "/checkout"; }
  else if (page === 'account') { pageTitle = "My Orders - OrderDrop.pk"; newUrl = "/my-orders"; }
  else if (page === 'track') { pageTitle = "Track Order - OrderDrop.pk"; newUrl = "/track-order"; }
  else if (page === 'all-deals') { pageTitle = "All Deals & Combos - OrderDrop.pk"; newUrl = "/deals"; }

  document.title = pageTitle;
  let metaDesc = document.querySelector('meta[name="description"]');
  if (metaDesc) metaDesc.content = pageDesc;

  if (!isBack) window.history.pushState({ page, category: currentCategory }, '', newUrl);

  const backBtn = document.getElementById('backBtn');
  const menuBtn = document.getElementById('menuBtn');
  if (page === 'home') {
    backBtn.classList.add('hidden');
    if (menuBtn) menuBtn.classList.remove('hidden');
  } else {
    backBtn.classList.remove('hidden');
    if (menuBtn) menuBtn.classList.add('hidden');
  }

  document.querySelectorAll('[id^="nav-"]').forEach(a => {
  a.classList.remove('active', 'text-brand-orange');
  a.classList.add('text-[#0B1B33]'); 
  });
  const navEl = document.getElementById('nav-' + page);
  if (navEl) { navEl.classList.remove('text-gray-500'); navEl.classList.add('active', 'text-brand-orange'); }

  requestAnimationFrame(() => {
    requestAnimationFrame(() => {
      const savedScroll = pageScrollPositions[page] || 0;
      window.scrollTo({ top: savedScroll, behavior: 'smooth' });
    });
  });
};

window.goBack = function() { 
  // Agar user ne koi search ki hai to pehle search clear karo
  if (searchQuery && currentPage === 'category') {
    searchQuery = '';
    document.getElementById('searchDesktop').value = '';
    document.getElementById('searchMobile').value = '';
    renderCategoryPage();
    return;
  }

  // Agar user Product page par hai
  if (currentPage === 'product') {
    // Agar product kisi category se khula tha to wapas usi category mein jao
    if (currentCategory && currentCategory !== 'all') {
      navigateTo('category', true);
    } else {
      // Warna home pe jao
      navigateTo('home', true);
    }
    return;
  }

  // Baqi sab pages (cart, track, account, policy etc) se direct Home pe jao
  navigateTo('home', true);
};

window.addEventListener('popstate', (event) => {
  if (event.state && event.state.page) {
    currentCategory = event.state.category || 'all';
    
    document.querySelectorAll('.page').forEach(p => p.classList.remove('active'));
    const target = document.getElementById('page-' + event.state.page);
    if (target) target.classList.add('active');
    currentPage = event.state.page;

    if (currentPage === 'home') renderHomeSections();
    if (currentPage === 'category') { renderFilterBar(); renderCategoryPage(); }
    if (currentPage === 'all-deals') renderAllDealsPage();
    if (currentPage === 'cart') renderCart();
    if (currentPage === 'account') renderAccountOrders();
    
    const backBtn = document.getElementById('backBtn');
    const menuBtn = document.getElementById('menuBtn');
    if (currentPage === 'home') {
      backBtn.classList.add('hidden');
      if (menuBtn) menuBtn.classList.remove('hidden');
    } else {
      backBtn.classList.remove('hidden');
      if (menuBtn) menuBtn.classList.add('hidden');
    }
  } else {
    navigateTo('home', true);
  }
});

window.toggleMenu = function() { document.getElementById('mobileMenu').classList.toggle('hidden'); };

window.filterCategory = function(cat) {
  currentCategory = cat;
  searchQuery = '';
  renderFilterBar();
  renderCategoryPage();
};

function renderFilterBar() {
  const el = document.getElementById('filterBar');
  if (!el) return;
  const cats = [{ id: 'all', name: 'All' }, ...CATEGORIES];
  el.innerHTML = cats.map(c => `
    <button onclick="filterCategory('${c.id}')" 
      class="shrink-0 px-4 py-2 text-xs font-bold rounded-full whitespace-nowrap transition ${
        currentCategory === c.id ? 'bg-brand-navy text-white shadow-md' : 'bg-white border border-gray-200 text-gray-700'
      }">${c.name}</button>`).join('');
  const activeBtn = el.querySelector('.bg-brand-navy');
  if (activeBtn) setTimeout(() => { activeBtn.scrollIntoView({ behavior: 'smooth', inline: 'center', block: 'nearest' }); }, 100);
}

function renderCategoryPage() {
  let list = PRODUCTS.filter(p => p.active !== false);
  if (currentCategory !== 'all') list = list.filter(p => p.cat === currentCategory);
  if (searchQuery) { const q = searchQuery.toLowerCase(); list = list.filter(p => (p.name || '').toLowerCase().includes(q)); }
  const cat = CATEGORIES.find(c => c.id === currentCategory);
  document.getElementById('categoryTitle').textContent = cat ? cat.name : (searchQuery ? `Search: "${searchQuery}"` : 'All Products');
  document.getElementById('productCount').textContent = `${list.length} products`;
  const el = document.getElementById('categoryProducts');
  if (list.length === 0) el.innerHTML = `<div class="col-span-full text-center py-16"><p class="font-bold text-gray-700">Kuch nahi mila</p><p class="text-xs text-gray-500 mt-1">Doosri category try karein</p></div>`;
  else el.innerHTML = list.map(productCardHTML).join('');
}

window.searchProducts = function(q) {
  searchQuery = q.trim();
  currentCategory = 'all';
  if (currentPage !== 'category') navigateTo('category');
  renderFilterBar();
  renderCategoryPage();
};

window.openProduct = function(id) {
  currentProductId = id;
  renderProductDetail();
  navigateTo('product');
  window.history.pushState({ page: 'product', id: id }, '', '/?id=' + id);
};

function renderProductDetail() {
  const p = getProduct(currentProductId);
  const el = document.getElementById('productDetail');
  if (!el) return;
  if (!p) { el.innerHTML = '<div class="max-w-3xl mx-auto p-8 text-center text-gray-500">Product not found</div>'; return; }
  const pid = p._fsId || p.id;
  const oldPrice = p.old || p.price;
  const discount = oldPrice > p.price ? Math.round(((oldPrice - p.price) / oldPrice) * 100) : 0;
  const catName = CATEGORIES.find(c => c.id === p.cat)?.name || p.cat;
  const manualReviews = p.reviews || 0;
  const realReviews = PRODUCT_REVIEWS[pid] || [];
  const totalCount = manualReviews + realReviews.length;
  const avgRating = realReviews.length > 0 ? (realReviews.reduce((s, r) => s + (r.rating || 0), 0) / realReviews.length).toFixed(1) : null;
  el.innerHTML = `
    <div class="max-w-3xl mx-auto bg-white p-4 md:p-6">
      <div class="aspect-square bg-gray-50 rounded-2xl overflow-hidden mb-4 relative border border-gray-100">
        ${discount > 0 ? `<span class="badge-discount" style="font-size:12px;padding:5px 10px;">-${discount}% OFF</span>` : ''}
        <img src="${p.img || ''}" alt="${p.name || 'Product Image'}" class="w-full h-full object-cover">
      </div>
      <h1 class="text-xl font-extrabold brand-navy mb-1">${p.name || ''}</h1>
      <p class="text-xs text-gray-500 mb-3 font-medium">${p.unit || ''}</p>
      <div class="rating-stars rating-stars-lg mb-4">
        ${STAR_SVG}${STAR_SVG}${STAR_SVG}${STAR_SVG}${STAR_SVG}
        ${totalCount > 0 ? `<span class="text-xs text-gray-500 font-medium ml-2">(${totalCount} reviews${avgRating ? ' · ' + avgRating + '★' : ''})</span>` : ''}
      </div>
      <div class="flex items-center gap-3 mb-5">
        <span class="text-3xl font-extrabold brand-orange">${formatPrice(p.price)}</span>
        ${oldPrice > p.price ? `<span class="text-sm text-gray-400 line-through">${formatPrice(oldPrice)}</span>` : ''}
      </div>
      <div class="bg-gray-50 rounded-xl p-4 mb-5 border border-gray-100">
        <h3 class="font-bold text-sm brand-navy mb-2">Product Details</h3>
        <div class="space-y-1.5 text-xs text-gray-600">
          <div class="flex justify-between"><span>Category</span><span class="font-semibold">${catName || 'Deal'}</span></div>
          <div class="flex justify-between"><span>Unit</span><span class="font-semibold">${p.unit || '-'}</span></div>
          <div class="flex justify-between"><span>Stock</span><span class="font-semibold text-green-600">Available</span></div>
        </div>
      </div>
      ${p.description && p.description.trim() ? `<div class="bg-blue-50 rounded-xl p-4 mb-5 border border-blue-100"><h3 class="font-bold text-sm brand-navy mb-2">Description</h3><p class="text-xs text-gray-700 leading-relaxed whitespace-pre-line">${p.description}</p></div>` : ''}
      <button onclick="addToCart('${pid}')" class="w-full btn-primary py-4 rounded-xl font-bold text-sm mb-3">Add to Cart</button>
      <button onclick="navigateTo('cart')" class="w-full btn-navy py-3.5 rounded-xl font-bold text-sm">Go to Cart</button>
      <div class="mt-6 border-t pt-5">
        <div class="flex items-center justify-between mb-3">
          <h3 class="font-extrabold brand-navy text-base">Customer Reviews</h3>
          <button onclick="openReviewModal('${pid}')" class="bg-brand-orange text-white font-bold text-xs px-4 py-2 rounded-xl">+ Write Review</button>
        </div>
        <div id="productReviewsList_${pid}"><div class="flex justify-center py-6"><div class="loading-spinner"></div></div></div>
      </div>
    </div>`;
  loadProductReviews(pid);
}

function loadProductReviews(productId) {
  if (reviewsUnsubscribers[productId]) reviewsUnsubscribers[productId]();
  const q = query(collection(db, 'reviews'), where('productId', '==', productId));
  reviewsUnsubscribers[productId] = onSnapshot(q, (snap) => {
    const reviews = snap.docs.map(d => ({ _fsId: d.id, ...d.data() }));
    reviews.sort((a,b) => (b.createdAt?.seconds || 0) - (a.createdAt?.seconds || 0));
    PRODUCT_REVIEWS[productId] = reviews;
    renderReviewsList(productId, reviews);
    updateProductRatingDisplay(productId);
  }, (err) => console.error('Reviews listener error:', err));
}

function renderReviewsList(productId, reviews) {
  const el = document.getElementById('productReviewsList_' + productId);
  if (!el) return;
  if (reviews.length === 0) { el.innerHTML = `<div class="text-center py-6 text-xs text-gray-400"></div>`; return; }
  el.innerHTML = reviews.map(r => {
    const stars = '★'.repeat(r.rating || 0) + '☆'.repeat(5 - (r.rating || 0));
    const date = r.date || (r.createdAt?.seconds ? new Date(r.createdAt.seconds * 1000).toLocaleDateString('en-PK') : '');
    return `<div class="bg-gray-50 rounded-xl p-3 mb-2">
      <div class="flex items-center justify-between mb-1">
        <div class="flex items-center gap-2">
          <div class="w-7 h-7 bg-brand-orange/10 rounded-full flex items-center justify-center text-brand-orange font-extrabold text-xs">${(r.customerName||'?')[0].toUpperCase()}</div>
          <span class="font-bold text-xs brand-navy">${r.customerName || 'Customer'}</span>
        </div>
        <span class="text-[10px] text-gray-400">${date}</span>
      </div>
      <div class="text-yellow-500 text-xs mb-1">${stars}</div>
      <p class="text-xs text-gray-600 leading-relaxed">${r.comment || ''}</p>
    </div>`;
  }).join('');
}

function updateProductRatingDisplay(productId) {
  const reviews = PRODUCT_REVIEWS[productId] || [];
  const product = getProduct(productId);
  if (!product) return;
  const manualReviews = product.reviews || 0;
  const totalCount = manualReviews + reviews.length;
  const avg = reviews.length > 0 ? (reviews.reduce((s, r) => s + (r.rating || 0), 0) / reviews.length).toFixed(1) : null;
  const cardEl = document.querySelector(`[data-product-id="${productId}"] .rating-stars`);
  if (cardEl) cardEl.innerHTML = `${STAR_SVG}${STAR_SVG}${STAR_SVG}${STAR_SVG}${STAR_SVG}${totalCount > 0 ? `<span class="text-gray-400 font-medium ml-1">(${totalCount}${avg ? ' · ' + avg + '★' : ''})</span>` : ''}`;
}

window.openReviewModal = function(productId) {
  const isLoggedIn = !!currentLoginPhone;
  let existingModal = document.getElementById('reviewModal');
  if (existingModal) existingModal.remove();
  const modal = document.createElement('div');
  modal.id = 'reviewModal';
  modal.className = 'fixed inset-0 bg-black/60 z-[80] flex items-end md:items-center justify-center p-0 md:p-4';
  modal.innerHTML = `
    <div class="bg-white w-full md:max-w-md rounded-t-3xl md:rounded-3xl p-5 slide-up">
      <div class="flex items-center justify-between mb-4">
        <h2 class="text-lg font-extrabold brand-navy">Review Dena</h2>
        <button onclick="closeReviewModal()" class="text-gray-400 text-2xl font-bold w-8 h-8 flex items-center justify-center rounded-full hover:bg-gray-100">×</button>
      </div>
      <form onsubmit="submitReview(event, '${productId}')" class="space-y-4">
        <div>
          <label class="text-xs font-bold block mb-2">Aapka Naam *</label>
          <input type="text" id="revName" required value="${isLoggedIn ? currentLoginName : ''}" placeholder="Muhammad Qammar Aseem" class="w-full border rounded-xl px-4 py-3 text-sm focus:outline-none focus:border-[#FF6B00]">
        </div>
        <div>
          <label class="text-xs font-bold block mb-2">Rating *</label>
          <div id="starPicker" class="flex gap-2 justify-center py-2">
            ${[1,2,3,4,5].map(i => `<button type="button" onclick="setRating(${i})" data-star="${i}" class="star-pick text-3xl text-gray-300 transition hover:scale-110">★</button>`).join('')}
          </div>
          <input type="hidden" id="revRating" value="0">
        </div>
        <div>
          <label class="text-xs font-bold block mb-2">Comment (optional)</label>
          <textarea id="revComment" rows="3" placeholder="Product ke baare mein kya khayal hai?" class="w-full border rounded-xl px-4 py-3 text-sm focus:outline-none focus:border-[#FF6B00]"></textarea>
        </div>
        <button type="submit" id="revSubmitBtn" class="w-full bg-gradient-to-br from-[#FF6B00] to-[#FF8A33] text-white py-3.5 rounded-xl font-bold text-sm">Submit Review</button>
      </form>
    </div>`;
  document.body.appendChild(modal);
};

window.setRating = function(n) {
  document.getElementById('revRating').value = n;
  document.querySelectorAll('.star-pick').forEach(el => {
    const star = +el.dataset.star;
    if (star <= n) { el.classList.remove('text-gray-300'); el.classList.add('text-yellow-400'); }
    else { el.classList.add('text-gray-300'); el.classList.remove('text-yellow-400'); }
  });
};

window.closeReviewModal = function() { const modal = document.getElementById('reviewModal'); if (modal) modal.remove(); };

window.submitReview = async function(e, productId) {
  e.preventDefault();
  const name = document.getElementById('revName').value.trim();
  const rating = +document.getElementById('revRating').value;
  const comment = document.getElementById('revComment').value.trim();
  if (!name) return showToast('Naam likhein', 'error');
  if (rating < 1) return showToast('Stars select karein', 'error');
  const btn = document.getElementById('revSubmitBtn');
  btn.disabled = true; btn.textContent = 'Submitting...';
  const product = getProduct(productId);
  const productName = product?.name || '';
  const dateStr = new Date().toISOString().split('T')[0];
  try {
    await addDoc(collection(db, 'reviews'), {
      productId, productName, customerName: name,
      phone: currentLoginPhone || '', rating, comment, date: dateStr, createdAt: serverTimestamp()
    });
    showToast('Shukriya! Review submit ho gaya');
    closeReviewModal();
  } catch(err) {
    console.error(err);
    showToast('Review submit nahi ho saka', 'error');
    btn.disabled = false; btn.textContent = 'Submit Review';
  }
};

function getCartCount() { return Object.values(cart).reduce((a, b) => a + b, 0); }

function getCartSubtotal() {
  let total = 0;
  for (const [id, qty] of Object.entries(cart)) {
    const p = getProduct(id);
    if (p) total += (p.price || 0) * qty;
  }
  return total;
}

window.addToCart = function(id, qty = 1) {
  cart[id] = (cart[id] || 0) + qty;
  localStorage.setItem('orderdrop_cart', JSON.stringify(cart));
  updateCartUI();
  showToast('Cart mein add ho gaya');
  if (currentPage === 'home') renderHomeSections();
  if (currentPage === 'category') renderCategoryPage();
  if (currentPage === 'product') renderProductDetail();
  if (currentPage === 'all-deals') renderAllDealsPage();
  
};

window.removeFromCart = function(id) {
  delete cart[id];
  localStorage.setItem('orderdrop_cart', JSON.stringify(cart));
  updateCartUI();
  if (currentPage === 'cart') renderCart();
};

window.changeQty = function(id, delta) {
  const newQty = (cart[id] || 0) + delta;
  if (newQty <= 0) removeFromCart(id);
  else {
    cart[id] = newQty;
    localStorage.setItem('orderdrop_cart', JSON.stringify(cart));
  }
  updateCartUI();
  if (currentPage === 'cart') renderCart();
  if (currentPage === 'home') renderHomeSections();
  if (currentPage === 'category') renderCategoryPage();
  if (currentPage === 'product') renderProductDetail();
  if (currentPage === 'all-deals') renderAllDealsPage();
};

function updateCartUI() {
  const count = getCartCount();
  const badge = document.getElementById('cartBadge');
  const navBadge = document.getElementById('navCartBadge');
  if (count > 0) {
    if (badge) { badge.textContent = count; badge.classList.remove('hidden'); }
    if (navBadge) { navBadge.textContent = count; navBadge.classList.remove('hidden'); }
  } else {
    if (badge) badge.classList.add('hidden');
    if (navBadge) navBadge.classList.add('hidden');
  }
}

function renderCart() {
  const items = Object.entries(cart).map(([id, qty]) => ({ p: getProduct(id), qty })).filter(x => x.p);
  const cartItemsEl = document.getElementById('cartItems');
  const cartEmptyEl = document.getElementById('cartEmpty');
  const cartSummaryEl = document.getElementById('cartSummary');
  if (!cartItemsEl) return;
  if (items.length === 0) {
    cartItemsEl.innerHTML = '';
    if (cartEmptyEl) cartEmptyEl.classList.remove('hidden');
    if (cartSummaryEl) cartSummaryEl.classList.add('hidden');
    return;
  }
  if (cartEmptyEl) cartEmptyEl.classList.add('hidden');
  if (cartSummaryEl) cartSummaryEl.classList.remove('hidden');
  cartItemsEl.innerHTML = items.map(({ p, qty }) => {
    const pid = p._fsId || p.id;
    return `
    <div class="bg-white rounded-2xl p-3 flex gap-3 border border-gray-100 shadow-sm">
      <img src="${p.img || ''}" alt="${p.name || 'Product Image'}" class="w-16 h-16 rounded-xl object-cover bg-gray-100">
      <div class="flex-1 min-w-0"><h3 class="font-bold text-[13px] text-gray-800 line-clamp-2">${p.name}</h3><p class="text-[10px] text-gray-400 mb-1">${p.unit || ''}</p><p class="font-extrabold brand-orange text-sm">${formatPrice(p.price)}</p></div>
      <div class="flex flex-col items-end justify-between">
        <button onclick="removeFromCart('${pid}')" class="text-gray-300 hover:text-red-500 transition">
          <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"/></svg>
        </button>
        <div class="flex items-center gap-1">
          <button onclick="changeQty('${pid}', -1)" class="qty-btn bg-gray-100 text-gray-700" style="font-size:20px;line-height:1;">-</button>
          <span class="w-7 text-center text-sm font-extrabold brand-navy">${qty}</span>
          <button onclick="changeQty('${pid}', 1)" class="qty-btn bg-brand-orange text-white" style="font-size:20px;line-height:1;">+</button>
        </div>
      </div>
    </div>`;
  }).join('');
  const cartTotalEl = document.getElementById('cartTotal');
  if (cartTotalEl) cartTotalEl.textContent = formatPrice(getCartSubtotal());
}

window.goToCheckout = function() {
  renderCheckout();
  navigateTo('checkout');
};

function renderCheckout() {
  const items = Object.entries(cart).map(([id, qty]) => ({ p: getProduct(id), qty })).filter(x => x.p);
  const checkoutItemsEl = document.getElementById('checkoutItems');
  const checkoutTotalEl = document.getElementById('checkoutTotal');
  if (checkoutItemsEl) checkoutItemsEl.innerHTML = items.map(({ p, qty }) => `<div class="flex justify-between text-xs"><span class="text-gray-600">${p.name} × ${qty}</span><span class="font-bold text-gray-800">${formatPrice((p.price||0) * qty)}</span></div>`).join('');
  if (checkoutTotalEl) checkoutTotalEl.textContent = formatPrice(getCartSubtotal());
  if (currentLoginPhone) {
    const custPhone = document.getElementById('custPhone');
    const custName = document.getElementById('custName');
    if (custPhone) custPhone.value = currentLoginPhone;
    if (custName && currentLoginName !== 'Customer') custName.value = currentLoginName;
  }
}

window.submitOrder = async function(e) {
  if (e) e.preventDefault();
  const name = document.getElementById('custName').value.trim();
  const phone = document.getElementById('custPhone').value.trim();
  const address = document.getElementById('custAddress').value.trim();
  if (!name || !phone || !address) { showToast('Tamam details enter karein', 'error'); return; }
  if (!isValidPakPhone(phone)) { showToast('Sahi 11-digit number dein', 'error'); return; }
  const items = Object.entries(cart).map(([id, qty]) => {
    const p = getProduct(id);
    return { name: p.name, price: p.price, qty };
  });
  const btn = document.getElementById('placeOrderBtn');
  btn.disabled = true; btn.textContent = 'Placing...';
  const orderNum = 'CD-' + Date.now().toString().slice(-6);
  const dateStr = new Date().toISOString().split('T')[0] + ' ' + new Date().toTimeString().slice(0,5);
  try {
    await addDoc(collection(db, 'orders'), {
      number: orderNum, name, phone, address,
      total: getCartSubtotal(), items: JSON.stringify(items),
      status: 'pending', date: dateStr, createdAt: serverTimestamp()
    });
    const custSnap = await getDocs(query(collection(db, 'customers'), where('phone', '==', phone)));
    if (custSnap.empty) {
      await addDoc(collection(db, 'customers'), { name, phone, loginAt: new Date().toISOString(), createdAt: serverTimestamp() });
    } else {
      await updateDoc(doc(db, 'customers', custSnap.docs[0].id), { name, lastLoginAt: new Date().toISOString() });
    }
    currentLoginPhone = phone;
    currentLoginName = name;
    localStorage.setItem('citydrop_login_phone', phone);
    localStorage.setItem('citydrop_login_name', name);
    updateAuthUI();
    document.getElementById('orderNumber').textContent = orderNum;
cart = {};
localStorage.removeItem('orderdrop_cart');
updateCartUI();
navigateTo('confirmation');
  } catch(err) {
    console.error(err);
    showToast('Order place nahi ho saka - dobara try karein', 'error');
  }
  btn.disabled = false; btn.textContent = 'Place Order';
};

window.handlePhoneLogin = async function(e) {
  e.preventDefault();
  const name = document.getElementById('loginNameInput').value.trim();
  const phone = document.getElementById('loginPhoneInput').value.trim();
  if (!isValidPakPhone(phone)) { showToast('Ghalat number! 11 digits enter karein', 'error'); return; }
  currentLoginName = name; currentLoginPhone = phone;
  localStorage.setItem('citydrop_login_name', name);
  localStorage.setItem('citydrop_login_phone', phone);
  try {
    const custSnap = await getDocs(query(collection(db, 'customers'), where('phone', '==', phone)));
    if (custSnap.empty) await addDoc(collection(db, 'customers'), { name, phone, loginAt: new Date().toISOString(), createdAt: serverTimestamp() });
    else await updateDoc(doc(db, 'customers', custSnap.docs[0].id), { name, lastLoginAt: new Date().toISOString() });
  } catch(err) { console.error(err); }
  closeAuthModal();
  updateAuthUI();
  navigateTo('account');
  showToast('Login ho gaye!');
};

window.handleLogout = function() {
  currentLoginPhone = null;
  currentLoginName = 'Customer';
  localStorage.removeItem('citydrop_login_phone');
  localStorage.removeItem('citydrop_login_name');
  localStorage.removeItem('orderdrop_cart');
  cart = {};
  updateCartUI();
  updateAuthUI();
  navigateTo('home');
  showToast('Logout ho gaye');
};

function updateAuthUI() {
  const btn = document.getElementById('authHeaderBtn');
  const mobileLabel = document.getElementById('mobileAccountLabel');
  if (currentLoginPhone) {
    if (btn) { btn.textContent = 'My Orders'; btn.onclick = () => navigateTo('account'); }
    if (mobileLabel) mobileLabel.textContent = 'My Orders (' + currentLoginPhone + ')';
  } else {
    if (btn) { btn.textContent = 'Login'; btn.onclick = window.openAuthModal; }
    if (mobileLabel) mobileLabel.textContent = 'My Orders';
  }
}

window.checkAccountNav = function() { if (currentLoginPhone) navigateTo('account'); else openAuthModal(); };

function renderAccountOrdersFromLive() {
  if (!currentLoginPhone) return;
  const listEl = document.getElementById('accountOrdersList');
  if (!listEl) return;
  const orders = ORDERS_LIVE.filter(o => o.phone === currentLoginPhone);
  orders.sort((a,b) => String(b.date||'').localeCompare(String(a.date||'')));
  if (orders.length === 0) { listEl.innerHTML = `<div class="bg-white rounded-2xl p-8 text-center border border-gray-100"><p class="text-sm text-gray-500 font-medium">Is number par abhi tak koi order nahi mila.</p></div>`; return; }
  listEl.innerHTML = orders.map(o => {
    let items = [];
    try { items = typeof o.items === 'string' ? JSON.parse(o.items) : (o.items || []); } catch(e) {}
    return `<div class="bg-white rounded-2xl p-4 border border-gray-100 mb-3 shadow-sm">
      <div class="flex justify-between items-center mb-2">
        <div class="flex items-center gap-2">
          <span class="font-extrabold text-sm brand-navy">${o.number}</span>
          <button onclick="copyOrderId('accOrderNum_${o._fsId}')" class="copy-btn" title="Copy Order ID">
            <svg class="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z"/></svg>
            Copy
          </button>
          <span id="accOrderNum_${o._fsId}" class="hidden">${o.number}</span>
        </div>
        <span class="order-status-badge bg-orange-100 text-orange-700">${o.status}</span>
      </div>
      <p class="text-[11px] text-gray-500 mb-3">${o.date} | Total: <b class="brand-orange">${formatPrice(o.total)}</b></p>
      <div class="border-t pt-2 space-y-1.5">
        ${items.map(i => `<div class="flex justify-between text-[11px] text-gray-600"><span>${i.name} × ${i.qty}</span><span class="font-semibold">${formatPrice(i.price * i.qty)}</span></div>`).join('')}
      </div>
    </div>`;
  }).join('');
}

async function renderAccountOrders() {
  if (!currentLoginPhone) { openAuthModal(); return; }
  const nameEl = document.getElementById('accountNameDisplay');
  const phoneEl = document.getElementById('accountPhoneDisplay');
  if (nameEl) nameEl.textContent = currentLoginName;
  if (phoneEl) phoneEl.textContent = currentLoginPhone;
  const listEl = document.getElementById('accountOrdersList');
  if (!listEl) return;
  listEl.innerHTML = '<div class="flex justify-center py-8"><div class="loading-spinner"></div></div>';
  try {
    const snap = await getDocs(query(collection(db, 'orders'), where('phone', '==', currentLoginPhone)));
    const orders = snap.docs.map(d => ({ _fsId: d.id, ...d.data() }));
    orders.sort((a,b) => String(b.date||'').localeCompare(String(a.date||'')));
    if (orders.length === 0) { listEl.innerHTML = `<div class="bg-white rounded-2xl p-8 text-center border border-gray-100"><p class="text-sm text-gray-500 font-medium">Is number par abhi tak koi order nahi mila.</p></div>`; return; }
    listEl.innerHTML = orders.map(o => {
      let items = [];
      try { items = typeof o.items === 'string' ? JSON.parse(o.items) : (o.items || []); } catch(e) {}
      return `<div class="bg-white rounded-2xl p-4 border border-gray-100 mb-3 shadow-sm">
        <div class="flex justify-between items-center mb-2">
          <div class="flex items-center gap-2">
            <span class="font-extrabold text-sm brand-navy">${o.number}</span>
            <button onclick="copyOrderId('accOrderNum2_${o._fsId}')" class="copy-btn" title="Copy Order ID">
              <svg class="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z"/></svg>
              Copy
            </button>
            <span id="accOrderNum2_${o._fsId}" class="hidden">${o.number}</span>
          </div>
          <span class="order-status-badge bg-orange-100 text-orange-700">${o.status}</span>
        </div>
        <p class="text-[11px] text-gray-500 mb-3">${o.date} | Total: <b class="brand-orange">${formatPrice(o.total)}</b></p>
        <div class="border-t pt-2 space-y-1.5">
          ${items.map(i => `<div class="flex justify-between text-[11px] text-gray-600"><span>${i.name} × ${i.qty}</span><span class="font-semibold">${formatPrice(i.price * i.qty)}</span></div>`).join('')}
        </div>
      </div>`;
    }).join('');
  } catch(err) {
    console.error(err);
    listEl.innerHTML = '<div class="text-center py-8 text-red-500 text-sm">Orders load nahi ho sake</div>';
  }
}

window.trackOrder = async function(e) {
  e.preventDefault();
  const num = document.getElementById('trackNum').value.trim().toUpperCase();
  const phone = document.getElementById('trackPhone').value.trim();
  if (!isValidPakPhone(phone)) { showToast('Theek 11-digit number enter karein', 'error'); return; }
  const resultEl = document.getElementById('trackResult');
  const errorEl = document.getElementById('trackError');
  resultEl.classList.add('hidden');
  errorEl.classList.add('hidden');
  resultEl.innerHTML = '<div class="flex justify-center py-8"><div class="loading-spinner"></div></div>';
  resultEl.classList.remove('hidden');
  try {
    const snap = await getDocs(query(collection(db, 'orders'), where('number', '==', num), where('phone', '==', phone)));
    if (snap.empty) {
      resultEl.classList.add('hidden');
      errorEl.textContent = 'Order nahi mila. Order number aur phone check karein.';
      errorEl.classList.remove('hidden');
      return;
    }
    const order = { _fsId: snap.docs[0].id, ...snap.docs[0].data() };
    lastTrackedOrderNumber = order.number;
    renderTrackResult(order);
  } catch(err) {
    console.error(err);
    resultEl.classList.add('hidden');
    errorEl.textContent = 'Error: ' + err.message;
    errorEl.classList.remove('hidden');
  }
};

function renderTrackResult(order) {
  const resultEl = document.getElementById('trackResult');
  const errorEl = document.getElementById('trackError');
  if (!order) {
    resultEl.classList.add('hidden');
    if (errorEl) { errorEl.textContent = 'Ye order ab exist nahi karta.'; errorEl.classList.remove('hidden'); }
    return;
  }
  if (errorEl) errorEl.classList.add('hidden');
  let items = [];
  try { items = typeof order.items === 'string' ? JSON.parse(order.items) : (order.items || []); } catch(e) {}
  const currentStatus = (order.status || 'pending').toLowerCase().replace(/\s+/g, '_');
  const statuses = [
    { key: 'pending', label: 'Order Placed', done: true },
    { key: 'processing', label: 'Processing', done: ['processing', 'on_the_way', 'delivered'].includes(currentStatus) },
    { key: 'on_the_way', label: 'On the Way', done: ['on_the_way', 'delivered'].includes(currentStatus) },
    { key: 'delivered', label: 'Delivered', done: currentStatus === 'delivered' },
  ];
  resultEl.innerHTML = `
    <div class="bg-white rounded-2xl p-5 border border-gray-100 mb-4 shadow-sm">
      <div class="flex items-center justify-between mb-5">
        <div>
          <p class="text-[10px] text-gray-500 font-medium">Order</p>
          <div class="flex items-center gap-2">
            <p id="trackOrderNum" class="font-extrabold brand-navy">${order.number}</p>
            <button onclick="copyOrderId('trackOrderNum')" class="copy-btn" title="Copy Order ID">
              <svg class="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z"/></svg>
              Copy
            </button>
          </div>
        </div>
        <span class="order-status-badge bg-orange-100 text-orange-700" id="trackStatusBadge">${currentStatus.replace(/_/g, ' ')}</span>
      </div>
      <div class="space-y-4" id="trackTimeline">
        ${statuses.map(s => `<div class="flex gap-3 ${s.done ? '' : 'opacity-40'}">
          <div class="w-7 h-7 ${s.done ? 'bg-brand-orange' : 'bg-gray-300'} rounded-full flex items-center justify-center shrink-0">
            ${s.done ? `<svg class="w-4 h-4 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="3" d="M5 13l4 4L19 7"/></svg>` : ''}
          </div>
          <div class="flex-1 pt-0.5"><p class="font-bold text-sm brand-navy">${s.label}</p></div>
        </div>`).join('')}
      </div>
    </div>
    <div class="bg-white rounded-2xl p-5 border border-gray-100 shadow-sm">
      <h3 class="font-extrabold brand-navy mb-3 text-sm">Ordered Items</h3>
      <div class="space-y-2 text-sm">
        ${items.map(i => `<div class="flex justify-between text-xs"><span class="text-gray-600">${i.name} ×${i.qty}</span><span class="font-bold text-gray-800">${formatPrice(i.price * i.qty)}</span></div>`).join('')}
        <div class="flex justify-between pt-3 border-t border-gray-100 mt-2">
          <span class="font-extrabold brand-navy text-sm">Total</span>
          <span class="font-extrabold brand-orange">${formatPrice(order.total)}</span>
        </div>
      </div>
    </div>`;
  resultEl.classList.remove('hidden');
}

function init() {
cart = JSON.parse(localStorage.getItem('orderdrop_cart') || '{}');
  if (window.location.pathname === '/sitemap.xml') {
    getDoc(doc(db, 'settings', 'live_sitemap')).then((docSnap) => {
      if (docSnap.exists()) {
        const xmlContent = docSnap.data().xml;
        document.documentElement.innerHTML = xmlContent;
      } else {
        document.documentElement.innerHTML = '<h1>Sitemap not found. Admin Panel se update karein.</h1>';
      }
    }).catch((err) => { document.documentElement.innerHTML = '<h1>Error loading sitemap</h1>'; });
    return;
  }

  // Handle URL params (from other pages + direct share links)
  const _up = new URLSearchParams(window.location.search);
  const _pageParam = _up.get('page');
  const _qParam = _up.get('q');
  const _installParam = _up.get('install');
  const _idParam = _up.get('id');
  const _catParam = _up.get('cat') || _up.get('category'); // cat ya category dono support karega

  if (_installParam === '1') {
    pendingInstallTrigger = true;
    setTimeout(() => {
      document.getElementById('installPopup').classList.remove('hidden');
      window.history.replaceState({}, '', '/');
    }, 300);
  }

  // Direct Product Link Support
  if (_idParam) {
    setTimeout(() => {
      currentProductId = _idParam;
      renderProductDetail();
      navigateTo('product', true);
    }, 500); // 500ms wait taake Firebase se products load ho jayein
  } 
  // Direct Category Link Support
  else if (_catParam) {
    setTimeout(() => {
      currentCategory = _catParam;
      navigateTo('category', true);
      renderFilterBar();
      renderCategoryPage();
    }, 500);
  }
  // Normal Page Routing
  else if (_pageParam) {
    setTimeout(() => {
      const validPages = ['category','cart','checkout','track','account','all-deals','home'];
      navigateTo(validPages.includes(_pageParam) ? _pageParam : 'home', true);
    }, 100);
  } 
  // Search Link Support
  else if (_qParam) {
    setTimeout(() => {
      searchQuery = _qParam;
      const sd = document.getElementById('searchDesktop');
      const sm = document.getElementById('searchMobile');
      if (sd) sd.value = _qParam;
      if (sm) sm.value = _qParam;
      navigateTo('category', true);
      renderFilterBar();
      renderCategoryPage();
    }, 100);
  }

  updateAuthUI();
  updateCartUI();
  pageScrollPositions = { home: 0 };
  startLiveListeners();

  if (!localStorage.getItem('installPopupDismissed') && !_installParam) {
    setTimeout(() => {
      const popup = document.getElementById('installPopup');
      if (popup && popup.classList.contains('hidden')) popup.classList.remove('hidden');
    }, 4000);
  }

  const path = window.location.pathname;
  if (path === '/cart') navigateTo('cart', true);
  else if (path === '/checkout') navigateTo('checkout', true);
  else if (path === '/my-orders') navigateTo('account', true);
  else if (path === '/track-order') navigateTo('track', true);
  else if (path === '/deals') navigateTo('all-deals', true);
  else if (path.startsWith('/category/')) { currentCategory = path.split('/category/')[1] || 'all'; navigateTo('category', true); }
  else if (!_pageParam && !_qParam && !_installParam && !_idParam && !_catParam) navigateTo('home', true);
}

init();

// Ye code purane pages ke ?page=... links ko theek karega
(function fixOldLinks() {
  const params = new URLSearchParams(window.location.search);
  const page = params.get('page');
  if (page) {
    if (page === 'track') { window.location.replace('/track-order'); return; }
    if (page === 'cart') { window.location.replace('/cart'); return; }
    if (page === 'account') { window.location.replace('/my-orders'); return; }
    if (page === 'category') { window.location.replace('/categories'); return; }
    if (page === 'home') { window.location.replace('/'); return; }
  }
})();

</script>
</body>
</html>