/**
 * Cast Conductor Proprietary License v5
 * SPDX-License-Identifier: LicenseRef-CastConductor-Proprietary-v5
 */
import { layoutSubset } from './util-hash.js';
import { ccveBus } from './event-bus.js';

let badgeEl = null;
let spinnerEl = null;

function baselineKey(contentBlockId){ return contentBlockId ? `ccve_baseline_${contentBlockId}` : null; }
function getBaseline(contentBlockId){ const key = baselineKey(contentBlockId); if(!key) return null; try { const raw=localStorage.getItem(key); return raw?JSON.parse(raw):null; } catch { return null; } }
function ensureBadge(){
  if (badgeEl && badgeEl.isConnected) return badgeEl;
  const controls = document.querySelector('#canvas-controls-panel');
  const saveBtn = document.getElementById('canvas-save-config') || document.getElementById('ccve-global-save');
  const host = saveBtn?.parentElement || controls || document.querySelector('.canvas-editor') || document.body;
  if (!host) return null;
  const el = document.createElement('div');
  el.className='ccve-preview-status-badge';
  Object.assign(el.style,{ display:'inline-flex', alignItems:'center', gap:'6px', marginLeft:'8px', padding:'2px 6px', fontSize:'11px', borderRadius:'4px', background:'rgba(34,139,34,0.65)', color:'#fff', fontFamily:'system-ui,sans-serif' });
  el.textContent='LIVE';
  if (saveBtn) { saveBtn.insertAdjacentElement('afterend', el); }
  else { host.appendChild(el); }
  badgeEl=el; return el;
}
function ensureSpinner(){
  if (spinnerEl && spinnerEl.isConnected) return spinnerEl;
  const controls = document.querySelector('#canvas-controls-panel');
  const saveBtn = document.getElementById('canvas-save-config') || document.getElementById('ccve-global-save');
  const host = controls || saveBtn?.parentElement || document.querySelector('.canvas-editor') || document.body;
  if (!host) return null;
  const el = document.createElement('div');
  el.className = 'ccve-preview-spinner';
  el.setAttribute('aria-live','polite');
  el.setAttribute('role','status');
  el.innerHTML = '<span class="ccve-spin-dot" style="display:inline-block;width:8px;height:8px;border-radius:50%;background:#64748b;animation:ccvePulse .9s infinite alternate ease-in-out;"></span><span style="opacity:.8">Updating…</span>';
  // Default styling: inline near Save button if available; otherwise anchored inside controls panel (non-overlay)
  if (saveBtn) {
    Object.assign(el.style, { display:'none', alignItems:'center', gap:'6px', fontSize:'12px', color:'#334155', marginLeft:'8px' });
    saveBtn.insertAdjacentElement('afterend', el);
  } else if (controls) {
    if (getComputedStyle(controls).position === 'static') { try { controls.style.position = 'relative'; } catch(_){} }
    Object.assign(el.style, { position:'absolute', top:'6px', left:'6px', display:'none', alignItems:'center', gap:'6px', fontSize:'12px', color:'#334155', zIndex:10 });
    controls.appendChild(el);
  } else {
    Object.assign(el.style, { display:'none', alignItems:'center', gap:'6px', fontSize:'12px', color:'#334155', margin:'6px' });
    host.appendChild(el);
  }
  try { if (!document.getElementById('ccve-spinner-style')) { const st=document.createElement('style'); st.id='ccve-spinner-style'; st.textContent='@keyframes ccvePulse{from{opacity:.35;transform:scale(.9)}to{opacity:1;transform:scale(1.1)}}'; document.head.appendChild(st); } } catch {}
  spinnerEl = el; return el;
}
function setState(state){ if(!badgeEl) return; badgeEl.classList.remove('stale','drift','error','live'); switch(state){ case 'STALE': badgeEl.textContent='STALE'; badgeEl.style.background='rgba(179,110,0,0.65)'; badgeEl.classList.add('stale'); break; case 'DRIFT': badgeEl.textContent='DRIFT'; badgeEl.style.background='rgba(178,34,34,0.75)'; badgeEl.classList.add('drift'); break; case 'ERROR': badgeEl.textContent='ERROR'; badgeEl.style.background='rgba(128,0,0,0.7)'; badgeEl.classList.add('error'); break; case 'LIVE': default: badgeEl.textContent='LIVE'; badgeEl.style.background='rgba(34,139,34,0.65)'; badgeEl.classList.add('live'); } }
function evaluateDrift(editor){ const base=getBaseline(editor?.currentContentBlockId); if(!base||!base.hash){ setState('LIVE'); return; } let current=''; try { current=JSON.stringify(layoutSubset(editor?.currentConfig)); } catch { current=''; } if(current && current!==base.hash) setState('DRIFT'); else setState('LIVE'); }
export function recaptureBaseline(editor){ const key=baselineKey(editor?.currentContentBlockId); if(!key) return; let current=''; try { current=JSON.stringify(layoutSubset(editor?.currentConfig)); } catch { current=''; } const meta={ hash: current, timestamp: new Date().toISOString() }; try { localStorage.setItem(key, JSON.stringify(meta)); } catch {} evaluateDrift(editor); }

export function initPreviewStatus(editor){
  if(!editor) return;
  const isAdmin = !!(window.castconductorCanvasAjax && Number(window.castconductorCanvasAjax.is_admin_user));
  if (isAdmin) {
    ensureBadge(); // render badge outside of visual editor
    ccveBus.on('preview:stale', ()=> setState('STALE'));
    ccveBus.on('preview:error', ()=> setState('ERROR'));
    ccveBus.on('preview:live', ()=> evaluateDrift(editor));
  } else {
    ensureSpinner();
    const show=()=>{ const el=ensureSpinner(); if (el) el.style.display='inline-flex'; };
    const hide=()=>{ if (spinnerEl) spinnerEl.style.display='none'; };
    ccveBus.on('preview:requested', show);
    ccveBus.on('preview:stale', show);
    ccveBus.on('preview:live', hide);
    ccveBus.on('preview:error', hide);
  }
}

// Expose on window for monolith delegation
if (typeof window !== 'undefined') {
  window.ccvePreviewStatus = { init: initPreviewStatus, recaptureBaseline: (id,cfg)=> recaptureBaseline(window.castconductorCanvasEditor || { currentContentBlockId:id, currentConfig: cfg }) };
}
