
// src/edit.js
import { state } from './state.js';
import { showContextMenuFor, hideContextMenu } from './contextmenu.js';

export function enterEditMode() {
  state.editMode = true;
  document.body.classList.add('edit-mode');
}

export function exitEditMode() {
  state.editMode = false;
  document.body.classList.remove('edit-mode');
  hideContextMenu();
}

/**
 * Configurazioni desktop
 */
const RIGHT_LONG_PRESS_CFG = {
  duration: 500,              // ms per long click destro → wiggle
  tolerancePx: 12,            // px di tolleranza movimento durante il long click destro
};
const RIGHT_DBLCLICK_WINDOW = 380; // ms per rilevare doppio click destro

export function initLongPressHandlers() {
  // =========================
  // TOUCH (Android) — invariato
  // =========================
  document.addEventListener('touchstart', e => {
    if (e.touches.length !== 1) return;
    const icon = e.touches[0].target.closest('.app-icon');
    if (icon) {
      state.longPressTarget = icon;
      state.longPressTimer = setTimeout(() => {
        if (!state.editMode) {
          enterEditMode();
          state.justEnteredEditMode = true;
          if (navigator.vibrate) navigator.vibrate(10);
          return;
        }
        if (state.justEnteredEditMode) {
          state.justEnteredEditMode = false;
          return;
        }
        const r = icon.getBoundingClientRect();
        showContextMenuFor(icon.dataset.id, r.left + r.width / 2, r.top + r.height);
        if (navigator.vibrate) navigator.vibrate(10);
      }, 350);
      return;
    }
    state.longPressTimer = setTimeout(() => {
      if (state.editMode) exitEditMode();
    }, 350);
  }, { passive: true });

  document.addEventListener('touchmove', e => {
    if (!state.longPressTimer) return;
    const touch = e.touches[0];
    const r = state.longPressTarget?.getBoundingClientRect();
    const dx = touch.clientX - (r?.left ?? touch.clientX);
    const dy = touch.clientY - (r?.top ?? touch.clientY);
    if (Math.hypot(dx, dy) > 15) {
      clearTimeout(state.longPressTimer);
      state.longPressTimer = null;
      state.longPressTarget = null;
    }
  }, { passive: true });

  document.addEventListener('touchend', () => {
    if (state.longPressTimer) {
      clearTimeout(state.longPressTimer);
      state.longPressTimer = null;
      state.longPressTarget = null;
    }
    state.justEnteredEditMode = false;
  }, { passive: true });

  // =========================
  // MOUSE (Desktop)
  // =========================
  // Stato interno long click destro
  let rightPressTimer = null;
  let rightPressStart = { x: 0, y: 0 };
  let rightPressIcon = null;
  let rightPressActive = false;

  // Stato interno doppio click destro
  let lastRightClickTime = 0;
  let lastRightClickIconId = null;

  // 1) Long click destro → entra in wiggle mode
  document.addEventListener('mousedown', e => {
    if (e.button !== 2) return; // solo tasto destro
    const icon = e.target.closest('.app-icon');
    if (!icon) return;

    // Sopprimi il menu nativo, lo gestiamo noi
    e.preventDefault();

    // Avvio long press
    rightPressIcon = icon;
    rightPressStart = { x: e.clientX, y: e.clientY };
    rightPressActive = true;

    rightPressTimer = setTimeout(() => {
      rightPressTimer = null;
      // Entra in wiggle se non lo è già
      if (!state.editMode) {
        enterEditMode();
      }
      rightPressActive = false;
    }, RIGHT_LONG_PRESS_CFG.duration);

    // 2) Doppio click destro → menu contestuale (SOLO se già in wiggle)
    const now = performance.now();
    const sameIcon = lastRightClickIconId === icon.dataset.id;
    if (state.editMode && sameIcon && (now - lastRightClickTime) <= RIGHT_DBLCLICK_WINDOW) {
      // Rilevato doppio click destro
      const r = icon.getBoundingClientRect();
      showContextMenuFor(icon.dataset.id, r.left + r.width / 2, r.top + r.height);
      // reset “doppio”
      lastRightClickTime = 0;
      lastRightClickIconId = null;
      // Importante: annulla eventuale long-press in corso
      if (rightPressTimer) clearTimeout(rightPressTimer);
      rightPressTimer = null;
      rightPressActive = false;
      return;
    }
    // Memorizza per possibile doppio
    lastRightClickTime = now;
    lastRightClickIconId = icon.dataset.id;
  });

  // Annulla long press destro se ti muovi troppo
  document.addEventListener('mousemove', e => {
    if (!rightPressActive || !rightPressIcon) return;
    const dx = e.clientX - rightPressStart.x;
    const dy = e.clientY - rightPressStart.y;
    if (Math.hypot(dx, dy) > RIGHT_LONG_PRESS_CFG.tolerancePx) {
      if (rightPressTimer) clearTimeout(rightPressTimer);
      rightPressTimer = null;
      rightPressActive = false;
      rightPressIcon = null;
    }
  });

  // Se rilasci prima del timeout, il long press non scatta
  document.addEventListener('mouseup', e => {
    if (e.button === 2) {
      if (rightPressTimer) clearTimeout(rightPressTimer);
      rightPressTimer = null;
      rightPressActive = false;
      rightPressIcon = null;
    }
  });

  // Gestione menu nativo: lo blocchiamo sempre, il nostro menu è gestito via doppio click destro
  document.addEventListener('contextmenu', e => {
    const icon = e.target.closest('.app-icon');
    if (!icon) return;
    // Evita il menu del browser
    e.preventDefault();
    // Non apriamo nulla qui: il menu è sul doppio click destro (gestito sopra).
  });
}

export function initGlobalCloseHandlers() {
  document.addEventListener('pointerdown', e => {
    const isIcon = e.target.closest('.app-icon');
    const isMenu = e.target.closest('#context-menu');
    const menuHidden = document.getElementById('context-menu').classList.contains('hidden');
    if (!isMenu && !isIcon && !menuHidden) hideContextMenu();
    if (!isIcon && state.editMode) exitEditMode();
  });
}

