/**
 * Legacy Layer Hydration (Sep 18 2025)
 * Transient in-memory mapping of pre-token legacy visual_config/background/artwork data
 * into normalized editable layer objects so they can participate in selection,
 * panel ordering, visibility, and export – without mutating persisted schema.
 *
 * Kinds Introduced (in-memory only):
 *  - static-text: Derived from legacy typography + inferred geometry (single block text)
 *  - static-image: Derived from legacy artwork primary item/fallback
 *  - background: Pseudo-layer representing background config (color/image/gradient)
 *
 * Contract:
 *  - Input: currentConfig (may lack .layers or .layers only contain token-* kinds)
 *  - Output: augmented array currentConfig._hydratedLegacyLayers (not persisted) and
 *            merged virtual layer list via getAllRenderableLayers(editor)
 *  - No DB writes; save augmentation still only persists token_layers side-channel.
 */

export function hydrateLegacyLayers(editor){
  try {
    if(!editor || !editor.currentConfig) return;
    const cfg = editor.currentConfig;
    if(cfg.__legacyHydrated) return; // idempotent
    cfg.__legacyHydrated = true;
    const hydrated = [];
    // Background layers: Expose individual layers from config.background.layers (overlay, image, gradient)
    // This allows users to control transparency, delete, and reorder background elements
    if(cfg.background && Array.isArray(cfg.background.layers)){
      cfg.background.layers.forEach((layer, idx) => {
        if (!layer || !layer.kind) return;
        const layerId = `bg_layer_${layer.kind}_${idx}`;
        const label = layer.kind === 'overlay' ? 'Overlay' : 
                     layer.kind === 'image' ? 'Background Image' : 
                     layer.kind === 'gradient' ? 'Gradient' : 
                     'Background';
        hydrated.push({
          id: layerId,
          kind: layer.kind, // 'overlay', 'image', or 'gradient'
          label: label,
          config: { ...layer },
          x:0, y:0, width:1280, height:720, 
          visible: layer.enabled !== false, 
          lock: false,
          _pseudo: false, // Changed from true - these are real configurable layers
          _backgroundLayerIndex: idx // Track which background layer this represents
        });
      });
    } else if(cfg.background && !cfg.background.layers){
      // Legacy fallback: if background exists but has no layers array, create a pseudo layer
      hydrated.push({
        id: 'bg_layer',
        kind: 'background',
        label: 'Background',
        config: { ...cfg.background },
        x:0,y:0,width:1280,height:720,visible:true,lock:false,_pseudo:true
      });
    }
    // Transient legacy text — create logical layer when typography exists; skip DOM render if text empty
    try {
      if (cfg.typography || cfg.sample_text) {
        const ty = cfg.typography || {};
        const layout = cfg.layout || {};
        const pad = layout.padding || { top:0,right:60,bottom:10,left:60 };
        const pos = layout.position || { x:0, y:480 };
        const w = Math.max(200, layout.width || 1280);
        const h = Math.max(60, layout.height || 240);
        const id = 'legacy_text';
        const color = ty.color || '#ffffff';
        const fontSize = ty.font_size || 24;
        const fontFamily = ty.font_family || 'system-ui,Arial,Helvetica,sans-serif';
        const fontWeight = ty.font_weight || '400';
        const textAlign = ty.text_align || 'left';
        hydrated.push({
          id,
          kind: 'static-text',
          label: 'Text',
          x: (pos.x||0) + (pad.left||0),
          y: (pos.y||0) + (pad.top||0),
          width: Math.max(200, w - (pad.left||0) - (pad.right||0)),
          height: Math.max(40, h - (pad.top||0) - (pad.bottom||0)),
          visible: true,
          lock: false,
          style: { color, fontSize, fontFamily, fontWeight, textAlign, lineHeight: ty.line_height || 1.2, shadow: ty.text_shadow || null },
          text: String(cfg.sample_text || '')
        });
      }
    } catch(_) {}
    // Transient legacy image from artwork settings
    try {
      // Support both new cfg.artwork and legacy cfg.album_artwork + layout.album_art_position
      const aw = cfg.artwork || cfg.album_artwork || {};
      const layout = cfg.layout || {};
      let primary = '';
      const items = Array.isArray(aw.items)? aw.items : [];
      if(items && items[0] && (items[0].url||items[0].src)) primary = items[0].url||items[0].src;
      primary = primary || aw.fallback_url || '';
      const enabled = (aw.enabled===true) || (layout.show_album_art===true);
      if (enabled) {
        const id = 'legacy_image';
        const pos = layout.album_art_position || layout.position || { x:60, y:740 };
        const width = (aw.size && Number.isFinite(aw.size.width)) ? aw.size.width : (Number.isFinite(layout.album_art_size) ? layout.album_art_size : 150);
        const height = (aw.size && Number.isFinite(aw.size.height)) ? aw.size.height : (Number.isFinite(layout.album_art_size) ? layout.album_art_size : 150);
        hydrated.push({
          id,
          kind: 'static-image',
          label: 'Image',
          x: pos.x||60,
          y: pos.y||560,
          width: width,
          height: height,
          visible: true,
          lock: false,
          url: primary,
          fit: aw.fit || 'cover',
          borderRadius: aw.border_radius || 8
        });
      }
    } catch(_) {}
    cfg._hydratedLegacyLayers = hydrated;
  } catch(e){ console.warn('[CCVE][hydrate] failed', e); }
}

/** Sync background layers from cfg.background.layers to _hydratedLegacyLayers.
 *  Call this whenever background layers are added/removed/reordered via the Background tab. */
export function syncBackgroundLayersToHydrated(editor){
  try {
    if(!editor || !editor.currentConfig) return;
    const cfg = editor.currentConfig;
    if(!Array.isArray(cfg._hydratedLegacyLayers)) cfg._hydratedLegacyLayers = [];
    
    // Remove existing background-related entries from _hydratedLegacyLayers
    cfg._hydratedLegacyLayers = cfg._hydratedLegacyLayers.filter(l => {
      // Keep non-background layers (static-text, static-image, etc.)
      return l.kind !== 'overlay' && l.kind !== 'image' && l.kind !== 'gradient' && l.kind !== 'background' && l.kind !== 'color';
    });
    
    // Re-add background layers from current cfg.background.layers
    if(cfg.background && Array.isArray(cfg.background.layers)){
      cfg.background.layers.forEach((layer, idx) => {
        if (!layer || !layer.kind) return;
        const layerId = layer._id || `bg_layer_${layer.kind}_${idx}`;
        const label = layer.kind === 'overlay' ? 'Overlay' : 
                     layer.kind === 'image' ? 'Background Image' : 
                     layer.kind === 'gradient' ? 'Gradient' :
                     layer.kind === 'color' ? 'Background Color' : 
                     'Background';
        cfg._hydratedLegacyLayers.unshift({ // unshift to put bg layers at bottom of list
          id: layerId,
          kind: layer.kind,
          label: label,
          config: { ...layer },
          x:0, y:0, width:1280, height:720, 
          visible: layer.enabled !== false, 
          lock: false,
          _pseudo: false,
          _backgroundLayerIndex: idx
        });
      });
    }
    console.log('[CCVE][syncBackgroundLayers] Synced', cfg._hydratedLegacyLayers.filter(l => ['overlay','image','gradient','color'].includes(l.kind)).length, 'background layers');
  } catch(e){ console.warn('[CCVE][syncBackgroundLayers] failed', e); }
}

/** Return combined list of layers for panel & selection (DOM-managed ones + hydrated). */
export function getAllRenderableLayers(editor){
  const cfg = editor?.currentConfig; if(!cfg) return [];
  const base = Array.isArray(cfg.layers)? cfg.layers.slice(): [];
  const legacy = Array.isArray(cfg._hydratedLegacyLayers)? cfg._hydratedLegacyLayers.slice(): [];
  const ov = cfg.legacy_overrides || {};
  const legacyFiltered = legacy.filter(l=> !(ov[l.id]?.converted===true) && !(ov[l.id]?.deleted===true));
  return [...legacyFiltered, ...base];
}

/** Simple DOM rendering for hydrated legacy layers (static-text/image) */
export function renderHydratedLegacyLayers(editor){
  try {
    const cfg = editor?.currentConfig; if(!cfg) return;
    const stage = document.querySelector('#block-stage'); if(!stage) return;
    const layers = Array.isArray(cfg._hydratedLegacyLayers)? cfg._hydratedLegacyLayers : [];
    // Policy: do not render legacy static layers; background is still handled elsewhere
    const layersToRender = layers.filter(l => l && l.kind !== 'static-text' && l.kind !== 'static-image');
    const hasAnyTokenText = (cfg.layers||[]).some(l=>l && l.kind==='token-text');
    const ov = cfg.legacy_overrides || {};
    const tokenIds = new Set((cfg.layers||[]).filter(l=>l && (l.kind==='token-text'||l.kind==='token-image')).map(l=>l.id));
    // Clean previous renders
    stage.querySelectorAll('.ccve-legacy-layer').forEach(n=>n.remove());
    for (const l of layersToRender) {
      if (ov[l.id]?.converted===true) continue; // skip converted
      if (ov[l.id]?.deleted===true) continue;   // skip deleted via override
      // Self-heal: if a token layer exists with the same id, hide legacy DOM to avoid duplicates
      if (tokenIds.has(l.id)) continue;
      // If any token-text layer exists in the block, do not render legacy static-text to avoid phantom overlays
      if (hasAnyTokenText && l.kind === 'static-text') continue;
      if (l.kind === 'background') continue; // managed by stage background renderer
      const o = ov[l.id] || {};
      const x = isFinite(o.x)? o.x : l.x;
      const y = isFinite(o.y)? o.y : l.y;
      const w = isFinite(o.width)? o.width : l.width;
      const h = isFinite(o.height)? o.height : l.height;
      if (l.kind === 'static-text') {
        const textVal = (o.text!=null? o.text : (l.text || ''));
        if (!String(textVal).trim()) continue; // skip DOM render when there is no text
        const n = document.createElement('div');
        n.className = 'ccve-legacy-layer ccve-legacy-text';
        n.setAttribute('data-layer-id', l.id);
        Object.assign(n.style, {
          position:'absolute', left:x+'px', top:y+'px', width:w+'px', height:h+'px',
          color: (o.color || l.style?.color || '#fff'), fontSize:((o.fontSize || l.style?.fontSize || 24))+'px', fontFamily:l.style?.fontFamily||'system-ui,Arial,Helvetica,sans-serif', fontWeight: l.style?.fontWeight||'400',
          textAlign: l.style?.textAlign||'left', lineHeight: (l.style?.lineHeight||1.2),
          overflow:'hidden', whiteSpace:'nowrap', textOverflow:'ellipsis', pointerEvents:'auto'
        });
        n.textContent = String(textVal);
        stage.appendChild(n);
      } else if (l.kind === 'static-image') {
        const urlVal = (ov[l.id]?.url || l.url || '');
        if (!String(urlVal).trim()) continue; // skip DOM render when no URL
        const n = document.createElement('div');
        n.className = 'ccve-legacy-layer ccve-legacy-image';
        n.setAttribute('data-layer-id', l.id);
        Object.assign(n.style, { position:'absolute', left:x+'px', top:y+'px', width:w+'px', height:h+'px', overflow:'hidden', borderRadius:(l.borderRadius||0)+'px', pointerEvents:'auto' });
        const img = document.createElement('img'); img.alt=''; img.src = urlVal; Object.assign(img.style, { width:'100%', height:'100%', objectFit: (ov[l.id]?.fit || l.fit || 'cover'), display:'block' });
        n.appendChild(img);
        stage.appendChild(n);
      }
    }
  } catch(e){ console.warn('[CCVE][legacy-render] failed', e); }
}

/** Panel row descriptor builder for unified listing */
export function buildUnifiedLayerRows(editor){
  const all = getAllRenderableLayers(editor);
  // Hide legacy items that collide by id with existing token layers
  const tokenIds = new Set((editor?.currentConfig?.layers||[]).filter(l=>l && (l.kind==='token-text'||l.kind==='token-image')).map(l=>l.id));
  return all.map(l=>({
    id: l.id,
    kind: l.kind,
    label: l.label || l.name || (l.kind==='background'?'Background': l.kind.replace('token-','').replace('static-','').replace('-image','').replace('-text','') + ' layer'),
    // All unified layer kinds are editable (8 core types + legacy/background)
    canEdit: (
      l.kind==='token-text' || l.kind==='token-image' || 
      l.kind==='static-text' || l.kind==='static-image' || 
      l.kind==='slideshow-image' || l.kind==='background-image' ||
      l.kind==='qr-image' || l.kind==='wordpress-post' ||
      l.kind==='background' || l.kind==='overlay' || l.kind==='image' || l.kind==='gradient'
    ),
    isPseudo: !!l._pseudo,
    hiddenByToken: tokenIds.has(l.id) && (l.kind==='static-text' || l.kind==='static-image'),
    _backgroundLayerIndex: l._backgroundLayerIndex // Pass through for delete handler
  }));
}

// Lightweight CSS (only once)
(()=>{ if(document.getElementById('ccve-legacy-hydration-style')) return; const s=document.createElement('style'); s.id='ccve-legacy-hydration-style'; s.textContent=`
  .ccve-legacy-layer{ pointer-events:auto; }
  .ccve-legacy-layer.hidden{ display:none !important; }
  .ccve-legacy-layer.ccve-locked{ outline:1px dashed #555; cursor:not-allowed; }
  .ccve-legacy-text{ text-shadow:0 0 0 transparent; }
  .ccve-legacy-image img{ user-select:none; -webkit-user-drag:none; }
`; document.head.appendChild(s); })();
