/**
 * Cast Conductor Proprietary License v5
 * SPDX-License-Identifier: LicenseRef-CastConductor-Proprietary-v5
 *
 * Copyright (c) 2025 CastConductor.com. All Rights Reserved.
 *
 * This file is part of Cast Conductor ("Software"). The Software and its source
 * code constitute proprietary, confidential, and trade secret information of
 * CastConductor.com ("Company"). Any access or use is governed strictly by the
 * Cast Conductor Proprietary License v5 ("License"). By installing, copying,
 * accessing, compiling, or otherwise using the Software you agree to be bound by
 * all terms of the License. If you do not agree, you must cease use immediately.
 *
 * Key Terms (Summary – see full License for binding terms):
 *  1. No Redistribution: You may not publish, distribute, sublicense, rent,
 *     lease, transfer, sell, or otherwise make the Software (or any derivative)
 *     available to any third party without prior written consent of Company.
 *  2. No Modification: Modification, reverse engineering, decompilation, or
 *     disassembly is prohibited except to the limited extent expressly permitted
 *     by applicable law that cannot be contractually waived.
 *  3. Confidentiality: Treat all source code and related artifacts as Company
 *     Confidential Information. Maintain at least the same degree of care as for
 *     your own confidential materials, and not less than reasonable care.
 *  4. No Patent License: No express or implied patent rights are granted. Future
 *     patents (if any) are fully reserved.
 *  5. No Trademark License: Company names, marks, and logos may not be used
 *     without prior written permission.
 *  6. Limited Internal Use: Use is limited solely to internal evaluation and
 *     operation of licensed Cast Conductor deployments. Commercial hosting or
 *     resale as a service requires a separate written agreement.
 *  7. Telemetry & License Validation: The Software may periodically transmit a
 *     hashed installation identifier, domain (or site ID), plugin/app version,
 *     and a truncated (non-reversible) fragment of the license key solely to
 *     validate activation status and enforce licensing. This minimal "phone home"
 *     check contains no personal or content data. If optional telemetry is later
 *     introduced it will be limited to aggregate operational metrics (no PII),
 *     fully documented, and optionally disableable per published instructions.
 *  8. Third-Party Components: The Software may include open source components
 *     covered by their own licenses. See THIRD-PARTY-NOTICES.md. Those licenses
 *     govern their respective components; this License governs all remaining code.
 *  9. Export Compliance: You are responsible for compliance with all applicable
 *     export control and sanctions laws.
 * 10. Warranty Disclaimer: THE SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF
 *     ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO MERCHANTABILITY,
 *     FITNESS FOR A PARTICULAR PURPOSE, TITLE, AND NON-INFRINGEMENT.
 * 11. Limitation of Liability: IN NO EVENT WILL COMPANY OR AUTHORS BE LIABLE FOR
 *     ANY INDIRECT, SPECIAL, INCIDENTAL, CONSEQUENTIAL, EXEMPLARY, OR PUNITIVE
 *     DAMAGES, OR LOST PROFITS, EVEN IF ADVISED OF THE POSSIBILITY.
 * 12. Acceptance: Use of the Software constitutes acceptance of the License.
 * 13. Enforcement: Unauthorized reproduction or distribution may result in civil
 *     and criminal penalties and will be prosecuted to the maximum extent allowed
 *     by law.
 *
 * Authoritative EULA: EULA-v5.1.md (repository root – private) and https://castconductor.com/eula
 * Precedence: If this summary conflicts with the EULA, the EULA governs.
 * Revision: Current EULA revision v5.1 (subject to update; check EULA for current enterprise thresholds).
 *
 * Full License text available from: licensing@castconductor.com
 * Security reports: security@castconductor.com
 * Commercial inquiries: licensing@castconductor.com
 *
 * END OF HEADER
 *
 * artwork-slideshow.js
 * Client-side management for multi-image artwork (slideshow) with optimistic preview.
 * 
 * ⚠️ DEPRECATED (Phase 1 Step 6 - Nov 24, 2025) ⚠️
 * 
 * This module managed the legacy config.artwork.items[] system.
 * It has been REPLACED by the unified slideshow-image layer kind.
 * 
 * Migration:
 * - Old: config.artwork.items[] array (separate from layers)
 * - New: slideshow-image layer in config.layers[]
 * - Migration: slideshow-migration.js handles automatic conversion
 * 
 * Status:
 * - attachArtworkSlideshow() no longer called in canvas-editor.js
 * - File kept for reference and potential rollback needs
 * - DO NOT USE for new implementations
 * - All slideshow functionality now via unified layer system
 * 
 * See:
 * - slideshow-migration.js - Migration utilities
 * - unified-layer-renderer.js - Renders slideshow layers
 * - add-layer-ui.js - UI for adding slideshow layers
 * - layer-constants.js - LAYER_KIND_SLIDESHOW_IMAGE definition
 */

export function attachArtworkSlideshow(editor) {
  if (editor.__artworkSlideshowAttached) return; editor.__artworkSlideshowAttached = true;

  editor.addArtworkItems = function addArtworkItems(items) {
    if (!this.currentConfig) this.currentConfig = this.getDefaultConfig();
    if (!this.currentConfig.artwork) this.currentConfig.artwork = { enabled:true, items:[] };
    if (!Array.isArray(this.currentConfig.artwork.items)) this.currentConfig.artwork.items = [];
    // Merge new items (avoid duplicate attachment_id + src pairs)
    items.forEach(it => {
      if (!it || !it.src) return;
      const exists = this.currentConfig.artwork.items.some(e => e.src === it.src || (it.attachment_id && e.attachment_id === it.attachment_id));
      if (!exists) this.currentConfig.artwork.items.push({
        attachment_id: it.attachment_id || 0,
        src: it.src,
        alt: it.alt || '',
        mime: it.mime || '',
        width: it.width || 0,
        height: it.height || 0
      });
    });
    if (typeof this.currentConfig.artwork.activeIndex !== 'number') this.currentConfig.artwork.activeIndex = 0;
    this.markUnsaved();
    this.triggerPreview(); // immediate to reflect new image
  };

  editor.removeArtworkItem = function removeArtworkItem(index) {
    if (!this.currentConfig?.artwork?.items) return;
    this.currentConfig.artwork.items.splice(index,1);
    if (this.currentConfig.artwork.activeIndex >= this.currentConfig.artwork.items.length) {
      this.currentConfig.artwork.activeIndex = 0;
    }
    this.markUnsaved();
    this.triggerPreview();
  };

  editor.setActiveArtworkIndex = function setActiveArtworkIndex(idx) {
    if (!this.currentConfig?.artwork?.items) return;
    if (idx < 0 || idx >= this.currentConfig.artwork.items.length) return;
    this.currentConfig.artwork.activeIndex = idx;
    this.markUnsaved();
    this.triggerPreview();
  };

  editor.configureSlideshow = function configureSlideshow({ enabled, interval, transition }) {
    if (!this.currentConfig) this.currentConfig = this.getDefaultConfig();
    if (!this.currentConfig.artwork) this.currentConfig.artwork = {};
    if (!this.currentConfig.artwork.slideshow) this.currentConfig.artwork.slideshow = { enabled:false, interval:5000, transition:'fade' };
    if (typeof enabled === 'boolean') this.currentConfig.artwork.slideshow.enabled = enabled;
    if (interval) this.currentConfig.artwork.slideshow.interval = Math.max(500, parseInt(interval));
    if (transition) this.currentConfig.artwork.slideshow.transition = transition;
    this.markUnsaved();
    this.triggerPreview();
  };

  // Auto-advance client-side (purely visual) – restart timer on each preview apply
  function scheduleAdvance() {
    if (!editor.currentConfig?.artwork?.slideshow?.enabled) return;
    const interval = editor.currentConfig.artwork.slideshow.interval || 5000;
    clearTimeout(editor._artworkAdvanceTimer);
    editor._artworkAdvanceTimer = setTimeout(()=>{
      const items = editor.currentConfig.artwork.items || [];
      if (items.length <= 1) return;
      let next = (editor.currentConfig.artwork.activeIndex + 1) % items.length;
      editor.currentConfig.artwork.activeIndex = next;
      // Optimistic DOM swap (no server round-trip): swap active class
      try {
        const cont = editor.previewContainer?.querySelector('.artwork-container');
        if (cont) {
          cont.querySelectorAll('img').forEach((img,i)=>{
            if (i === next) img.classList.add('ccve-artwork-active'); else img.classList.remove('ccve-artwork-active');
          });
        }
      } catch(_) {}
      // Update list highlight without full rebuild
      try {
        const list = document.getElementById('ccve-artwork-items');
        if (list) {
          [...list.children].forEach((li,i)=>{ li.style.background = (i===next)?'#e0f2fe':'#f9fafb'; });
        }
      } catch(_) {}
      scheduleAdvance();
    }, interval);
  }
  editor.onPreviewLiveHook = function(){ scheduleAdvance(); };
  // Integrate with preview bus if available
  try { (window.ccveBus || editor.ccveBus)?.on?.('preview:live', ()=>{ scheduleAdvance(); }); } catch(_) {}

  // --- UI Wiring (executed lazily after DOM ready) ---
  function bindUi() {
    if (editor.__artworkUiBound) return; // Avoid duplicate
    const listEl = document.getElementById('ccve-artwork-items');
    const addBtn = document.getElementById('ccve-artwork-add-media');
    const enabledCb = document.getElementById('canvas-artwork-enabled');
    const widthInput = document.getElementById('canvas-artwork-width');
    const heightInput = document.getElementById('canvas-artwork-height');
    const gapInput = document.getElementById('canvas-artwork-gap');
    const brInput = document.getElementById('canvas-artwork-border-radius');
    const positionSel = document.getElementById('canvas-artwork-position');
    const ssEnabled = document.getElementById('ccve-slideshow-enabled');
    const ssInterval = document.getElementById('ccve-slideshow-interval');
    const ssTransition = document.getElementById('ccve-slideshow-transition');
    if (!listEl || !addBtn) return; // wait until markup exists
    editor.__artworkUiBound = true;

    function rebuildList() {
      if (!editor.currentConfig?.artwork) return;
      const items = editor.currentConfig.artwork.items || [];
      listEl.innerHTML = '';
      items.forEach((it, idx) => {
        const tpl = document.getElementById('ccve-artwork-item-template');
        if (!tpl) return;
        const node = tpl.content.firstElementChild.cloneNode(true);
        const thumb = node.querySelector('.ccve-artwork-thumb');
        if (thumb) {
          if (it.src) {
            thumb.textContent='';
            const img=document.createElement('img');
            img.src=it.src; img.alt=it.alt||''; img.style.width='100%'; img.style.height='100%'; img.style.objectFit='cover';
            thumb.appendChild(img);
          } else { thumb.textContent='NOIMG'; }
        }
        const altInput = node.querySelector('.ccve-artwork-alt');
        if (altInput) {
          altInput.value = it.alt || '';
          altInput.addEventListener('input', () => {
            editor.currentConfig.artwork.items[idx].alt = altInput.value;
            editor.markUnsaved();
            // Optimistic alt update in preview active image if matches index
            if (idx === editor.currentConfig.artwork.activeIndex) {
              try {
                const cont = editor.previewContainer?.querySelector('.artwork-container');
                const imgs = cont?.querySelectorAll('img');
                if (imgs && imgs[idx]) imgs[idx].setAttribute('alt', altInput.value);
              } catch(_){ }
            }
          });
        }
        // Active indicator
        if (idx === editor.currentConfig.artwork.activeIndex) node.style.background='#e0f2fe';
        node.querySelector('.ccve-artwork-set-active')?.addEventListener('click', ()=>{
          editor.setActiveArtworkIndex(idx);
          rebuildList();
        });
        node.querySelector('.ccve-artwork-remove')?.addEventListener('click', ()=>{
          editor.removeArtworkItem(idx);
          rebuildList();
        });
        node.querySelector('.ccve-artwork-move-up')?.addEventListener('click', ()=>{
          if (idx === 0) return;
          const arr = editor.currentConfig.artwork.items;
          [arr[idx-1],arr[idx]]=[arr[idx],arr[idx-1]];
          if (editor.currentConfig.artwork.activeIndex === idx) editor.currentConfig.artwork.activeIndex = idx-1;
          else if (editor.currentConfig.artwork.activeIndex === idx-1) editor.currentConfig.artwork.activeIndex = idx;
          editor.markUnsaved(); rebuildList(); editor.triggerPreview();
        });
        node.querySelector('.ccve-artwork-move-down')?.addEventListener('click', ()=>{
          const arr = editor.currentConfig.artwork.items;
          if (idx >= arr.length-1) return;
          [arr[idx+1],arr[idx]]=[arr[idx],arr[idx+1]];
            if (editor.currentConfig.artwork.activeIndex === idx) editor.currentConfig.artwork.activeIndex = idx+1;
            else if (editor.currentConfig.artwork.activeIndex === idx+1) editor.currentConfig.artwork.activeIndex = idx;
          editor.markUnsaved(); rebuildList(); editor.triggerPreview();
        });
        listEl.appendChild(node);
      });
    }

    // Basic field bindings
    function bindNumeric(el, pathCb) {
      if (!el) return;
      el.addEventListener('input', ()=>{
        const v = parseInt(el.value||'0',10);
        if (Number.isFinite(v)) pathCb(v);
        editor.markUnsaved(); editor.generatePreviewDebounced?.();
      });
    }
    if (enabledCb) enabledCb.addEventListener('change', ()=>{ editor.currentConfig.artwork.enabled = enabledCb.checked; editor.markUnsaved(); editor.triggerPreview(); });
    bindNumeric(widthInput, v=> editor.currentConfig.artwork.size.width = v);
    bindNumeric(heightInput, v=> editor.currentConfig.artwork.size.height = v);
    bindNumeric(gapInput, v=> editor.currentConfig.artwork.gap = v);
    bindNumeric(brInput, v=> editor.currentConfig.artwork.border_radius = v);
    if (positionSel) positionSel.addEventListener('change', ()=>{ editor.currentConfig.artwork.position = positionSel.value; editor.markUnsaved(); editor.triggerPreview(); });
    if (ssEnabled) ssEnabled.addEventListener('change', ()=>{ editor.configureSlideshow({ enabled:ssEnabled.checked }); });
    if (ssInterval) ssInterval.addEventListener('input', ()=>{ editor.configureSlideshow({ interval:ssInterval.value }); });
    if (ssTransition) ssTransition.addEventListener('change', ()=>{ editor.configureSlideshow({ transition:ssTransition.value }); });

    // Media picker (WordPress)
    if (addBtn) addBtn.addEventListener('click', (e)=>{
      e.preventDefault();
      try {
        if (!window.wp || !window.wp.media) {
          console.warn('WP media not available');
          return;
        }
        const frame = window.wp.media({ title:'Select Artwork Images', button:{ text:'Use Images' }, multiple:true });
        frame.on('select', ()=>{
          const selection = frame.state().get('selection');
          const items = [];
          selection.each(att=>{
            const a = att.toJSON();
            items.push({
              attachment_id: a.id,
              src: a.sizes?.medium?.url || a.sizes?.full?.url || a.url,
              alt: a.alt || a.title || '',
              mime: a.mime || a.mime_type || '',
              width: a.width || 0,
              height: a.height || 0
            });
          });
            if (items.length) {
              editor.addArtworkItems(items);
              rebuildList();
            }
        });
        frame.open();
      } catch(err) { console.error('Media picker failed', err); }
    });

    // Initial population sync when config loads
    const origPopulate = editor.populateControls?.bind(editor);
    editor.populateControls = function patchedPopulate(c){
      const r = origPopulate ? origPopulate(c) : undefined;
      try {
        if (c?.artwork) {
          if (enabledCb) enabledCb.checked = !!c.artwork.enabled;
          if (widthInput) widthInput.value = c.artwork.size?.width ?? '';
          if (heightInput) heightInput.value = c.artwork.size?.height ?? '';
          if (gapInput) gapInput.value = c.artwork.gap ?? '';
          if (brInput) brInput.value = c.artwork.border_radius ?? '';
          if (positionSel) positionSel.value = c.artwork.position || 'left';
          if (ssEnabled) ssEnabled.checked = !!c.artwork.slideshow?.enabled;
          if (ssInterval) ssInterval.value = c.artwork.slideshow?.interval ?? 5000;
          if (ssTransition) ssTransition.value = c.artwork.slideshow?.transition || 'fade';
          rebuildList();
        }
      } catch(e) { console.warn('populate artwork controls failed', e); }
      return r;
    };

    rebuildList();
  }

  // Attempt bind after small delay (to ensure admin markup rendered)
  setTimeout(bindUi, 200);
  document.addEventListener('DOMContentLoaded', bindUi);

  // Diagnostics: expose dropped preview count if preview glue tracks it
  if (!editor._artworkMetricsInterval) {
    editor._artworkMetricsInterval = setInterval(()=>{
      try {
        if (typeof editor._previewDropped === 'number') {
          console.debug('[CC][Metrics] Preview drops so far:', editor._previewDropped);
        }
      } catch(_) {}
    }, 15000);
  }
}

export default { attachArtworkSlideshow };