/**
 * Token Export Modal (Phase 6 initial)
 * Provides combined + per-block (current block) JSON exports of token-driven layers.
 */

function buildLayerSummaries(config){
  if(!config || !Array.isArray(config.layers)) return [];
  return config.layers.filter(l=>l && (l.kind==='token-text' || l.kind==='token-image'))
    .map(l=>{
      if(l.kind==='token-text') return { kind:'token-text', template:l.templateText };
      if(l.kind==='token-image') return { kind:'token-image', token:l.token };
      return null;
    }).filter(Boolean);
}

export function openTokenExportModal(editor){
  if(!editor || typeof editor.showModal!=='function') return;
  const blockId = editor.currentContentBlockId || null;
  const layers = buildLayerSummaries(editor.currentConfig||{});
  const perBlock = { content_block_id:blockId, layers };
  const combined = { layers };
  const perBlockJson = JSON.stringify(perBlock, null, 2);
  const combinedJson = JSON.stringify(combined, null, 2);
  const html = `
  <style>
    .timexp-wrap { display:flex; flex-direction:column; gap:10px; font:12px system-ui,Arial; }
    .timexp-code { width:100%; min-height:140px; font:11px/1.4 monospace; padding:6px; resize:vertical; background:#0f172a; color:#e2e8f0; border:1px solid #334155; }
    .timexp-actions { display:flex; justify-content:flex-end; gap:8px; }
    .timexp-close { background:#64748b; color:#fff; border:1px solid #475569; padding:6px 12px; border-radius:4px; cursor:pointer; font-size:12px; }
    .timexp-hint { font-size:11px; color:#94a3b8; }
  </style>
  <div class="timexp-wrap" id="ccve-token-export-modal">
    <div><strong>Combined Layers JSON</strong></div>
    <textarea readonly class="timexp-code" id="timexp-combined">${combinedJson}</textarea>
    <div><strong>Per-Block JSON</strong> <span class="timexp-hint">Includes current content_block_id</span></div>
    <textarea readonly class="timexp-code" id="timexp-perblock">${perBlockJson}</textarea>
    <div class="timexp-hint">Copy & integrate into activation wizard defaults. Only token layers shown.</div>
    <div class="timexp-actions"><button type=button class="timexp-close">Close</button></div>
  </div>`;
  editor.showModal('Export Token Layers', html);
  const root = document.getElementById('ccve-token-export-modal');
  if(!root) return;
  root.querySelector('.timexp-close').addEventListener('click', ()=>editor.closeModal());
}

export default { openTokenExportModal };
