/**
 * VSR Premium Upgrade Modal
 *
 * Global surface: window.vsrUpgrade.show(featureName?)
 */
(function (global) {
  'use strict';

  // ── Feature definitions ────────────────────────────────────────────
  const FEATURES = [
    {
      icon: '🔥',
      color: 'rose',
      name: 'Heatmaps',
      desc: 'Visual click, scroll depth, mouse movement & attention heatmaps for any page. Compare desktop, tablet & mobile side by side with a split-screen view.',
    },
    {
      icon: '🎯',
      color: 'violet',
      name: 'Funnels & Goals',
      desc: 'Build multi-step conversion funnels, track drop-off % at each step & auto-detect goal completions — URL visit, element click or form submit.',
    },
    {
      icon: '🧠',
      color: 'emerald',
      name: 'UX Insights Engine',
      desc: '11 automated UX detectors surface critical issues — rage clicks, quick bounces, form abandonment, wasted traffic & more — ranked by severity.',
    },
    {
      icon: '🔍',
      color: 'amber',
      name: 'Visitor Insights',
      desc: 'Behavioural analysis, intent scoring & date-wise insights per visitor. Know exactly what every user did and why.',
    },
    {
      icon: '🌅',
      color: 'lime',
      name: 'Daily Insights Digest',
      desc: 'Morning briefing with at-a-glance insights — daily visitor statistics, top pages, conversion signals, rage hotspots & site health score, delivered straight to your inbox.',
      badge: 'New',
    },
    {
      icon: '📊',
      color: 'blue',
      name: 'Advanced Analytics',
      desc: 'Frustration scoring, user profile pages, advanced session filters & cross-visit funnel analysis.',
    },
    {
      icon: '⚡',
      color: 'orange',
      name: 'Core Web Vitals',
      desc: 'Per-session LCP, FID, INP & CLS tracking. Correlate performance metrics directly with user behaviour.',
    },
    {
      icon: '🛒',
      color: 'green',
      name: 'WooCommerce Integration',
      desc: 'Revenue analytics, cart abandonment tracking, checkout friction heatmaps & full order journey replays.',
    },
    {
      icon: '📋',
      color: 'pink',
      name: 'Form Abandonment',
      desc: 'Field-level form analytics, drop-off detection, partial submission tracking & conversion improvement tips.',
    },
    {
      icon: '♿',
      color: 'indigo',
      name: 'Accessibility Insights',
      desc: 'Keyboard-only user detection, a11y struggle scoring & per-page accessibility issue reporting.',
    },
    {
      icon: '🔔',
      color: 'yellow',
      name: 'Alerts & Automation',
      desc: 'Smart alerts for traffic spikes, rage click surges & conversion events. Webhook & email delivery.',
    },
    {
      icon: '👥',
      color: 'purple',
      name: 'Team & Collaboration',
      desc: 'Role-based access (Viewer / Analyst / Admin), session notes, tags & shareable replay links.',
    },
    {
      icon: '🐛',
      color: 'red',
      name: 'JS Error Tracking',
      desc: 'JavaScript error aggregation, broken resource detection & performance regression alerts per release.',
    },
    {
      icon: '📤',
      color: 'slate',
      name: 'Data Export & Management',
      desc: 'Export sessions as CSV or JSON. Bulk-delete filtered sessions. Full storage usage dashboard.',
    },
    {
      icon: '📅',
      color: 'teal',
      name: 'Weekly Summary Reports',
      desc: 'Automated weekly digest with key traffic trends, top pages & UX health scores sent to your team.',
    },
    {
      icon: '🔗',
      color: 'cyan',
      name: 'Shared Replay Links',
      desc: 'Share session replays with clients or teammates via a secure, time-limited public link — no login needed.',
    },
  ];

  // ── Light-mode color palette for icon badges ───────────────────────
  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' },
    lime:    { bg: '#ecfccb', text: '#3f6212', border: '#bef264' },
    blue:    { bg: '#dbeafe', text: '#1e40af', border: '#bfdbfe' },
    orange:  { bg: '#ffedd5', text: '#c2410c', border: '#fed7aa' },
    green:   { bg: '#dcfce7', text: '#15803d', border: '#bbf7d0' },
    pink:    { bg: '#fce7f3', text: '#9d174d', border: '#fbcfe8' },
    indigo:  { bg: '#e0e7ff', text: '#3730a3', border: '#c7d2fe' },
    yellow:  { bg: '#fef9c3', text: '#854d0e', border: '#fef08a' },
    purple:  { bg: '#f3e8ff', text: '#6b21a8', border: '#e9d5ff' },
    red:     { bg: '#fee2e2', text: '#991b1b', border: '#fecaca' },
    slate:   { bg: '#f1f5f9', text: '#334155', border: '#e2e8f0' },
    teal:    { bg: '#ccfbf1', text: '#0f766e', border: '#99f6e4' },
    cyan:    { bg: '#cffafe', text: '#0e7490', border: '#a5f3fc' },
  };

  function esc(s) {
    const d = document.createElement('div');
    d.textContent = s || '';
    return d.innerHTML;
  }

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

    // Callout — shown when a specific feature triggered the modal
    let calloutHtml = '';
    if (triggerFeature) {
      const matched = FEATURES.find(f => f.name === triggerFeature);
      const label   = matched ? matched.name : triggerFeature;
      const matchedColor = matched ? (COLOR[matched.color] || COLOR.amber) : COLOR.amber;
      calloutHtml = `
        <div class="vsr-up-callout">
          <span class="vsr-up-callout-icon"
            style="background:${matchedColor.bg};color:${matchedColor.text};border-color:${matchedColor.border}">
            ${matched ? matched.icon : '🔒'}
          </span>
          <div class="vsr-up-callout-text">
            <strong>${esc(label)}</strong> is a Premium feature —
            unlock it and 12 more with a single upgrade.
          </div>
        </div>`;
    }

    // Feature cards
    const featureCards = FEATURES.map(f => {
      const c         = COLOR[f.color] || COLOR.slate;
      const active    = triggerFeature && f.name === triggerFeature ? ' vsr-up-feat--active' : '';
      const badgeHtml = f.badge
        ? `<span class="vsr-up-feat-badge">${esc(f.badge)}</span>`
        : '';
      return `
        <div class="vsr-up-feat${active}">
          <span class="vsr-up-feat-icon"
            style="background:${c.bg};color:${c.text};border-color:${c.border}">${f.icon}</span>
          <div class="vsr-up-feat-body">
            <div class="vsr-up-feat-name">${esc(f.name)}${badgeHtml}</div>
            <div class="vsr-up-feat-desc">${esc(f.desc)}</div>
          </div>
        </div>`;
    }).join('');

    return `
      <div class="vsr-up-modal" role="dialog" aria-modal="true" aria-labelledby="vsrUpTitle" tabindex="-1">

        <!-- ── Header ── -->
        <div class="vsr-up-header">
          <div class="vsr-up-brand">
            <svg class="vsr-up-brand-eye" width="20" height="20" 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 id="vsrUpTitle">Visitor<em>Lens</em></span>
            <span class="vsr-up-brand-pro">PRO</span>
          </div>
          <div class="vsr-up-header-pill">✨ Premium Features</div>
          <button class="vsr-up-close" onclick="window.vsrUpgrade.close()" aria-label="Close">
            <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5">
              <line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/>
            </svg>
          </button>
        </div>

        <!-- ── Hero banner (non-scrolling) ── -->
        <div class="vsr-up-banner">
          <div class="vsr-up-banner-deco" aria-hidden="true"></div>
          <div class="vsr-up-banner-content">
            <div class="vsr-up-banner-left">
              <h2 class="vsr-up-hero-title">
                Everything you need to truly<br>
                <em>understand your visitors</em>
              </h2>
              <p class="vsr-up-hero-sub">
                One upgrade unlocks the complete analytics stack —
                real-time insights, smart automations, team tools & more.
              </p>
              ${calloutHtml}
            </div>
            <div class="vsr-up-banner-stats">
              <div class="vsr-up-stat">
                <span class="vsr-up-stat-n">16+</span>
                <span class="vsr-up-stat-l">Premium features</span>
              </div>
              <div class="vsr-up-stat-divider"></div>
              <div class="vsr-up-stat">
                <span class="vsr-up-stat-n">∞</span>
                <span class="vsr-up-stat-l">Sessions stored</span>
              </div>
              <div class="vsr-up-stat-divider"></div>
              <div class="vsr-up-stat">
                <span class="vsr-up-stat-n">1-click</span>
                <span class="vsr-up-stat-l">Activation</span>
              </div>
            </div>
          </div>
        </div>

        <!-- ── Scrollable feature grid ── -->
        <div class="vsr-up-body">
          <p class="vsr-up-grid-label">What's included in Premium</p>
          <div class="vsr-up-grid">
            ${featureCards}
          </div>
        </div>

        <!-- ── Footer CTA ── -->
        <div class="vsr-up-footer">
          <div class="vsr-up-trust">
            <span class="vsr-up-trust-item">
              <svg width="14" height="14" 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
            </span>
            <span class="vsr-up-trust-dot"></span>
            <span class="vsr-up-trust-item">
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2">
                <polyline points="20 6 9 17 4 12"/>
              </svg>
              No recurring fees — lifetime option available
            </span>
            <span class="vsr-up-trust-dot"></span>
            <span class="vsr-up-trust-item">
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2">
                <circle cx="12" cy="12" r="10"/>
                <polyline points="12 6 12 12 16 14"/>
              </svg>
              Instant activation
            </span>
          </div>
          <a class="vsr-up-cta" href="${esc(upgradeUrl)}" target="_blank" rel="noopener">
            <span>Upgrade to Premium</span>
            <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5">
              <line x1="5" y1="12" x2="19" y2="12"/>
              <polyline points="12 5 19 12 12 19"/>
            </svg>
          </a>
        </div>

      </div>`;
  }

  // ── Public API ─────────────────────────────────────────────────────
  function show(triggerFeature) {
    close();

    const gate = document.getElementById('vsrPremiumGate');
    if (gate) gate.remove();

    const overlay = document.createElement('div');
    overlay.id        = 'vsrUpgradeOverlay';
    overlay.className = 'vsr-up-overlay';
    overlay.innerHTML = _buildHtml(triggerFeature);
    document.body.appendChild(overlay);

    requestAnimationFrame(() => overlay.classList.add('vsr-up-overlay--in'));
    overlay.addEventListener('click', e => { if (e.target === overlay) close(); });
    document.addEventListener('keydown', _escHandler);

    const modal = overlay.querySelector('.vsr-up-modal');
    if (modal) modal.focus();

    // Scroll triggered feature card into view
    if (triggerFeature) {
      setTimeout(() => {
        const active = overlay.querySelector('.vsr-up-feat--active');
        if (active) active.scrollIntoView({ block: 'nearest', behavior: 'smooth' });
      }, 320);
    }
  }

  function close() {
    const el = document.getElementById('vsrUpgradeOverlay');
    if (!el) return;
    el.classList.remove('vsr-up-overlay--in');
    el.classList.add('vsr-up-overlay--out');
    setTimeout(() => { if (el.parentNode) el.remove(); }, 240);
    document.removeEventListener('keydown', _escHandler);
  }

  function _escHandler(e) { if (e.key === 'Escape') close(); }

  global.vsrUpgrade = { show, close };

})(window);
