/* Car Services flow (app-services.jsx) — Speero's second product line: a
   marketplace of car-service COUPONS from vendors (car care, quick service,
   tinting, wash...). Unlike parts, the hero value is the DISCOUNT, not fitment.
   This file will hold the whole flow (home entry → discover → PDP), sharing
   index.html's global scope. Task 1 is the home entry, previewed inside the
   real home chrome at #/services-home-demo (like #/home-car-demo).

   Everything here is prefixed svc- / Svc* to avoid colliding with the app's
   shared scope. */

/* ---------- Service icons (line style matches the app's icon set) ---------- */
const svcIP = { fill: "none", stroke: "currentColor", strokeWidth: 1.8, strokeLinecap: "round", strokeLinejoin: "round" };

// Car care / detailing — a sparkle (shine).
const SvcCareIcon = () => (
  <svg viewBox="0 0 24 24" {...svcIP}>
    <path d="M12 3l1.7 4.6L18 9l-4.3 1.4L12 15l-1.7-4.6L6 9l4.3-1.4z" />
    <path d="M18.5 14l.7 2 2 .7-2 .7-.7 2-.7-2-2-.7 2-.7z" />
  </svg>
);
// Quick service — Feather "tool" wrench.
const SvcQuickIcon = () => (
  <svg viewBox="0 0 24 24" {...svcIP}>
    <path d="M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z" />
  </svg>
);
// Tinting — a side window with shade lines + sun.
const SvcTintIcon = () => (
  <svg viewBox="0 0 24 24" {...svcIP}>
    <rect x="2.5" y="8" width="13" height="9" rx="2" />
    <path d="M6.5 8L4 17M10.5 8L8 17M14 8l-2.2 9" />
    <circle cx="19" cy="6" r="2.4" />
    <path d="M19 1.6v1M19 10.4v-1M23.4 6h-1M15.6 6h-1" />
  </svg>
);
// Wash & polish — a water droplet + bubbles.
const SvcWashIcon = () => (
  <svg viewBox="0 0 24 24" {...svcIP}>
    <path d="M12 3.5c2.9 3.1 4.6 5.5 4.6 7.8a4.6 4.6 0 1 1-9.2 0C7.4 9 9.1 6.6 12 3.5z" />
    <circle cx="18.6" cy="16.5" r="1.4" />
    <circle cx="5.8" cy="17.6" r="1" />
  </svg>
);
const SvcStar = () => (
  <svg viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
    <path d="M12 2.5l2.9 5.9 6.5.95-4.7 4.6 1.1 6.45L12 17.9l-5.8 3 1.1-6.44-4.7-4.6 6.5-.95z" />
  </svg>
);
const SvcPinIcon = () => (
  // Filled teardrop with the inner circle punched out (even-odd → real hole).
  <svg viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
    <path fillRule="evenodd" clipRule="evenodd"
      d="M12 21s7-6.3 7-11a7 7 0 0 0-14 0c0 4.7 7 11 7 11zM12 12.6a2.6 2.6 0 1 0 0-5.2 2.6 2.6 0 0 0 0 5.2z" />
  </svg>
);
// Sort — decreasing lines (order/arrange).
const SvcSortIcon = () => (
  <svg viewBox="0 0 24 24" {...svcIP}>
    <path d="M6 7h12M6 12h8M6 17h4" />
  </svg>
);
// Open in maps — external-link box with an out-arrow.
const SvcMapIcon = () => (
  <svg viewBox="0 0 24 24" {...svcIP}>
    <path d="M14 4h6v6M20 4l-8.5 8.5" />
    <path d="M18 13.5V18.5A1.5 1.5 0 0 1 16.5 20h-11A1.5 1.5 0 0 1 4 18.5v-11A1.5 1.5 0 0 1 5.5 6H10.5" />
  </svg>
);

/* ---------- Data (prototype stand-in for the coupons catalog) ----------
   `slug` mirrors the live URL shape: /car-services/category/{slug}. */
const SVC_CATEGORIES = [
  { id: "care",    slug: "detailing-services", label: "العناية",      icon: SvcCareIcon,  desc: "خدمات العناية والتلميع للحفاظ على مظهر سيارتك ولمعانها من الداخل والخارج." },
  { id: "quick",   slug: "quick-services",     label: "صيانة سريعة",  icon: SvcQuickIcon, desc: "صيانة سريعة موثوقة: تغيير الزيت والفلاتر والفرامل بأيدي فنيين محترفين." },
  { id: "tinting", slug: "tinting-services",   label: "تظليل",         icon: SvcTintIcon,  desc: "تظليل حراري عازل لكامل زجاج سيارتك مع ضمان، من مراكز معتمدة." },
  { id: "wash",    slug: "wash-services",      label: "غسيل وتلميع",  icon: SvcWashIcon,  desc: "غسيل وتلميع داخلي وخارجي احترافي يعيد لسيارتك لمعانها." },
];
const SVC_ALL_DESC = "عروض وخصومات على خدمات سيارتك من مراكز موثوقة: عناية، صيانة سريعة، تظليل وغسيل — احجز بأفضل الأسعار.";
const SVC_CAT_ICON = SVC_CATEGORIES.reduce((m, c) => { m[c.id] = c.icon; return m; }, {});
const SVC_CAT_BY_SLUG = SVC_CATEGORIES.reduce((m, c) => { m[c.slug] = c.id; return m; }, {});
// Live URL shape: /car-services (all) · /car-services/category/{slug} · /car-services/{offer}
const svcCatPath = (id) => {
  const c = SVC_CATEGORIES.find((x) => x.id === id);
  return "/car-services/category/" + (c ? c.slug : id);
};
const svcOfferPath = (key) => "/car-services/" + key;
// An offer's images: an `images` array (multiple) or a single `image`. Cards/hero
// show the first; the PDP shows the whole gallery.
const svcImgs = (o) => o.images || (o.image ? [o.image] : []);
const svcImg0 = (o) => svcImgs(o)[0] || null;
// Google Maps link for a branch (prototype: a text search of vendor + area +
// city; swap for real coordinates at port time).
const svcMapUrl = (vendor, b) => "https://www.google.com/maps/search/?api=1&query=" + encodeURIComponent(vendor + " " + b.area + " " + b.city);

const SVC_OFFERS = [
  { key: "caliper-paint",  cat: "care",    hero: true, vendor: "زووم ZOOM",        title: "طلاء الكاليبرات", desc: "طلاء احترافي للكاليبرات بألوان ثابتة تقاوم الحرارة", pct: 30, price: "180", oldPrice: "260", rating: "4.7", rc: 120, images: ["assets/services/caliper.png", "assets/services/caliper-2.png"] },
  { key: "wash-detail",    cat: "wash",    vendor: "مركز اللمسة الأخيرة", title: "غسيل وتلميع خارجي وداخلي كامل", desc: "غسيل خارجي وداخلي، تلميع، وتنظيف كامل للمقصورة", pct: 40, price: "90",  oldPrice: "150",  rating: "4.8", rc: 214 },
  { key: "tint-thermal",   cat: "tinting", vendor: "درع للعزل الحراري",    title: "تظليل حراري كامل مع ضمان 5 سنوات", desc: "عزل حراري عالٍ لكامل الزجاج مع ضمان خمس سنوات", pct: 30, price: "350", oldPrice: "500",  rating: "4.7", rc: 156 },
  { key: "oil-quick",      cat: "quick",   vendor: "سرعة الصيانة",         title: "تغيير زيت وفلتر — خدمة سريعة",  desc: "زيت أصلي وفلتر جديد مع فحص شامل خلال 30 دقيقة", pct: 25, price: "135", oldPrice: "180",  rating: "4.6", rc: 320 },
  // Multi-option offer: the buyer picks a variant (here by car size), and the
  // price / discount / add-to-cart follow the pick. Top-level price mirrors the
  // cheapest option so discover cards read "starting from". See doc/CAR_SERVICES §3.
  { key: "ceramic",        cat: "care",    vendor: "أسواف للعناية",        title: "3 طبقات نانو سيراميك لحماية الطلاء", desc: "ثلاث طبقات نانو سيراميك بمنتجات أمريكية، لمعان أعمق وحماية تدوم مع ضمان سنة", rating: "4.9", rc: 98, pct: 50, price: "800", oldPrice: "1600", image: "assets/services/ceramic.png",
    options: [
      { id: "s", label: "سيارة صغيرة", sub: "سيدان صغير",          pct: 50, price: "800",  oldPrice: "1600" },
      { id: "m", label: "سيارة متوسطة", sub: "سيدان · كروس أوفر", pct: 47, price: "950",  oldPrice: "1800" },
      { id: "l", label: "سيارة كبيرة",  sub: "دفع رباعي · SUV",    pct: 42, price: "1150", oldPrice: "2000" },
    ] },
  { key: "ac-clean",       cat: "quick",   vendor: "برودة للتكييف",        title: "تنظيف وتعقيم دورة التكييف",      desc: "تنظيف دورة التكييف وتعقيمها لهواء نقي وبارد", pct: 20, price: "160", oldPrice: "200",  rating: "4.5", rc: 142 },
  { key: "polish",         cat: "wash",    vendor: "لمعان",                title: "تلميع وإزالة الخدوش الخفيفة",    desc: "تلميع احترافي يزيل الخدوش الخفيفة ويعيد اللمعان", pct: 30, price: "210", oldPrice: "300",  rating: "4.6", rc: 187 },
  { key: "interior-detail", cat: "care",   vendor: "مركز العناية الفائقة", title: "تنظيف وتلميع المقصورة الداخلية", desc: "تنظيف عميق للمقاعد والسجاد وتلميع الأسطح الداخلية", pct: 33, price: "200", oldPrice: "300",  rating: "4.8", rc: 176 },
  { key: "tint-front",     cat: "tinting", vendor: "رؤية للتظليل",         title: "تظليل الزجاج الأمامي العازل",   desc: "شريحة أمامية عازلة للحرارة تحافظ على وضوح الرؤية", pct: 25, price: "150", oldPrice: "200" /* new — no rating yet */ },
  { key: "brake-service",  cat: "quick",   vendor: "أمان لصيانة الفرامل",   title: "تغيير فحمات الفرامل مع فحص", desc: "فحمات أصلية مع فحص الأقراص وسائل الفرامل", pct: 20, price: "240", oldPrice: "300",  rating: "4.7", rc: 205 },
  { key: "nano-coat",      cat: "care",    vendor: "قمة اللمعان",          title: "طلاء نانو للحماية واللمعان",    desc: "طبقة نانو تمنح لمعاناً عالياً وحماية من الخدوش", pct: 40, price: "480", oldPrice: "800",  rating: "4.9", rc: 64 },
  { key: "quick-wash",     cat: "wash",    vendor: "غسيل سريع",            title: "غسيل خارجي سريع مع تجفيف",       desc: "غسيل خارجي وتجفيف احترافي خلال 15 دقيقة", pct: 50, price: "25",  oldPrice: "50",   rating: "4.3", rc: 512 },
  { key: "battery-check",  cat: "quick",   vendor: "طاقة للبطاريات",       title: "فحص وتغيير البطارية مع التركيب", desc: "فحص مجاني وتركيب فوري للبطارية في موقعك", pct: 15, price: "290", oldPrice: "340" /* new — no rating yet */ },
];

/* ---------- Featured offer (coupon) card — discount is the hero ---------- */
function SvcOfferCard({ o, onClick }) {
  const Glyph = SVC_CAT_ICON[o.cat];
  return (
    <button type="button" className="svc-offer" onClick={onClick}>
      <div className="svc-offer-media">
        {o.rating && <span className="svc-offer-rating"><SvcStar />{o.rating}</span>}
        {svcImg0(o) ? <img src={svcImg0(o)} alt="" onError={(e) => { e.currentTarget.style.display = "none"; }} /> : <span className="svc-offer-glyph">{Glyph && <Glyph />}</span>}
      </div>
      <div className="svc-offer-body">
        <div className="svc-offer-vendor">{o.vendor}</div>
        <div className="svc-offer-title">{o.title}</div>
        {o.desc && <div className="svc-offer-desc">{o.desc}</div>}
        <div className="svc-offer-foot">
          {o.options && <span className="svc-from">من</span>}
          <span className="svc-offer-price mono">{o.price}<Riyal /></span>
          <span className="svc-offer-was mono">{o.oldPrice}</span>
          <span className="svc-offer-off">خصم {o.pct}%</span>
        </div>
      </div>
    </button>
  );
}

/* ---------- Coupon list row (discover) — full-width, richer than the card ---------- */
function SvcOfferRow({ o, onClick }) {
  const Glyph = SVC_CAT_ICON[o.cat];
  return (
    <button type="button" className="svc-row" onClick={onClick}>
      <div className="svc-row-media">
        {svcImg0(o) ? <img src={svcImg0(o)} alt="" onError={(e) => { e.currentTarget.style.display = "none"; }} /> : <span className="svc-row-glyph">{Glyph && <Glyph />}</span>}
      </div>
      <div className="svc-row-body">
        <div className="svc-row-head">
          <span className="svc-row-vendor">{o.vendor}</span>
          {o.rating && (
            <span className="svc-row-rating">
              <SvcStar />{o.rating}{o.rc && <span className="svc-row-rcount"> ({o.rc})</span>}
            </span>
          )}
        </div>
        <div className="svc-row-title">{o.title}</div>
        {o.desc && <div className="svc-row-desc">{o.desc}</div>}
        <div className="svc-row-foot">
          {o.options && <span className="svc-from">من</span>}
          <span className="svc-row-price mono">{o.price}<Riyal /></span>
          <span className="svc-row-was mono">{o.oldPrice}</span>
          <span className="svc-row-off">خصم {o.pct}%</span>
        </div>
      </div>
    </button>
  );
}

/* ---------- Spotlight hero — the single best deal, full-width ---------- */
function SvcHeroOffer({ o, onClick }) {
  const Glyph = SVC_CAT_ICON[o.cat];
  return (
    <button type="button" className="svc-hero" onClick={onClick}>
      <div className="svc-hero-media">
        <span className="svc-hero-badge">خصم {o.pct}%</span>
        {o.rating && <span className="svc-hero-rating"><SvcStar />{o.rating}</span>}
        {svcImg0(o) ? <img src={svcImg0(o)} alt="" onError={(e) => { e.currentTarget.style.display = "none"; }} /> : <span className="svc-hero-glyph">{Glyph && <Glyph />}</span>}
      </div>
      <div className="svc-hero-body">
        <div className="svc-hero-eyebrow"><IconClock />عرض اليوم · لفترة محدودة</div>
        <div className="svc-hero-vendor">{o.vendor}</div>
        <div className="svc-hero-title">{o.title}</div>
        {o.desc && <div className="svc-hero-desc">{o.desc}</div>}
        <div className="svc-hero-foot">
          <span className="svc-hero-prices">
            {o.options && <span className="svc-from">من</span>}
            <span className="svc-hero-price mono">{o.price}<Riyal /></span>
            <span className="svc-hero-was mono">{o.oldPrice}</span>
          </span>
          <span className="svc-hero-cta">اطلب العرض <IconChevron /></span>
        </div>
      </div>
    </button>
  );
}

/* ---------- Loading skeletons (shaped like the coupon cards) ---------- */
function SvcSkelRow() {
  return (
    <div className="svc-row svc-skel" aria-hidden="true">
      <div className="svc-skmedia svc-skmedia-row sk-shimmer" />
      <div className="svc-row-body">
        <div className="sk-line sk-shimmer" style={{ width: "40%" }} />
        <div className="sk-line sk-shimmer" style={{ width: "78%", height: 15 }} />
        <div className="sk-line sk-shimmer" style={{ width: "92%" }} />
        <div className="sk-line sk-shimmer" style={{ width: "32%", height: 16, marginTop: 4 }} />
      </div>
    </div>
  );
}
function SvcSkelCard() {
  return (
    <div className="svc-offer svc-skel" aria-hidden="true">
      <div className="svc-skmedia svc-skmedia-card sk-shimmer" />
      <div className="svc-offer-body">
        <div className="sk-line sk-shimmer" style={{ width: "50%" }} />
        <div className="sk-line sk-shimmer" style={{ width: "85%", height: 15 }} />
        <div className="sk-line sk-shimmer" style={{ width: "70%" }} />
        <div className="sk-line sk-shimmer" style={{ width: "40%", height: 16, marginTop: 4 }} />
      </div>
    </div>
  );
}
function SvcSkelHero() {
  return (
    <div className="svc-hero svc-skel" aria-hidden="true">
      <div className="svc-skmedia svc-skmedia-hero sk-shimmer" />
      <div className="svc-hero-body">
        <div className="sk-line sk-shimmer" style={{ width: "28%" }} />
        <div className="sk-line sk-shimmer" style={{ width: "65%", height: 16, marginTop: 8 }} />
        <div className="sk-line sk-shimmer" style={{ width: "90%", marginTop: 6 }} />
        <div className="sk-line sk-shimmer" style={{ width: "40%", height: 18, marginTop: 10 }} />
      </div>
    </div>
  );
}

/* ---------- Home entry — the section that lives on the /car home ---------- */
function ServicesHomeEntry() {
  const go = (path) => navigate(path);
  return (
    <section className="a-section svc-home">
      <div className="section-head svc-head">
        <div>
          <div className="svc-eyebrow">عروض وخصومات</div>
          <h2 className="section-title">خدمات سيارتك</h2>
        </div>
        <button type="button" className="section-link" onClick={() => go("/car-services")}>
          الكل <IconChevron />
        </button>
      </div>

      {/* Service categories — quick entry into the services discover */}
      <div className="svc-cats">
        {SVC_CATEGORIES.map((c) => {
          const Glyph = c.icon;
          return (
            <button key={c.id} type="button" className="svc-cat" onClick={() => go(svcCatPath(c.id))}>
              <span className="svc-cat-icon"><Glyph /></span>
              <span className="svc-cat-label">{c.label}</span>
            </button>
          );
        })}
      </div>

      {/* Featured coupons — leads with the discount to sell the value */}
      <div className="svc-offers">
        {SVC_OFFERS.map((o) => (
          <SvcOfferCard key={o.key} o={o} onClick={() => go(svcOfferPath(o.key))} />
        ))}
      </div>
    </section>
  );
}

/* ---------- Demo: the /car home with the services section injected ----------
   Reproduces the home's top chrome + parts categories so the services block is
   seen in real placement (after parts, before the finding tools). Rendered
   inside the real chrome, like #/home-car-demo. */
function ServicesHomeDemo({ onMenu, onCart, cartCount, onSearch }) {
  const partsCats = [
    { id: "bumpers-grilles",    label: "الصدامات", icon: <IconBumper /> },
    { id: "suspension",         label: "المساعدات", icon: <IconShock /> },
    { id: "brakes",             label: "الفرامل", icon: <IconBrakeDisc /> },
    { id: "ac",                 label: "التكييف", icon: <IconAC /> },
    { id: "lighting",           label: "الإضاءة", icon: <IconHeadlight /> },
    { id: "engine-trans",       label: "المحرك", icon: <IconEngine /> },
    { id: "filters",            label: "الفلاتر", icon: <IconOil /> },
    { id: "electrical-battery", label: "الكهرباء", icon: <IconBolt /> },
  ];
  const recent = ["bumperR", "shockR", "pads", "bracketR", "grille", "bumperL"];
  return (
    <>
      {/* Car bar + search (mirrors AnchoredHome) */}
      <div className="stick-anchor">
        <div className="car-bar">
          <button type="button" className="car-bar-photo-btn" onClick={onMenu} aria-label="فتح القائمة">
            <img className="car-bar-photo" src={CURRENT_CAR.image} alt={CURRENT_CAR.name} />
          </button>
          <div className="car-bar-body">
            <div className="car-bar-eyebrow">سيارتك الحالية</div>
            <div className="car-bar-name">{CURRENT_CAR.name}</div>
          </div>
          <div className="car-bar-actions">
            <button className="car-edit" aria-label="تغيير السيارة" onClick={onMenu}><IconEdit /></button>
            <button className="car-cart" aria-label="السلة" onClick={onCart}><IconCart />{cartCount > 0 && <span className="cart-badge">{cartCount}</span>}</button>
          </div>
        </div>
        <div className="anchor-trust"><div className="anchor-trust-inner"><TrustBadges /></div></div>
        <div className="search-wrap">
          <button className="big-search" onClick={onSearch}>
            <span className="bs-icon"><IconSearch /></span>
            <span className="bs-text">ابحث في قطع {CURRENT_CAR.short}</span>
          </button>
        </div>
      </div>

      {/* Parts categories */}
      <section className="a-section">
        <div className="section-head"><h2 className="section-title">اختر القسم</h2></div>
        <div className="cd-cats">
          {partsCats.map((c, i) => (
            <button key={i} className="cat-card" onClick={() => navigate("/spare-parts/" + c.id)}>
              <span className="cat-icon">{c.icon}</span>
              <span className="cat-label">{c.label}</span>
            </button>
          ))}
        </div>
        <button className="home-browse-all cd-browse" onClick={() => navigate("/spare-parts/all")}>
          <span className="cd-browse-icon"><IconGrid /></span>
          <span className="home-browse-all-title">اكتشف القطع والحلول</span>
          <span className="home-browse-all-arrow"><IconChevron /></span>
        </button>
      </section>

      {/* NEW — car services entry */}
      <ServicesHomeEntry />

      {/* Recently viewed (context below the services block) */}
      <section className="a-section" style={{ paddingInline: 0 }}>
        <div className="section-head" style={{ padding: "0 16px" }}>
          <h2 className="section-title">شاهدت مؤخراً</h2>
        </div>
        <div className="prod-rail">
          {recent.map((k, i) => <ProductCard key={k + i} p={findProduct(k)} onClick={() => navigate("/p/" + k)} />)}
        </div>
      </section>
    </>
  );
}

/* ---------- Above-fold entry (locked: the vertical toggle) ----------
   The services SECTION lives below the fold, so services went unnoticed. The
   locked answer is a toggle under the search that switches the home between two
   co-equal verticals (parts / services). The look is the underline-tabs style
   (`.svc-vtabs`, sliding underline), picked from #/services-toggle-demo
   variant 2. Previewed at #/services-entry-demo. */

function ServicesEntryDemo({ onMenu, onCart, cartCount, onSearch }) {
  const [vertical, setVertical] = React.useState("parts");

  // Sticky collapse — trust values fold away, car bar + search + toggle pin,
  // same mechanism as AnchoredHome (sentinel + IntersectionObserver → .stuck).
  const sentinelRef = React.useRef(null);
  const [stuck, setStuck] = React.useState(false);
  React.useEffect(() => {
    const el = sentinelRef.current;
    if (!el || !("IntersectionObserver" in window)) return;
    const io = new IntersectionObserver(([e]) => setStuck(!e.isIntersecting), { threshold: 0 });
    io.observe(el);
    return () => io.disconnect();
  }, []);

  // Switching vertical returns to the top so the new tab starts from its head.
  // Scroll AFTER the swapped content commits (an effect), otherwise the smooth
  // scroll starts against the old tab's height and gets clamped mid-animation.
  const firstRun = React.useRef(true);
  React.useEffect(() => {
    if (firstRun.current) { firstRun.current = false; return; }
    window.scrollTo({ top: 0, behavior: "smooth" });
  }, [vertical]);
  const selectVertical = (v) => setVertical(v);

  const partsCats = [
    { id: "bumpers-grilles",    label: "الصدامات", icon: <IconBumper /> },
    { id: "suspension",         label: "المساعدات", icon: <IconShock /> },
    { id: "brakes",             label: "الفرامل", icon: <IconBrakeDisc /> },
    { id: "ac",                 label: "التكييف", icon: <IconAC /> },
    { id: "lighting",           label: "الإضاءة", icon: <IconHeadlight /> },
    { id: "engine-trans",       label: "المحرك", icon: <IconEngine /> },
    { id: "filters",            label: "الفلاتر", icon: <IconOil /> },
    { id: "electrical-battery", label: "الكهرباء", icon: <IconBolt /> },
  ];
  const recent = ["bumperR", "shockR", "pads", "bracketR", "grille", "bumperL"];

  const isServices = vertical === "services";
  // Chrome above the tabs (car bar + trust + search) stays constant — the tabs
  // only change what's BELOW them; that's how users read a tab switch.
  const CarBar = (
    <div className={"stick-anchor" + (stuck ? " stuck" : "")}>
      <div className="car-bar">
        <button type="button" className="car-bar-photo-btn" onClick={onMenu} aria-label="فتح القائمة">
          <img className="car-bar-photo" src={CURRENT_CAR.image} alt={CURRENT_CAR.name} />
        </button>
        <div className="car-bar-body">
          <div className="car-bar-eyebrow">سيارتك الحالية</div>
          <div className="car-bar-name">{CURRENT_CAR.name}</div>
        </div>
        <div className="car-bar-actions">
          <button className="car-edit" aria-label="تغيير السيارة" onClick={onMenu}><IconEdit /></button>
          <button className="car-cart" aria-label="السلة" onClick={onCart}><IconCart />{cartCount > 0 && <span className="cart-badge">{cartCount}</span>}</button>
        </div>
      </div>
      <div className="anchor-trust"><div className="anchor-trust-inner"><TrustBadges /></div></div>
      <div className="search-wrap">
        <button className="big-search" onClick={onSearch}>
          <span className="bs-icon"><IconSearch /></span>
          <span className="bs-text">ابحث في قطع {CURRENT_CAR.short}</span>
        </button>
      </div>
      <div className={"svc-vtabs" + (isServices ? " is-b" : "")} role="tablist">
        <span className="svc-vtabs-bar" />
        <button className={!isServices ? "is-active" : ""} onClick={() => selectVertical("parts")} role="tab" aria-selected={!isServices}>
          <SvcQuickIcon />قطع الغيار
        </button>
        <button className={isServices ? "is-active" : ""} onClick={() => selectVertical("services")} role="tab" aria-selected={isServices}>
          <SvcCareIcon />خدمات السيارة
        </button>
      </div>
    </div>
  );

  const PartsCategories = (
    <section className="a-section">
      <div className="section-head"><h2 className="section-title">اختر القسم</h2></div>
      <div className="cd-cats">
        {partsCats.map((c, i) => (
          <button key={i} className="cat-card" onClick={() => navigate("/spare-parts/" + c.id)}>
            <span className="cat-icon">{c.icon}</span>
            <span className="cat-label">{c.label}</span>
          </button>
        ))}
      </div>
      <button className="home-browse-all cd-browse" onClick={() => navigate("/spare-parts/all")}>
        <span className="cd-browse-icon"><IconGrid /></span>
        <span className="home-browse-all-title">اكتشف القطع والحلول</span>
        <span className="home-browse-all-arrow"><IconChevron /></span>
      </button>
    </section>
  );

  const RecentlyViewed = (
    <section className="a-section" style={{ paddingInline: 0 }}>
      <div className="section-head" style={{ padding: "0 16px" }}>
        <h2 className="section-title">شاهدت مؤخراً</h2>
      </div>
      <div className="prod-rail">
        {recent.map((k, i) => <ProductCard key={k + i} p={findProduct(k)} onClick={() => navigate("/p/" + k)} />)}
      </div>
    </section>
  );

  // Services landing — deals-led (the discount is the value, so lead with it):
  // spotlight hero → offers rail → categories as a compact secondary row →
  // browse-all. Every path feeds the discover / a coupon PDP.
  const servicesLanding = (
    <>
      {/* Spotlight — the single best deal */}
      <section className="a-section">
        <SvcHeroOffer o={SVC_OFFERS[0]} onClick={() => navigate(svcOfferPath(SVC_OFFERS[0].key))} />
      </section>

      {/* Categories — browse by service; الكل is the entry into the discover */}
      <section className="a-section svc-home">
        <div className="section-head">
          <h2 className="section-title">تصفّح حسب الخدمة</h2>
          <button type="button" className="section-link" onClick={() => navigate("/car-services")}>الكل <IconChevron /></button>
        </div>
        <div className="svc-cats">
          {SVC_CATEGORIES.map((c) => {
            const Glyph = c.icon;
            return (
              <button key={c.id} type="button" className="svc-cat" onClick={() => navigate(svcCatPath(c.id))}>
                <span className="svc-cat-icon"><Glyph /></span>
                <span className="svc-cat-label">{c.label}</span>
              </button>
            );
          })}
        </div>
      </section>

      {/* More offers */}
      <section className="a-section svc-home">
        <div className="section-head">
          <h2 className="section-title">أبرز العروض</h2>
          <button type="button" className="section-link" onClick={() => navigate("/car-services")}>الكل <IconChevron /></button>
        </div>
        <div className="svc-offers">
          {SVC_OFFERS.slice(1).map((o) => (
            <SvcOfferCard key={o.key} o={o} onClick={() => navigate(svcOfferPath(o.key))} />
          ))}
        </div>
      </section>

    </>
  );

  const body = isServices ? servicesLanding : (<>{PartsCategories}{RecentlyViewed}</>);

  return (
    <>
      <div ref={sentinelRef} aria-hidden="true" style={{ height: 1 }} />
      {CarBar}
      {body}
    </>
  );
}

const SVC_SORTS = [
  { id: "recent", label: "الأحدث" },
  { id: "popular", label: "الأكثر رواجاً" },
  { id: "price-asc", label: "السعر من الأقل" },
  { id: "price-desc", label: "السعر من الأعلى" },
];

const SVC_CITIES = [
  "الرياض", "جدة", "مكة المكرمة", "المدينة المنورة", "الدمام", "الخبر", "الظهران",
  "الأحساء", "القطيف", "الجبيل", "بريدة", "عنيزة", "حائل", "تبوك", "أبها",
  "خميس مشيط", "نجران", "جازان", "الطائف", "ينبع", "الباحة", "عرعر", "سكاكا",
];

/* City picker — services are location-based, so the browse is scoped to a city.
   Reuses the app's BottomSheet + dsc-pick, like the sort/parts sheets. */
function SvcCitySheet({ open, city, onSelect, onClose }) {
  return (
    <BottomSheet open={open} onClose={onClose} title="اختر المدينة">
      <div className="svc-city-list">
        {SVC_CITIES.map((c) => (
          <button key={c} type="button"
            className={"svc-city-item" + (city === c ? " is-active" : "")}
            onClick={() => { onSelect(c); onClose(); }}>
            <span>{c}</span>
            {city === c && <IconCheck />}
          </button>
        ))}
      </div>
    </BottomSheet>
  );
}

/* ---------- Branch card + full-list sheet (PDP الفروع) ---------- */
function SvcBranchCard({ b, vendor }) {
  return (
    <a
      className="svc-branch-card"
      href={svcMapUrl(vendor, b)}
      target="_blank"
      rel="noopener noreferrer"
      aria-label={"عرض فرع " + b.area + " على الخريطة"}
    >
      <span className="svc-branch-ic"><SvcPinIcon /></span>
      <span className="svc-branch-info">
        <span className="svc-branch-area">{b.area}</span>
        {b.rating && (
          <span className="svc-branch-rating">
            <SvcStar />{b.rating}+
            {b.reviews != null && <span className="svc-branch-rating-count">({b.reviews}+)</span>}
            <span className="svc-branch-source">· جوجل</span>
          </span>
        )}
        <span className="svc-branch-city">{[b.street, b.city].filter(Boolean).join(" · ")}</span>
        {b.hours && <span className="svc-branch-hours"><IconClock />{b.hours}</span>}
      </span>
      <span className="svc-branch-go"><SvcMapIcon /></span>
    </a>
  );
}

// All branches in a bottom sheet, filterable by city. Scales past the inline
// preview without stretching the page.
function SvcBranchesSheet({ open, branches, vendor, onClose }) {
  const [cityFilter, setCityFilter] = React.useState("all");
  const listRef = React.useRef(null);
  React.useEffect(() => { if (listRef.current) listRef.current.scrollTop = 0; }, [cityFilter]);
  const cities = branches.reduce((acc, b) => (acc.includes(b.city) ? acc : acc.concat(b.city)), []);
  const shown = cityFilter === "all" ? branches : branches.filter((b) => b.city === cityFilter);
  return (
    <BottomSheet open={open} onClose={onClose} title="الفروع">
      <div className="svc-branches-sheet">
        {cities.length > 1 && (
          <div className="svc-branches-filter">
            <button type="button" className={"svc-fchip" + (cityFilter === "all" ? " is-active" : "")} onClick={() => setCityFilter("all")}>الكل</button>
            {cities.map((c) => (
              <button key={c} type="button" className={"svc-fchip" + (cityFilter === c ? " is-active" : "")} onClick={() => setCityFilter(c)}>{c}</button>
            ))}
          </div>
        )}
        <div className="svc-branches-sheet-list" ref={listRef}>
          {shown.map((b, i) => <SvcBranchCard key={i} b={b} vendor={vendor} />)}
        </div>
      </div>
    </BottomSheet>
  );
}

/* ---------- Services discover (/services and /services/{cat}) ----------
   Car-agnostic coupon feed. No fitment/position — the axes are category,
   discount, rating and location. The card unit is a vendor coupon. */
function ServicesDiscover({ catSlug, onSearch }) {
  const cat = catSlug ? (SVC_CAT_BY_SLUG[catSlug] || catSlug) : "all";
  const [sort, setSort] = React.useState("recent");
  const [city, setCity] = React.useState(SVC_CITIES[0]);
  const [cityOpen, setCityOpen] = React.useState(false);
  const [descOpen, setDescOpen] = React.useState(false);
  React.useEffect(() => { setDescOpen(false); }, [cat]); // collapse on category change
  // Brief skeleton whenever a filter changes (category / city / sort) and on
  // entry, reads as "fetching new results", and jumps back to the top so the
  // user sees the refreshed set from its head.
  const [loading, setLoading] = React.useState(true);
  React.useEffect(() => {
    setLoading(true);
    window.scrollTo(0, 0);
    const t = setTimeout(() => setLoading(false), 420);
    return () => clearTimeout(t);
  }, [cat, city, sort]);
  // Keep the active category chip fully in view on load (it was clipped at the
  // rail edge otherwise).
  const activeChipRef = React.useRef(null);
  React.useEffect(() => {
    // Only pull a selected category into view; "all" is the rail's natural
    // start, and scrolling it would clip it against the edge (eats the padding).
    if (cat !== "all" && activeChipRef.current) {
      activeChipRef.current.scrollIntoView({ inline: "center", block: "nearest" });
    }
  }, [cat]);
  const catObj = SVC_CATEGORIES.find((c) => c.id === cat);
  const catLabel = cat === "all" ? "خدمات سيارتك" : (catObj ? catObj.label : cat);

  // Filter to the category, then seed to a realistic count (clones keep a
  // unique key but route to the real offer via origKey). Drop at port time.
  const base = SVC_OFFERS.filter((o) => cat === "all" || o.cat === cat);
  const SEED = 12;
  const seeded = base.length
    ? Array.from({ length: Math.max(base.length, SEED) }, (_, i) => {
        const b = base[i % base.length];
        return i < base.length ? b : { ...b, key: b.key + "__s" + i, origKey: b.key };
      })
    : base;
  const sorted = [...seeded].sort((a, b) => {
    if (sort === "popular") return (b.rc || 0) - (a.rc || 0);
    if (sort === "price-asc") return Number(a.price) - Number(b.price);
    if (sort === "price-desc") return Number(b.price) - Number(a.price);
    return 0; // recent = insertion (authoring) order
  });

  const cats = [{ id: "all", label: "الكل" }, ...SVC_CATEGORIES.map((c) => ({ id: c.id, label: c.label }))];

  // Merchandised storefront (الكل view only): a hero + themed rails break the
  // monotony of a flat list. A selected category stays a focused list.
  const isAll = cat === "all";
  const heroOffer = SVC_OFFERS.find((o) => o.hero) || SVC_OFFERS.slice().sort((a, b) => b.pct - a.pct)[0];
  const featured = ["quick-wash", "interior-detail", "nano-coat", "tint-front", "brake-service", "polish"]
    .map((k) => SVC_OFFERS.find((o) => o.key === k)).filter(Boolean);
  const topRated = SVC_OFFERS.slice().sort((a, b) => (parseFloat(b.rating) || 0) - (parseFloat(a.rating) || 0)).slice(0, 6);
  const mostBooked = SVC_OFFERS.slice().sort((a, b) => (b.rc || 0) - (a.rc || 0)).slice(0, 6);
  const rail = (title, offers) => (
    <section className="a-section svc-home">
      <div className="section-head">
        <h2 className="section-title">{title}</h2>
      </div>
      <div className="svc-offers">
        {offers.map((o) => <SvcOfferCard key={title + o.key} o={o} onClick={() => navigate(svcOfferPath(o.key))} />)}
      </div>
    </section>
  );
  const rows = sorted.map((o) => (
    <SvcOfferRow key={o.key} o={o} onClick={() => navigate(svcOfferPath(o.origKey || o.key))} />
  ));

  return (
    <div className="dsc svc-dsc">
      <nav className="dsc-crumb" aria-label="breadcrumb">
        <a className="dsc-crumb-link" onClick={() => navigate("/car")}>الرئيسية</a>
        <span className="dsc-crumb-sep">/</span>
        {isAll ? (
          // On the storefront, "خدمات السيارة" IS this page (the leaf).
          <span className="dsc-crumb-current">خدمات السيارة</span>
        ) : (
          // On a category, it links back to the storefront; category is the leaf.
          <React.Fragment>
            <a className="dsc-crumb-link" onClick={() => navigate("/car-services")}>خدمات السيارة</a>
            <span className="dsc-crumb-sep">/</span>
            <span className="dsc-crumb-current">{catLabel}</span>
          </React.Fragment>
        )}
      </nav>
      {/* Title row — page title + the city scope in one fixed, prominent slot */}
      <div className="svc-dsc-head">
        <h1 className="svc-dsc-h1">{catLabel}</h1>
        <button type="button" className="dsc-control svc-citybtn" onClick={() => setCityOpen(true)}>
          <SvcPinIcon /><span>{city}</span>
          <span className="svc-caret"><IconChevron /></span>
        </button>
      </div>
      {(() => {
        const d = isAll ? SVC_ALL_DESC : (catObj && catObj.desc);
        if (!d) return null;
        return (
          <button type="button" className={"svc-dsc-desc" + (descOpen ? " is-open" : "")}
            onClick={() => setDescOpen((v) => !v)}
            aria-expanded={descOpen} aria-label={descOpen ? "عرض أقل" : "عرض المزيد"}>
            <span className="svc-dsc-desc-text">{d}</span>
            <span className="svc-dsc-desc-btn" aria-hidden="true"><IconChevron /></span>
          </button>
        );
      })()}

      <div className="stick-anchor dsc-anchor svc-dsc-chrome">
        {/* Category filter — the one inline narrowing rail */}
        <div className="svc-dsc-chips">
          {cats.map((c) => (
            <button key={c.id} type="button" ref={c.id === cat ? activeChipRef : null}
              className={"svc-fchip" + (c.id === cat ? " is-active" : "")}
              onClick={() => navigate(c.id === "all" ? "/car-services" : svcCatPath(c.id))}>
              {c.label}
            </button>
          ))}
        </div>
        {/* Sort — inline single-select chips (only on a focused category list).
            Labeled + lighter outline-active so they don't read as more category
            chips. */}
        {!isAll && (
          <div className="svc-sortchips">
            <span className="svc-sortchips-label"><SvcSortIcon />{"الترتيب :"}</span>
            <div className="svc-sortchips-track">
              {SVC_SORTS.map((s) => (
                <button key={s.id} type="button"
                  className={"svc-schip" + (sort === s.id ? " is-active" : "")}
                  onClick={() => setSort(s.id)}>
                  {s.label}
                </button>
              ))}
            </div>
          </div>
        )}
      </div>

      <SvcCitySheet open={cityOpen} city={city} onSelect={setCity} onClose={() => setCityOpen(false)} />

      {loading ? (
        isAll ? (
          <>
            <section className="a-section"><SvcSkelHero /></section>
            <section className="a-section svc-home">
              <div className="section-head"><div className="sk-line sk-shimmer" style={{ width: 110, height: 18 }} /></div>
              <div className="svc-offers">{[0, 1, 2].map((i) => <SvcSkelCard key={i} />)}</div>
            </section>
            <section className="a-section svc-home">
              <div className="svc-list svc-list-flush">{[0, 1, 2].map((i) => <SvcSkelRow key={i} />)}</div>
            </section>
          </>
        ) : (
          <div className="svc-list">{[0, 1, 2, 3].map((i) => <SvcSkelRow key={i} />)}</div>
        )
      ) : isAll ? (
        <>
          <section className="a-section">
            <SvcHeroOffer o={heroOffer} onClick={() => navigate(svcOfferPath(heroOffer.key))} />
          </section>
          {rail("عروض مختارة", featured)}
          {rail("الأكثر مبيعاً", mostBooked)}
          {rail("الأعلى تقييماً", topRated)}
          <section className="a-section svc-home">
            <div className="section-head"><h2 className="section-title">كل العروض</h2></div>
            <div className="svc-list svc-list-flush">{rows}</div>
          </section>
        </>
      ) : (
        <div className="svc-list">{rows}</div>
      )}
    </div>
  );
}

/* ---------- PDP image gallery — single image, or swipeable if multiple ---------- */
function SvcPdpGallery({ images, Glyph }) {
  const [idx, setIdx] = React.useState(0);
  if (!images.length) {
    return <div className="svc-pdp-media"><span className="svc-pdp-glyph">{Glyph && <Glyph />}</span></div>;
  }
  if (images.length === 1) {
    return (
      <div className="svc-pdp-media">
        <img src={images[0]} alt="" onError={(e) => { e.currentTarget.style.display = "none"; }} />
      </div>
    );
  }
  const onScroll = (e) => {
    const el = e.currentTarget;
    const i = Math.round(Math.abs(el.scrollLeft) / el.clientWidth);
    if (i !== idx) setIdx(i);
  };
  return (
    <div className="svc-pdp-gallery">
      <div className="svc-pdp-track" onScroll={onScroll}>
        {images.map((src, i) => (
          <div className="svc-pdp-slide" key={i}>
            <img src={src} alt="" onError={(e) => { e.currentTarget.style.display = "none"; }} />
          </div>
        ))}
      </div>
      <div className="svc-pdp-dots">
        {images.map((_, i) => <span key={i} className={"svc-pdp-dot" + (i === idx ? " is-on" : "")} />)}
      </div>
    </div>
  );
}

/* ---------- Coupon PDP (/car-services/{offer}) ----------
   Models the live services offer page: vendor + title + rating, price/discount,
   description, how-to-use (the coupon flow), terms, branches, related. Buy is a
   coupon purchase (booking flow not built → قيد الإنشاء toast). */
function ServicesPdp({ offerKey, cart, onAddToCart, onCart, onToast }) {
  const o = SVC_OFFERS.find((x) => x.key === offerKey) || SVC_OFFERS[0];
  const Glyph = SVC_CAT_ICON[o.cat];
  const catObj = SVC_CATEGORIES.find((c) => c.id === o.cat);
  const catLabel = catObj ? catObj.label : "خدمات";
  // Multi-option offers let the buyer pick a variant (here, car size). The
  // chosen option drives the price, the discount, and what lands in the cart;
  // single-option offers just use the offer itself as the view.
  const hasOpts = Array.isArray(o.options) && o.options.length > 0;
  const [optId, setOptId] = React.useState(hasOpts ? o.options[0].id : null);
  const opt = hasOpts ? (o.options.find((x) => x.id === optId) || o.options[0]) : null;
  const view = opt || o;                                // the currently-priced thing
  const cartKey = opt ? o.key + "__" + opt.id : o.key;  // unique per option
  // Same add-to-cart action + button as parts: tap adds, then it flips to
  // "في السلة" and opens the cart on the next tap.
  const qty = (cart || []).reduce((n, it) => (it.key === cartKey ? n + it.qty : n), 0);
  const isAdded = qty > 0;
  // Inline CTA in the page; the sticky bar slides up only once the inline one
  // scrolls out of view, so the action is always reachable but not redundant.
  const inlineRef = React.useRef(null);
  const [showBar, setShowBar] = React.useState(false);
  // Save-for-later. Local to the prototype (favourites aren't wired to a store
  // yet); the heart fills charcoal (--text) on tap and pops. Not red — red is
  // reserved for the buy CTA so the two don't compete.
  const [faved, setFaved] = React.useState(false);
  React.useEffect(() => {
    const el = inlineRef.current;
    if (!el || !("IntersectionObserver" in window)) return;
    // Only when scrolled PAST the inline CTA (above the viewport), not when it's
    // still below (not reached) — both read as "not intersecting".
    const io = new IntersectionObserver(([e]) => setShowBar(!e.isIntersecting && e.boundingClientRect.top < 0), { threshold: 0 });
    io.observe(el);
    return () => io.disconnect();
  }, []);
  const buyBtn = (
    <button
      className={"pdp-add" + (isAdded ? " added" : "")}
      onClick={isAdded ? onCart : () => onAddToCart && onAddToCart(cartKey)}
      aria-label={isAdded ? "في السلة، اضغط لفتح السلة" : "أضف للسلة"}
    >
      {isAdded ? (<>في السلة <IconCheckSmall /></>) : "أضف للسلة"}
    </button>
  );

  const steps = [
    { t: "أضف العرض للسلة", s: "أكمل الدفع ويصلك كوبون العرض فوراً." },
    { t: "احجز موعدك", s: "اختر الوقت المناسب لك مع المركز." },
    { t: "قدّم الكوبون", s: "توجّه للفرع وقدّم الكوبون لتحصل على الخدمة." },
  ];
  const terms = [
    "العرض صالح لمدة 30 يوماً من تاريخ الشراء.",
    "يلزم حجز موعد مسبق مع المركز بعد شراء العرض.",
    "السعر لا يشمل أجور العمالة أو قطع الغيار ما لم يُذكر خلاف ذلك.",
    "صالح في جميع فروع " + o.vendor + " المشاركة.",
    "صالح طوال أيام الأسبوع خلال ساعات العمل الرسمية.",
  ];
  // Google rating/reviews are the place's, attributed to Google (Speero has no
  // first-party reviews yet). Per-branch, since Google rates the location.
  const branches = [
    { area: "حي النخيل",   city: "الرياض", street: "طريق الأمير محمد بن سلمان", hours: "٩:٠٠ ص - ١١:٠٠ م", rating: "4.6", reviews: 210 },
    { area: "حي العليا",   city: "الرياض", street: "طريق العليا العام",         hours: "٩:٠٠ ص - ١١:٠٠ م", rating: "4.8", reviews: 512 },
    { area: "حي الملز",    city: "الرياض", street: "شارع جرير",                 hours: "٨:٠٠ ص - ١٠:٠٠ م", rating: "4.3", reviews: 86 },
    { area: "حي الياسمين", city: "الرياض", street: "طريق أنس بن مالك",          hours: "١٠:٠٠ ص - ١٢:٠٠ م", rating: "4.7", reviews: 148 },
    { area: "حي الروضة",   city: "جدة",    street: "شارع صاري",                 hours: "٩:٠٠ ص - ١١:٠٠ م", rating: "4.5", reviews: 301 },
    { area: "حي السلامة",  city: "جدة",    street: "شارع الأمير سلطان",         hours: "٩:٠٠ ص - ١١:٠٠ م", rating: "4.6", reviews: 174 },
    { area: "حي الشاطئ",   city: "الدمام", street: "طريق الكورنيش",             hours: "٨:٠٠ ص - ١٠:٠٠ م", rating: "4.4", reviews: 122 },
    { area: "حي العزيزية", city: "مكة",    street: "شارع الحج",                 hours: "٩:٠٠ ص - ١١:٠٠ م", rating: "4.9", reviews: 64 },
  ];
  // A few branches show inline; the full list (with a city filter) lives in a
  // bottom sheet so the page stays short even with many locations.
  const BRANCH_PREVIEW = 3;
  const [branchesSheet, setBranchesSheet] = React.useState(false);
  const related = [
    ...SVC_OFFERS.filter((x) => x.cat === o.cat && x.key !== o.key),
    ...SVC_OFFERS.filter((x) => x.cat !== o.cat && x.key !== o.key),
  ].slice(0, 6);

  return (
    <div className="dsc svc-pdp">
      <nav className="dsc-crumb" aria-label="breadcrumb">
        <a className="dsc-crumb-link" onClick={() => navigate("/car")}>الرئيسية</a>
        <span className="dsc-crumb-sep">/</span>
        <a className="dsc-crumb-link" onClick={() => navigate("/car-services")}>خدمات السيارة</a>
        <span className="dsc-crumb-sep">/</span>
        <a className="dsc-crumb-link" onClick={() => navigate(svcCatPath(o.cat))}>{catLabel}</a>
        <span className="dsc-crumb-sep">/</span>
        <span className="dsc-crumb-current">{o.title}</span>
      </nav>

      <SvcPdpGallery images={svcImgs(o)} Glyph={Glyph} />

      <div className="svc-pdp-head">
        <div className="svc-pdp-headtop">
          <div className="svc-pdp-headtext">
            <div className="svc-pdp-vendor">{o.vendor}</div>
            <h1 className="svc-pdp-title">{o.title}</h1>
          </div>
          <button
            className={"svc-pdp-fav" + (faved ? " is-faved" : "")}
            onClick={() => {
              const nv = !faved;
              setFaved(nv);
              onToast && onToast(nv ? "تمت الإضافة للمفضلة" : "تمت الإزالة من المفضلة");
            }}
            aria-pressed={faved}
            aria-label={faved ? "إزالة من المفضلة" : "أضف للمفضلة"}
          >
            <IconHeart />
          </button>
        </div>
        {o.desc && <div className="svc-pdp-desc">{o.desc}</div>}
        {o.rating && (
          <div className="svc-pdp-rate"><SvcStar />{o.rating}{o.rc && <span className="svc-pdp-rate-count"> · {o.rc} تقييم</span>}</div>
        )}
        {hasOpts && (
          <div className="svc-opts">
            <div className="svc-opts-label">اختر حجم سيارتك</div>
            <div className="svc-opts-list" role="radiogroup" aria-label="اختر حجم سيارتك">
              {o.options.map((op) => {
                const sel = op.id === optId;
                return (
                  <button
                    key={op.id}
                    type="button"
                    role="radio"
                    aria-checked={sel}
                    className={"svc-opt" + (sel ? " is-sel" : "")}
                    onClick={() => setOptId(op.id)}
                  >
                    <span className="svc-opt-radio" aria-hidden="true" />
                    <span className="svc-opt-main">
                      <span className="svc-opt-label">{op.label}</span>
                      {op.sub && <span className="svc-opt-sub">{op.sub}</span>}
                    </span>
                    <span className="svc-opt-price">
                      <span className="svc-opt-now mono">{op.price}<Riyal /></span>
                      {op.oldPrice && (
                        <span className="svc-opt-sub-price">
                          <span className="svc-opt-was mono">{op.oldPrice}</span>
                          <span className="svc-opt-off">-{op.pct}%</span>
                        </span>
                      )}
                    </span>
                  </button>
                );
              })}
            </div>
          </div>
        )}
        <div className="svc-pdp-price">
          <span className="svc-pdp-now mono">{view.price}<Riyal /></span>
          <span className="svc-pdp-old mono">{view.oldPrice}</span>
          <span className="svc-pdp-off">خصم {view.pct}%</span>
        </div>
        <div className="pdp-cta-row svc-pdp-inline" ref={inlineRef}>{buyBtn}</div>
      </div>

      <section className="svc-pdp-sec">
        <h2 className="svc-pdp-h2">الوصف</h2>
        <p className="svc-pdp-text">احصل على {o.title} من {o.vendor} بأيدي فنيين محترفين وخامات موثوقة، مع ضمان على جودة الخدمة والتزام بالمواعيد، وبأفضل سعر عبر سبيرو.</p>
      </section>

      <section className="svc-pdp-sec">
        <h2 className="svc-pdp-h2">كيف تستفيد من العرض</h2>
        <ol className="svc-pdp-steps">
          {steps.map((st, i) => (
            <li key={i}>
              <span className="svc-pdp-step-n">{i + 1}</span>
              <div className="svc-pdp-step-body">
                <div className="svc-pdp-step-t">{st.t}</div>
                <div className="svc-pdp-step-s">{st.s}</div>
              </div>
            </li>
          ))}
        </ol>
      </section>

      <section className="svc-pdp-sec">
        <h2 className="svc-pdp-h2">الشروط والأحكام</h2>
        <ul className="svc-pdp-terms">
          {terms.map((t, i) => <li key={i}>{t}</li>)}
        </ul>
      </section>

      <section className="svc-pdp-sec">
        <h2 className="svc-pdp-h2">الفروع</h2>
        <div className="svc-pdp-branches">
          {branches.slice(0, BRANCH_PREVIEW).map((b, i) => <SvcBranchCard key={i} b={b} vendor={o.vendor} />)}
        </div>
        {branches.length > BRANCH_PREVIEW && (
          <button className="svc-branch-more" onClick={() => setBranchesSheet(true)}>
            عرض كل الفروع ({branches.length}) <IconChevron />
          </button>
        )}
      </section>

      <section className="svc-pdp-sec svc-home">
        <div className="section-head"><h2 className="section-title">خدمات ذات صلة</h2></div>
        <div className="svc-offers">
          {related.map((r) => <SvcOfferCard key={r.key} o={r} onClick={() => navigate(svcOfferPath(r.key))} />)}
        </div>
      </section>

      <SvcBranchesSheet open={branchesSheet} branches={branches} vendor={o.vendor} onClose={() => setBranchesSheet(false)} />

      {/* Sticky buy bar — shared .buybar with parts; slides up on scroll */}
      <div className={"buybar" + (showBar ? " is-visible" : "")}>
        <div className="buybar-price">
          <span className="buybar-now mono">{view.price}<Riyal /></span>
          <span className="buybar-was mono">{view.oldPrice}</span>
        </div>
        {buyBtn}
      </div>
    </div>
  );
}

/* ---------- Toggle look exploration (#/services-toggle-demo) ----------
   The parts/services toggle currently reads as a generic segmented pill. This
   demo stacks candidate looks so the PM can compare, then we wire the winner
   into the real entry (ServicesEntryDemo). */
function ServicesToggleDemo() {
  const P = "قطع الغيار", S = "خدمات السيارة";
  const [a, setA] = React.useState("parts");
  const [b, setB] = React.useState("parts");
  const [c, setC] = React.useState("parts");
  const [d, setD] = React.useState("parts");
  const [e, setE] = React.useState("parts");
  const [f, setF] = React.useState("parts");
  const [g, setG] = React.useState("parts");
  return (
    <div className="tgd">
      <div className="tgd-title">أنماط التبديل — قطع / خدمات</div>
      <p className="tgd-note">يظهر أسفل شريط البحث في الرئيسية. اضغط للتبديل بين النمطين.</p>

      {/* Placement context */}
      <button className="tgd-search"><IconSearch /><span>ابحث في قطع لاندكروزر</span></button>

      {/* 1 — Sliding segmented (evolve the current pill) */}
      <div className="tgd-block">
        <div className="tgd-label">١ · شريط منزلق</div>
        <div className={"tg-seg" + (a === "services" ? " is-b" : "")} role="tablist">
          <span className="tg-seg-thumb" />
          <button className={a === "parts" ? "is-active" : ""} onClick={() => setA("parts")} role="tab" aria-selected={a === "parts"}><SvcQuickIcon />{P}</button>
          <button className={a === "services" ? "is-active" : ""} onClick={() => setA("services")} role="tab" aria-selected={a === "services"}><SvcCareIcon />{S}</button>
        </div>
      </div>

      {/* 2 — Underline tabs (editorial, no track) */}
      <div className="tgd-block">
        <div className="tgd-label">٢ · تبويب بخط سفلي</div>
        <div className={"tg-underline" + (b === "services" ? " is-b" : "")} role="tablist">
          <span className="tg-underline-bar" />
          <button className={b === "parts" ? "is-active" : ""} onClick={() => setB("parts")} role="tab" aria-selected={b === "parts"}><SvcQuickIcon />{P}</button>
          <button className={b === "services" ? "is-active" : ""} onClick={() => setB("services")} role="tab" aria-selected={b === "services"}><SvcCareIcon />{S}</button>
        </div>
      </div>

      {/* 3 — Split cards (two destinations, with sublabels) */}
      <div className="tgd-block">
        <div className="tgd-label">٣ · بطاقتان</div>
        <div className="tg-cards" role="tablist">
          <button className={c === "parts" ? "is-active" : ""} onClick={() => setC("parts")} role="tab" aria-selected={c === "parts"}>
            <span className="tg-card-ic"><SvcQuickIcon /></span>
            <span className="tg-card-main"><span className="tg-card-t">{P}</span><span className="tg-card-s">أصلية وبديلة</span></span>
          </button>
          <button className={c === "services" ? "is-active" : ""} onClick={() => setC("services")} role="tab" aria-selected={c === "services"}>
            <span className="tg-card-ic"><SvcCareIcon /></span>
            <span className="tg-card-main"><span className="tg-card-t">{S}</span><span className="tg-card-s">عروض وخصومات</span></span>
          </button>
        </div>
      </div>

      {/* 4 — Solid pill chips (matches the discover category chips) */}
      <div className="tgd-block">
        <div className="tgd-label">٤ · شرائح ممتلئة</div>
        <div className="tg-chips" role="tablist">
          <button className={d === "parts" ? "is-active" : ""} onClick={() => setD("parts")} role="tab" aria-selected={d === "parts"}><SvcQuickIcon />{P}</button>
          <button className={d === "services" ? "is-active" : ""} onClick={() => setD("services")} role="tab" aria-selected={d === "services"}><SvcCareIcon />{S}</button>
        </div>
      </div>

      {/* 5 — Underline, icon-free (quietest) */}
      <div className="tgd-block">
        <div className="tgd-label">٥ · خط سفلي بدون أيقونات</div>
        <div className={"tg-underline tg-underline-plain" + (e === "services" ? " is-b" : "")} role="tablist">
          <span className="tg-underline-bar" />
          <button className={e === "parts" ? "is-active" : ""} onClick={() => setE("parts")} role="tab" aria-selected={e === "parts"}>{P}</button>
          <button className={e === "services" ? "is-active" : ""} onClick={() => setE("services")} role="tab" aria-selected={e === "services"}>{S}</button>
        </div>
      </div>

      <div className="tgd-divider">أوضح كزر تبديل ↓</div>

      {/* 6 — Filled sliding thumb (reads unmistakably as a switch) */}
      <div className="tgd-block">
        <div className="tgd-label">٦ · شريط ممتلئ منزلق</div>
        <div className={"tg-fill" + (f === "services" ? " is-b" : "")} role="tablist">
          <span className="tg-fill-thumb" />
          <button className={f === "parts" ? "is-active" : ""} onClick={() => setF("parts")} role="tab" aria-selected={f === "parts"}><SvcQuickIcon />{P}</button>
          <button className={f === "services" ? "is-active" : ""} onClick={() => setF("services")} role="tab" aria-selected={f === "services"}><SvcCareIcon />{S}</button>
        </div>
      </div>

      {/* 7 — Underline tabs housed in a bordered control (adds "buttonness") */}
      <div className="tgd-block">
        <div className="tgd-label">٧ · تبويب داخل إطار</div>
        <div className={"tg-ucon" + (g === "services" ? " is-b" : "")} role="tablist">
          <span className="tg-ucon-bar" />
          <button className={g === "parts" ? "is-active" : ""} onClick={() => setG("parts")} role="tab" aria-selected={g === "parts"}><SvcQuickIcon />{P}</button>
          <button className={g === "services" ? "is-active" : ""} onClick={() => setG("services")} role="tab" aria-selected={g === "services"}><SvcCareIcon />{S}</button>
        </div>
      </div>
    </div>
  );
}

/* ---------- Stacked scroll-spy entry (#/services-stacked-demo) ----------
   Alternative to the switch-entry: both verticals stacked on ONE page, the
   pinned toggle acts as a scroll-spy anchor nav — tapping scrolls to a section,
   and scrolling flips the active tab automatically. */
function ServicesStackedDemo({ onMenu, onCart, cartCount, onSearch }) {
  const [active, setActive] = React.useState("parts");
  const [stuck, setStuck] = React.useState(false);
  const sentinelRef = React.useRef(null);
  const chromeRef = React.useRef(null);
  const partsRef = React.useRef(null);
  const servicesRef = React.useRef(null);
  // While a tap-scroll is animating, freeze the scroll-spy so it doesn't fight
  // the programmatic scroll and flicker the active tab.
  const spyLock = React.useRef(false);
  const spyTimer = React.useRef(null);
  // Visual-search card rolls its wheel when it scrolls into view (same as home).
  const peekRef = React.useRef(null);
  const [peekRolling, setPeekRolling] = React.useState(false);
  React.useEffect(() => {
    const el = peekRef.current;
    if (!el || !("IntersectionObserver" in window)) return;
    const io = new IntersectionObserver(([e]) => setPeekRolling(e.isIntersecting), { threshold: 0.6 });
    io.observe(el);
    return () => io.disconnect();
  }, []);

  // Chrome collapse (trust folds, car bar + search + toggle pin), same as the
  // switch-entry / AnchoredHome.
  React.useEffect(() => {
    const el = sentinelRef.current;
    if (!el || !("IntersectionObserver" in window)) return;
    const io = new IntersectionObserver(([e]) => setStuck(!e.isIntersecting), { threshold: 0 });
    io.observe(el);
    return () => io.disconnect();
  }, []);

  // Scroll-spy: the services section becoming active once its top passes just
  // below the pinned chrome (a thin band near the top of the viewport).
  React.useEffect(() => {
    const el = servicesRef.current;
    if (!el || !("IntersectionObserver" in window)) return;
    const io = new IntersectionObserver(([e]) => {
      if (spyLock.current) return;
      setActive(e.isIntersecting ? "services" : "parts");
    }, { rootMargin: "-150px 0px -55% 0px", threshold: 0 });
    io.observe(el);
    return () => io.disconnect();
  }, []);
  React.useEffect(() => () => clearTimeout(spyTimer.current), []);

  // Gap we want between the pinned bar and the section header on landing.
  const STACK_GAP = 18;
  const go = (v) => {
    setActive(v);
    spyLock.current = true;
    clearTimeout(spyTimer.current);
    if (v === "parts") {
      window.scrollTo({ top: 0, behavior: "smooth" });
    } else if (servicesRef.current) {
      // One smooth scroll. Subtracting the chrome's CURRENT height works whether
      // it's expanded (at top) or already stuck: the collapse that happens
      // mid-scroll cancels out, so the header always lands (bar height + gap)
      // below the top — no guessed constant, no bounce.
      const absTop = servicesRef.current.getBoundingClientRect().top + window.scrollY;
      const chromeH = chromeRef.current ? chromeRef.current.getBoundingClientRect().height : 170;
      const y = Math.max(0, absTop - chromeH - STACK_GAP);
      window.scrollTo({ top: y, behavior: "smooth" });
    }
    spyTimer.current = setTimeout(() => { spyLock.current = false; }, 800);
  };

  const partsCats = [
    { id: "bumpers-grilles",    label: "الصدامات", icon: <IconBumper /> },
    { id: "suspension",         label: "المساعدات", icon: <IconShock /> },
    { id: "brakes",             label: "الفرامل", icon: <IconBrakeDisc /> },
    { id: "ac",                 label: "التكييف", icon: <IconAC /> },
    { id: "lighting",           label: "الإضاءة", icon: <IconHeadlight /> },
    { id: "engine-trans",       label: "المحرك", icon: <IconEngine /> },
  ];
  const recent = ["bumperR", "shockR", "pads", "bracketR", "grille", "bumperL"];

  return (
    <div>
      <div ref={sentinelRef} style={{ height: 1 }} />
      <div ref={chromeRef} className={"stick-anchor" + (stuck ? " stuck" : "")}>
        <div className="car-bar">
          <button type="button" className="car-bar-photo-btn" onClick={onMenu} aria-label="فتح القائمة">
            <img className="car-bar-photo" src={CURRENT_CAR.image} alt={CURRENT_CAR.name} />
          </button>
          <div className="car-bar-body">
            <div className="car-bar-eyebrow">سيارتك الحالية</div>
            <div className="car-bar-name">{CURRENT_CAR.name}</div>
          </div>
          <div className="car-bar-actions">
            <button className="car-edit" aria-label="تغيير السيارة" onClick={onMenu}><IconEdit /></button>
            <button className="car-cart" aria-label="السلة" onClick={onCart}><IconCart />{cartCount > 0 && <span className="cart-badge">{cartCount}</span>}</button>
          </div>
        </div>
        <div className="anchor-trust"><div className="anchor-trust-inner"><TrustBadges /></div></div>
        <div className="search-wrap">
          <button className="big-search" onClick={onSearch}>
            <span className="bs-icon"><IconSearch /></span>
            <span className="bs-text">ابحث في قطع {CURRENT_CAR.short}</span>
          </button>
        </div>
        <div className={"svc-vtabs" + (active === "services" ? " is-b" : "")} role="tablist">
          <span className="svc-vtabs-bar" />
          <button className={active === "parts" ? "is-active" : ""} onClick={() => go("parts")} role="tab" aria-selected={active === "parts"}>
            <SvcQuickIcon />قطع الغيار
          </button>
          <button className={active === "services" ? "is-active" : ""} onClick={() => go("services")} role="tab" aria-selected={active === "services"}>
            <SvcCareIcon />خدمات السيارة
          </button>
        </div>
      </div>

      {/* Parts section */}
      <div ref={partsRef} className="svc-stack-sec">
        <section className="a-section">
          <div className="section-head"><h2 className="section-title">اختر القسم</h2></div>
          <div className="cd-cats">
            {partsCats.map((c, i) => (
              <button key={i} className="cat-card" onClick={() => navigate("/spare-parts/" + c.id)}>
                <span className="cat-icon">{c.icon}</span>
                <span className="cat-label">{c.label}</span>
              </button>
            ))}
          </div>
          <button className="home-browse-all cd-browse" onClick={() => navigate("/spare-parts/all")}>
            <span className="cd-browse-icon"><IconGrid /></span>
            <span className="home-browse-all-title">اكتشف القطع والحلول</span>
            <span className="home-browse-all-arrow"><IconChevron /></span>
          </button>
        </section>
        {/* Visual search — its own moment right after the categories (mirrors home) */}
        <section className="a-section">
          <button className={"h3d-peek cd-peek" + (peekRolling ? " is-rolling" : "")} ref={peekRef} onClick={() => navigate("/locate")}>
            <div className="h3d-peek-stage">
              <svg className="h3dp-base" viewBox="0 0 240 270" fill="none" aria-hidden="true">
                <g stroke="#2A2C31" strokeLinejoin="round" strokeLinecap="round">
                  <path d="M 108 15 A 78 120 0 0 0 108 255 L 142 255 A 78 120 0 0 0 142 15 Z" strokeWidth="4" />
                  <ellipse cx="142" cy="135" rx="78" ry="120" strokeWidth="4" />
                  <ellipse cx="142" cy="135" rx="65" ry="107" strokeWidth="2.6" />
                  <path d="M 48.25 212.13 L 82.25 212.13" strokeWidth="2.6" />
                  <path d="M 34.7 176.04 L 68.7 176.04" strokeWidth="2.6" />
                  <path d="M 30 135 L 64 135" strokeWidth="2.6" />
                  <path d="M 34.7 93.96 L 68.7 93.96" strokeWidth="2.6" />
                  <path d="M 48.25 57.87 L 82.25 57.87" strokeWidth="2.6" />
                </g>
              </svg>
              <svg className="h3dp-face" viewBox="0 0 200 200" fill="none" aria-hidden="true">
                <g stroke="#2A2C31" strokeLinejoin="round" strokeLinecap="round">
                  <circle cx="100" cy="100" r="96" strokeWidth="5" />
                  <circle cx="100" cy="100" r="80" strokeWidth="4" />
                  <line x1="100" y1="72" x2="100" y2="24" strokeWidth="5" />
                  <line x1="126.63" y1="91.35" x2="172.28" y2="76.51" strokeWidth="5" />
                  <line x1="116.46" y1="122.65" x2="144.67" y2="161.49" strokeWidth="5" />
                  <line x1="83.54" y1="122.65" x2="55.33" y2="161.49" strokeWidth="5" />
                  <line x1="73.37" y1="91.35" x2="27.72" y2="76.51" strokeWidth="5" />
                  <circle cx="100" cy="100" r="20" strokeWidth="5" />
                  <circle cx="100" cy="100" r="7" strokeWidth="3.5" />
                  <circle cx="100" cy="88" r="2.4" strokeWidth="3" />
                  <circle cx="111.41" cy="96.29" r="2.4" strokeWidth="3" />
                  <circle cx="107.05" cy="109.71" r="2.4" strokeWidth="3" />
                  <circle cx="92.95" cy="109.71" r="2.4" strokeWidth="3" />
                  <circle cx="88.59" cy="96.29" r="2.4" strokeWidth="3" />
                </g>
              </svg>
            </div>
            <span className="h3d-peek-eyebrow"><IconSearch />دلّنا على مكان القطعة</span>
          </button>
        </section>
      </div>

      {/* Services section */}
      <div ref={servicesRef} className="svc-stack-sec">
        <div className="svc-stack-sep"><span>خدمات السيارة</span></div>
        <section className="a-section">
          <SvcHeroOffer o={SVC_OFFERS[0]} onClick={() => navigate(svcOfferPath(SVC_OFFERS[0].key))} />
        </section>
        <section className="a-section svc-home">
          <div className="section-head">
            <h2 className="section-title">تصفّح حسب الخدمة</h2>
            <button type="button" className="section-link" onClick={() => navigate("/car-services")}>الكل <IconChevron /></button>
          </div>
          <div className="svc-cats">
            {SVC_CATEGORIES.map((c) => {
              const Glyph = c.icon;
              return (
                <button key={c.id} type="button" className="svc-cat" onClick={() => navigate(svcCatPath(c.id))}>
                  <span className="svc-cat-icon"><Glyph /></span>
                  <span className="svc-cat-label">{c.label}</span>
                </button>
              );
            })}
          </div>
        </section>
        <section className="a-section svc-home">
          <div className="section-head"><h2 className="section-title">أبرز العروض</h2></div>
          <div className="svc-offers">
            {SVC_OFFERS.slice(1, 7).map((o) => <SvcOfferCard key={o.key} o={o} onClick={() => navigate(svcOfferPath(o.key))} />)}
          </div>
        </section>
      </div>

      {/* Recently viewed — global (cross-vertical) history rail, sits below both
          sections as a "resume where you left off" convenience. Parts-only for
          now; should mix parts + services once that history exists. marginTop 30
          matches the parts→services chapter seam so both breaks breathe equally. */}
      <section className="a-section" style={{ paddingInline: 0, marginTop: 30 }}>
        <div className="section-head" style={{ padding: "0 16px" }}><h2 className="section-title">شاهدت مؤخراً</h2></div>
        <div className="prod-rail">
          {recent.map((k, i) => <ProductCard key={k + i} p={findProduct(k)} onClick={() => navigate("/p/" + k)} />)}
        </div>
      </section>
    </div>
  );
}

/* ---------- Registration ---------- */
window.CL = Object.assign(window.CL || {}, {
  ServicesHomeEntry: ServicesHomeEntry,
  ServicesDiscover: ServicesDiscover,
  ServicesPdp: ServicesPdp,
  // Lets index.html's findProduct resolve a service offer into a cart line
  // (title/price/kind), so a services add-to-cart renders + counts like parts.
  svcOffer: (key) => {
    // A multi-option add carries a composite key "{offer}__{optionId}"; resolve
    // it back to the offer + chosen option so the cart line shows the right
    // variant label + price. Single-option keys pass straight through.
    const parts = String(key).split("__");
    const o = SVC_OFFERS.find((x) => x.key === parts[0]);
    if (!o) return null;
    const opt = parts[1] && Array.isArray(o.options) ? o.options.find((x) => x.id === parts[1]) : null;
    return {
      key,
      title: opt ? o.title + " · " + opt.label : o.title,
      price: opt ? opt.price : o.price,
      oldPrice: opt ? opt.oldPrice : o.oldPrice,
      kind: "service", cat: "service", inStock: true, vendor: o.vendor,
      desc: opt ? (opt.sub || o.desc) : o.desc,
    };
  },
});
window.DEMOS = Object.assign(window.DEMOS || {}, {
  "services-home-demo": ServicesHomeDemo,
  "services-entry-demo": ServicesEntryDemo,
  "services-toggle-demo": ServicesToggleDemo,
  "services-stacked-demo": ServicesStackedDemo,
});
window.dispatchEvent(new Event("hashchange"));
