import { ADMIN_NAV_SECTIONS } from "../config/adminNav.jsx";

export const DEFAULT_NAV = "overview";

export const VALID_NAV_IDS = new Set([
  DEFAULT_NAV,
  "users-access",
  "permits-submissions",
  "fill-form",
  "activity-log",
  "form-management",
  "job-type-management",
  "section-management",
  "question-management",
  "raise-ticket",
  "ticket-list",
  "ticket-logs",
  "permit-handover",
  "permit-handback",
  "permit-audit",
  "permit-preview"
]);

/** @returns {{ id: string, params: Record<string, string> }} */
export function parseNavFromHash(hash = typeof window !== "undefined" ? window.location.hash : "") {
  const raw = String(hash || "").replace(/^#\/?/, "").trim();
  if (!raw) {
    return { id: DEFAULT_NAV, params: {} };
  }

  const [pathPart, queryPart] = raw.split("?");
  const id = (pathPart.split("/").filter(Boolean)[0] || DEFAULT_NAV).trim();

  /** @type {Record<string, string>} */
  const params = {};
  if (queryPart) {
    new URLSearchParams(queryPart).forEach((value, key) => {
      params[key] = value;
    });
  }

  if (!VALID_NAV_IDS.has(id)) {
    return { id: DEFAULT_NAV, params: {} };
  }

  return { id, params };
}

export function buildNavHash(id, params = {}) {
  const safeId = VALID_NAV_IDS.has(id) ? id : DEFAULT_NAV;
  const qs = new URLSearchParams();
  Object.entries(params).forEach(([key, value]) => {
    if (value != null && String(value).trim() !== "") {
      qs.set(key, String(value));
    }
  });
  const query = qs.toString();
  return `#/${safeId}${query ? `?${query}` : ""}`;
}

export function writeNavHash(id, params = {}, { replace = false } = {}) {
  if (typeof window === "undefined") return;

  const hash = buildNavHash(id, params);
  const nextUrl = `${window.location.pathname}${window.location.search}${hash}`;

  if (replace) {
    window.history.replaceState(null, "", nextUrl);
    return;
  }

  if (window.location.hash === hash) return;
  window.location.hash = hash;
}

export function isExternalNavId(id) {
  for (const section of ADMIN_NAV_SECTIONS) {
    const item = section.items.find((entry) => entry.id === id);
    if (item?.external) return true;
  }
  return false;
}

export function navParamsFromOptions(options = {}) {
  const params = {};
  if (options.ticketId != null && String(options.ticketId).trim() !== "") {
    params.ticketId = String(options.ticketId);
  }
  if (options.permitId != null && String(options.permitId).trim() !== "") {
    params.permitId = String(options.permitId);
  }
  if (options.previewStep != null && String(options.previewStep).trim() !== "") {
    params.previewStep = String(options.previewStep);
  }
  if (options.jobTypeId != null && String(options.jobTypeId).trim() !== "") {
    params.jobTypeId = String(options.jobTypeId);
  }
  if (options.dashFilter != null && String(options.dashFilter).trim() !== "") {
    params.dashFilter = String(options.dashFilter);
  }
  if (options.dashJobType != null && String(options.dashJobType).trim() !== "") {
    params.dashJobType = String(options.dashJobType);
  }
  return params;
}
