/**
 * VisitorLens — Dashboard Page
 * Renders KPI cards, visitor chart, top pages, recent visitors,
 * and the live incomplete-orders widget.
 */
(function () {
  'use strict';

  if (typeof vlensAdmin === 'undefined') return;

  var app = document.getElementById('vsr-dashboard-app');
  if (!app) return;

  var acLink = (vlensAdmin.adminUrl || '') + 'admin.php?page=visitorlens-incomplete-orders';

  /* ── Inline styles ─────────────────────────────────────── */
  var css = document.createElement('style');
  css.textContent = `
    @import url('https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700;800&display=swap');
    .vsr-wrap{max-width:1140px;font-family:'Plus Jakarta Sans',-apple-system,BlinkMacSystemFont,'Segoe UI',sans-serif}

    /* Page header */
    .vsr-ph{display:flex;align-items:center;justify-content:space-between;margin-bottom:28px;flex-wrap:wrap;gap:12px;padding-bottom:20px;border-bottom:1px solid #e8e4de}
    .vsr-ph h1{font-family:'Plus Jakarta Sans',-apple-system,BlinkMacSystemFont,'Segoe UI',sans-serif;font-size:24px;font-weight:800;font-style:normal;letter-spacing:-.02em;color:#0f172a;margin:0 0 3px;line-height:1.25}
    .vsr-ph h1 em{color:#f59e0b;font-style:normal;font-weight:800}
    .vsr-ph p{font-size:13px;color:#64748b;margin:0}

    /* Header right badges */
    .vsr-ph-badges{display:flex;align-items:center;gap:8px;flex-wrap:wrap}
    .vsr-online{font-size:12.5px;font-weight:600;padding:6px 14px;border-radius:20px;background:rgba(34,197,94,.1);color:#15803d;white-space:nowrap;border:1px solid rgba(34,197,94,.2)}
    .vsr-today-badge{font-size:12.5px;font-weight:600;padding:6px 14px;border-radius:20px;background:rgba(59,130,246,.1);color:#1d4ed8;white-space:nowrap;border:1px solid rgba(59,130,246,.2)}

    /* KPI grid */
    .vsr-kpis{display:grid;grid-template-columns:repeat(auto-fill,minmax(190px,1fr));gap:16px;margin-bottom:24px}
    .vsr-kpi{background:#fff;border-radius:12px;padding:22px 24px;border:1px solid #e8e4de;box-shadow:0 1px 4px rgba(0,0,0,.05);position:relative;overflow:hidden;transition:box-shadow .15s}
    .vsr-kpi:hover{box-shadow:0 4px 16px rgba(0,0,0,.08)}
    .vsr-kpi::after{content:'';position:absolute;top:-24px;right:-24px;width:72px;height:72px;border-radius:50%;background:rgba(245,158,11,.06)}
    .vsr-kpi:first-child{border-top:3px solid #3b82f6}
    .vsr-kpi:first-child .vsr-kpi-val{color:#3b82f6}
    .vsr-kpi-label{font-size:11px;font-weight:700;color:#94a3b8;text-transform:uppercase;letter-spacing:.07em;margin-bottom:10px}
    .vsr-kpi-val{font-family:'Plus Jakarta Sans',-apple-system,BlinkMacSystemFont,'Segoe UI',sans-serif;font-size:32px;font-weight:800;letter-spacing:-.02em;color:#0f172a;line-height:1}
    .vsr-kpi-sub{font-size:12px;color:#94a3b8;margin-top:6px}

    /* Cards */
    .vsr-card{background:#fff;border-radius:12px;border:1px solid #e8e4de;box-shadow:0 1px 4px rgba(0,0,0,.05);margin-bottom:20px;overflow:hidden}
    .vsr-card-hd{display:flex;align-items:center;justify-content:space-between;padding:16px 22px;border-bottom:1px solid #e8e4de;background:#faf9f7}
    .vsr-card-title{font-family:'Plus Jakarta Sans',-apple-system,BlinkMacSystemFont,'Segoe UI',sans-serif;font-size:14px;font-weight:700;font-style:normal;letter-spacing:-.01em;color:#0f172a}
    .vsr-card-body-pad{padding:20px 22px}
    .vsr-chart-wrap{position:relative;height:230px;padding:4px 22px 20px}

    /* 2-col grid */
    .vsr-g2{display:grid;grid-template-columns:1fr 1fr;gap:20px}

    /* Tables */
    .vsr-tbl{width:100%;border-collapse:collapse;font-size:13px}
    .vsr-tbl th{text-align:left;font-size:11px;font-weight:700;color:#94a3b8;text-transform:uppercase;letter-spacing:.06em;padding:0 22px 10px;border-bottom:1px solid #e8e4de}
    .vsr-tbl td{padding:10px 22px;border-bottom:1px solid #f1ede8;color:#334155;vertical-align:middle}
    .vsr-tbl tr:last-child td{border-bottom:none}
    .vsr-tbl tr:hover td{background:#faf9f7}

    /* Live badge */
    .vsr-badge-live{display:inline-flex;align-items:center;gap:4px;padding:2px 8px;border-radius:20px;font-size:11px;font-weight:600;background:rgba(34,197,94,.1);color:#15803d;border:1px solid rgba(34,197,94,.2)}

    /* Empty / error */
    .vsr-empty{text-align:center;padding:36px;color:#94a3b8;font-size:13px;font-style:italic}
    .vsr-err{text-align:center;padding:40px;color:#ef4444;font-size:14px}

    /* Skeleton */
    .vsr-skel{background:linear-gradient(90deg,#f1ede8 25%,#e8e4de 50%,#f1ede8 75%);background-size:200% 100%;animation:vsrSkel 1.4s ease-in-out infinite;border-radius:12px;min-height:95px}
    @keyframes vsrSkel{0%{background-position:200% 0}100%{background-position:-200% 0}}

    /* ── Incomplete Orders widget ── */
    .vsr-ic-card{border-top:3px solid #f59e0b}
    .vsr-ic-viewall{font-size:12px;font-weight:600;color:#6366f1;text-decoration:none;padding:5px 12px;border:1px solid rgba(99,102,241,.25);border-radius:6px;transition:background .15s}
    .vsr-ic-viewall:hover{background:rgba(99,102,241,.06)}
    .vsr-ic-stats{display:grid;grid-template-columns:repeat(3,1fr);border-bottom:1px solid #e8e4de}
    .vsr-ic-stat{padding:18px 22px;border-right:1px solid #e8e4de}
    .vsr-ic-stat:last-child{border-right:none}
    .vsr-ic-stat-label{font-size:10px;font-weight:700;color:#94a3b8;text-transform:uppercase;letter-spacing:.07em;margin-bottom:7px}
    .vsr-ic-stat-val{font-family:'Plus Jakarta Sans',-apple-system,BlinkMacSystemFont,'Segoe UI',sans-serif;font-size:26px;font-weight:800;letter-spacing:-.02em;color:#0f172a;line-height:1}
    .vsr-ic-stat-val.amber{color:#f59e0b}
    .vsr-ic-stat-val.red{color:#ef4444}
    .vsr-ic-stat-sub{font-size:11px;color:#94a3b8;margin-top:5px}
    .vsr-badge-ic-order{display:inline-block;padding:2px 7px;border-radius:4px;font-size:10px;font-weight:700;letter-spacing:.03em;background:#fef3f2;color:#dc2626}
    .vsr-badge-ic-cart{display:inline-block;padding:2px 7px;border-radius:4px;font-size:10px;font-weight:700;letter-spacing:.03em;background:#fff7ed;color:#ea580c}
    .vsr-ic-status-pending{color:#d97706}
    .vsr-ic-status-on-hold{color:#7c3aed}
    .vsr-ic-status-failed,.vsr-ic-status-cancelled{color:#ef4444}
    .vsr-ic-status-abandoned{color:#ea580c}

    @media(max-width:780px){.vsr-g2{grid-template-columns:1fr}.vsr-kpis{grid-template-columns:1fr 1fr}.vsr-ic-stats{grid-template-columns:1fr 1fr}}
    @media(max-width:480px){.vsr-kpis{grid-template-columns:1fr}.vsr-ic-stats{grid-template-columns:1fr}}
  `;
  document.head.appendChild(css);

  /* ── Shell HTML ────────────────────────────────────────── */
  app.innerHTML = `
    <div class="vsr-ph">
      <div>
        <h1>Visitor<em>Lens</em> Dashboard</h1>
        <p>Site traffic overview &amp; session analytics</p>
      </div>
      <div class="vsr-ph-badges">
        <span class="vsr-today-badge" id="vsr-today-badge">● Today: —</span>
        <span class="vsr-online" id="vsr-online-badge">● Checking…</span>
      </div>
    </div>

    <div class="vsr-kpis" id="vsr-kpis">
      <div class="vsr-skel"></div>
      <div class="vsr-skel"></div>
      <div class="vsr-skel"></div>
      <div class="vsr-skel"></div>
    </div>

    <div class="vsr-card">
      <div class="vsr-card-hd">
        <span class="vsr-card-title">Visitors &amp; Page Views — Last 30 Days</span>
      </div>
      <div class="vsr-chart-wrap"><canvas id="vsr-dash-chart"></canvas></div>
    </div>

    <div class="vsr-g2">
      <div class="vsr-card">
        <div class="vsr-card-hd"><span class="vsr-card-title">Top Pages</span></div>
        <div id="vsr-pages"><div class="vsr-empty">Loading…</div></div>
      </div>
      <div class="vsr-card">
        <div class="vsr-card-hd"><span class="vsr-card-title">Recent Visitors</span></div>
        <div id="vsr-recent"><div class="vsr-empty">Loading…</div></div>
      </div>
    </div>

    <div class="vsr-card vsr-ic-card" id="vsr-ic-card" style="display:none">
      <div class="vsr-card-hd">
        <span class="vsr-card-title">Incomplete Orders</span>
        <a href="${esc(acLink)}" class="vsr-ic-viewall">View all &rarr;</a>
      </div>
      <div class="vsr-ic-stats" id="vsr-ic-stats"></div>
      <div id="vsr-ic-table"></div>
    </div>
  `;

  /* ── Fetch all data ────────────────────────────────────── */
  Promise.all([
    VSR.get('stats/summary?range=30'),
    VSR.get('stats/chart?range=30'),
    VSR.get('stats/pages?range=30'),
    VSR.get('stats/recent'),
    VSR.get('stats/performance?range=30'),
    VSR.get('abandoned-cart/summary').catch(function (e) {
      var msg  = (e && e.message) || '';
      var code = 0;
      var m    = msg.match(/VSR API error: (\d+)/);
      if (m) code = parseInt(m[1], 10);
      if (code !== 404) console.warn('[VisitorLens] Incomplete orders endpoint:', msg || e);
      return code === 404 ? null : {};
    }),
  ]).then(function (results) {
    var summary = results[0], chart = results[1], pages = results[2],
        recent  = results[3], perf  = results[4], ic    = results[5];
    renderKpis(summary, perf);
    renderChart(chart);
    renderPages(pages);
    renderRecent(recent);
    if (ic !== null) renderIncompleteOrders(ic);
    startOnlineRefresh(summary);
  }).catch(function () {
    app.innerHTML = '<div class="vsr-err">Failed to load dashboard data. Please check REST API access.</div>';
  });

  /* ── KPI Cards ─────────────────────────────────────────── */
  function renderKpis(s, perf) {
    var onlineBadge = document.getElementById('vsr-online-badge');
    if (onlineBadge) onlineBadge.textContent = '● ' + (s.online || 0) + ' Online';

    var todayBadge = document.getElementById('vsr-today-badge');
    if (todayBadge) todayBadge.textContent = '● Today: ' + VSR.fmt(s.today_visitors || 0) + ' visitors';

    var avgMs    = (perf && perf.period_avg_ms) ? perf.period_avg_ms : 0;
    var loadLabel= avgMs > 0 ? fmtMs(avgMs) : '—';

    document.getElementById('vsr-kpis').innerHTML =
      kpi('Today Visitors',    s.today_visitors,  'Unique visitors today',  'vsr-kv-today-visitors') +
      kpi('Today Page Views',  s.today_views,     'Total views today',      'vsr-kv-today-views')     +
      kpi('30-Day Visitors',   s.period_visitors, 'Last 30 days')           +
      kpi('30-Day Page Views', s.period_views,    'Last 30 days')           +
      kpi('Avg Load Time',     loadLabel,          'Last 30 days');
  }

  function fmtMs(ms) {
    if (ms >= 1000) return (ms / 1000).toFixed(2) + 's';
    return ms + 'ms';
  }

  function kpi(label, val, sub, valueId) {
    var display = typeof val === 'string' ? val : VSR.fmt(val || 0);
    var valHtml = valueId
      ? '<div class="vsr-kpi-val" id="' + valueId + '">' + esc(display) + '</div>'
      : '<div class="vsr-kpi-val">' + esc(display) + '</div>';
    return '<div class="vsr-kpi">' +
      '<div class="vsr-kpi-label">' + esc(label) + '</div>' +
      valHtml +
      '<div class="vsr-kpi-sub">' + esc(sub) + '</div>' +
      '</div>';
  }

  /* ── 60-second online/today refresh ───────────────────── */
  function startOnlineRefresh() {
    setInterval(function () {
      VSR.get('stats/summary?range=30').then(function (s) {
        var onlineBadge = document.getElementById('vsr-online-badge');
        if (onlineBadge) onlineBadge.textContent = '● ' + (s.online || 0) + ' Online';

        var todayBadge = document.getElementById('vsr-today-badge');
        if (todayBadge) todayBadge.textContent = '● Today: ' + VSR.fmt(s.today_visitors || 0) + ' visitors';

        var tvEl = document.getElementById('vsr-kv-today-visitors');
        if (tvEl) tvEl.textContent = VSR.fmt(s.today_visitors || 0);

        var twEl = document.getElementById('vsr-kv-today-views');
        if (twEl) twEl.textContent = VSR.fmt(s.today_views || 0);
      });
    }, 60000);
  }

  /* ── Visitor Chart ─────────────────────────────────────── */
  function renderChart(data) {
    var canvas = document.getElementById('vsr-dash-chart');
    if (!canvas || !data || !data.length) return;
    if (typeof Chart === 'undefined') return;

    new Chart(canvas, {
      type: 'line',
      data: {
        labels: data.map(function (d) { return VSR.fmtDate(d.date); }),
        datasets: [
          {
            label: 'Visitors',
            data: data.map(function (d) { return +d.visitors; }),
            borderColor: '#3b82f6',
            backgroundColor: 'rgba(59,130,246,0.08)',
            tension: 0.3, fill: true, pointRadius: 3,
          },
          {
            label: 'Page Views',
            data: data.map(function (d) { return +d.page_views; }),
            borderColor: '#f59e0b',
            backgroundColor: 'rgba(245,158,11,0.07)',
            tension: 0.3, fill: true, pointRadius: 3,
          },
        ],
      },
      options: {
        responsive: true, maintainAspectRatio: false,
        plugins: { legend: { position: 'top', labels: { font: { size: 12 }, padding: 16 } } },
        scales: {
          x: { grid: { display: false }, ticks: { font: { size: 11 }, maxTicksLimit: 10 } },
          y: { beginAtZero: true, ticks: { font: { size: 11 } } },
        },
      },
    });
  }

  /* ── Top Pages ─────────────────────────────────────────── */
  function renderPages(pages) {
    var el = document.getElementById('vsr-pages');
    if (!pages || !pages.length) {
      el.innerHTML = '<div class="vsr-empty">No page data yet</div>';
      return;
    }
    var rows = pages.slice(0, 8).map(function (p) {
      return '<tr>' +
        '<td style="max-width:220px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap" title="' + esc(p.page_uri) + '">' +
          esc(p.page_title || p.page_uri) +
        '</td>' +
        '<td style="text-align:right;font-weight:600;color:#3b82f6">' + VSR.fmt(p.v) + '</td>' +
        '</tr>';
    }).join('');
    el.innerHTML = '<table class="vsr-tbl"><thead><tr><th>Page</th><th style="text-align:right">Views</th></tr></thead><tbody>' + rows + '</tbody></table>';
  }

  /* ── Recent Visitors ───────────────────────────────────── */
  function renderRecent(data) {
    var el       = document.getElementById('vsr-recent');
    var list     = (data && data.visitors) ? data.visitors : [];
    var onlineSet= {};
    if (data && data.online_ips) {
      data.online_ips.forEach(function (ip) { onlineSet[ip] = true; });
    }
    if (!list.length) {
      el.innerHTML = '<div class="vsr-empty">No recent visitors</div>';
      return;
    }
    var rows = list.slice(0, 8).map(function (v) {
      var live = onlineSet[v.ip_raw]
        ? '<span class="vsr-badge-live">● Live</span> '
        : '';
      return '<tr>' +
        '<td>' + live + VSR.flag(v.country_code) + ' ' + esc(v.ip_raw || '?') + '</td>' +
        '<td style="max-width:140px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:#64748b" title="' + esc(v.page_uri || '') + '">' +
          esc(v.page_title || v.page_uri || '/') +
        '</td>' +
        '<td style="text-align:right;color:#94a3b8;white-space:nowrap;font-size:12px">' + VSR.fmtTime(v.created_at) + '</td>' +
        '</tr>';
    }).join('');
    el.innerHTML = '<table class="vsr-tbl"><thead><tr><th>Visitor</th><th>Page</th><th style="text-align:right">Time</th></tr></thead><tbody>' + rows + '</tbody></table>';
  }

  /* ── Incomplete Orders Widget ──────────────────────────── */
  function renderIncompleteOrders(data) {
    var card = document.getElementById('vsr-ic-card');
    if (!card) return;
    card.style.display = '';

    // KPI stats row
    var statsEl = document.getElementById('vsr-ic-stats');
    if (statsEl) {
      var totalVal  = (data && data.total_count)     || 0;
      var yestVal   = (data && data.yesterday_count) || 0;
      var valueStr  = (data && data.currency)
        ? data.currency + ' ' + parseFloat(data.total_value || 0).toFixed(2)
        : parseFloat((data && data.total_value) || 0).toFixed(2);

      statsEl.innerHTML =
        icStat('Total incomplete', totalVal, 'All open orders &amp; carts', totalVal > 0 ? 'amber' : '') +
        icStat('New yesterday',    yestVal,  'Created yesterday',            yestVal  > 0 ? 'red'   : '') +
        icStatRaw('Total value',   valueStr, 'Combined cart &amp; order value', '');
    }

    // Mini table
    var tableEl = document.getElementById('vsr-ic-table');
    if (!tableEl) return;

    var items = (data && data.latest) || [];
    if (!items.length) {
      tableEl.innerHTML = '<div class="vsr-empty">No incomplete orders</div>';
      return;
    }

    var rows = items.map(function (it) {
      var badge = it.type === 'order'
        ? '<span class="vsr-badge-ic-order">WC Order</span>'
        : '<span class="vsr-badge-ic-cart">Cart</span>';

      var statusCls = 'vsr-ic-status-' + (it.status || 'abandoned').replace(/\s+/g, '-');
      var statusLbl = it.status ? it.status.replace(/-/g, ' ') : 'abandoned';
      var total     = it.total
        ? esc((it.currency || '') + ' ' + parseFloat(it.total).toFixed(2))
        : '—';
      var products  = (it.products || '').length > 40
        ? esc((it.products || '').substring(0, 40)) + '…'
        : esc(it.products || '—');

      return '<tr>' +
        '<td>' + badge + '</td>' +
        '<td style="font-weight:500">' + esc(it.customer_name || 'Anonymous') + '</td>' +
        '<td style="max-width:180px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:#64748b" title="' + esc(it.products || '') + '">' + products + '</td>' +
        '<td style="font-weight:600">' + total + '</td>' +
        '<td><span class="' + esc(statusCls) + '" style="font-weight:600;text-transform:capitalize">' + esc(statusLbl) + '</span></td>' +
        '<td style="color:#94a3b8;font-size:12px;white-space:nowrap">' + VSR.fmtTime(it.date) + '</td>' +
        '</tr>';
    }).join('');

    tableEl.innerHTML = '<table class="vsr-tbl">' +
      '<thead><tr>' +
      '<th>Type</th><th>Customer</th><th>Products</th><th>Total</th><th>Status</th><th>Date</th>' +
      '</tr></thead>' +
      '<tbody>' + rows + '</tbody>' +
      '</table>';
  }

  function icStat(label, val, sub, colorCls) {
    return '<div class="vsr-ic-stat">' +
      '<div class="vsr-ic-stat-label">' + label + '</div>' +
      '<div class="vsr-ic-stat-val ' + (colorCls || '') + '">' + VSR.fmt(val) + '</div>' +
      '<div class="vsr-ic-stat-sub">' + sub + '</div>' +
      '</div>';
  }

  function icStatRaw(label, valStr, sub, colorCls) {
    return '<div class="vsr-ic-stat">' +
      '<div class="vsr-ic-stat-label">' + esc(label) + '</div>' +
      '<div class="vsr-ic-stat-val ' + (colorCls || '') + '">' + esc(valStr) + '</div>' +
      '<div class="vsr-ic-stat-sub">' + sub + '</div>' +
      '</div>';
  }

  /* ── Helper ────────────────────────────────────────────── */
  function esc(s) {
    var d = document.createElement('div');
    d.textContent = s || '';
    return d.innerHTML;
  }

})();
