import { menuMapping, menuPublicMapping } from "./menuMapping.js";
// Urutan kategori manual
const categoryOrder = [
  "General",
  "Authorization",
  "Master Data",
  "Info Control",
  "Assocation Management",
  "Sales",
  "Report",
  "Setting",
];

/**
 * Generate breadcrumb Metronic-style dan inject ke elemen target
 * @param {string|HTMLElement} targetSelector - selector CSS atau elemen container
 * @param {Array<string>} menuList - daftar label breadcrumb, urut dari kiri ke kanan
 */
export function setBreadcrumb(targetSelector, menuList = []) {
  const container =
    typeof targetSelector === "string"
      ? document.querySelector(targetSelector)
      : targetSelector;

  if (!container) {
    console.error("Breadcrumb container not found:", targetSelector);
    return;
  }

  // Fungsi helper untuk dapatkan url_path dari nama menu
  const getUrlByName = (name) => {
    const item = menuMapping.find((m) => m.displayValue === name);
    return item ? item.url_path : "#";
  };

  // Buat HTML breadcrumb
  let html = `
        <div class="d-flex flex-wrap align-items-center justify-content-between mb-4">
            <div class="d-flex flex-column">
                <ul class="breadcrumb breadcrumb-separatorless fw-semibold fs-7 mb-0">
    `;

  menuList.forEach((name, i) => {
    const isLast = i === menuList.length - 1;
    const url = getUrlByName(name);

    if (!isLast) {
      html += `
                <li class="breadcrumb-item text-muted">
                    <a href="${url}" class="text-muted text-hover-primary">${name}</a>
                </li>
                <li class="breadcrumb-item">
                    <span class="bullet bg-gray-400 w-5px h-2px"></span>
                </li>
            `;
    } else {
      html += ` <li class="breadcrumb-item text-muted">
                    <a href="${url}" class="text-muted text-hover-primary">${name}</a>
                </li>`;
    }
  });

  html += `
                </ul>
            </div>
        </div>
    `;

  container.innerHTML = html;
}
/**
 * Generate breadcrumb Metronic-style dengan dukungan:
 * - menuMappingPublic jika IsPublic = true
 * - customUrl per item: { name, customUrl, displayName }
 * - displayName digunakan sebagai teks jika tidak kosong
 *
 * @param {string|HTMLElement} targetSelector - container target
 * @param {Array} menuList - array label/string atau object { name, customUrl, displayName }
 * @param {boolean} IsPublic - jika true, pakai menuMappingPublic
 */
export function setBreadcrumb_URL(targetSelector, menuList = [], IsPublic = false) {
    const container =
        typeof targetSelector === "string"
            ? document.querySelector(targetSelector)
            : targetSelector;

    if (!container) {
        console.error("Breadcrumb container not found:", targetSelector);
        return;
    }

    // Tentukan mapping mana yang dipakai
    const mapping = IsPublic ? menuMappingPublic : menuMapping;

    // Helper ambil URL dari mapping
    const getUrlByName = (name) => {
        const item = mapping.find((m) => m.displayValue === name);
        return item ? item.url_path : "#";
    };

    let html = `
        <div class="d-flex flex-wrap align-items-center justify-content-between mb-4">
            <div class="d-flex flex-column">
                <ul class="breadcrumb breadcrumb-separatorless fw-semibold fs-7 mb-0">
    `;

    menuList.forEach((item, i) => {
        const isLast = i === menuList.length - 1;

        // Jika item string → convert ke object
        const name = typeof item === "string" ? item : item.name;
        const customUrl =
            typeof item === "object" && item.customUrl ? item.customUrl : null;

        const displayName =
            typeof item === "object" && item.displayName ? item.displayName : name;

        const url = customUrl || getUrlByName(name);

        if (!isLast) {
            html += `
                <li class="breadcrumb-item text-muted">
                    <a href="${url}" class="text-muted text-hover-primary">${displayName}</a>
                </li>
                <li class="breadcrumb-item">
                    <span class="bullet bg-gray-400 w-5px h-2px"></span>
                </li>
            `;
        } else {
            html += `
                <li class="breadcrumb-item text-muted">
                    <a href="${url}" class="text-muted text-hover-primary">${displayName}</a>
                </li>
            `;
        }
    });

    html += `
                </ul>
            </div>
        </div>
    `;

    container.innerHTML = html;
}


/**
 * Generate menu utama berdasarkan akses dan kategori
 * @param {string|HTMLElement} targetSelector - selector CSS atau elemen container
 * @param {Array<Object>} listAkses - daftar akses user, berisi field AksesName
 */
export function setMainMenu(targetSelector, listAkses) {
  if (!targetSelector || !listAkses) {
    console.error("Parameter targetSelector dan listAkses wajib diisi");
    return;
  }

  const container =
    typeof targetSelector === "string"
      ? document.querySelector(targetSelector)
      : targetSelector;

  if (!container) {
    console.error("Main menu container not found:", targetSelector);
    return;
  }

  const aksesNames = listAkses.map((a) => a.AksesName);

  // Tambahkan kategori lain jika ada di mapping tapi belum di daftar
  const allCategories = [
    ...categoryOrder,
    ...[...new Set(menuMapping.map((m) => m.category))].filter(
      (c) => !categoryOrder.includes(c)
    ),
  ];

  let html = "";

  allCategories.forEach((category, idx) => {
    // Ambil menu dalam kategori ini yang boleh ditampilkan
    const menus = menuMapping.filter(
      (m) =>
        m.category === category &&
        m.ShowForMenu !== false &&
        (!m.aksesNeeded || aksesNames.includes(m.aksesNeeded))
    );

    if (menus.length === 0) return; // skip kalau kosong

    html += `
            <div class="menu-section mb-5">
                <h5 class="fw-bold mb-4">${category}</h5>
                <div class="d-flex flex-wrap justify-content-start gap-5">
        `;

    menus.forEach((menu) => {
      const icon = menu.iconClass || "fa-solid fa-circle";
      html += `
                <div class="text-center">
                    <a href="${menu.url_path}" class="btn btn-icon btn-light-primary rounded-circle mb-2">
                        <i class="${icon} fs-3"></i>
                    </a>
                    <div class="fw-semibold text-gray-700 fs-7">${menu.displayValue}</div>
                </div>
            `;
    });

    html += `
                </div>
            </div>
        `;

    // Separator antar kategori (kecuali terakhir yang tampil)
    html += `<hr class="border-gray-300 my-4">`;
  });

  container.innerHTML =
    html ||
    `<div class="text-center text-muted py-5">Tidak ada menu yang tersedia</div>`;
}

/**
 * Generate dynamic header menu (public + administrator)
 * @param {string|HTMLElement} selectorHeader - Target <ul> container untuk header tabs
 * @param {string|HTMLElement} selectorItem - Target <div.tab-content> untuk menu isi
 * @param {Array<Object>} listAkses - daftar akses user, boleh kosong
 */
export function setHeaderMenu(selectorHeader, selectorItem, listAkses = []) {
  console.log("inside setHeaderMenu");

  const headerEl =
    typeof selectorHeader === "string"
      ? document.querySelector(selectorHeader)
      : selectorHeader;

  const itemEl =
    typeof selectorItem === "string"
      ? document.querySelector(selectorItem)
      : selectorItem;

  if (!headerEl) {
    console.error("Header container not found.");
    return;
  }

  if (!itemEl) {
    console.error("item container not found.");
    return;
  }

  const aksesNames = listAkses.map((a) => a.AksesName);
  const hasAdminAccess = aksesNames.includes("Administrator.Access");

  // --- 1️⃣ Generate Header Tabs ---
  let headerTabsHtml = `
    
  `;

  if (hasAdminAccess) {
    headerTabsHtml += `
      <li class="nav-item">
        <a class="nav-link active" data-bs-toggle="tab" href="#kt_header_administrator_tab">
          Administrator Menu
        </a>
      </li>
    `;
  }

  headerEl.innerHTML = headerTabsHtml;

  // --- 2️⃣ Generate Public Menu Content ---
  const publicMenuOrder = [
    { name: "Dashboard" },
    { name: "Daftar Produk" },
   // { category: "Shop" },
    //{ name: "Help" },
  ];

  const publicHtml = generateMenuHtml(menuPublicMapping, publicMenuOrder);

  // --- 3️⃣ Generate Admin Menu Content ---
  let adminHtml = "";
  if (hasAdminAccess) {
    adminHtml = generateMenuHtml(
      menuMapping.filter(
        (m) =>
          m.ShowForMenu !== false &&
          (!m.aksesNeeded || aksesNames.includes(m.aksesNeeded))
      ),
      categoryOrder
    );
  }

  // --- 4️⃣ Combine Tab Panels ---
  let tabHtml = `
    
  `;

  if (hasAdminAccess) {
    tabHtml += `
      <div class="tab-pane fade active show" id="kt_header_administrator_tab">
        <div class="header-menu flex-column align-items-stretch flex-lg-row">
          <div class="menu menu-rounded menu-column menu-lg-row menu-root-here-bg-desktop menu-active-bg 
          menu-title-gray-700 menu-state-primary menu-arrow-gray-500 fw-semibold align-items-stretch 
          flex-grow-1 px-2 px-lg-0" data-kt-menu="true">
            ${adminHtml}
          </div>
        </div>
      </div>
    `;
  }

  itemEl.innerHTML = tabHtml;
}

/**
 * Helper untuk generate HTML menu item + dropdown kategori
 */
function generateMenuHtml(menuList, orderList) {
  let html = "";

  orderList.forEach((o) => {
    // kalau orderList berupa string kategori langsung
    const category = typeof o === "string" ? o : o.category;
    const name = typeof o === "string" ? null : o.name;

    if (name) {
      const item = menuList.find((m) => m.displayValue === name);
      if (item) {
        html += `
          <div class="menu-item me-0 me-lg-2">
            <a class="menu-link py-3" href="${item.url_path}">
              <span class="menu-title">${item.displayValue}</span>
            </a>
          </div>
        `;
      }
    } else if (category) {
      const items = menuList
        .filter((m) => m.category === category)
        .sort((a, b) => a.displayValue.localeCompare(b.displayValue));

      if (items.length > 0) {
        html += `
          <div class="menu-item menu-lg-down-accordion me-0 me-lg-2" 
               data-kt-menu-trigger="click" 
               data-kt-menu-placement="bottom-start">
            <span class="menu-link py-3">
              <span class="menu-title">${category}</span>
              <span class="menu-arrow"></span>
            </span>
            <div class="menu-sub menu-sub-lg-down-accordion menu-sub-lg-dropdown p-2">
              ${items
                .map(
                  (m) => `
                    <div class="menu-item">
                      <a class="menu-link" href="${m.url_path}">
                        <span class="menu-title">${m.displayValue}</span>
                      </a>
                    </div>`
                )
                .join("")}
            </div>
          </div>
        `;
      }
    }
  });

  return html;
}
