/**
 * VSR Premium Sidebar
 *
 * Vertically shows premium features on the right side of:
 *   - admin.php?page=visitorlens          (dashboard)
 *   - admin.php?page=visitorlens-stats    (stats)
 *   - admin.php?page=visitorlens-replay   (replay)
 *
 * Collapses to a thin tab. State persisted per-page in localStorage.
 */
(function (global) {
  'use strict';

  // ── Top features shown in the sidebar (8 flagships) ───────────────
  const ITEMS = [
    { icon: '🔥', color: 'rose',    name: 'Heatmaps',               sub: 'Click, scroll & attention maps' },
    { icon: '🎯', color: 'violet',  name: 'Funnels & Goals',         sub: 'Step-by-step conversion tracking' },
    { icon: '🧠', color: 'emerald', name: 'UX Insights Engine',      sub: '11 automated issue detectors' },
    { icon: '🔍', color: 'amber',   name: 'Visitor Insights',        sub: 'Intent scoring & behaviour analysis' },
    { icon: '🛒', color: 'green',   name: 'WooCommerce Integration', sub: 'Revenue, cart & checkout analytics' },
    { icon: '🌅', color: 'lime',    name: 'Daily Insights Digest',   sub: 'Morning briefing with stats at a glance' },
    { icon: '🔔', color: 'yellow',  name: 'Alerts & Automation',     sub: 'Smart triggers & webhook delivery' },
    { icon: '♿', color: 'indigo',  name: 'Accessibility Insights',  sub: 'Keyboard-only user detection & scoring' },
  ];

  const COLOR = {
    rose:    { bg: '#fff1f2', text: '#9f1239', border: '#fecdd3' },
    violet:  { bg: '#f5f3ff', text: '#5b21b6', border: '#ddd6fe' },
    emerald: { bg: '#ecfdf5', text: '#065f46', border: '#a7f3d0' },
    amber:   { bg: '#fef3c7', text: '#92400e', border: '#fde68a' },
    green:   { bg: '#dcfce7', text: '#15803d', border: '#bbf7d0' },
    lime:    { bg: '#ecfccb', text: '#3f6212', border: '#bef264' },
    yellow:  { bg: '#fef9c3', text: '#854d0e', border: '#fef08a' },
    indigo:  { bg: '#e0e7ff', text: '#3730a3', border: '#c7d2fe' },
  };

  // ── Per-page localStorage key ──────────────────────────────────────
  function _lsKey() {
    const p = new URLSearchParams(window.location.search).get('page') || 'vsl';
    return 'vlens_psb_' + p;
  }

  // Default open on all sidebar pages
  function _defaultOpen() {
    return true;
  }

  function _getState() {
    try {
      const v = localStorage.getItem(_lsKey());
      return v !== null ? v === '1' : _defaultOpen();
    } catch (_) { return _defaultOpen(); }
  }

  function _setState(open) {
    try { localStorage.setItem(_lsKey(), open ? '1' : '0'); } catch (_) {}
  }

  // ── Build sidebar HTML ─────────────────────────────────────────────
  function _buildHtml() {
    const upgradeUrl = (typeof vlensAdmin !== 'undefined' && vlensAdmin.upgradeUrl)
      ? vlensAdmin.upgradeUrl
      : 'https://myrecorp.com/visitor-lens/';

    const rows = ITEMS.map(f => {
      const c = COLOR[f.color] || COLOR.amber;
      return `
        <a class="vsr-psb-item" href="${upgradeUrl}" target="_blank" rel="noopener" title="${f.name}">
          <span class="vsr-psb-item-icon" style="background:${c.bg};color:${c.text};border:1px solid ${c.border}">${f.icon}</span>
          <span class="vsr-psb-item-text">
            <span class="vsr-psb-item-name">${f.name}</span>
            <span class="vsr-psb-item-sub">${f.sub}</span>
          </span>
          <svg class="vsr-psb-item-arrow" width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round">
            <polyline points="9 18 15 12 9 6"/>
          </svg>
        </a>`;
    }).join('');

    return `
      <!-- Collapsed tab: sticks out when panel is hidden -->
      <div class="vsr-psb-tab" id="vsrPsbTab" onclick="window.vsrPremiumSidebar.open()" title="VisitorLens Pro features">
        <svg width="13" height="13" viewBox="0 0 24 24" fill="currentColor"><path d="M13 2L3 14h9l-1 8 10-12h-9l1-8z"/></svg>
        <span class="vsr-psb-tab-label">PRO</span>
      </div>

      <!-- Expanded panel -->
      <aside class="vsr-psb-panel" id="vsrPsbPanel" aria-label="VisitorLens Pro features">

        <!-- Panel header -->
        <div class="vsr-psb-head">
          <div class="vsr-psb-head-brand">
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
              <path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/>
              <circle cx="12" cy="12" r="3" fill="currentColor" stroke="none"/>
            </svg>
            <span>VisitorLens Pro</span>
          </div>
          <button class="vsr-psb-head-close" onclick="window.vsrPremiumSidebar.close()" title="Collapse sidebar" aria-label="Collapse">
            <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.8">
              <polyline points="9 18 15 12 9 6"/>
            </svg>
          </button>
        </div>

        <!-- Eyebrow + headline -->
        <div class="vsr-psb-intro">
          <p class="vsr-psb-eyebrow">Available in</p>
          <h3 class="vsr-psb-headline">VisitorLens Pro<br>separate plugin</h3>
        </div>

        <!-- Feature rows -->
        <div class="vsr-psb-list">
          ${rows}
        </div>

        <!-- More link -->
        <a class="vsr-psb-more-link" href="${upgradeUrl}" target="_blank" rel="noopener">
          + 8 more features included
          <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><polyline points="9 18 15 12 9 6"/></svg>
        </a>

        <!-- CTA -->
        <div class="vsr-psb-cta-area">
          <a class="vsr-psb-cta-btn" href="${upgradeUrl}" target="_blank" rel="noopener">
            <svg width="13" height="13" viewBox="0 0 24 24" fill="currentColor"><path d="M13 2L3 14h9l-1 8 10-12h-9l1-8z"/></svg>
            Get VisitorLens Pro
          </a>
          <a class="vsr-psb-cta-details" href="${upgradeUrl}" target="_blank" rel="noopener">
            See all features →
          </a>
          <p class="vsr-psb-guarantee">
            <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/></svg>
            14-day money-back guarantee
          </p>
        </div>

      </aside>`;
  }

  // ── Init ───────────────────────────────────────────────────────────
  function init() {
    if (document.getElementById('vsrPremiumSidebar')) return;

    const host = document.createElement('div');
    host.id        = 'vsrPremiumSidebar';
    host.className = 'vsr-psb';
    host.innerHTML = _buildHtml();
    document.body.appendChild(host);

    _applyState(_getState(), false /* no animation on load */);
    _positionBelow();

    // Re-position when window resizes (sticky nav may reflow)
    window.addEventListener('resize', _positionBelow);
  }

  // Position sidebar just below the WP admin bar (responsive)
  function _positionBelow() {
    const host    = document.getElementById('vsrPremiumSidebar');
    if (!host) return;
    const adminBar = document.getElementById('wpadminbar');
    const offset   = adminBar ? adminBar.getBoundingClientRect().height : 0;
    host.style.top    = offset + 'px';
    host.style.height = 'calc(100vh - ' + offset + 'px)';
  }

  function open() {
    _applyState(true, true);
    _setState(true);
  }

  function close() {
    _applyState(false, true);
    _setState(false);
  }

  function _applyState(isOpen, animate) {
    const host = document.getElementById('vsrPremiumSidebar');
    if (!host) return;
    if (!animate) host.classList.add('vsr-psb--instant');
    if (isOpen) {
      host.classList.remove('vsr-psb--collapsed');
    } else {
      host.classList.add('vsr-psb--collapsed');
    }
    if (!animate) {
      requestAnimationFrame(() => host.classList.remove('vsr-psb--instant'));
    }
    _syncTopbarMargin(isOpen);
  }

  // Push entire page content away from the sidebar panel
  function _syncTopbarMargin(isOpen) {
    document.body.style.marginRight = isOpen ? '248px' : '';
  }

  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', init);
  } else {
    init();
  }

  global.vsrPremiumSidebar = { open, close };

})(window);
