/* =========================================================
   LUXURY PLUMBING (Salla - Theme Editor) | Vanilla JS
   Author: Copilot
   Notes:
   - Injects premium styles + UX enhancements.
   - Uses safe selectors + MutationObserver to handle theme differences.
   ========================================================= */

(() => {
  "use strict";

  /* -------------------------
     1) CONFIG (عدل هنا فقط)
     ------------------------- */
  const CONFIG = {
    brandName: "متجرك",
    whatsappNumber: "", // مثال: "9665XXXXXXXX" بدون +
    whatsappMessage: "مرحبًا، أحتاج مساعدة بخصوص منتج في متجر الأدوات الصحية.",
    enableWhatsApp: true,
    enableBackToTop: true,
    enableTrustBar: true,
    enableProductBadges: true,
    enableImageZoom: true,
    enableToast: true,

    // ألوان فخمة (ماء/تركواز + لمسة ذهبية)
    colors: {
      bg: "#f7f8fb",
      text: "#111827",
      muted: "#6b7280",
      brand: "#0b5ed7",
      brand2: "#0ea5a4",
      brandDark: "#083b8a",
      gold: "#b48a2a",
      surface: "#ffffff",
      line: "rgba(15,23,42,.10)",
      shadow: "0 14px 40px rgba(2, 8, 23, 0.08)",
    },

    // نصوص شريط الثقة
    trustItems: [
      { icon: "🛡️", title: "ضمان معتمد", desc: "على القطع الأساسية" },
      { icon: "🚚", title: "شحن سريع", desc: "وتغليف آمن" },
      { icon: "✅", title: "منتجات أصلية", desc: "جودة عالية" },
      { icon: "💧", title: "مناسبة للمنزل", desc: "خامات مقاومة" },
    ],

    // Selectors مرنة (تغطي اختلافات الثيمات)
    selectors: {
      header: ["header", ".site-header", ".header", ".navbar"],
      productCard: [".product-item", ".product-card", ".product", ".products .item", "[data-product-card]"],
      productTitle: [".product-title", ".product-name", "h3", "h2"],
      price: [".product-price", ".price", "[data-price]"],
      oldPrice: ["del", ".old-price", ".compare-at-price"],
      addToCart: [".btn-add-to-cart", ".add-to-cart", "button[name='add-to-cart']", "button[type='submit']"],
      productGalleryImages: [".product-images img", ".product-gallery img", ".swiper-slide img", "img[data-zoomable]"],
    },

    // أداء: تقليل التأثيرات على الجوال
    reduceMotionOnMobile: true,
  };

  /* -------------------------
     2) HELPERS
     ------------------------- */
  const $ = (sel, root = document) => root.querySelector(sel);
  const $$ = (sel, root = document) => Array.from(root.querySelectorAll(sel));

  const firstMatch = (selectors, root = document) => {
    for (const s of selectors) {
      const el = $(s, root);
      if (el) return el;
    }
    return null;
  };

  const allMatches = (selectors, root = document) => {
    const found = [];
    for (const s of selectors) found.push(...$$(s, root));
    // unique
    return [...new Set(found)];
  };

  const isMobile = () => matchMedia("(max-width: 768px)").matches;

  const onReady = (fn) => {
    if (document.readyState === "loading") document.addEventListener("DOMContentLoaded", fn, { once: true });
    else fn();
  };

  const safeText = (el) => (el?.textContent || "").trim();

  const injectStyle = (cssText, id = "lux-plumbing-style") => {
    if (document.getElementById(id)) return;
    const style = document.createElement("style");
    style.id = id;
    style.textContent = cssText;
    document.head.appendChild(style);
  };

  const createEl = (tag, attrs = {}, children = []) => {
    const el = document.createElement(tag);
    Object.entries(attrs).forEach(([k, v]) => {
      if (k === "class") el.className = v;
      else if (k === "html") el.innerHTML = v;
      else el.setAttribute(k, v);
    });
    children.forEach((c) => el.appendChild(typeof c === "string" ? document.createTextNode(c) : c));
    return el;
  };

  const throttle = (fn, wait = 100) => {
    let last = 0;
    return (...args) => {
      const now = Date.now();
      if (now - last >= wait) {
        last = now;
        fn(...args);
      }
    };
  };

  /* -------------------------
     3) INJECT LUXURY CSS
     (تصميم عالمي بدون تدخل CSS منفصل)
     ------------------------- */
  const LUX_CSS = `
    :root{
      --lux-bg:${CONFIG.colors.bg};
      --lux-surface:${CONFIG.colors.surface};
      --lux-text:${CONFIG.colors.text};
      --lux-muted:${CONFIG.colors.muted};
      --lux-brand:${CONFIG.colors.brand};
      --lux-brand2:${CONFIG.colors.brand2};
      --lux-brandDark:${CONFIG.colors.brandDark};
      --lux-gold:${CONFIG.colors.gold};
      --lux-line:${CONFIG.colors.line};
      --lux-shadow:${CONFIG.colors.shadow};
      --lux-radius:18px;
      --lux-radius2:14px;
    }

    html, body{ background:var(--lux-bg) !important; color:var(--lux-text) !important; }
    body{ font-family:"Cairo","Tajawal",system-ui,-apple-system,"Segoe UI",Arial,sans-serif !important; }
    a{ color:var(--lux-brandDark); }
    a:hover{ color:var(--lux-brand); }

    /* Glass header on scroll */
    .lux-header-glass{
      background:rgba(255,255,255,.86) !important;
      backdrop-filter: blur(10px);
      border-bottom:1px solid var(--lux-line);
      transition: box-shadow .2s ease, transform .2s ease, background .2s ease;
    }
    .lux-header-glass.lux-scrolled{
      box-shadow: 0 10px 30px rgba(2,8,23,.08);
    }

    /* Trust bar */
    .lux-trustbar{
      background:var(--lux-surface);
      border:1px solid var(--lux-line);
      border-radius:var(--lux-radius);
      box-shadow: 0 12px 30px rgba(2,8,23,.05);
      margin: 14px auto;
      padding: 14px 12px;
      max-width: 1200px;
    }
    .lux-trustbar__grid{
      display:grid;
      grid-template-columns: repeat(4, minmax(0, 1fr));
      gap: 10px;
    }
    .lux-trustbar__item{
      display:flex;
      gap:10px;
      align-items:flex-start;
      padding: 10px 12px;
      border-radius: 14px;
      border: 1px solid rgba(180,138,42,.16);
      background: linear-gradient(180deg, rgba(180,138,42,.10), rgba(14,165,164,.06));
    }
    .lux-trustbar__icon{ font-size: 20px; line-height: 1; }
    .lux-trustbar__title{ font-weight: 900; font-size: 14px; margin-bottom: 2px; }
    .lux-trustbar__desc{ color:var(--lux-muted); font-weight: 700; font-size: 12px; }

    @media (max-width: 900px){
      .lux-trustbar__grid{ grid-template-columns: repeat(2, minmax(0, 1fr)); }
    }

    /* Product card enhancement */
    .lux-card{
      position:relative;
      border-radius: var(--lux-radius) !important;
      border:1px solid var(--lux-line) !important;
      overflow:hidden;
      background: var(--lux-surface) !important;
      box-shadow: 0 10px 24px rgba(2,8,23,.05);
      transition: transform .22s ease, box-shadow .22s ease, border-color .22s ease;
    }
    .lux-card:hover{
      transform: translateY(-6px);
      box-shadow: var(--lux-shadow);
      border-color: rgba(14,165,164,.25) !important;
    }
    .lux-badges{
      position:absolute; top:12px; left:12px;
      display:flex; flex-wrap:wrap; gap:6px;
      z-index: 3;
    }
    .lux-badge{
      border-radius: 999px;
      padding: 6px 10px;
      font-size: 12px;
      font-weight: 900;
      border: 1px solid rgba(180,138,42,.22);
      background: linear-gradient(180deg, rgba(180,138,42,.16), rgba(180,138,42,.06));
      color: #6b4f12;
      box-shadow: 0 10px 20px rgba(2,8,23,.06);
      user-select:none;
      white-space:nowrap;
    }
    .lux-badge--water{
      border-color: rgba(14,165,164,.30);
      background: linear-gradient(180deg, rgba(14,165,164,.14), rgba(11,94,215,.08));
      color: var(--lux-brandDark);
    }

    /* Floating buttons */
    .lux-float{
      position: fixed;
      inset-inline-end: 18px;
      bottom: 18px;
      display:flex;
      flex-direction:column;
      gap: 10px;
      z-index: 9999;
    }
    .lux-float__btn{
      border: 1px solid rgba(11,94,215,.20);
      background: linear-gradient(135deg, var(--lux-brand), var(--lux-brand2));
      color: #fff;
      border-radius: 999px;
      padding: 10px 14px;
      font-weight: 900;
      box-shadow: 0 14px 40px rgba(2,8,23,.14);
      cursor:pointer;
      display:flex;
      align-items:center;
      gap: 8px;
      transition: transform .18s ease, filter .18s ease;
    }
    .lux-float__btn:hover{ transform: translateY(-2px); filter:saturate(1.05); }
    .lux-float__btn--light{
      background:#fff;
      color: var(--lux-brandDark);
      border: 1px solid rgba(8,59,138,.18);
    }

    /* Toast */
    .lux-toast{
      position: fixed;
      left: 18px;
      bottom: 18px;
      z-index: 9999;
      background: rgba(255,255,255,.92);
      backdrop-filter: blur(10px);
      border: 1px solid var(--lux-line);
      border-radius: 16px;
      padding: 12px 14px;
      box-shadow: 0 16px 50px rgba(2,8,23,.16);
      max-width: min(360px, calc(100vw - 36px));
      display:none;
    }
    .lux-toast.show{ display:block; animation: luxPop .22s ease; }
    @keyframes luxPop { from { transform: translateY(8px); opacity:.0; } to { transform: translateY(0); opacity:1; } }
    .lux-toast__title{ font-weight: 900; margin-bottom: 2px; }
    .lux-toast__desc{ color: var(--lux-muted); font-weight: 700; font-size: 12.5px; }

    /* Image zoom overlay */
    .lux-zoom{
      position: fixed;
      inset: 0;
      background: rgba(2,8,23,.72);
      display:none;
      align-items:center;
      justify-content:center;
      z-index: 10000;
      padding: 22px;
    }
    .lux-zoom.show{ display:flex; }
    .lux-zoom img{
      max-width: min(1100px, 96vw);
      max-height: 88vh;
      border-radius: 18px;
      box-shadow: 0 24px 80px rgba(0,0,0,.35);
      background:#fff;
    }
    .lux-zoom__hint{
      position:absolute;
      top: 14px;
      left: 14px;
      color: rgba(255,255,255,.9);
      font-weight: 800;
      font-size: 13px;
    }
  `;

  /* -------------------------
     4) FEATURES
     ------------------------- */

  // (A) Header glass + scroll state
  const setupHeader = () => {
    const header = firstMatch(CONFIG.selectors.header);
    if (!header) return;

    header.classList.add("lux-header-glass");

    const onScroll = throttle(() => {
      header.classList.toggle("lux-scrolled", window.scrollY > 20);
    }, 80);

    window.addEventListener("scroll", onScroll, { passive: true });
    onScroll();
  };

  // (B) Trust bar insertion (below header or at top of main content)
  const setupTrustBar = () => {
    if (!CONFIG.enableTrustBar) return;
    if ($(".lux-trustbar")) return;

    const trust = createEl("div", { class: "lux-trustbar", role: "note" });
    const grid = createEl("div", { class: "lux-trustbar__grid" });

    CONFIG.trustItems.forEach((it) => {
      const item = createEl("div", { class: "lux-trustbar__item" }, [
        createEl("div", { class: "lux-trustbar__icon", "aria-hidden": "true" }, [it.icon]),
        createEl("div", {}, [
          createEl("div", { class: "lux-trustbar__title" }, [it.title]),
          createEl("div", { class: "lux-trustbar__desc" }, [it.desc]),
        ]),
      ]);
      grid.appendChild(item);
    });

    trust.appendChild(grid);

    // Try to place after header, else prepend to body
    const header = firstMatch(CONFIG.selectors.header);
    if (header && header.parentElement) {
      header.insertAdjacentElement("afterend", trust);
    } else {
      document.body.insertAdjacentElement("afterbegin", trust);
    }
  };

  // (C) Floating buttons (Back to top + WhatsApp)
  const setupFloating = () => {
    if (!CONFIG.enableBackToTop && !CONFIG.enableWhatsApp) return;
    if ($(".lux-float")) return;

    const wrap = createEl("div", { class: "lux-float" });

    if (CONFIG.enableWhatsApp && CONFIG.whatsappNumber) {
      const waLink = `https://wa.me/${encodeURIComponent(CONFIG.whatsappNumber)}?text=${encodeURIComponent(CONFIG.whatsappMessage)}`;
      const waBtn = createEl("a", {
        class: "lux-float__btn",
        href: waLink,
        target: "_blank",
        rel: "noopener",
        title: "تواصل واتساب",
      }, ["واتساب", "💬"]);
      wrap.appendChild(waBtn);
    }

    if (CONFIG.enableBackToTop) {
      const upBtn = createEl("button", {
        class: "lux-float__btn lux-float__btn--light",
        type: "button",
        title: "للأعلى",
      }, ["للأعلى", "⬆️"]);
      upBtn.addEventListener("click", () => window.scrollTo({ top: 0, behavior: "smooth" }));
      wrap.appendChild(upBtn);
    }

    document.body.appendChild(wrap);
  };

  // (D) Toast
  let toastEl = null;
  const setupToast = () => {
    if (!CONFIG.enableToast) return;
    if ($(".lux-toast")) {
      toastEl = $(".lux-toast");
      return;
    }
    toastEl = createEl("div", { class: "lux-toast", role: "status", "aria-live": "polite" }, [
      createEl("div", { class: "lux-toast__title" }, ["تمت الإضافة للسلة ✅"]),
      createEl("div", { class: "lux-toast__desc" }, ["اختيار ممتاز! يمكنك إكمال التسوق أو الذهاب للسلة."]),
    ]);
    document.body.appendChild(toastEl);
  };

  const showToast = (title, desc) => {
    if (!toastEl) return;
    const t = $(".lux-toast__title", toastEl);
    const d = $(".lux-toast__desc", toastEl);
    if (t && title) t.textContent = title;
    if (d && desc) d.textContent = desc;

    toastEl.classList.add("show");
    window.clearTimeout(showToast._timer);
    showToast._timer = window.setTimeout(() => toastEl.classList.remove("show"), 2600);
  };

  // (E) Product cards: add luxury class + badges
  const enhanceProductCard = (card) => {
    if (!card || card.dataset.luxEnhanced === "1") return;
    card.dataset.luxEnhanced = "1";
    card.classList.add("lux-card");

    if (!CONFIG.enableProductBadges) return;

    // Create badge container
    const badges = createEl("div", { class: "lux-badges" });

    // Badge 1: "Premium" for plumbing (generic)
    badges.appendChild(createEl("div", { class: "lux-badge lux-badge--water" }, ["جودة فخمة"]));

    // Badge 2: Detect discount (if old price exists)
    const old = firstMatch(CONFIG.selectors.oldPrice, card);
    if (old && safeText(old)) {
      badges.appendChild(createEl("div", { class: "lux-badge" }, ["عرض"]));
    }

    // Badge 3: If title contains common plumbing keywords -> "مقاوم للصدأ"
    const titleEl = firstMatch(CONFIG.selectors.productTitle, card);
    const title = safeText(titleEl).toLowerCase();
    const plumbingHints = ["خلاط", "حنفية", "صنبور", "دش", "سيفون", "مصرف", "كروم", "ستانلس", "مغسلة"];
    if (title && plumbingHints.some((w) => title.includes(w))) {
      badges.appendChild(createEl("div", { class: "lux-badge lux-badge--water" }, ["مقاوم للصدأ"]));
    }

    // Attach badges
    card.insertAdjacentElement("afterbegin", badges);

    // Add toast hook on add-to-cart click
    const addBtn = firstMatch(CONFIG.selectors.addToCart, card);
    if (addBtn && CONFIG.enableToast) {
      addBtn.addEventListener("click", () => {
        const name = title ? title : "المنتج";
        showToast("تمت الإضافة للسلة ✅", `تم إضافة "${name}" بنجاح.`);
      }, { passive: true });
    }

    // Subtle hover tilt (desktop only)
    if (!isMobile() && !(CONFIG.reduceMotionOnMobile && isMobile())) {
      card.addEventListener("mousemove", (e) => {
        const r = card.getBoundingClientRect();
        const x = (e.clientX - r.left) / r.width - 0.5;
        const y = (e.clientY - r.top) / r.height - 0.5;
        card.style.transform = `translateY(-6px) rotateX(${(-y * 3).toFixed(2)}deg) rotateY(${(x * 3).toFixed(2)}deg)`;
      });
      card.addEventListener("mouseleave", () => {
        card.style.transform = "";
      });
    }
  };

  const setupProductCards = () => {
    const cards = allMatches(CONFIG.selectors.productCard);
    cards.forEach(enhanceProductCard);
  };

  // (F) Observe DOM changes (for infinite scroll / dynamic sections)
  const setupObserver = () => {
    const obs = new MutationObserver(throttle(() => {
      setupProductCards();
      setupImageZoom(); // in case gallery loads later
    }, 200));

    obs.observe(document.documentElement, { childList: true, subtree: true });
  };

  // (G) Image zoom modal on product page
  let zoomOverlay = null;

  const ensureZoomOverlay = () => {
    if (zoomOverlay) return zoomOverlay;
    zoomOverlay = createEl("div", { class: "lux-zoom", role: "dialog", "aria-modal": "true" }, [
      createEl("div", { class: "lux-zoom__hint" }, ["اضغط خارج الصورة للإغلاق / Esc"]),
    ]);
    zoomOverlay.addEventListener("click", (e) => {
      if (e.target === zoomOverlay) zoomOverlay.classList.remove("show");
    });
    document.addEventListener("keydown", (e) => {
      if (e.key === "Escape") zoomOverlay?.classList.remove("show");
    });
    document.body.appendChild(zoomOverlay);
    return zoomOverlay;
  };

  const openZoom = (src) => {
    const overlay = ensureZoomOverlay();
    // remove old img
    const oldImg = $("img", overlay);
    if (oldImg) oldImg.remove();

    const img = createEl("img", { src, alt: "عرض صورة المنتج" });
    overlay.appendChild(img);
    overlay.classList.add("show");
  };

  const setupImageZoom = () => {
    if (!CONFIG.enableImageZoom) return;
    const imgs = allMatches(CONFIG.selectors.productGalleryImages);
    imgs.forEach((img) => {
      if (img.dataset.luxZoom === "1") return;
      img.dataset.luxZoom = "1";
      img.style.cursor = "zoom-in";
      img.addEventListener("click", () => {
        const src = img.currentSrc || img.src;
        if (src) openZoom(src);
      });
    });
  };

  // (H) Smooth scroll for anchor links
  const setupSmoothAnchors = () => {
    document.addEventListener("click", (e) => {
      const a = e.target.closest && e.target.closest("a[href^='#']");
      if (!a) return;
      const id = a.getAttribute("href");
      if (!id || id === "#") return;
      const target = $(id);
      if (target) {
        e.preventDefault();
        target.scrollIntoView({ behavior: "smooth", block: "start" });
      }
    });
  };

  /* -------------------------
     5) INIT
     ------------------------- */
  onReady(() => {
    injectStyle(LUX_CSS);

    // Base class hook
    document.documentElement.classList.add("lux-plumbing");
    document.body.classList.add("lux-plumbing");

    setupHeader();
    setupTrustBar();
    setupFloating();
    setupToast();

    setupProductCards();
    setupImageZoom();
    setupSmoothAnchors();

    setupObserver();
  });
})();
``