/**
 * Token Image Layer Modal (Phase 5b)
 * Allows user to select which artwork token (track/sponsor/promo) to insert as an image layer.
 */
import { isValidToken } from './token-registry.js';

const ARTWORK_TOKENS = ['track.artwork','sponsor.artwork','promo.artwork'];

export function openTokenImageModal(editor){
  if (!editor || typeof editor.showModal!=='function') return;
  const html = `
  <style>
    .timimg-wrap { display:flex; flex-direction:column; gap:10px; font:12px system-ui,Arial; }
    .timimg-options { display:flex; gap:8px; }
    .timimg-options label { background:#1e293b; color:#fff; padding:6px 10px; border-radius:4px; cursor:pointer; display:flex; align-items:center; gap:6px; border:1px solid #334155; }
    .timimg-actions { display:flex; justify-content:space-between; align-items:center; margin-top:4px; }
    .timimg-insert { background:#2563eb; color:#fff; border:1px solid #1d4ed8; padding:6px 14px; border-radius:4px; cursor:pointer; font-weight:600; font-size:12px; }
    .timimg-cancel { background:#64748b; color:#fff; border:1px solid #475569; padding:6px 10px; border-radius:4px; cursor:pointer; font-size:12px; }
    .timimg-hint { font-size:11px; color:#94a3b8; }
  </style>
  <div class="timimg-wrap" id="ccve-token-image-modal">
    <div><strong>Select artwork token</strong></div>
    <div class="timimg-options" role="radiogroup">
      ${ARTWORK_TOKENS.map((t,i)=>`<label><input type=radio name=timimg-token value="${t}" ${i===0?'checked':''}/> ${t}</label>`).join('')}
    </div>
    <div class="timimg-hint">Image auto-updates via live data; branding artwork used as fallback when token empty.</div>
    <div class="timimg-actions">
      <button type=button class="timimg-cancel">Cancel</button>
      <button type=button class="timimg-insert">Insert Image Layer</button>
    </div>
  </div>`;
  editor.showModal('Insert Artwork Token Layer', html);
  const root = document.getElementById('ccve-token-image-modal');
  if (!root) return;
  root.querySelector('.timimg-cancel').addEventListener('click', ()=>editor.closeModal());
  root.querySelector('.timimg-insert').addEventListener('click', ()=>{
    const val = root.querySelector('input[name="timimg-token"]:checked')?.value;
    if (!val || !isValidToken(val)) return;
    try { editor.addTokenImageLayer(val); } catch(e){ console.warn('addTokenImageLayer failed', e); }
    editor.closeModal();
    try { editor.refreshLiveTokens(); } catch(_){}
  });
}

export default { openTokenImageModal };
