import { $ } from '../core/dom.js';
import { normalizeUiText } from '../core/text.js';
import { closeFolder, openFolder, stepImage } from '../services/batch.js';
import { desktopBridgeState, state, statusDetailsState } from '../state/app-state.js';
import { getDesktopImageLabel } from './events.js';

export function getDesktopStatusSnapshot() {
  const projectRootInput = $("projectRoot");
  const projectRoot = projectRootInput ? String(projectRootInput.value || "").trim() : "";
  const batch = String(state.batch || "");
  const status = String(desktopBridgeState.status || "");
  const imageLabel = getDesktopImageLabel();
  const zoom = Number.isFinite(state.zoom) ? state.zoom : "";
  return { projectRoot, status, batch, imageLabel, zoom };
}


export function updateVisibleStatusBar() {
  const snapshot = getDesktopStatusSnapshot();
  const stateEl = $("statusBar");
  const contextEl = $("statusContext");
  const contextRaw = [snapshot.batch, snapshot.imageLabel].filter(Boolean).join(" | ");
  if (contextEl) contextEl.textContent = "Lot/Image: " + (contextRaw || "-");
  if (stateEl) stateEl.textContent = "État: " + normalizeUiText(snapshot.status || "Prêt");
}


export function publishDesktopBridge() {
  window.DatafixDesktopBridge = {
    getStatusSnapshot() {
      return getDesktopStatusSnapshot();
    },
    openFolder() {
      void openFolder();
    },
    closeFolder() {
      void closeFolder();
    },
    prevImage() {
      void stepImage(-1);
    },
    nextImage() {
      void stepImage(1);
    },
  };
}


export function initFileMenu() {
  const root = $("menuFile");
  const toggle = $("menuFileToggle");
  const panel = $("menuFilePanel");
  if (!root || !toggle || !panel) return;

  const closeMenu = () => {
    root.classList.remove("is-open");
    toggle.setAttribute("aria-expanded", "false");
  };
  const openMenu = () => {
    root.classList.add("is-open");
    toggle.setAttribute("aria-expanded", "true");
  };
  const toggleMenu = () => {
    if (root.classList.contains("is-open")) closeMenu();
    else openMenu();
  };

  toggle.addEventListener("click", (e) => {
    e.preventDefault();
    toggleMenu();
  });

  document.addEventListener("click", (e) => {
    if (!root.contains(e.target)) closeMenu();
  });

  document.addEventListener("keydown", (e) => {
    if (e.key === "Escape") closeMenu();
  });
}



export function closeStatusDetails() {
  const dialog = $("statusDetailsDialog");
  const backdrop = $("statusDetailsBackdrop");
  statusDetailsState.open = false;
  if (dialog) dialog.hidden = true;
  if (backdrop) backdrop.hidden = true;
}


export function openStatusDetails() {
  const dialog = $("statusDetailsDialog");
  const backdrop = $("statusDetailsBackdrop");
  const textarea = $("statusDetailsText");
  if (!dialog || !backdrop || !textarea) return;
  const fullText = String(statusDetailsState.raw || "");
  if (!fullText.trim()) return;
  statusDetailsState.open = true;
  textarea.value = fullText;
  dialog.hidden = false;
  backdrop.hidden = false;
  textarea.focus();
  textarea.select();
}


export function initStatusDetails() {
  const statusBtn = $("statusBar");
  const dialog = $("statusDetailsDialog");
  const backdrop = $("statusDetailsBackdrop");
  const closeBtn = $("btnStatusDetailsClose");
  const copyBtn = $("btnStatusDetailsCopy");
  const textarea = $("statusDetailsText");
  if (!statusBtn || !dialog || !backdrop || !closeBtn || !copyBtn || !textarea) return;

  statusBtn.addEventListener("click", () => {
    openStatusDetails();
  });
  closeBtn.addEventListener("click", () => {
    closeStatusDetails();
  });
  backdrop.addEventListener("click", () => {
    closeStatusDetails();
  });
  copyBtn.addEventListener("click", async () => {
    const fullText = String(textarea.value || "");
    if (!fullText) return;
    try {
      await navigator.clipboard.writeText(fullText);

    } catch (_) {
      textarea.focus();
      textarea.select();
      document.execCommand("copy");

    }
  });
  document.addEventListener("keydown", (e) => {
    if (!statusDetailsState.open) return;
    if (e.key === "Escape") {
      e.preventDefault();
      closeStatusDetails();
    }
  });
}


export function setStatus(msg, isError) {
  const text = String(msg == null ? "" : msg);
  const displayText = normalizeUiText(text);
  desktopBridgeState.status = displayText;
  statusDetailsState.raw = text;
  const el = $("statusBar");
  if (el) {
    el.textContent = "État: " + displayText;
    el.title = displayText;
    el.style.color = isError ? "#e88" : "";
  }
  updateVisibleStatusBar();
}
