async function loadPublicOffers() {
  const r = await fetch("/public-offers");
  const offers = await r.json();
  const featured = offers.filter((o) => o.is_featured);
  const daily = offers.filter((o) => !o.is_featured);
  renderOffers("featuredOffers", featured, true);
  renderOffers("dailyOffers", daily, false);
  featuredCount.textContent = `${featured.length} عرض`;
  dailyCount.textContent = `${daily.length} عرض`;
  featuredEmpty.style.display = featured.length ? "none" : "block";
  dailyEmpty.style.display = daily.length ? "none" : "block";
  const today = new Date();

lastUpdate.textContent = today.toLocaleDateString("ar-SA", {
  day: "numeric",
  month: "numeric"
});
}
function renderOffers(id, offers, featured) {
  const c = document.getElementById(id);
  c.innerHTML = "";

  offers.forEach((o) => {

    c.innerHTML += `
      <article class="offer-card ${featured ? "big featured-card" : "daily-card"}">

        <div class="discount-tag">
          ${featured ? "مميز" : "عرض اليوم"}
        </div>

        <div class="product-img">
          ${
            o.image_url
              ? `<img src="${o.image_url}" alt="${o.title}">`
              : "🛒"
          }
        </div>

        <h3 style="color: var(--product-title-color) !important;">
          ${o.title}
        </h3>

        <div class="price-row">

          <span
            class="old-price"
            style="color: var(--old-price-color) !important;"
          >
            ${o.old_price ?? ""}
          </span>

          <span class="new-price">
            ${o.new_price ?? ""}
          </span>

        </div>

      </article>
    `;
  });

  document.querySelectorAll(".offer-card h3").forEach(title => {
  let size = 15;

  title.style.setProperty("font-size", size + "px", "important");
  title.style.setProperty("white-space", "nowrap", "important");
  title.style.setProperty("overflow", "visible", "important");

  while (
    title.scrollWidth > title.clientWidth &&
    size > 6
  ) {
    size--;
    title.style.setProperty("font-size", size + "px", "important");
  }
});
}
async function sharePage() {

    try {
  
      if (navigator.share) {
  
        await navigator.share({
          title: "مجلة أيمن مارك",
          text: "تابع عروض أيمن مارك",
          url: window.location.href
        });
  
      } else {
  
        await navigator.clipboard.writeText(
          window.location.href
        );
  
        alert("تم نسخ الرابط");
  
      }
  
    } catch (e) {
  
      console.log(e);
  
    }
  
  }
let deferredInstallPrompt = null;
window.addEventListener("beforeinstallprompt", (e) => {
  e.preventDefault();
  deferredInstallPrompt = e;
  showInstallHint("اضغط زر أيقونة لإضافة المجلة على شاشة جوالك.");
});
window.addEventListener("load", () => {
  loadPublicSettings();
  loadPublicOffers();
  loadPublicSliders();
  loadPublicEvents();

  const isIOS =
    /iphone|ipad|ipod/i.test(navigator.userAgent);

  setTimeout(() => {
    if (isIOS) {
      showInstallHint(
        ' اضغط زر "مشاركة" ثم اختر "إضافة إلى الشاشة الرئيسية لتظهر كتطبيق أو انسخ الرابط".'
      );
    } else {
      showInstallHint(
        "اضغط زر أيقونة لإضافة المجلة كتطبيق."
      );
    }
  }, 1800);
});

async function installApp() {
  if (deferredInstallPrompt) {
    deferredInstallPrompt.prompt();
    await deferredInstallPrompt.userChoice;
    deferredInstallPrompt = null;
    closeInstallHint();
    return;
  }
  if (/iphone|ipad|ipod/i.test(navigator.userAgent))
    showInstallHint(
      "للآيفون: اضغط زر المشاركة في سفاري، ثم اختر: إضافة إلى الشاشة الرئيسية."
    );
  else
    showInstallHint(
      "من المتصفح اضغط القائمة ⋮ ثم اختر: إضافة إلى الشاشة الرئيسية."
    );
}
function showInstallHint(t) {
  installHintText.textContent = t;
  installHint.classList.add("show");
}
function closeInstallHint() {
    // تركنا الرسالة دائمة بدون إغلاق
  }

async function loadPublicSliders() {
    const response = await fetch('/public-sliders');
    const sliders = await response.json();
  
    const activeSliders = sliders.filter(item => item.is_active);
  
    const sliderBox = document.querySelector('.hero-slider');
  
    if (!activeSliders.length) {
      sliderBox.innerHTML = `
        <div class="media-placeholder">
          <span>لا توجد وسائط في السلايدر حالياً</span>
        </div>
      `;
      return;
    }
  
    let currentIndex = 0;
  
    function showSlide(index) {
      const item = activeSliders[index];
  
      if (item.media_type === 'video') {
        sliderBox.innerHTML = `
          <video
            src="${item.media_url}"
            autoplay
            muted
            playsinline
            controls
            class="slider-media"
            onended="nextSlide()"
          ></video>
        `;
      } else {
        sliderBox.innerHTML = `
          <img
            src="${item.media_url}"
            class="slider-media"
            alt="إعلان أيمن مارك"
          >
        `;
  
        setTimeout(() => {
            nextSlide();
          }, (window.sliderSeconds || 10) * 1000);
      }
    }
  
    window.nextSlide = function () {
      currentIndex++;
  
      if (currentIndex >= activeSliders.length) {
        currentIndex = 0;
      }
  
      showSlide(currentIndex);
    };
  
    showSlide(currentIndex);
  }

async function loadPublicEvents() {
  const response = await fetch("/public-events");
  const events = await response.json();

  const banner = document.querySelector(".moving-banner");

  if (!banner) return;

  if (!events.length) {
  const eventsSection = banner.closest(".events-section");
  if (eventsSection) eventsSection.style.display = "none";
  return;
}

  banner.innerHTML = `
    <div class="events-row">
      ${events
        .map((event) => {
          const endDate = event.end_date
            ? new Date(event.end_date).toLocaleDateString("ar-SA")
            : "غير محدد";

          return `
            <article class="event-card-small">

  <div class="event-card-image">
    ${
  event.image_url
    ? `
      <img
        src="${event.image_url}"
        alt="${event.title}"
      >

      <button
        class="event-zoom-btn"
        onclick="openEventImage('${event.image_url}')"
      >
        ⛶
      </button>
    `
    : ""
}

    <div class="event-card-title">
      <div class="event-title-main">
        ${event.title}
      </div>

      <div class="event-date-mini">
  ${
    event.end_date
      ? (() => {
          const today = new Date();
          today.setHours(0,0,0,0);

          const end = new Date(event.end_date);
          end.setHours(0,0,0,0);

          if (end < today) return "منتهي";
if (end.getTime() === today.getTime()) return "ينتهي: اليوم";

return `ينتهي: ${endDate}`;
        })()
      : ""
  }
</div>

</article>
          `;
        })
        .join("")}
    </div>
  `;
}

  async function loadPublicSettings() {

    const response = await fetch("/settings");
    const settings = await response.json();
  
    // اسم المجلة
    document.querySelector(".title-box h1").textContent =
      settings.magazine_title || "مجلة عروض أيمن مارك";
  
    // الروابط
    const siteBtn = document.querySelector(".float-btn.site");
    const googleBtn = document.querySelector(".float-btn.google");
  
    if (siteBtn?.parentElement)
      siteBtn.parentElement.href =
        settings.website_url || "#";
  
    if (googleBtn?.parentElement)
      googleBtn.parentElement.href =
        settings.google_review_url || "#";
  
    // الألوان
    document.documentElement.style.setProperty(
      "--primary-color",
      settings.primary_color || "#0b6b46"
    );
  
    document.documentElement.style.setProperty(
      "--secondary-color",
      settings.secondary_color || "#ffcf4d"
    );
  
    document.documentElement.style.setProperty(
      "--background-color",
      settings.background_color || "#f7faf6"
    );
  
    document.documentElement.style.setProperty(
      "--title-color",
      settings.title_color || "#0b4b34"
    );
  
    document.documentElement.style.setProperty(
      "--price-color",
      settings.price_color || "#0b7a4d"
    );
  
    document.documentElement.style.setProperty(
      "--button-color",
      settings.button_color || "#0b6b46"
    );
  
    document.documentElement.style.setProperty(
      "--discount-color",
      settings.discount_color || "#e92424"
    );

    document.documentElement.style.setProperty(
        "--header-color",
        settings.header_color || "#ffffff"
      );

    document.documentElement.style.setProperty(
  "--install-icon-color",
  settings.install_icon_color || "#0b6b46"
);

document.documentElement.style.setProperty(
  "--share-icon-color",
  settings.share_icon_color || "#173d31"
);

document.documentElement.style.setProperty(
  "--location-icon-color",
  settings.location_icon_color || "#214d85"
);

document.documentElement.style.setProperty(
  "--product-title-color",
  settings.product_title_color || "#222222"
);

document.documentElement.style.setProperty(
  "--old-price-color",
  settings.old_price_color || "#888888"
);

document.documentElement.style.setProperty(
  "--magazine-title-color",
  settings.magazine_title_color || "#ffffff"
);

document.documentElement.style.setProperty(
  "--title-color",
  settings.title_color || "#0b4b34");

  document.documentElement.style.setProperty(
  "--featured-card-color",
  settings.featured_card_color || "#ffffff"
);

document.documentElement.style.setProperty(
  "--daily-card-color",
  settings.daily_card_color || "#ffffff"
);
  
    // الأقسام
  
    const sliderSection =
  document.querySelector(".hero-slider");
  
  const eventsSection =
  document.querySelector(".moving-banner");
  
    const featuredSection =
      document.getElementById("featuredOffers")
        ?.closest("section");
  
    const dailySection =
      document.getElementById("dailyOffers")
        ?.closest("section");
  
    if (sliderSection)
      sliderSection.style.display =
        settings.show_slider ? "" : "none";
  
    if (eventsSection)
      eventsSection.style.display =
        settings.show_events ? "" : "none";
  
    if (featuredSection)
      featuredSection.style.display =
        settings.show_featured ? "" : "none";
  
    if (dailySection)
      dailySection.style.display =
        settings.show_daily ? "" : "none";
  
    if (typeof lastUpdate !== "undefined") {
      lastUpdate.parentElement.style.display =
        settings.show_update_time
          ? ""
          : "none";
    }
  
    // مدة السلايدر
    window.sliderSeconds =
      settings.slider_image_seconds || 10;
  }

  function openEventImage(src) {
  document.getElementById("eventModalImg").src = src;

  document
    .getElementById("eventImageModal")
    .classList.add("show");

  document.body.style.overflow = "hidden";
}

function closeEventImage() {
  document
    .getElementById("eventImageModal")
    .classList.remove("show");

  document.body.style.overflow = "";
}

window.addEventListener("load", () => {

  setTimeout(() => {

    document
      .getElementById("welcomeNotice")
      ?.classList.add("show");

  }, 2000);

});

function closeNotice() {

  document
    .getElementById("welcomeNotice")
    ?.classList.remove("show");

}


const isIOS =
  /iphone|ipad|ipod/i.test(navigator.userAgent);

if (isIOS) {
  const installBtn =
    document.getElementById("installBtnBox");

  if (installBtn) {
    installBtn.style.display = "none";
  }
}

