(function () {
  function injectStyles() {
    if (document.getElementById("md-delivery-date-styles")) return;

    const style = document.createElement("style");
    style.id = "md-delivery-date-styles";
    style.textContent = `
      .md-dd-wrapper {
        direction: rtl;
        margin-top: 10px;
        font-family: inherit;
        width: 100%;
      }

      .md-dd-cards {
        display: grid;
        grid-template-columns: repeat(4, minmax(0, 1fr));
        gap: 6px;
        width: 100%;
      }

      .md-dd-card {
        width: 100%;
        min-width: 0;
        height: 50px;
        border: 1px solid #e5e5e5;
        border-radius: 9px;
        padding: 0;
        text-align: center;
        cursor: pointer;
        background: #f3f3f3;
        transition: all 0.18s ease;
        user-select: none;
        box-sizing: border-box;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
      }

      .md-dd-card:hover {
        border-color: #111;
      }

      .md-dd-card.active {
        background: #000;
        color: #fff;
        border-color: #000;
      }

      .md-dd-card-label {
        display: block;
        line-height: 1;
        margin: 0;
      }

      .md-dd-card-date {
        display: block;
        line-height: 1;
        margin-top: 8px;
        opacity: 0.85;
      }

      .md-dd-card.active .md-dd-card-date {
        opacity: 1;
      }

      .md-dd-calendar-overlay {
        display: none;
        position: fixed;
        inset: 0;
        z-index: 99999;
        align-items: center;
        justify-content: center;
        background: rgba(0, 0, 0, 0.35);
        padding: 16px;
        box-sizing: border-box;
      }

      .md-dd-calendar-overlay.open {
        display: flex;
      }

      .md-dd-calendar-box {
        width: 100%;
        max-width: 360px;
        background: #fff;
        border-radius: 16px;
        padding: 18px;
        box-shadow: 0 10px 40px rgba(0,0,0,0.2);
        direction: ltr;
        box-sizing: border-box;
      }

      .md-dd-cal-header {
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-bottom: 14px;
      }

      .md-dd-cal-title {
        font-size: 15px;
        font-weight: 700;
        color: #111;
      }

      .md-dd-cal-nav {
        border: none;
        background: transparent;
        font-size: 20px;
        cursor: pointer;
        color: #333;
        border-radius: 8px;
        padding: 4px 10px;
        transition: background 0.15s ease;
      }

      .md-dd-cal-nav:hover {
        background: #f2f2f2;
      }

      .md-dd-cal-grid {
        display: grid;
        grid-template-columns: repeat(7, 1fr);
        gap: 4px;
      }

      .md-dd-cal-day-name {
        text-align: center;
        font-size: 11px;
        color: #888;
        font-weight: 700;
        padding: 5px 0;
      }

      .md-dd-cal-day {
        text-align: center;
        padding: 9px 0;
        border-radius: 9px;
        font-size: 13px;
        color: #222;
        cursor: pointer;
        transition: all 0.15s ease;
      }

      .md-dd-cal-day:hover:not(.disabled):not(.empty) {
        background: #f2f2f2;
      }

      .md-dd-cal-day.today {
        background: #f7f7f7;
        font-weight: 700;
      }

      .md-dd-cal-day.selected {
        background: #111;
        color: #fff !important;
        font-weight: 700;
      }

      .md-dd-cal-day.disabled {
        color: #ccc;
        cursor: not-allowed;
      }

      .md-dd-cal-day.empty {
        cursor: default;
      }

      .md-dd-cal-close {
        width: 100%;
        margin-top: 14px;
        padding: 10px 12px;
        border: none;
        border-radius: 10px;
        background: #111;
        color: #fff;
        font-size: 14px;
        font-weight: 700;
        cursor: pointer;
        transition: background 0.15s ease;
      }

      .md-dd-cal-close:hover {
        background: #2a2a2a;
      }

      @media (max-width: 768px) {
        .md-dd-cards {
          gap: 5px;
        }

        .md-dd-card {
          height: 50px;
          border-radius: 8px;
        }

        .md-dd-card-label,
        .md-dd-card-date {
          margin-top: 0;
        }

        .md-dd-card-date {
          margin-top: 8px;
        }

        .md-dd-calendar-box {
          max-width: 100%;
        }
      }
    `;
    document.head.appendChild(style);
  }

  function formatDate(date) {
    const y = date.getFullYear();
    const m = String(date.getMonth() + 1).padStart(2, "0");
    const d = String(date.getDate()).padStart(2, "0");
    return `${y}-${m}-${d}`;
  }

  function getArabicMonth(date) {
    return [
      "يناير", "فبراير", "مارس", "أبريل", "مايو", "يونيو",
      "يوليو", "أغسطس", "سبتمبر", "أكتوبر", "نوفمبر", "ديسمبر"
    ][date.getMonth()];
  }

  function getArabicDayName(date) {
    return [
      "الأحد", "الاثنين", "الثلاثاء", "الأربعاء",
      "الخميس", "الجمعة", "السبت"
    ][date.getDay()];
  }

  function getStartOffset() {
    const now = new Date();
    const hours = now.getHours();
    const minutes = now.getMinutes();
    return (hours > 22 || (hours === 22 && minutes >= 30)) ? 1 : 0;
  }

  function buildCards() {
    const today = new Date();
    today.setHours(0, 0, 0, 0);

    const startOffset = getStartOffset();
    const cards = [];

    for (let i = 0; i < 3; i++) {
      const d = new Date(today);
      d.setDate(today.getDate() + startOffset + i);

      cards.push({
        label: i === 0 ? (startOffset === 0 ? "اليوم" : "غداً") : getArabicDayName(d),
        dateNum: d.getDate(),
        month: getArabicMonth(d),
        value: formatDate(d)
      });
    }

    cards.push({
      label: "التقويم",
      dateNum: null,
      month: "يوم آخر",
      value: "custom"
    });

    return cards;
  }

  function setInputValue(input, value) {
    if (!input || !value) return;

    input.value = value;

    if (input._flatpickr) {
      input._flatpickr.setDate(value, true);
    }

    ["input", "change", "blur"].forEach((eventName) => {
      input.dispatchEvent(new Event(eventName, { bubbles: true }));
    });
  }

  function findDeliveryDateOption() {
    const options = document.querySelectorAll('.s-product-options-option[data-option-type="date"]');

    for (const option of options) {
      const label = option.querySelector(".s-product-options-option-label");
      if (label && label.textContent.includes("تاريخ التوصيل")) {
        return option;
      }
    }
    return null;
  }

  function applyCityOptionTypography(scope) {
    const sample = document.querySelector('.s-product-options-grid-mode-span');
    if (!sample || !scope) return;

    const styles = getComputedStyle(sample);
    scope.querySelectorAll('.md-dd-card-label, .md-dd-card-date').forEach((el) => {
      el.style.fontFamily = styles.fontFamily;
      el.style.fontSize = styles.fontSize;
      el.style.fontWeight = styles.fontWeight;
      el.style.letterSpacing = styles.letterSpacing;
      el.style.lineHeight = styles.lineHeight === "normal" ? "1" : styles.lineHeight;
    });
  }

  function buildUI(optionWrapper, targetInput, nativeContainer) {
    if (optionWrapper.querySelector(".md-dd-wrapper")) return;

    const cards = buildCards();

    const wrapper = document.createElement("div");
    wrapper.className = "md-dd-wrapper";
    wrapper.innerHTML = `
      <div class="md-dd-cards">
        ${cards.map((c, i) => `
          <div class="md-dd-card${i === 0 ? " active" : ""}" data-value="${c.value}">
            <span class="md-dd-card-label">${c.label}</span>
            <span class="md-dd-card-date">${c.dateNum !== null ? `${c.dateNum} ${c.month}` : c.month}</span>
          </div>
        `).join("")}
      </div>
    `;

    const overlay = document.createElement("div");
    overlay.className = "md-dd-calendar-overlay";
    overlay.innerHTML = `
      <div class="md-dd-calendar-box">
        <div class="md-dd-cal-header">
          <button type="button" class="md-dd-cal-nav" data-nav="prev">&#8249;</button>
          <span class="md-dd-cal-title"></span>
          <button type="button" class="md-dd-cal-nav" data-nav="next">&#8250;</button>
        </div>
        <div class="md-dd-cal-grid"></div>
        <button type="button" class="md-dd-cal-close">إغلاق</button>
      </div>
    `;

    document.body.appendChild(overlay);

    nativeContainer.style.display = "none";
    nativeContainer.insertAdjacentElement("afterend", wrapper);

    applyCityOptionTypography(wrapper);

    const customCard = wrapper.querySelector('.md-dd-card[data-value="custom"]');

    let calYear;
    let calMonth;
    let selectedCustomDate = null;

    function setActiveCardByValue(value) {
      wrapper.querySelectorAll(".md-dd-card").forEach((card) => {
        card.classList.remove("active");
      });

      const matchedCard = wrapper.querySelector(`.md-dd-card[data-value="${value}"]`);
      if (matchedCard) {
        matchedCard.classList.add("active");
      } else if (customCard) {
        customCard.classList.add("active");
      }
    }

    function updateCustomCardText(dateObj) {
      if (!customCard || !dateObj) return;

      customCard.querySelector(".md-dd-card-label").textContent = "التقويم";
      customCard.querySelector(".md-dd-card-date").textContent =
        `${dateObj.getDate()} ${getArabicMonth(dateObj)}`;
    }

    function resetCustomCardText() {
      if (!customCard) return;

      customCard.querySelector(".md-dd-card-label").textContent = "التقويم";
      customCard.querySelector(".md-dd-card-date").textContent = "يوم آخر";
    }

    function openCalendar() {
      const base = selectedCustomDate || new Date();
      calYear = base.getFullYear();
      calMonth = base.getMonth();
      renderCalendar();
      overlay.classList.add("open");
    }

    function closeCalendar() {
      overlay.classList.remove("open");
    }

    function renderCalendar() {
      const monthNames = [
        "January", "February", "March", "April", "May", "June",
        "July", "August", "September", "October", "November", "December"
      ];

      overlay.querySelector(".md-dd-cal-title").textContent = `${monthNames[calMonth]} ${calYear}`;

      const grid = overlay.querySelector(".md-dd-cal-grid");
      grid.innerHTML = "";

      ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"].forEach((name) => {
        const dayName = document.createElement("div");
        dayName.className = "md-dd-cal-day-name";
        dayName.textContent = name;
        grid.appendChild(dayName);
      });

      const firstDay = new Date(calYear, calMonth, 1).getDay();
      const daysInMonth = new Date(calYear, calMonth + 1, 0).getDate();

      const today = new Date();
      today.setHours(0, 0, 0, 0);

      const minAllowedDate = new Date(today);
      minAllowedDate.setDate(today.getDate() + getStartOffset());
      minAllowedDate.setHours(0, 0, 0, 0);

      for (let i = 0; i < firstDay; i++) {
        const empty = document.createElement("div");
        empty.className = "md-dd-cal-day empty";
        grid.appendChild(empty);
      }

      for (let day = 1; day <= daysInMonth; day++) {
        const dateObj = new Date(calYear, calMonth, day);
        dateObj.setHours(0, 0, 0, 0);

        const dayEl = document.createElement("div");
        dayEl.className = "md-dd-cal-day";
        dayEl.textContent = day;

        if (dateObj.getTime() === today.getTime()) {
          dayEl.classList.add("today");
        }

        if (
          selectedCustomDate &&
          formatDate(dateObj) === formatDate(selectedCustomDate)
        ) {
          dayEl.classList.add("selected");
        }

        if (dateObj < minAllowedDate) {
          dayEl.classList.add("disabled");
        } else {
          dayEl.addEventListener("click", () => {
            const selectedValue = formatDate(dateObj);
            const matchedQuickCard = wrapper.querySelector(`.md-dd-card[data-value="${selectedValue}"]`);

            setInputValue(targetInput, selectedValue);

            if (matchedQuickCard) {
              selectedCustomDate = null;
              resetCustomCardText();
              setActiveCardByValue(selectedValue);
            } else {
              selectedCustomDate = new Date(dateObj);
              updateCustomCardText(dateObj);
              setActiveCardByValue("custom");
            }

            closeCalendar();
          });
        }

        grid.appendChild(dayEl);
      }
    }

    overlay.querySelector('[data-nav="prev"]').addEventListener("click", () => {
      calMonth--;
      if (calMonth < 0) {
        calMonth = 11;
        calYear--;
      }
      renderCalendar();
    });

    overlay.querySelector('[data-nav="next"]').addEventListener("click", () => {
      calMonth++;
      if (calMonth > 11) {
        calMonth = 0;
        calYear++;
      }
      renderCalendar();
    });

    overlay.querySelector(".md-dd-cal-close").addEventListener("click", closeCalendar);

    overlay.addEventListener("click", (e) => {
      if (e.target === overlay) closeCalendar();
    });

    wrapper.querySelectorAll(".md-dd-card").forEach((card) => {
      card.addEventListener("click", () => {
        const value = card.dataset.value;

        if (value === "custom") {
          setActiveCardByValue("custom");
          openCalendar();
          return;
        }

        selectedCustomDate = null;
        resetCustomCardText();
        setActiveCardByValue(value);
        setInputValue(targetInput, value);
      });
    });

    setInputValue(targetInput, cards[0].value);
    setActiveCardByValue(cards[0].value);
    resetCustomCardText();
  }

  function init() {
    if (document.querySelector('salla-hook[name="cart:start"]')) return;

    const optionWrapper = findDeliveryDateOption();
    if (!optionWrapper) return;

    if (optionWrapper.querySelector(".md-dd-wrapper")) return;

    const nativeContainer = optionWrapper.querySelector(".s-product-options-date-element");
    if (!nativeContainer) return;

    const targetInput =
      nativeContainer.querySelector("input.s-datetime-picker-input") ||
      nativeContainer.querySelector("input[name^='options[']") ||
      nativeContainer.querySelector("input[type='text']");

    if (!targetInput) return;

    injectStyles();
    buildUI(optionWrapper, targetInput, nativeContainer);

    console.log("[Mademoiselle Delivery Date] Ready");
  }

  function tryInit(attemptsLeft) {
    if (document.querySelector(".md-dd-wrapper")) return init();

    if (findDeliveryDateOption()) {
      setTimeout(init, 250);
      return;
    }

    if (attemptsLeft > 0) {
      setTimeout(() => tryInit(attemptsLeft - 1), 300);
    }
  }

  if (document.readyState === "loading") {
    document.addEventListener("DOMContentLoaded", function () {
      tryInit(12);
    });
  } else {
    tryInit(12);
  }

  window.addEventListener("load", function () {
    tryInit(12);
  });
})();