/**
 * Legacy Layer Interactions
 * Enable selection, drag/resize, and precision editing for transient legacy layers
 * (static-text, static-image) rendered by legacy-layer-hydration.
 *
 * Persistence model: writes to currentConfig.legacy_overrides[id] and updates
 * hydrated DOM via renderHydratedLegacyLayers(editor).
 */
import { renderHydratedLegacyLayers } from './legacy-layer-hydration.js';

export function attachLegacyLayerInteractions(editor){
  const stage = document.getElementById('block-stage');
  if(!stage) return;
  if(stage.__ccveLegacyDragBound) return; stage.__ccveLegacyDragBound = true;

  const getLayerById = (id)=>{
    const cfg = editor?.currentConfig; if(!cfg) return null;
    const arr = Array.isArray(cfg._hydratedLegacyLayers)? cfg._hydratedLegacyLayers : [];
    return arr.find(l=>l && l.id===id) || null;
  };
  const ensureOverrides = ()=>{ if(!editor.currentConfig) editor.currentConfig = editor.getDefaultConfig(); editor.currentConfig.legacy_overrides = editor.currentConfig.legacy_overrides || {}; return editor.currentConfig.legacy_overrides; };

  function _createResizeHandles(el){
    if(el.querySelector('.ccve-layer-handle')) return; // already added
    const dirs = ['nw','n','ne','e','se','s','sw','w'];
    dirs.forEach(dir=>{ const h=document.createElement('div'); h.className='ccve-layer-handle ccve-layer-h-'+dir; h.dataset.dir=dir; el.appendChild(h); });
  }

  function _ensureHandlesForSelection(target){
    stage.querySelectorAll('.ccve-legacy-layer').forEach(n=>{
      if(n===target){ n.classList.add('ccve-selected'); _createResizeHandles(n); }
      else { n.classList.remove('ccve-selected'); }
    });
  }

  let drag=null; // { id, kind, startX,startY, origX,origY,origW,origH, mode, dir, el }
  const snap=(v)=>{ try{ const s = editor.canvasSnap||8; return Math.round(v/s)*s; }catch(_){ return v; } };

  const onPointerDown=(e)=>{
    const node = e.target.closest('.ccve-legacy-layer'); if(!node) return;
    if(node.classList.contains('ccve-locked')) return; // respect lock from layers panel
    const id = node.getAttribute('data-layer-id'); if(!id) return;
    const layer = getLayerById(id); if(!layer) return;
    _ensureHandlesForSelection(node);
    const handle = e.target.closest('.ccve-layer-handle');
    // Resolve DOM rect fallback
    const domX = parseInt(node.style.left,10); const domY = parseInt(node.style.top,10);
    const rectX = Number.isFinite(domX) ? domX : (node.offsetLeft || 0);
    const rectY = Number.isFinite(domY) ? domY : (node.offsetTop || 0);
    const domW = parseInt(node.style.width,10); const domH = parseInt(node.style.height,10);
    const rectW = (Number.isFinite(domW) && domW>0) ? domW : (node.offsetWidth || layer.width || 40);
    const rectH = (Number.isFinite(domH) && domH>0) ? domH : (node.offsetHeight || layer.height || 40);
    if(!layer.width || layer.width<=0) layer.width = rectW;
    if(!layer.height || layer.height<=0) layer.height = rectH;
    if(!Number.isFinite(layer.x)) layer.x = rectX;
    if(!Number.isFinite(layer.y)) layer.y = rectY;
    drag = { id, kind:layer.kind, startX:e.clientX, startY:e.clientY, origX:layer.x||rectX, origY:layer.y||rectY, origW:layer.width||rectW, origH:layer.height||rectH, mode: handle?'resize':'move', dir: handle?handle.dataset.dir:null, el: node };
    document.addEventListener('mousemove', onPointerMove);
    document.addEventListener('mouseup', onPointerUp, { once:true });
    e.preventDefault();
  };

  function _applyMoveResize(clientX, clientY, shiftKey){
    if(!drag) return; const dx=clientX-drag.startX, dy=clientY-drag.startY;
    const bounds = (editor && editor.canvasBounds) ? editor.canvasBounds : { w:1280, h:720 };
    const snapEdgeThreshold = 16;
    let newX=drag.origX, newY=drag.origY, newW=drag.origW, newH=drag.origH;
    if(drag.mode==='move'){
      const curW = drag.origW||0; const curH = drag.origH||0;
      newX = snap(drag.origX + dx); newY = snap(drag.origY + dy);
      // Clamp to bounds
      newX = Math.max(0, Math.min(bounds.w - curW, newX));
      newY = Math.max(0, Math.min(bounds.h - curH, newY));
      // Edge snap
      if (Math.abs(newX) <= snapEdgeThreshold) newX = 0;
      if (Math.abs(bounds.w - (newX + curW)) <= snapEdgeThreshold) newX = bounds.w - curW;
      if (Math.abs(newY) <= snapEdgeThreshold) newY = 0;
      if (Math.abs(bounds.h - (newY + curH)) <= snapEdgeThreshold) newY = bounds.h - curH;
    } else {
      const dir=drag.dir||''; const aspect = drag.origW && drag.origH ? drag.origW/drag.origH : 1;
      if(/e/.test(dir)) newW = drag.origW + dx;
      if(/s/.test(dir)) newH = drag.origH + dy;
      if(/w/.test(dir)) { newW = drag.origW - dx; newX = drag.origX + dx; }
      if(/n/.test(dir)) { newH = drag.origH - dy; newY = drag.origY + dy; }
      newW = Math.max(20, newW); newH = Math.max(20, newH);
      if(drag.kind==='static-image' && !shiftKey){ // keep aspect by default for images
        if(/n|s/.test(dir) && !/e|w/.test(dir)) newW = Math.round(newH * aspect);
        else if(/e|w/.test(dir) && !/n|s/.test(dir)) newH = Math.round(newW / aspect);
        else newH = Math.round(newW / aspect);
        if(/w/.test(dir)) newX = drag.origX + (drag.origW - newW);
        if(/n/.test(dir)) newY = drag.origY + (drag.origH - newH);
      }
      // Clamp to bounds
      if (newX < 0) { newW += newX; newX = 0; }
      if (newY < 0) { newH += newY; newY = 0; }
      if (newX + newW > bounds.w) { newW = bounds.w - newX; }
      if (newY + newH > bounds.h) { newH = bounds.h - newY; }
      // Edge snapping
      if (Math.abs(newX) <= snapEdgeThreshold) { newW += newX; newX = 0; }
      if (Math.abs(bounds.w - (newX + newW)) <= snapEdgeThreshold) { newW = bounds.w - newX; }
      if (Math.abs(newY) <= snapEdgeThreshold) { newH += newY; newY = 0; }
      if (Math.abs(bounds.h - (newY + newH)) <= snapEdgeThreshold) { newH = bounds.h - newY; }
      // Grid snap last
      newX = snap(newX); newY = snap(newY); newW = snap(newW); newH = snap(newH);
    }
    // Update overrides and live DOM
    const ov = ensureOverrides(); ov[drag.id] = ov[drag.id] || {};
    ov[drag.id].x = newX; ov[drag.id].y = newY; ov[drag.id].width = newW; ov[drag.id].height = newH;
    drag.el.style.left = newX + 'px'; drag.el.style.top = newY + 'px'; drag.el.style.width = newW + 'px'; drag.el.style.height = newH + 'px';
  }

  const onPointerMove=(e)=>{ if(!drag) return; _applyMoveResize(e.clientX, e.clientY, e.shiftKey); };
  const onPointerUp=()=>{ if(drag){ editor.unsavedChanges = true; try{ renderHydratedLegacyLayers(editor); }catch(_){} drag=null; } document.removeEventListener('mousemove', onPointerMove); };

  function _openPrecisionDialog(layer){
    const existing = document.getElementById('ccve-legacy-precision'); if(existing) existing.remove();
    const ov = ensureOverrides(); const id = layer.id; const cur = { x:ov[id]?.x ?? layer.x, y:ov[id]?.y ?? layer.y, w:ov[id]?.width ?? layer.width, h:ov[id]?.height ?? layer.height };
    const dlg = document.createElement('div'); dlg.id='ccve-legacy-precision'; dlg.className='ccve-legacy-precision-dialog';
    dlg.innerHTML = `
      <div class="ccve-lp-inner">
        <h3>Layer Settings (${layer.kind.replace('static-','')})</h3>
        <label>X <input type="number" id="ccve-lp-x" value="${cur.x}" /></label>
        <label>Y <input type="number" id="ccve-lp-y" value="${cur.y}" /></label>
        <label>Width <input type="number" id="ccve-lp-w" value="${cur.w}" /></label>
        <label>Height <input type="number" id="ccve-lp-h" value="${cur.h}" /></label>
        ${layer.kind==='static-text' ? `<label>Text <textarea id="ccve-lp-text" rows="3">${(layer.text||'').replace(/</g,'&lt;')}</textarea></label>` : ''}
        ${layer.kind==='static-text' ? `<label>Font Size <input type="number" id="ccve-lp-font" value="${layer.style?.fontSize||24}" /></label>` : ''}
        ${layer.kind==='static-text' ? `<label>Color <input type="text" id="ccve-lp-color" value="${layer.style?.color||'#ffffff'}" /></label>` : ''}
        ${layer.kind==='static-image' ? `<label>Image URL <input type="text" id="ccve-lp-url" value="${layer.url||''}" /></label>` : ''}
        ${layer.kind==='static-image' ? `<label>Fit <select id="ccve-lp-fit"><option value="cover" ${layer.fit==='cover'?'selected':''}>cover</option><option value="contain" ${layer.fit==='contain'?'selected':''}>contain</option></select></label>` : ''}
        <div class="ccve-lp-actions"><button type="button" id="ccve-lp-apply">Apply</button><button type="button" id="ccve-lp-cancel">Cancel</button></div>
      </div>`;
    document.body.appendChild(dlg);
    const close=()=>dlg.remove();
    dlg.querySelector('#ccve-lp-cancel').addEventListener('click', close);
    dlg.querySelector('#ccve-lp-apply').addEventListener('click', ()=>{
      const x=parseInt(dlg.querySelector('#ccve-lp-x').value,10)||0;
      const y=parseInt(dlg.querySelector('#ccve-lp-y').value,10)||0;
      const w=Math.max(20, parseInt(dlg.querySelector('#ccve-lp-w').value,10)||layer.width);
      const h=Math.max(20, parseInt(dlg.querySelector('#ccve-lp-h').value,10)||layer.height);
      const overrides = ensureOverrides(); overrides[id] = overrides[id] || {}; overrides[id].x=x; overrides[id].y=y; overrides[id].width=w; overrides[id].height=h;
      if(layer.kind==='static-text'){
        const text = (dlg.querySelector('#ccve-lp-text').value||'').trim();
        const font = parseInt(dlg.querySelector('#ccve-lp-font').value,10)||24;
        const color = (dlg.querySelector('#ccve-lp-color').value||'#ffffff').trim();
        overrides[id].text = text; overrides[id].fontSize = font; overrides[id].color = color;
      } else if(layer.kind==='static-image') {
        const url = (dlg.querySelector('#ccve-lp-url').value||'').trim();
        const fit = (dlg.querySelector('#ccve-lp-fit').value||'cover').trim();
        overrides[id].url = url; overrides[id].fit = fit;
      }
      try { renderHydratedLegacyLayers(editor); } catch(_) {}
      editor.unsavedChanges = true; close();
    });
  }

  stage.addEventListener('mousedown', onPointerDown);
  stage.addEventListener('dblclick', (e)=>{ const node=e.target.closest('.ccve-legacy-layer'); if(!node) return; const id=node.getAttribute('data-layer-id'); const layer=getLayerById(id); if(!layer) return; _openPrecisionDialog(layer); });

  // Keyboard delete/duplicate are disabled for legacy to avoid accidental destructive ops; rely on visibility lock/order via panel.
}

export default { attachLegacyLayerInteractions };

// Inject minimal styles for legacy selection/handles/dialog (once)
(()=>{ if(document.getElementById('ccve-legacy-layer-style')) return; const s=document.createElement('style'); s.id='ccve-legacy-layer-style'; s.textContent=`
  .ccve-legacy-layer.ccve-selected { outline: 2px solid #38bdf8; }
  .ccve-layer-handle { position:absolute; width:10px; height:10px; background:#38bdf8; border-radius:2px; transform:translate(-50%,-50%); }
  .ccve-layer-h-nw { left:0%; top:0%; }
  .ccve-layer-h-n { left:50%; top:0%; }
  .ccve-layer-h-ne { left:100%; top:0%; }
  .ccve-layer-h-e { left:100%; top:50%; }
  .ccve-layer-h-se { left:100%; top:100%; }
  .ccve-layer-h-s { left:50%; top:100%; }
  .ccve-layer-h-sw { left:0%; top:100%; }
  .ccve-layer-h-w { left:0%; top:50%; }
  .ccve-legacy-precision-dialog { position:fixed; top:50%; left:50%; transform:translate(-50%,-50%); background:#1f2937; color:#fff; padding:16px; border:1px solid #334155; border-radius:8px; z-index:4001; width:340px; font:13px system-ui,sans-serif; }
  .ccve-legacy-precision-dialog h3 { margin:0 0 10px; font-size:14px; }
  .ccve-legacy-precision-dialog label { display:flex; flex-direction:column; gap:4px; margin:6px 0; font-weight:600; }
  .ccve-legacy-precision-dialog input, .ccve-legacy-precision-dialog textarea, .ccve-legacy-precision-dialog select { width:100%; background:#0b1220; border:1px solid #334155; color:#fff; padding:6px 8px; border-radius:4px; box-sizing:border-box; }
  .ccve-legacy-precision-dialog .ccve-lp-actions { display:flex; justify-content:flex-end; gap:8px; margin-top:12px; }
  .ccve-legacy-precision-dialog button { background:#2563eb; border:none; padding:6px 12px; color:#fff; cursor:pointer; border-radius:4px; font-weight:600; }
  .ccve-legacy-precision-dialog button#ccve-lp-cancel { background:#64748b; }
`; document.head.appendChild(s); })();
