/**
 * Jalpi Page Builder — Starter Sites admin page JS
 * Handles: card preview modal, one-click import flow.
 */
/* global jalpiWT */
(function () {
  'use strict';

  const api   = jalpiWT.apiUrl;
  const nonce = jalpiWT.nonce;
  const i18n  = jalpiWT.i18n || {}; // Localized strings

  // Kit index: id → data object (populated from data-kit attributes on boot)
  const kitMap = {};

  let pendingKit      = null; // kit pending import confirmation
  let previewingKit   = null; // kit currently open in wireframe preview modal
  let fullPreviewKit  = null; // kit open in full-site preview overlay

  // ── Boot ─────────────────────────────────────────────────────────────────

  document.addEventListener('DOMContentLoaded', () => {
    // Index all card data
    document.querySelectorAll('.cbss-card[data-kit]').forEach(card => {
      try {
        const kit = JSON.parse(card.dataset.kit);
        kitMap[kit.id] = kit;
      } catch (_) {}
    });

    bindPreviewButtons();
    bindPreviewModal();
    bindFullPreview();
    bindImportButtons();
    bindImportModal();
  });

  // ═══════════════════════ PREVIEW MODAL ══════════════════════════════════

  // Build the standalone full-front-end preview URL for a kit page.
  function buildPreviewUrl(kitId, pageSlug) {
    return jalpiWT.ajaxUrl
      + '?action=jalpi_site_preview'
      + '&website_id=' + encodeURIComponent(kitId)
      + '&page_slug='  + encodeURIComponent(pageSlug || '__front__')
      + '&_wpnonce='   + encodeURIComponent(jalpiWT.previewNonce);
  }

  function bindPreviewButtons() {
    document.querySelectorAll('.cbss-preview-btn').forEach(btn => {
      btn.addEventListener('click', e => {
        e.stopPropagation();
        const kit = kitMap[btn.dataset.id];
        if (!kit) return;
        // Open the full front-end preview in a NEW browser tab (not the modal),
        // so it never affects the editor / current session.
        if (jalpiWT.ajaxUrl && jalpiWT.previewNonce) {
          window.open(buildPreviewUrl(kit.id, '__front__'), '_blank', 'noopener');
        } else {
          openFullPreview(kit); // fallback: in-page preview if nonce missing
        }
      });
    });
  }

  function openPreview(kit) {
    previewingKit = kit;

    // ── Populate left panel (gradient + detailed wireframe) ────────────────
    const left = document.getElementById('cbss-preview-left');
    if (left) {
      left.style.background =
        'linear-gradient(145deg,' + kit.grad_from + ',' + kit.grad_to + ')';
      left.innerHTML = buildDetailedWireframe(kit);
    }

    // ── Populate right panel ───────────────────────────────────────────────
    setText('cbss-preview-cat',   ucfirst(kit.category));
    setText('cbss-preview-title', kit.name);
    setText('cbss-preview-desc',  kit.description);

    const listEl = document.getElementById('cbss-preview-page-list');
    if (listEl && Array.isArray(kit.page_titles)) {
      // Each page is a clickable link that opens THAT page's preview in a new
      // tab. Previously these were static <li> labels, so inner pages appeared
      // in the list but could not be opened — the "Preview" button only ever
      // loaded the home page. page_slugs is parallel to page_titles.
      const slugs = Array.isArray(kit.page_slugs) ? kit.page_slugs : [];
      const canPreview = !!(jalpiWT.ajaxUrl && jalpiWT.previewNonce);
      listEl.innerHTML = kit.page_titles.map((title, i) => {
        const icon = i === 0
          ? '<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><path d="M3 9l9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"/><polyline points="9 22 9 12 15 12 15 22"/></svg>'
          : '<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/></svg>';
        const inner = '<span class="cbss-pv-page-icon">' + icon + '</span>'
                    + '<span>' + escHtml(title) + '</span>';
        if (canPreview) {
          const slug = i === 0 ? '__front__' : (slugs[i] || '');
          const href = buildPreviewUrl(kit.id, slug);
          return '<li><a class="cbss-pv-page-link" href="' + href + '" target="_blank" rel="noopener">'
               + inner + '</a></li>';
        }
        return '<li>' + inner + '</li>';
      }).join('');
    }

    // Wire up the "Import Website" button inside the preview modal
    const importBtn = document.getElementById('cbss-preview-import');
    if (importBtn) {
      importBtn.dataset.id    = kit.id;
      importBtn.dataset.name  = kit.name;
      importBtn.dataset.pages = kit.pages_count;
    }

    openOverlay('cbss-preview-overlay');
  }

  function closePreview() {
    closeOverlay('cbss-preview-overlay');
    previewingKit = null;
  }

  function bindPreviewModal() {
    document.getElementById('cbss-preview-close')?.addEventListener('click', closePreview);
    document.getElementById('cbss-preview-cancel')?.addEventListener('click', closePreview);
    document.getElementById('cbss-preview-overlay')?.addEventListener('click', e => {
      if (e.target === e.currentTarget) closePreview();
    });

    // "Import Website" button inside preview → close preview, open import confirm
    document.getElementById('cbss-preview-import')?.addEventListener('click', () => {
      const kit = previewingKit;
      closePreview();
      if (kit) {
        setTimeout(() => {
          pendingKit = { id: kit.id, name: kit.name, pages: kit.pages_count };
          openImportModal();
        }, 160); // let preview close first
      }
    });
  }

  // Build a detailed wireframe SVG for the preview panel
  function buildDetailedWireframe(kit) {
    const c  = kit.color;
    const hi = c + '55'; // semi-transparent accent
    const lo = c + '25';
    const vl = c + '18';

    return `
    <div class="cbss-pv-wire" aria-hidden="true">
      <!-- Nav bar -->
      <div class="cbss-pv-wire__nav" style="background:${c}30">
        <div class="cbss-pv-wire__logo" style="background:${hi}"></div>
        <div class="cbss-pv-wire__nav-links">
          <div style="background:${hi}"></div>
          <div style="background:${hi}"></div>
          <div style="background:${hi}"></div>
          <div class="cbss-pv-wire__nav-btn" style="background:${c}"></div>
        </div>
      </div>
      <!-- Hero -->
      <div class="cbss-pv-wire__hero" style="background:${lo}">
        <div class="cbss-pv-wire__hero-inner">
          <div class="cbss-pv-wire__line cbss-pv-wire__line--xl" style="background:${hi}"></div>
          <div class="cbss-pv-wire__line cbss-pv-wire__line--lg" style="background:${c}40"></div>
          <div class="cbss-pv-wire__line cbss-pv-wire__line--md" style="background:${c}35"></div>
          <div class="cbss-pv-wire__btns">
            <div class="cbss-pv-wire__btn" style="background:${c}"></div>
            <div class="cbss-pv-wire__btn cbss-pv-wire__btn--ghost" style="border-color:${c}60"></div>
          </div>
        </div>
      </div>
      <!-- Features row -->
      <div class="cbss-pv-wire__features" style="background:${vl}">
        <div class="cbss-pv-wire__feat">
          <div class="cbss-pv-wire__feat-icon" style="background:${hi}"></div>
          <div class="cbss-pv-wire__line cbss-pv-wire__line--sm" style="background:${c}50"></div>
          <div class="cbss-pv-wire__line cbss-pv-wire__line--xs" style="background:${c}30"></div>
          <div class="cbss-pv-wire__line cbss-pv-wire__line--xs" style="background:${c}30"></div>
        </div>
        <div class="cbss-pv-wire__feat">
          <div class="cbss-pv-wire__feat-icon" style="background:${hi}"></div>
          <div class="cbss-pv-wire__line cbss-pv-wire__line--sm" style="background:${c}50"></div>
          <div class="cbss-pv-wire__line cbss-pv-wire__line--xs" style="background:${c}30"></div>
          <div class="cbss-pv-wire__line cbss-pv-wire__line--xs" style="background:${c}30"></div>
        </div>
        <div class="cbss-pv-wire__feat">
          <div class="cbss-pv-wire__feat-icon" style="background:${hi}"></div>
          <div class="cbss-pv-wire__line cbss-pv-wire__line--sm" style="background:${c}50"></div>
          <div class="cbss-pv-wire__line cbss-pv-wire__line--xs" style="background:${c}30"></div>
          <div class="cbss-pv-wire__line cbss-pv-wire__line--xs" style="background:${c}30"></div>
        </div>
      </div>
      <!-- CTA bar -->
      <div class="cbss-pv-wire__cta" style="background:${c}20">
        <div class="cbss-pv-wire__line cbss-pv-wire__line--lg" style="background:${hi}; margin:0 auto 8px;"></div>
        <div class="cbss-pv-wire__btn" style="background:${c}; margin:0 auto;"></div>
      </div>
      <!-- Footer -->
      <div class="cbss-pv-wire__footer" style="background:${c}15">
        <div class="cbss-pv-wire__line cbss-pv-wire__line--sm" style="background:${c}40"></div>
        <div class="cbss-pv-wire__line cbss-pv-wire__line--xs" style="background:${c}25"></div>
      </div>
    </div>`;
  }

  // ═══════════════════════ FULL SITE PREVIEW ═══════════════════════════════

  function openFullPreview(kit) {
    fullPreviewKit = kit;

    // Populate toolbar name
    setText('cbss-fullpv-name', kit.name);

    // Build page tabs
    const pagesEl = document.getElementById('cbss-fullpv-pages');
    if (pagesEl) {
      const titles = kit.page_titles || [];
      const slugs  = kit.page_slugs  || [];
      pagesEl.innerHTML = titles.map((title, i) => {
        const raw  = slugs[i] !== undefined ? slugs[i] : '';
        const slug = raw === '' ? '__front__' : raw;
        return '<button type="button" class="cbss-fullpv-page-tab' + (i === 0 ? ' is-active' : '')
             + '" data-slug="' + escHtml(slug) + '">' + escHtml(title) + '</button>';
      }).join('');

      // Tab click → load page
      pagesEl.querySelectorAll('.cbss-fullpv-page-tab').forEach(tab => {
        tab.addEventListener('click', () => {
          pagesEl.querySelectorAll('.cbss-fullpv-page-tab').forEach(t => t.classList.remove('is-active'));
          tab.classList.add('is-active');
          loadPreviewPage(kit.id, tab.dataset.slug);
        });
      });
    }

    // Wire Import button
    const importBtn = document.getElementById('cbss-fullpv-import');
    if (importBtn) {
      importBtn.dataset.id    = kit.id;
      importBtn.dataset.name  = kit.name;
      importBtn.dataset.pages = kit.pages_count;
    }

    // Reset viewport to desktop
    setViewport('desktop');
    document.querySelectorAll('.cbss-fullpv-vp__btn').forEach(b => {
      b.classList.toggle('is-active', b.dataset.vp === 'desktop');
    });

    // Open overlay and load home page
    openOverlay('cbss-fullpv-overlay');
    loadPreviewPage(kit.id, '__front__');
  }

  function loadPreviewPage(kitId, pageSlug) {
    if (!jalpiWT.ajaxUrl || !jalpiWT.previewNonce) return;

    const iframe = document.getElementById('cbss-fullpv-iframe');
    const loader = document.getElementById('cbss-fullpv-loader');
    if (!iframe) return;

    // Show loader, hide iframe
    if (loader) loader.style.display = 'flex';
    iframe.style.opacity = '0';

    const url = jalpiWT.ajaxUrl
      + '?action=jalpi_site_preview'
      + '&website_id=' + encodeURIComponent(kitId)
      + '&page_slug='  + encodeURIComponent(pageSlug)
      + '&_wpnonce='   + encodeURIComponent(jalpiWT.previewNonce);

    iframe.onload = function () {
      if (loader) loader.style.display = 'none';
      iframe.style.opacity = '1';
    };
    iframe.src = url;
  }

  function closeFullPreview() {
    closeOverlay('cbss-fullpv-overlay');
    const iframe = document.getElementById('cbss-fullpv-iframe');
    if (iframe) { iframe.onload = null; iframe.src = 'about:blank'; }
    fullPreviewKit = null;
  }

  function setViewport(vp) {
    const shell = document.getElementById('cbss-fullpv-frame-shell');
    if (!shell) return;
    shell.classList.remove('vp-desktop', 'vp-tablet', 'vp-mobile');
    shell.classList.add('vp-' + vp);
  }

  function bindFullPreview() {
    // Close button
    document.getElementById('cbss-fullpv-close')?.addEventListener('click', closeFullPreview);

    // Click outside
    document.getElementById('cbss-fullpv-overlay')?.addEventListener('click', e => {
      if (e.target === e.currentTarget) closeFullPreview();
    });

    // Viewport switcher
    document.getElementById('cbss-fullpv-vp')?.addEventListener('click', e => {
      const btn = e.target.closest('.cbss-fullpv-vp__btn');
      if (!btn) return;
      document.querySelectorAll('.cbss-fullpv-vp__btn').forEach(b => b.classList.remove('is-active'));
      btn.classList.add('is-active');
      setViewport(btn.dataset.vp);
    });

    // Import from preview
    document.getElementById('cbss-fullpv-import')?.addEventListener('click', () => {
      if (!fullPreviewKit) return;
      const kit = fullPreviewKit;
      closeFullPreview();
      setTimeout(() => {
        pendingKit = { id: kit.id, name: kit.name, pages: kit.pages_count };
        openImportModal();
      }, 180);
    });
  }

  // ═══════════════════════ IMPORT MODAL ═══════════════════════════════════

  function bindImportButtons() {
    document.querySelectorAll('.cbss-import-btn').forEach(btn => {
      btn.addEventListener('click', e => {
        e.stopPropagation();
        pendingKit = {
          id:    btn.dataset.id,
          name:  btn.dataset.name,
          pages: parseInt(btn.dataset.pages, 10) || 0,
        };
        openImportModal();
      });
    });
  }

  function openImportModal() {
    if (!pendingKit) return;
    showState('confirm');
    setText('cbss-modal-title', pendingKit.name);
    const pageMsg = i18n.pagesWillBeCreated
      ? i18n.pagesWillBeCreated.replace('%d', pendingKit.pages)
      : pendingKit.pages + ' pages will be created';
    setText('cbss-modal-sub', pageMsg);
    openOverlay('cbss-overlay');
  }

  function closeImportModal() {
    closeOverlay('cbss-overlay');
    setTimeout(() => {
      pendingKit = null;
      showState('confirm');
    }, 200);
  }

  function bindImportModal() {
    document.getElementById('cbss-close')?.addEventListener('click', closeImportModal);
    document.getElementById('cbss-cancel')?.addEventListener('click', closeImportModal);
    document.getElementById('cbss-overlay')?.addEventListener('click', e => {
      if (e.target === e.currentTarget) closeImportModal();
    });

    document.getElementById('cbss-confirm')?.addEventListener('click', runImport);
    document.getElementById('cbss-done')?.addEventListener('click', closeImportModal);

    document.getElementById('cbss-err-close')?.addEventListener('click', closeImportModal);
    document.getElementById('cbss-err-close-btn')?.addEventListener('click', closeImportModal);
  }

  // ── Import REST call ────────────────────────────────────────────────────

  function runImport() {
    if (!pendingKit) return;
    showState('progress');

    fetch(api + '/import-website', {
      method:  'POST',
      headers: { 'Content-Type': 'application/json', 'X-WP-Nonce': nonce },
      body:    JSON.stringify({ website_id: pendingKit.id }),
    })
      .then(r => r.json().then(data => ({ ok: r.ok, data })))
      .then(({ ok, data }) => {
        if (!ok) throw new Error(data.message || 'Import failed.');
        showSuccess(data);
      })
      .catch(err => showError(err.message || String(err)));
  }

  function showSuccess(data) {
    showState('success');
    const successMsg = data.pages_created === 1
      ? (i18n.pageCreated || 'page created successfully.')
      : (i18n.pagesCreated || 'pages created successfully.');
    setText('cbss-success-sub', data.pages_created + ' ' + successMsg);

    const listEl = document.getElementById('cbss-page-list');
    if (listEl && Array.isArray(data.pages)) {
      const editText = i18n.edit || 'Edit';
      const viewText = i18n.view || 'View';
      listEl.innerHTML = data.pages.map(p =>
        '<li><span class="cbss-page-title">' + escHtml(p.title) + '</span>'
        + '<span class="cbss-page-links">'
        + '<a href="' + escHtml(p.edit || '#') + '">' + escHtml(editText) + '</a>'
        + '<a href="' + escHtml(p.url  || '#') + '" target="_blank">' + escHtml(viewText) + '</a>'
        + '</span></li>'
      ).join('');
    }

    if (data.front_page_id && data.pages) {
      const front = data.pages.find(p => p.id === data.front_page_id);
      const link  = document.getElementById('cbss-view-site');
      if (link && front) link.href = front.url;
    }
  }

  function showError(msg) {
    showState('error');
    setText('cbss-error-msg', msg);
  }

  // ── State switcher ──────────────────────────────────────────────────────

  function showState(name) {
    ['confirm', 'progress', 'success', 'error'].forEach(s => {
      const el = document.getElementById('cbss-state-' + s);
      if (el) el.style.display = s === name ? '' : 'none';
    });
  }

  // ── Overlay helpers ─────────────────────────────────────────────────────

  function openOverlay(id) {
    const el = document.getElementById(id);
    if (el) { el.classList.add('is-open'); el.removeAttribute('aria-hidden'); }
  }
  function closeOverlay(id) {
    const el = document.getElementById(id);
    if (el) { el.classList.remove('is-open'); el.setAttribute('aria-hidden', 'true'); }
  }

  document.addEventListener('keydown', e => {
    if (e.key !== 'Escape') return;
    // Full preview has highest ESC priority
    if (document.getElementById('cbss-fullpv-overlay')?.classList.contains('is-open')) {
      closeFullPreview();
    } else if (document.getElementById('cbss-preview-overlay')?.classList.contains('is-open')) {
      closePreview();
    } else {
      const importOverlay = document.getElementById('cbss-overlay');
      if (importOverlay?.classList.contains('is-open')) {
        const prog = document.getElementById('cbss-state-progress');
        if (!prog || prog.style.display === 'none') closeImportModal();
      }
    }
  });

  // ── Utilities ───────────────────────────────────────────────────────────

  function setText(id, text) {
    const el = document.getElementById(id);
    if (el) el.textContent = text;
  }
  function ucfirst(str) {
    return str ? str.charAt(0).toUpperCase() + str.slice(1) : '';
  }
  function escHtml(str) {
    return String(str)
      .replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')
      .replace(/"/g, '&quot;').replace(/'/g, '&#x27;');
  }

}());
