const STORAGE_KEYS = {
  session: "sunny_erp_web_session",
  rememberedEmail: "sunny_erp_web_remembered_email",
};

const MODULES = [
  { key: "dashboard", label: "Dashboard", subtitle: "Quick summary area reserved for future operational overviews and KPIs." },
  { key: "purchase_order", label: "Purchase Order", subtitle: "Import, compare, inspect, and export PO records from one workspace." },
  { key: "costing", label: "Costing", subtitle: "Read line sheet PDFs and extract collection, season, style, image, and description data." },
  { key: "admin", label: "Admin", subtitle: "Full control area for system administration, future feature flags, and moderator permissions." },
  { key: "moderate", label: "Moderate", subtitle: "Management area for department leads with access delegated by admin." },
  { key: "user", label: "User", subtitle: "Workspace for end users based on permissions granted by admin or moderator." },
  { key: "tech_pack", label: "Tech Pack", subtitle: "Central workspace for style-level tech pack tracking and future collaboration flows." },
  { key: "samples", label: "Samples", subtitle: "Track sample-making progress with a dedicated sample follow-up table." },
  { key: "production", label: "Production", subtitle: "Reserved workspace for production planning, tracking, and future execution tools." },
  { key: "qa", label: "QA", subtitle: "Reserved workspace for quality assurance workflows and review records." },
  { key: "hr", label: "HR", subtitle: "Reserved workspace for HR coordination, staffing, and internal follow-up." },
  { key: "accountant", label: "Accountant", subtitle: "Reserved workspace for accounting operations and future finance-related tools." },
  { key: "tool", label: "Tool", subtitle: "Shared utilities for the whole app, including the report builder and tech pack helper." },
  { key: "setting", label: "Setting", subtitle: "Configure where data is stored and how the desktop app connects to local or online services." },
];

const loginView = document.getElementById("login-view");
const appView = document.getElementById("app-view");
const loginForm = document.getElementById("login-form");
const emailInput = document.getElementById("email-input");
const passwordInput = document.getElementById("password-input");
const showPasswordInput = document.getElementById("show-password-input");
const rememberEmailInput = document.getElementById("remember-email-input");
const loginStatus = document.getElementById("login-status");
const loginButton = document.getElementById("login-button");
const moduleList = document.getElementById("module-list");
const heroTitle = document.getElementById("hero-title");
const heroSubtitle = document.getElementById("hero-subtitle");
const moduleCardTitle = document.getElementById("module-card-title");
const moduleRoleBadge = document.getElementById("module-role-badge");
const moduleCardCopy = document.getElementById("module-card-copy");
const currentUserSummary = document.getElementById("current-user-summary");
const statusText = document.getElementById("status-text");
const logoutButton = document.getElementById("logout-button");
const releaseVersion = document.getElementById("release-version");
const releaseNotes = document.getElementById("release-notes");
const releaseStatusPill = document.getElementById("release-status-pill");
const downloadAppLink = document.getElementById("download-app-link");
const macosReleaseVersion = document.getElementById("macos-release-version");
const macosReleaseNotes = document.getElementById("macos-release-notes");
const deployStatus = document.getElementById("deploy-status");

let currentUser = null;
let currentModuleKey = "dashboard";
let effectivePermissions = {};
let visibleModules = [];

function loadStoredSession() {
  try {
    const payload = window.localStorage.getItem(STORAGE_KEYS.session);
    if (!payload) return null;
    const parsed = JSON.parse(payload);
    if (!parsed || typeof parsed !== "object" || !parsed.email) {
      clearStoredSession();
      return null;
    }
    return parsed;
  } catch (_error) {
    clearStoredSession();
    return null;
  }
}

function saveStoredSession(user) {
  window.localStorage.setItem(STORAGE_KEYS.session, JSON.stringify(user));
}

function clearStoredSession() {
  window.localStorage.removeItem(STORAGE_KEYS.session);
}

function normalizeRole(role) {
  const normalized = String(role || "user").trim().toLowerCase();
  if (normalized === "admin" || normalized === "moderate" || normalized === "user") {
    return normalized;
  }
  return "user";
}

function roleSummary(role) {
  if (role === "admin") {
    return "Admin manages the full system here, including moderator and user permissions.";
  }
  if (role === "moderate") {
    return "Moderate manages delegated modules here and can configure standard users within allowed scope.";
  }
  return "User works inside the permissions granted by admin or moderate.";
}

function isModulePermitted(moduleKey) {
  const role = normalizeRole(currentUser && currentUser.role);
  if (moduleKey === "admin" || moduleKey === "moderate" || moduleKey === "user") {
    return moduleKey === role;
  }
  if (role === "admin") {
    return true;
  }
  return Boolean(effectivePermissions[`module.${moduleKey}`]);
}

function getVisibleModules() {
  return MODULES.filter((module) => isModulePermitted(module.key));
}

function setStatus(message) {
  statusText.textContent = message || "Ready";
}

function setLoginStatus(message, isError = false) {
  loginStatus.textContent = message;
  loginStatus.style.color = isError ? "#a1372d" : "#8a4b1f";
}

function toggleView(isLoggedIn) {
  loginView.classList.toggle("hidden", isLoggedIn);
  loginView.setAttribute("aria-hidden", isLoggedIn ? "true" : "false");
  appView.classList.toggle("hidden", !isLoggedIn);
  appView.setAttribute("aria-hidden", isLoggedIn ? "false" : "true");
}

function renderModuleShell() {
  moduleList.innerHTML = "";
  visibleModules = getVisibleModules();
  visibleModules.forEach((module) => {
    const button = document.createElement("button");
    button.type = "button";
    button.className = `module-button${module.key === currentModuleKey ? " active" : ""}`;
    button.textContent = module.label;
    button.addEventListener("click", () => {
      currentModuleKey = module.key;
      updateModuleContent();
      renderModuleShell();
    });
    moduleList.appendChild(button);
  });
}

function updateModuleContent() {
  visibleModules = getVisibleModules();
  const module = visibleModules.find((item) => item.key === currentModuleKey) || visibleModules[0] || MODULES[0];
  heroTitle.textContent = module.label;
  heroSubtitle.textContent = module.subtitle;
  moduleCardTitle.textContent = module.label;
  moduleRoleBadge.textContent = String((currentUser && currentUser.role) || "user").toUpperCase();

  if (module.key === "admin") {
    const displayName = String((currentUser && currentUser.display_name) || "").trim();
    const email = String((currentUser && currentUser.email) || "-").trim();
    const userLabel = displayName ? `${displayName} <${email}>` : email;
    moduleCardCopy.innerHTML = `
      <div class="role-summary-block">
        <p><strong>Current User:</strong> ${escapeHtml(userLabel)}</p>
        <p><strong>Current Role:</strong> ${escapeHtml(String((currentUser && currentUser.role) || "user").toUpperCase())}</p>
        <p>${escapeHtml(roleSummary(module.key))}</p>
        <button id="open-folder-explorer" class="primary-button" type="button">Folder Explorer</button>
      </div>
    `;
    const folderButton = document.getElementById("open-folder-explorer");
    if (folderButton) {
      folderButton.addEventListener("click", openFolderExplorer);
    }
  } else if (module.key === "tool") {
    moduleCardCopy.innerHTML = `
      <div class="tool-actions">
        <p>Shared utilities for the next development phase will appear here.</p>
      </div>
    `;
  } else if (module.key === "moderate" || module.key === "user") {
    const displayName = String((currentUser && currentUser.display_name) || "").trim();
    const email = String((currentUser && currentUser.email) || "-").trim();
    const userLabel = displayName ? `${displayName} <${email}>` : email;
    moduleCardCopy.innerHTML = `
      <div class="role-summary-block">
        <p><strong>Current User:</strong> ${escapeHtml(userLabel)}</p>
        <p><strong>Current Role:</strong> ${escapeHtml(String((currentUser && currentUser.role) || "user").toUpperCase())}</p>
        <p>${escapeHtml(roleSummary(module.key))}</p>
      </div>
    `;
  } else {
    moduleCardCopy.textContent = "This tab is ready for the next development phase.";
  }
  setStatus(`Ready - ${module.label}`);
}

function applyUserSession(user, permissions = null) {
  currentUser = user;
  effectivePermissions = permissions && typeof permissions === "object" ? permissions : effectivePermissions;
  visibleModules = getVisibleModules();
  if (!visibleModules.some((module) => module.key === currentModuleKey)) {
    currentModuleKey = visibleModules[0] ? visibleModules[0].key : "dashboard";
  }
  currentUserSummary.textContent = user.display_name ? `${user.display_name} <${user.email}>` : user.email;
  updateModuleContent();
  renderModuleShell();
  toggleView(true);
}

async function postJson(url, payload) {
  const response = await fetch(url, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      "Cache-Control": "no-store",
    },
    body: JSON.stringify(payload),
  });
  const data = await response.json().catch(() => ({}));
  if (!response.ok) {
    throw new Error(data.detail || `Request failed: ${response.status}`);
  }
  return data;
}

async function fetchJson(url) {
  const response = await fetch(url, {
    headers: {
      "Cache-Control": "no-store",
    },
  });
  const data = await response.json().catch(() => ({}));
  if (!response.ok) {
    throw new Error(data.detail || `Request failed: ${response.status}`);
  }
  return data;
}

async function handleLoginSubmit(event) {
  event.preventDefault();
  const email = emailInput.value.trim();
  const password = passwordInput.value;
  if (!email) {
    setLoginStatus("Please enter your email.", true);
    return;
  }
  if (!password) {
    setLoginStatus("Please enter your password.", true);
    return;
  }

  loginButton.disabled = true;
  setLoginStatus("Signing in...");
  try {
    const payload = await postJson("/api/auth/login", { email, password });
    const user = payload.user || {};
    const permissions = payload.effective_permissions || {};
    if (rememberEmailInput.checked) {
      window.localStorage.setItem(STORAGE_KEYS.rememberedEmail, email);
    } else {
      window.localStorage.removeItem(STORAGE_KEYS.rememberedEmail);
    }
    saveStoredSession(user);
    applyUserSession(user, permissions);
    setLoginStatus("Signed in.");
  } catch (error) {
    clearStoredSession();
    effectivePermissions = {};
    visibleModules = [];
    toggleView(false);
    setLoginStatus(error.message || "Email or password is incorrect.", true);
  } finally {
    loginButton.disabled = false;
  }
}

function handleLogout() {
  clearStoredSession();
  currentUser = null;
  effectivePermissions = {};
  visibleModules = [];
  currentModuleKey = "dashboard";
  passwordInput.value = "";
  setLoginStatus("Sign in to continue using CitiFox ERP App.");
  setStatus("Ready");
  toggleView(false);
}

function hydrateRememberedEmail() {
  const rememberedEmail = window.localStorage.getItem(STORAGE_KEYS.rememberedEmail) || "";
  if (rememberedEmail) {
    emailInput.value = rememberedEmail;
    rememberEmailInput.checked = true;
  }
}

async function hydrateReleaseCard() {
  try {
    const payload = await fetchJson("/api/releases/latest");
    if (payload.available) {
      releaseVersion.textContent = `Version ${payload.version}`;
      releaseNotes.textContent = payload.notes || "Latest packaged desktop build is ready to download.";
      releaseStatusPill.textContent = "Ready";
      releaseStatusPill.style.background = "#dcebdd";
      releaseStatusPill.style.color = "#29603a";
      downloadAppLink.href = payload.download_url || "/downloads/latest";
      deployStatus.textContent = `Latest file: ${payload.filename || "desktop package"}${payload.updated_at_utc ? ` | UTC ${payload.updated_at_utc}` : ""}`;
    } else {
      releaseVersion.textContent = `Version ${payload.version || "-"}`;
      releaseNotes.textContent = payload.notes || "Desktop package is not available yet.";
      releaseStatusPill.textContent = "Pending";
      downloadAppLink.removeAttribute("href");
      downloadAppLink.setAttribute("aria-disabled", "true");
      downloadAppLink.style.pointerEvents = "none";
      downloadAppLink.style.opacity = "0.7";
    }
  } catch (error) {
    releaseVersion.textContent = "Release info unavailable";
    releaseNotes.textContent = error.message || "Could not load release information from the server.";
    releaseStatusPill.textContent = "Offline";
    deployStatus.textContent = "Server release check failed.";
  }

  if (!macosReleaseVersion || !macosReleaseNotes) {
    return;
  }
  try {
    const macPayload = await fetchJson("/api/releases/macos/latest");
    if (macPayload.available) {
      macosReleaseVersion.textContent = `macOS v${macPayload.version || "-"}`;
      macosReleaseNotes.textContent = `Apple Silicon build ${macPayload.version || "-"}${macPayload.updated_at_utc ? ` | UTC ${macPayload.updated_at_utc}` : ""}.`;
    } else {
      macosReleaseVersion.textContent = "macOS Pending";
      macosReleaseNotes.textContent = macPayload.notes || "macOS build is not available yet.";
    }
  } catch (error) {
    macosReleaseVersion.textContent = "macOS Offline";
    macosReleaseNotes.textContent = error.message || "Could not load macOS release information.";
  }
}

async function hydrateUserContext(email) {
  const payload = await fetchJson(`/api/auth/context?email=${encodeURIComponent(String(email || "").trim())}`);
  return {
    user: payload.user || {},
    effectivePermissions: payload.effective_permissions || {},
  };
}

let currentFolderPath = "";
const folderExplorerOverlay = document.getElementById("folder-explorer-overlay");
const folderExplorerItems = document.getElementById("folder-explorer-items");
const folderExplorerStatus = document.getElementById("folder-explorer-status");
const folderExplorerBreadcrumb = document.getElementById("folder-explorer-breadcrumb");

function openFolderExplorer() {
  if (!folderExplorerOverlay || !folderExplorerStatus || !folderExplorerItems || !folderExplorerBreadcrumb) {
    setStatus("Folder Explorer is not available in this web build.");
    return;
  }
  folderExplorerOverlay.classList.remove("hidden");
  folderExplorerOverlay.setAttribute("aria-hidden", "false");
  loadFolder("");
}

function closeFolderExplorer() {
  if (!folderExplorerOverlay) {
    return;
  }
  folderExplorerOverlay.classList.add("hidden");
  folderExplorerOverlay.setAttribute("aria-hidden", "true");
}

function getParentPath(path) {
  if (!path) return "";
  const lastSlash = Math.max(path.lastIndexOf("/"), path.lastIndexOf("\\"));
  if (lastSlash < 0) return "";
  return path.slice(0, lastSlash);
}

async function loadFolder(path) {
  if (!folderExplorerStatus || !folderExplorerItems) {
    return;
  }
  folderExplorerStatus.textContent = "Loading...";
  folderExplorerItems.innerHTML = "";
  try {
    const currentEmail = encodeURIComponent(String((currentUser && currentUser.email) || "").trim());
    const data = await fetchJson(`/api/folder/contents?path=${encodeURIComponent(path)}&email=${currentEmail}`);
    currentFolderPath = data.path || "";
    renderFolderExplorer(data);
  } catch (error) {
    folderExplorerStatus.textContent = error.message || "Failed to load folder.";
  }
}

function renderFolderExplorer(data) {
  if (!folderExplorerStatus || !folderExplorerBreadcrumb || !folderExplorerItems) {
    return;
  }
  folderExplorerStatus.textContent = "";
  folderExplorerBreadcrumb.textContent = data.path || "";
  const items = [];
  (data.folders || []).forEach((folder) => {
    items.push({ ...folder, kind: "folder" });
  });
  (data.files || []).forEach((file) => {
    items.push({ ...file, kind: "file" });
  });
  folderExplorerItems.innerHTML = items
    .map((item) => {
      if (item.kind === "folder") {
        return `
          <tr>
            <td><span class="folder-icon">ðŸ“</span> ${escapeHtml(item.name)}</td>
            <td>-</td>
            <td>-</td>
            <td><button class="secondary-button folder-open" data-path="${escapeHtml(item.path)}" type="button">Open</button></td>
          </tr>
        `;
      }
      const size = formatBytes(item.size);
      return `
        <tr>
          <td><span class="file-icon">ðŸ“„</span> ${escapeHtml(item.name)}</td>
          <td>${size}</td>
          <td>${escapeHtml(item.modified || "")}</td>
          <td><a class="secondary-button" href="/api/files?path=${encodeURIComponent(item.path)}&email=${encodeURIComponent(String((currentUser && currentUser.email) || "").trim())}">Download</a></td>
        </tr>
      `;
    })
    .join("");
  folderExplorerItems.querySelectorAll(".folder-open").forEach((button) => {
    button.addEventListener("click", () => loadFolder(button.dataset.path));
  });
}

function formatBytes(bytes) {
  if (!bytes && bytes !== 0) return "-";
  if (bytes === 0) return "0 B";
  const units = ["B", "KB", "MB", "GB"];
  const i = Math.min(Math.floor(Math.log(bytes) / Math.log(1024)), units.length - 1);
  return `${(bytes / Math.pow(1024, i)).toFixed(1)} ${units[i]}`;
}

function escapeHtml(value) {
  if (value === null || value === undefined) return "";
  return String(value)
    .replace(/&/g, "&amp;")
    .replace(/</g, "&lt;")
    .replace(/>/g, "&gt;")
    .replace(/"/g, "&quot;");
}

const folderExplorerCloseButton = document.getElementById("folder-explorer-close");
const folderExplorerUpButton = document.getElementById("folder-explorer-up");
const folderExplorerRefreshButton = document.getElementById("folder-explorer-refresh");

if (folderExplorerCloseButton) {
  folderExplorerCloseButton.addEventListener("click", closeFolderExplorer);
}
if (folderExplorerUpButton) {
  folderExplorerUpButton.addEventListener("click", () => loadFolder(getParentPath(currentFolderPath)));
}
if (folderExplorerRefreshButton) {
  folderExplorerRefreshButton.addEventListener("click", () => loadFolder(currentFolderPath));
}
if (folderExplorerOverlay) {
  folderExplorerOverlay.addEventListener("click", (event) => {
    if (event.target === folderExplorerOverlay) closeFolderExplorer();
  });
}

async function initialize() {
  toggleView(false);
  setStatus("Ready");
  hydrateRememberedEmail();
  hydrateReleaseCard();

  showPasswordInput.addEventListener("change", () => {
    passwordInput.type = showPasswordInput.checked ? "text" : "password";
  });
  loginForm.addEventListener("submit", handleLoginSubmit);
  logoutButton.addEventListener("click", handleLogout);

  const session = loadStoredSession();
  if (session && session.email) {
    try {
      const context = await hydrateUserContext(session.email);
      saveStoredSession(context.user);
      applyUserSession(context.user, context.effectivePermissions);
      setLoginStatus("Session restored.");
    } catch (_error) {
      clearStoredSession();
      setLoginStatus("Sign in to continue using CitiFox ERP App.");
    }
  }
}

initialize();
