import { FORM_MIN, FORM_WIDTH_LS, IMAGES_PANEL_COLLAPSED_LS, RESIZER_W, SIDEBAR_COLLAPSED, SIDEBAR_DEFAULT, SIDEBAR_MAX, SIDEBAR_MIN, SIDEBAR_WIDTH_LS } from '../config/constants.js';
import { $ } from '../core/dom.js';
import { readLs, writeLs } from '../core/storage.js';
import { selectImageByIndex, showImageListContextMenu } from '../services/batch.js';
import { scheduleUserPreferencesSave } from '../services/preferences.js';
import { state, userPrefsStore } from '../state/app-state.js';

let activeImageListButton = null;
let activeImageListIndex = -1;

export function sidebarWidthClamped(sw) {
  if (sw == null || !Number.isFinite(sw)) return SIDEBAR_DEFAULT;
  return Math.max(SIDEBAR_MIN, Math.min(SIDEBAR_MAX, Math.round(sw)));
}


export function readSidebarWidth() {
  if (state.sidebarWidthPx != null) return sidebarWidthClamped(state.sidebarWidthPx);
  if (userPrefsStore.sidebar_width != null) {
    return sidebarWidthClamped(Number(userPrefsStore.sidebar_width));
  }
  const raw = readLs(SIDEBAR_WIDTH_LS);
  const s = raw ? parseInt(raw, 10) : NaN;
  if (Number.isFinite(s) && s >= SIDEBAR_MIN && s <= SIDEBAR_MAX) return s;
  return SIDEBAR_DEFAULT;
}


export function defaultFormWidth() {
  const sw = readSidebarWidth();
  return Math.max(
    FORM_MIN,
    Math.round((window.innerWidth - sw - 2 * RESIZER_W) * 0.34)
  );
}


export function maxFormWidth() {
  return Math.max(FORM_MIN, Math.round(window.innerWidth * 0.52));
}

/**
   * Grille : liste images | séparateur | aperçu | séparateur | formulaire.
 */

export function getSidebarAndFirstResizerForGrid() {
  if (state.imagesPanelCollapsed) {
    return { sw: SIDEBAR_COLLAPSED, r0: 0 };
  }
  const sw = sidebarWidthClamped(readSidebarWidth());
  return { sw, r0: RESIZER_W };
}


export function applyLayoutColumns() {
  const layout = $("mainLayout");
  if (!layout) return;
  const cap = maxFormWidth();
  if (!state.imagesPanelCollapsed) {
    const sw = sidebarWidthClamped(readSidebarWidth());
    state.sidebarWidthPx = sw;
    try {
      writeLs(SIDEBAR_WIDTH_LS, String(sw));
      scheduleUserPreferencesSave({ sidebar_width: sw });
    } catch (_) {
      /* ignore */
    }
  }

  let fw = state.formWidthPx;
  if (fw == null) {
    if (userPrefsStore.form_width != null) {
      const fromStore = parseInt(String(userPrefsStore.form_width), 10);
      if (Number.isFinite(fromStore) && fromStore >= FORM_MIN && fromStore <= cap) {
        fw = fromStore;
      }
    }
    const raw = readLs(FORM_WIDTH_LS);
    const saved = raw ? parseInt(raw, 10) : NaN;
    if (Number.isFinite(saved) && saved >= FORM_MIN && saved <= cap) {
      fw = saved;
    }
  }

  let formCol;
  if (fw != null) {
    fw = Math.max(FORM_MIN, Math.min(cap, fw));
    state.formWidthPx = fw;
    try {
      writeLs(FORM_WIDTH_LS, String(fw));
      scheduleUserPreferencesSave({ form_width: fw });
    } catch (_) {
      /* ignore */
    }
    formCol = `${fw}px`;
  } else {
    state.formWidthPx = null;
    formCol = `minmax(${FORM_MIN}px, 1fr)`;
  }

  const { sw, r0 } = getSidebarAndFirstResizerForGrid();
  layout.style.gridTemplateColumns = `${sw}px ${r0}px minmax(0, 1.55fr) ${RESIZER_W}px ${formCol}`;
}


export function setImagesPanelCollapsed(collapsed) {
  state.imagesPanelCollapsed = !!collapsed;
  try {
    writeLs(IMAGES_PANEL_COLLAPSED_LS, state.imagesPanelCollapsed ? "1" : "0");
    scheduleUserPreferencesSave({ images_panel_collapsed: !!state.imagesPanelCollapsed });
  } catch (_) {
    /* ignore */
  }
  applyLayoutColumns();
  renderImageList();
  syncImagesPanelToggleUi();
}


export function syncImagesPanelToggleUi() {
  const layout = $("mainLayout");
  const aside = document.querySelector(".sidebar");
  const resizer = $("sidebarResizer");
  const toggle = $("btnImagesPanelToggle");
  const c = !!state.imagesPanelCollapsed;
  if (layout) layout.classList.toggle("layout--images-panel-collapsed", c);
  if (aside) aside.setAttribute("aria-hidden", "false");
  if (resizer) {
    resizer.setAttribute("aria-hidden", c ? "true" : "false");
    resizer.tabIndex = c ? -1 : 0;
  }
  if (toggle) {
    toggle.setAttribute("aria-expanded", c ? "false" : "true");
    /* Left arrow hides, right arrow shows. */
    toggle.textContent = c ? "\u25B6" : "\u25C0";
  }
  const floatHost = $("imagesPanelToggleHostToolbar");
  if (floatHost) {
    floatHost.hidden = true;
  }
}


export function initImagesPanelToggle() {
  const btn = $("btnImagesPanelToggle");
  if (btn) {
    btn.addEventListener("click", () => {
      setImagesPanelCollapsed(!state.imagesPanelCollapsed);
    });
  }
}


export function markUserSizedForm(widthPx) {
  state.formWidthPx = widthPx;
  writeLs(FORM_WIDTH_LS, String(widthPx));
  scheduleUserPreferencesSave({ form_width: widthPx });
}


export function initSplitResizer() {
  const handle = $("splitResizer");
  const layout = $("mainLayout");
  if (!handle || !layout) return;
  let startX = 0;
  let startW = 0;

  function onMove(e) {
    const dx = e.clientX - startX;
    const cap = maxFormWidth();
    const next = Math.max(FORM_MIN, Math.min(cap, startW - dx));
    markUserSizedForm(next);
    const { sw, r0 } = getSidebarAndFirstResizerForGrid();
    layout.style.gridTemplateColumns = `${sw}px ${r0}px minmax(0, 1.55fr) ${RESIZER_W}px ${next}px`;
  }

  function onUp() {
    handle.classList.remove("is-dragging");
    document.removeEventListener("mousemove", onMove);
    document.removeEventListener("mouseup", onUp);
  }

  handle.addEventListener("mousedown", (e) => {
    if (e.button !== 0) return;
    e.preventDefault();
    const formPane = $("formPane");
    const measured =
      formPane && formPane.getBoundingClientRect
        ? Math.round(formPane.getBoundingClientRect().width)
        : defaultFormWidth();
    startX = e.clientX;
    startW = state.formWidthPx != null ? state.formWidthPx : measured;
    handle.classList.add("is-dragging");
    document.addEventListener("mousemove", onMove);
    document.addEventListener("mouseup", onUp);
  });
}


export function initSidebarResizer() {
  const handle = $("sidebarResizer");
  const layout = $("mainLayout");
  if (!handle || !layout) return;
  let startX = 0;
  let startW = 0;

  function onMove(e) {
    const dx = e.clientX - startX;
    const next = sidebarWidthClamped(startW + dx);
    state.sidebarWidthPx = next;
    writeLs(SIDEBAR_WIDTH_LS, String(next));
    scheduleUserPreferencesSave({ sidebar_width: next });
    applyLayoutColumns();
  }

  function onUp() {
    handle.classList.remove("is-dragging");
    document.removeEventListener("mousemove", onMove);
    document.removeEventListener("mouseup", onUp);
  }

  handle.addEventListener("mousedown", (e) => {
    if (e.button !== 0) return;
    e.preventDefault();
    const aside = document.querySelector(".sidebar");
    const measured =
      aside && aside.getBoundingClientRect
        ? Math.round(aside.getBoundingClientRect().width)
        : readSidebarWidth();
    startX = e.clientX;
    startW = state.sidebarWidthPx != null ? state.sidebarWidthPx : measured;
    handle.classList.add("is-dragging");
    document.addEventListener("mousemove", onMove);
    document.addEventListener("mouseup", onUp);
  });
}



export function renderImageList() {
  const ul = $("imageList");
  if (!ul) return;
  ul.innerHTML = "";
  activeImageListButton = null;
  activeImageListIndex = -1;
  const showCollapsedImageIds = !!state.imagesPanelCollapsed;
  const frag = document.createDocumentFragment();
  state.images.forEach((im, i) => {
    const li = document.createElement("li");
    const btn = document.createElement("button");
    btn.type = "button";
    btn.dataset.imageIndex = String(i);
    btn.dataset.imageId = String(im.image_id);
    btn.title = "ImageID " + im.image_id;
    if (showCollapsedImageIds) {
      btn.textContent = String(im.image_id);
    } else {
      btn.textContent = im.image_name || "Image " + im.image_id;
    }
    btn.addEventListener("click", () => selectImageByIndex(i));
    btn.addEventListener("contextmenu", (e) => {
      e.preventDefault();
      showImageListContextMenu(e.clientX, e.clientY, im.image_id);
    });
    if (i === state.imageIndex) {
      btn.classList.add("active");
      activeImageListButton = btn;
      activeImageListIndex = i;
    }
    li.appendChild(btn);
    frag.appendChild(li);
  });
  ul.appendChild(frag);
}


export function highlightList() {
  if (activeImageListIndex === state.imageIndex && activeImageListButton) return;
  if (activeImageListButton) {
    activeImageListButton.classList.remove("active");
  }
  activeImageListButton = null;
  activeImageListIndex = -1;
  if (state.imageIndex < 0) return;
  const ul = $("imageList");
  if (!ul) return;
  const next = ul.querySelector(`button[data-image-index="${state.imageIndex}"]`);
  if (!next) return;
  next.classList.add("active");
  activeImageListButton = next;
  activeImageListIndex = state.imageIndex;
  next.scrollIntoView({ block: "nearest" });
}
