
// src/drag.js
import { state } from './state.js';
import { saveOrder } from './order.js';
import { renderApps } from './render.js';
import { hideContextMenu } from './contextmenu.js';

/** Ottieni posizione pointer/touch */
function getPointerPosition(e) {
  if (e.touches && e.touches.length > 0) {
    return {
      pageX: e.touches[0].pageX,
      pageY: e.touches[0].pageY,
      clientX: e.touches[0].clientX,
      clientY: e.touches[0].clientY,
    };
  }
  return {
    pageX: e.pageX,
    pageY: e.pageY,
    clientX: e.clientX,
    clientY: e.clientY,
  };
}

function startDrag(icon, pos) {
  const folderEl = document.getElementById('folder');
  state.draggingId = icon.dataset.id;

  const r = icon.getBoundingClientRect();
  state.dragOffsetX = pos.pageX - r.left;
  state.dragOffsetY = pos.pageY - r.top;

  state.draggingIcon = icon;
  state.draggingIcon.classList.add('dragging');

  // Posizionamento “float”
  Object.assign(state.draggingIcon.style, {
    position: 'fixed',
    left: `${r.left}px`,
    top: `${r.top}px`,
    width: `${r.width}px`,
    height: `${r.height}px`,
    zIndex: '1000',
    pointerEvents: 'none',
    transform: 'translate3d(0,0,0)',
  });

  // Placeholder
  state.placeholderEl = document.createElement('div');
  state.placeholderEl.className = 'app-icon placeholder';
  state.placeholderEl.style.visibility = 'hidden';
  folderEl.insertBefore(state.placeholderEl, icon);

  hideContextMenu();
}


function updateDragPosition(pos) {
  if (!state.draggingIcon || !state.placeholderEl) return;

  const x = pos.pageX - state.dragOffsetX;
  const y = pos.pageY - state.dragOffsetY;
  state.draggingIcon.style.left = `${x}px`;
  state.draggingIcon.style.top = `${y}px`;

  const centerX = pos.clientX;
  const centerY = pos.clientY;

  const elem = document.elementFromPoint(centerX, centerY);
  const targetIcon = elem && elem.closest('.app-icon:not(.dragging)');
  if (!targetIcon || targetIcon === state.placeholderEl) return;

  const folderEl = document.getElementById('folder');
  const targetRect = targetIcon.getBoundingClientRect();

  const isBefore = centerX < targetRect.left + targetRect.width / 2;

  // Evita inserimenti ridondanti
  const currentNext = state.placeholderEl.nextSibling;
  if (isBefore && currentNext === targetIcon) return;
  if (!isBefore && state.placeholderEl === targetIcon.nextSibling) return;

  folderEl.insertBefore(state.placeholderEl, isBefore ? targetIcon : targetIcon.nextSibling);
}



function endDrag(Storage) {
  if (!state.draggingIcon || !state.placeholderEl) return;

  const folderEl = document.getElementById('folder');
  const children = Array.from(folderEl.children).filter(el => el !== state.draggingIcon && el !== state.placeholderEl);
  const finalIndex = children.indexOf(state.placeholderEl.previousSibling) + 1;

  // Ripristina stile icona
  state.draggingIcon.classList.remove('dragging');
  Object.assign(state.draggingIcon.style, {
    position: '',
    left: '',
    top: '',
    width: '',
    height: '',
    zIndex: '',
    pointerEvents: '',
    transform: '',
  });

  // Aggiorna ordine
  const currentIndex = state.appsOrder.indexOf(state.draggingId);
  if (currentIndex !== -1 && currentIndex !== finalIndex) {
    state.appsOrder.splice(currentIndex, 1);
    state.appsOrder.splice(finalIndex, 0, state.draggingId);
    saveOrder(Storage);
  }

  // Rimuovi placeholder
  if (state.placeholderEl.parentNode) {
    state.placeholderEl.parentNode.removeChild(state.placeholderEl);
  }

  state.draggingIcon = null;
  state.placeholderEl = null;
  state.dragStartX = 0;
  state.dragStartY = 0;

  renderApps();
}


export function initDragHandlers(Storage) {
  // TOUCH
  document.addEventListener('touchstart', e => {
    if (!state.editMode) return;
    if (e.touches.length !== 1) return;
    if (state.contextMenuTargetId) return;

    const pos = getPointerPosition(e);
    const icon = e.touches[0].target.closest('.app-icon');
    if (!icon) return;

    state.dragStartX = pos.clientX;
    state.dragStartY = pos.clientY;
    state.draggingIcon = null;
    state.draggingId = null;
  }, { passive: true });

  document.addEventListener('touchmove', e => {
    if (!state.editMode) return;
    if (e.touches.length !== 1) return;

    const pos = getPointerPosition(e);

    if (!state.draggingIcon) {
      const dx = pos.clientX - state.dragStartX;
      const dy = pos.clientY - state.dragStartY;
      if (Math.hypot(dx, dy) > 10) {
        const icon = e.touches[0].target.closest('.app-icon');
        if (icon) {
          if (state.longPressTimer) {
            clearTimeout(state.longPressTimer);
            state.longPressTimer = null;
            state.longPressTarget = null;
          }
          startDrag(icon, pos);
        }
      }
    } else {
      updateDragPosition(pos);
      e.preventDefault();
    }
  }, { passive: false });

  document.addEventListener('touchend', e => {
    if (!state.editMode) return;
    if (!state.draggingIcon) {
      state.dragStartX = 0;
      state.dragStartY = 0;
      return;
    }
    if (!e.touches || e.touches.length === 0) {
      endDrag(Storage);
    }
  }, { passive: true });

  // MOUSE
  document.addEventListener('mousedown', e => {
    if (!state.editMode) return;
    if (e.button !== 0) return;
    if (state.contextMenuTargetId) return;

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

    const pos = getPointerPosition(e);
    state.dragStartX = pos.clientX;
    state.dragStartY = pos.clientY;
    state.draggingIcon = null;
    state.draggingId = null;
  });

  document.addEventListener('mousemove', e => {
    if (!state.editMode) return;

    const pos = getPointerPosition(e);

    if (!state.draggingIcon) {
      if (!state.dragStartX && !state.dragStartY) return;
      const dx = pos.clientX - state.dragStartX;
      const dy = pos.clientY - state.dragStartY;
      if (Math.hypot(dx, dy) > 10) {
        const icon = e.target.closest('.app-icon');
        if (icon) {
          if (state.longPressTimer) {
            clearTimeout(state.longPressTimer);
            state.longPressTimer = null;
            state.longPressTarget = null;
          }
          startDrag(icon, pos);
        }
      }
    } else {
      updateDragPosition(pos);
    }
  });

  document.addEventListener('mouseup', () => {
    if (!state.editMode) return;
    if (!state.draggingIcon) {
      state.dragStartX = 0;
      state.dragStartY = 0;
      return;
    }
    endDrag(Storage);
  });
}
