// 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();
}

/* ============================================================
   GESTURE MANAGER UNIFICATO (TOUCH)
   - Long press su icona → entra in wiggle / menu
   - Long press su sfondo → esci dal wiggle
   - Pinch → annulla long press e NON esci dal wiggle
   ============================================================ */

const touchState = {
  startX: 0,
  startY: 0,
  startTime: 0,
  longPressTimer: null,
  targetIcon: null,
  isPinching: false,
};

export function initLongPressHandlers() {

  /* TOUCHSTART ------------------------------------------------ */
  document.addEventListener('touchstart', e => {
    // PINCH → annulla tutto
    if (e.touches.length >= 2) {
      touchState.isPinching = true;
      clearTimeout(touchState.longPressTimer);
      touchState.longPressTimer = null;
      return;
    }

    const t = e.touches[0];
    touchState.startX = t.clientX;
    touchState.startY = t.clientY;
    touchState.startTime = performance.now();
    touchState.isPinching = false;

    const icon = t.target.closest('.app-icon');
    touchState.targetIcon = icon;

    // LONG PRESS TIMER
    touchState.longPressTimer = setTimeout(() => {
      if (touchState.isPinching) return;

      if (icon) {
        // Long press su icona
        if (!state.editMode) {
          enterEditMode();
          if (navigator.vibrate) navigator.vibrate(10);
        } else {
          const r = icon.getBoundingClientRect();
          showContextMenuFor(icon.dataset.id, r.left + r.width / 2, r.top + r.height);
          if (navigator.vibrate) navigator.vibrate(10);
        }
      } else {
        // Long press sullo sfondo → uscita dal wiggle
        if (state.editMode) exitEditMode();
      }
    }, 350);

  }, { passive: true });

  /* TOUCHMOVE ------------------------------------------------ */
  document.addEventListener('touchmove', e => {
    if (!touchState.longPressTimer) return;

    // Se diventa pinch → annulla
    if (e.touches.length >= 2) {
      touchState.isPinching = true;
      clearTimeout(touchState.longPressTimer);
      touchState.longPressTimer = null;
      return;
    }

    const t = e.touches[0];
    const dx = t.clientX - touchState.startX;
    const dy = t.clientY - touchState.startY;

    // Movimento eccessivo → annulla long press
    if (Math.hypot(dx, dy) > 12) {
      clearTimeout(touchState.longPressTimer);
      touchState.longPressTimer = null;
    }
  }, { passive: true });

  /* TOUCHEND ------------------------------------------------ */
  document.addEventListener('touchend', () => {
    clearTimeout(touchState.longPressTimer);
    touchState.longPressTimer = null;
    touchState.targetIcon = null;
    touchState.isPinching = false;
  }, { passive: true });

  /* ============================================================
     MOUSE (DESKTOP) — invariato
     ============================================================ */

  let rightPressTimer = null;
  let rightPressStart = { x: 0, y: 0 };
  let rightPressIcon = null;
  let rightPressActive = false;

  let lastRightClickTime = 0;
  let lastRightClickIconId = null;

  document.addEventListener('mousedown', e => {
    if (e.button !== 2) return;

    const icon = e.target.closest('.app-icon');
    if (!icon) return;

    e.preventDefault();

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

    rightPressTimer = setTimeout(() => {
      rightPressTimer = null;
      if (!state.editMode) enterEditMode();
      rightPressActive = false;
    }, 500);

    const now = performance.now();
    const sameIcon = lastRightClickIconId === icon.dataset.id;

    if (state.editMode && sameIcon && (now - lastRightClickTime) <= 380) {
      const r = icon.getBoundingClientRect();
      showContextMenuFor(icon.dataset.id, r.left + r.width / 2, r.top + r.height);
      lastRightClickTime = 0;
      lastRightClickIconId = null;
      if (rightPressTimer) clearTimeout(rightPressTimer);
      rightPressTimer = null;
      rightPressActive = false;
      return;
    }

    lastRightClickTime = now;
    lastRightClickIconId = icon.dataset.id;
  });

  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) > 12) {
      if (rightPressTimer) clearTimeout(rightPressTimer);
      rightPressTimer = null;
      rightPressActive = false;
      rightPressIcon = null;
    }
  });

  document.addEventListener('mouseup', e => {
    if (e.button === 2) {
      if (rightPressTimer) clearTimeout(rightPressTimer);
      rightPressTimer = null;
      rightPressActive = false;
      rightPressIcon = null;
    }
  });

  document.addEventListener('contextmenu', e => {
    const icon = e.target.closest('.app-icon');
    if (!icon) return;
    e.preventDefault();
  });
}

/* ============================================================
   CHIUSURA MENU E USCITA WIGGLE (DESKTOP + TOUCH)
   ============================================================ */

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();

    // NON uscire dal wiggle mode su touch (gestito dal long-press unificato)
    if (e.pointerType === 'touch') return;

    // Desktop: clic fuori → esci
    if (!isIcon && state.editMode) exitEditMode();
  });
}

