// Scenes Panel: Modal-based UI for editing scene background & branding
import { getActiveScene as apiGetActive, updateScene as apiUpdate, listScenes as apiList, getScene as apiGet, createScene as apiCreate, activateScene as apiActivate } from './scenes-api.js';

export function attachScenesPanel(editor) {
  if (editor.__scenesPanelAttached) return;
  editor.__scenesPanelAttached = true;

  editor.openScenesPanel = async function openScenesPanel(sceneId) {
    try {
      // Ensure modal system is available
      if (typeof editor.showModal !== 'function') {
        console.warn('[ScenesPanel] editor.showModal not present');
        return;
      }

      // Resolve scene id and load details for defaults
      let id = sceneId;
      if (!id) {
        const active = await apiGetActive();
        id = active && active.data && active.data.id;
      }
      if (!id) {
        alert('No active scene found.');
        return;
      }
      const sceneResp = await apiGet(id);
      const scene = (sceneResp && sceneResp.data) || {};

      const brandingObj = typeof scene.branding === 'string' ? JSON.parse(scene.branding || '{}') : (scene.branding || {});
      const brandingEnabled = brandingObj.enabled !== false; // Default to true if not set
      const brandingText = normalizeJsonText(scene.branding);
      const backgroundText = normalizeJsonText(scene.background);

      const html = `
        <div class="ccve-scenes-panel">
          <div class="ccve-field" style="margin-bottom:12px;padding:10px;background:#0d1526;border-radius:6px;border:1px solid #1f2a44;">
            <label style="display:flex;align-items:center;gap:8px;cursor:pointer;">
              <input type="checkbox" id="ccve-scenes-branding-enabled" ${brandingEnabled ? 'checked' : ''} style="width:18px;height:18px;cursor:pointer;" />
              <strong>Show Branding (Logo)</strong>
            </label>
            <div class="ccve-hint" style="margin-top:4px;margin-left:26px;">When disabled, the scene logo/branding will not be displayed. Use this if you prefer to add branding via a content block instead.</div>
          </div>
          <div class="ccve-field">
            <label><strong>Branding (JSON)</strong></label>
            <textarea id="ccve-scenes-branding" rows="8" style="width:100%;font-family:monospace;">${escapeHtml(brandingText)}</textarea>
            <div class="ccve-hint">Example: {"logoUrl":"https://...","tint":"#112233","opacity":0.9}</div>
          </div>
          <div class="ccve-field" style="margin-top:10px;">
            <label><strong>Background (JSON)</strong></label>
            <textarea id="ccve-scenes-background" rows="8" style="width:100%;font-family:monospace;">${escapeHtml(backgroundText)}</textarea>
            <div class="ccve-hint">Example: {"color":"#1e1e1e","gradient":true,"gradient_colors":["#1e3c72","#2a5298"],"gradient_direction":"135deg"}</div>
          </div>
          <div class="ccve-actions" style="margin-top:12px;display:flex;gap:8px;justify-content:flex-end;">
            <button type="button" class="button" id="ccve-scenes-cancel">Cancel</button>
            <button type="button" class="button button-primary" id="ccve-scenes-save">Save</button>
          </div>
          <div id="ccve-scenes-error" style="color:#b00020;margin-top:8px;display:none"></div>
        </div>`;

      editor.showModal('Scene: Background & Branding', html);

      const elBrandingEnabled = document.getElementById('ccve-scenes-branding-enabled');
      const elBranding = document.getElementById('ccve-scenes-branding');
      const elBackground = document.getElementById('ccve-scenes-background');
      const elError = document.getElementById('ccve-scenes-error');
      const btnSave = document.getElementById('ccve-scenes-save');
      const btnCancel = document.getElementById('ccve-scenes-cancel');

      const parseSafe = (txt) => {
        const t = (txt || '').trim();
        if (!t) return null; // treat empty as unchanged
        try { return JSON.parse(t); } catch(e) { return e; }
      };

      const showError = (msg) => { if (!elError) return; elError.textContent = msg || ''; elError.style.display = msg ? 'block' : 'none'; };

      btnCancel && (btnCancel.onclick = () => editor.closeModal());

      btnSave && (btnSave.onclick = async () => {
        showError('');
        const bObj = parseSafe(elBranding.value);
        if (bObj instanceof Error) { showError('Branding JSON is invalid: ' + bObj.message); return; }
        const bgObj = parseSafe(elBackground.value);
        if (bgObj instanceof Error) { showError('Background JSON is invalid: ' + bgObj.message); return; }

        const payload = {};
        // Always include branding to capture the enabled flag
        const brandingData = bObj || {};
        brandingData.enabled = elBrandingEnabled ? elBrandingEnabled.checked : true;
        payload.branding = brandingData;
        if (bgObj !== null) payload.background = bgObj;

        btnSave.disabled = true; btnSave.textContent = 'Saving…';
        try {
          await apiUpdate(id, payload);
          editor.closeModal();
          try { editor.renderActiveBackground && await editor.renderActiveBackground(); } catch(_) {}
          try { editor.generatePreview && await editor.generatePreview(); } catch(_) {}
          try { editor.showNotification && editor.showNotification('Scene updated','success'); } catch(_) {}
        } catch(e) {
          showError('Failed to save: ' + (e && e.message ? e.message : 'unknown error'));
        } finally {
          btnSave.disabled = false; btnSave.textContent = 'Save';
        }
      });
    } catch (e) {
      console.warn('[ScenesPanel] openScenesPanel failed', e);
    }
  };

  // Visual-first New Scene flow (keeps JSON as advanced)
  editor.openNewSceneModal = function openNewSceneModal() {
    try {
      const html = `
        <div class="ccve-new-scene" style="display:flex;flex-direction:column;gap:12px">
          <div class="ccve-field"><label><strong>Scene name</strong></label>
            <input id="ccve-newscene-name" type="text" placeholder="Default Scene" style="width:100%" />
          </div>
          <details id="ccve-newscene-branding" style="background:#0b1220;border:1px solid #1f2a44;padding:8px;border-radius:6px">
            <summary style="cursor:pointer">Branding (logo, tint, opacity)</summary>
            <div class="ccve-field" style="margin-top:8px">
              <label>Logo URL</label>
              <div style="display:flex;gap:8px;align-items:center">
                <input id="ccve-newscene-logo" type="url" placeholder="https://…/logo.png" style="flex:1"/>
                <button type="button" id="ccve-newscene-logo-media">Media…</button>
              </div>
            </div>
            <div class="ccve-field-grid" style="display:grid;grid-template-columns:1fr 1fr;gap:8px;margin-top:6px">
              <div><label>Tint</label><input id="ccve-newscene-tint" type="text" placeholder="#112233" /></div>
              <div><label>Opacity</label><input id="ccve-newscene-opacity" type="number" min="0" max="1" step="0.05" value="0.9" /></div>
            </div>
          </details>
          <details id="ccve-newscene-background" style="background:#0b1220;border:1px solid #1f2a44;padding:8px;border-radius:6px">
            <summary style="cursor:pointer">Background (color or static image)</summary>
            <div class="ccve-field" style="margin-top:8px">
              <label>Type</label>
              <select id="ccve-newscene-bg-type"><option value="color">Color</option><option value="static">Static Image</option></select>
            </div>
            <div class="ccve-field"><label>Color</label><input id="ccve-newscene-bg-color" type="text" placeholder="#000000" /></div>
            <div class="ccve-field">
              <label>Image URL</label>
              <div style="display:flex;gap:8px;align-items:center">
                <input id="ccve-newscene-bg-image" type="url" placeholder="https://…/image.jpg" style="flex:1"/>
                <button type="button" id="ccve-newscene-bg-media">Media…</button>
              </div>
            </div>
          </details>
          <details id="ccve-newscene-advanced" style="background:#0b1220;border:1px solid #1f2a44;padding:8px;border-radius:6px">
            <summary style="cursor:pointer">Advanced JSON</summary>
            <div style="display:grid;grid-template-columns:1fr 1fr;gap:8px;margin-top:8px">
              <div>
                <label><strong>Branding JSON</strong></label>
                <textarea id="ccve-newscene-branding-json" rows="6" style="width:100%;font-family:monospace">{}</textarea>
              </div>
              <div>
                <label><strong>Background JSON</strong></label>
                <textarea id="ccve-newscene-background-json" rows="6" style="width:100%;font-family:monospace">{}</textarea>
              </div>
            </div>
          </details>
          <div style="display:flex;justify-content:flex-end;gap:8px">
            <button type="button" id="ccve-newscene-cancel" class="button">Cancel</button>
            <button type="button" id="ccve-newscene-create" class="button button-primary">Create</button>
          </div>
          <div id="ccve-newscene-error" style="color:#b00020;display:none"></div>
        </div>`;
      editor.showModal('Create Scene', html);
      const $ = (id)=>document.getElementById(id);
      const showError=(m)=>{ const el=$('ccve-newscene-error'); if(el){ el.textContent=m||''; el.style.display=m?'block':'none'; } };
      const bindMedia=(btnId, inputId)=>{
        const btn=$(btnId), input=$(inputId);
        if(!btn||!input||btn.__ccveBound) return; btn.__ccveBound=true;
        btn.addEventListener('click', (e)=>{
          e.preventDefault(); try{
            if(window.wp && window.wp.media){
              const frame = window.wp.media({ title:'Select image', button:{ text:'Use this image' }, multiple:false });
              frame.on('select', function(){ const a=frame.state().get('selection').first().toJSON(); input.value = a.url || ''; });
              frame.open();
            }
          } catch(_){}
        });
      };
      bindMedia('ccve-newscene-logo-media','ccve-newscene-logo');
      bindMedia('ccve-newscene-bg-media','ccve-newscene-bg-image');

      $('ccve-newscene-cancel')?.addEventListener('click', ()=> editor.closeModal());
      $('ccve-newscene-create')?.addEventListener('click', async ()=>{
        const btn=$('ccve-newscene-create'); if(btn){ btn.disabled=true; btn.textContent='Creating…'; }
        try {
          showError('');
          const name = ($('ccve-newscene-name')?.value||'').trim() || 'Default Scene';
          // Build objects from visual fields, then allow Advanced overrides when valid
          const branding = {};
          const logo=($('ccve-newscene-logo')?.value||'').trim(); if(logo) branding.logoUrl = logo;
          const tint=($('ccve-newscene-tint')?.value||'').trim(); if(tint) branding.tint = tint;
          const opRaw=$('ccve-newscene-opacity')?.value; const op=parseFloat(opRaw); if(Number.isFinite(op)) branding.opacity=op;
          const background = {};
          const bgType=$('ccve-newscene-bg-type')?.value||'color'; background.type=bgType;
          const bgColor=($('ccve-newscene-bg-color')?.value||'').trim(); if(bgColor) background.color = bgColor;
          const bgImg=($('ccve-newscene-bg-image')?.value||'').trim(); if(bgImg) background.image_url = bgImg;
          // Advanced JSON (optional overrides)
          const parseMaybe=(txt)=>{ const t=(txt||'').trim(); if(!t) return null; try{ return JSON.parse(t); } catch(e){ return e; } };
          const bJson = parseMaybe($('ccve-newscene-branding-json')?.value);
          if (bJson instanceof Error) { showError('Branding JSON invalid: '+bJson.message); return; }
          const bgJson = parseMaybe($('ccve-newscene-background-json')?.value);
          if (bgJson instanceof Error) { showError('Background JSON invalid: '+bgJson.message); return; }
          const payload = { name, description:'', rotation_enabled:false, rotation_interval:60, branding: Object.assign(branding, bJson||{}), background: Object.assign(background, bgJson||{}), metadata:{} };
          const res = await apiCreate(payload);
          console.log('[ScenesPanel] apiCreate response:', res);
          if (!(res && res.success)) {
            console.warn('[ScenesPanel] createScene returned unexpected response', res);
            // Show more detailed error message
            let errorMsg = 'Failed to create scene';
            if (res && res.error) {
              errorMsg += ': ' + res.error;
            } else if (res && res.message) {
              errorMsg += ': ' + res.message;
            } else if (res && res.httpStatus) {
              errorMsg += ` (HTTP ${res.httpStatus})`;
            } else {
              errorMsg += ' (unexpected response)';
            }
            showError(errorMsg);
            return;
          }
          const id = res.data && (res.data.id || res.data);
          if (!id) {
            showError('Failed to create scene (no id returned)');
            return;
          }
          try { await apiActivate(id); } catch(eAct){ console.warn('[ScenesPanel] activateScene failed', eAct); }
          editor.closeModal();
          // Rebuild toolbar (refresh scenes list + active marker)
          try { editor.initScenesToolbar && await editor.initScenesToolbar(); } catch(eInit){ console.warn('[ScenesPanel] initScenesToolbar after create failed', eInit); }
          // Attempt to ensure the select shows the new active scene without another user interaction
          try {
            const sel = document.getElementById('ccve-scene-select');
            if (sel) { sel.querySelectorAll('option').forEach(o=>{ o.selected = (parseInt(o.value,10)===parseInt(id,10)); }); }
          } catch(_){ }
          // Visual refresh
          try { editor.renderActiveBackground && await editor.renderActiveBackground(); } catch(eBg){ console.warn('[ScenesPanel] renderActiveBackground failed', eBg); }
          try { editor.generatePreview && await editor.generatePreview(); } catch(ePrev){ console.warn('[ScenesPanel] generatePreview failed', ePrev); }
          try { editor.showNotification && editor.showNotification('Scene created','success'); } catch(_) {}
        } catch(e){ showError(e && e.message ? e.message : 'Create failed'); }
        finally { if(btn){ btn.disabled=false; btn.textContent='Create'; } }
      });
    } catch(e) { console.warn('[ScenesPanel] openNewSceneModal failed', e); }
  };
}

function normalizeJsonText(val) {
  if (!val) return '{}';
  // Accept objects, JSON strings, or empty
  if (typeof val === 'string') {
    try { const obj = JSON.parse(val); return JSON.stringify(obj, null, 2); } catch(_) { return val; }
  }
  try { return JSON.stringify(val, null, 2); } catch(_) { return '{}'; }
}

function escapeHtml(s) {
  return String(s || '')
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/"/g, '&quot;')
    .replace(/'/g, '&#039;');
}
