<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>BrowserFriend — Admin Dashboard</title>
  <style>
    :root {
      --bg: #0a0a0f;
      --surface: #12121a;
      --surface2: #1a1a26;
      --border: #2a2a3a;
      --text: #e4e4ef;
      --text-dim: #8888a0;
      --accent: #06b6d4;
      --accent-dim: #0e7490;
      --green: #22c55e;
      --red: #ef4444;
      --yellow: #eab308;
      --purple: #a855f7;
      --radius: 12px;
    }
    * { margin: 0; padding: 0; box-sizing: border-box; }
    body {
      font-family: 'SF Mono', 'Cascadia Code', 'Fira Code', 'JetBrains Mono', monospace;
      background: var(--bg);
      color: var(--text);
      min-height: 100vh;
      line-height: 1.6;
    }

    /* Header */
    .header {
      background: var(--surface);
      border-bottom: 1px solid var(--border);
      padding: 16px 32px;
      display: flex;
      align-items: center;
      justify-content: space-between;
      position: sticky;
      top: 0;
      z-index: 100;
      backdrop-filter: blur(12px);
    }
    .header-brand {
      display: flex;
      align-items: center;
      gap: 12px;
    }
    .header-brand .logo {
      width: 32px;
      height: 32px;
      background: linear-gradient(135deg, var(--accent), var(--purple));
      border-radius: 8px;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 16px;
    }
    .header-brand h1 {
      font-size: 18px;
      font-weight: 600;
      color: var(--text);
    }
    .header-brand h1 span {
      color: var(--accent);
    }
    .header-meta {
      font-size: 13px;
      color: var(--text-dim);
    }

    /* Tabs */
    .tabs {
      display: flex;
      gap: 4px;
      padding: 16px 32px 0;
      border-bottom: 1px solid var(--border);
      background: var(--surface);
    }
    .tab {
      padding: 10px 20px;
      font-size: 13px;
      font-weight: 500;
      color: var(--text-dim);
      cursor: pointer;
      border: none;
      background: none;
      font-family: inherit;
      border-bottom: 2px solid transparent;
      transition: all 0.2s;
    }
    .tab:hover { color: var(--text); }
    .tab.active {
      color: var(--accent);
      border-bottom-color: var(--accent);
    }

    /* Main */
    .main { padding: 24px 32px; max-width: 1400px; margin: 0 auto; }

    /* Stats Row */
    .stats-row {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
      gap: 16px;
      margin-bottom: 24px;
    }
    .stat-card {
      background: var(--surface);
      border: 1px solid var(--border);
      border-radius: var(--radius);
      padding: 20px;
    }
    .stat-card .label {
      font-size: 12px;
      color: var(--text-dim);
      text-transform: uppercase;
      letter-spacing: 0.5px;
      margin-bottom: 6px;
    }
    .stat-card .value {
      font-size: 28px;
      font-weight: 700;
    }
    .stat-card .value.accent { color: var(--accent); }
    .stat-card .value.green { color: var(--green); }
    .stat-card .value.purple { color: var(--purple); }
    .stat-card .value.yellow { color: var(--yellow); }

    /* Table */
    .table-wrapper {
      background: var(--surface);
      border: 1px solid var(--border);
      border-radius: var(--radius);
      overflow: hidden;
    }
    .table-header {
      padding: 16px 20px;
      border-bottom: 1px solid var(--border);
      display: flex;
      align-items: center;
      justify-content: space-between;
    }
    .table-header h2 {
      font-size: 15px;
      font-weight: 600;
    }
    .table-header .badge {
      background: var(--accent-dim);
      color: var(--accent);
      font-size: 11px;
      padding: 3px 10px;
      border-radius: 99px;
      font-weight: 600;
    }
    table {
      width: 100%;
      border-collapse: collapse;
      font-size: 13px;
    }
    thead th {
      text-align: left;
      padding: 12px 20px;
      font-size: 11px;
      font-weight: 600;
      color: var(--text-dim);
      text-transform: uppercase;
      letter-spacing: 0.5px;
      border-bottom: 1px solid var(--border);
      background: var(--surface2);
    }
    tbody td {
      padding: 14px 20px;
      border-bottom: 1px solid var(--border);
      vertical-align: middle;
    }
    tbody tr:last-child td { border-bottom: none; }
    tbody tr:hover { background: var(--surface2); }

    .status-dot {
      width: 8px;
      height: 8px;
      border-radius: 50%;
      display: inline-block;
      margin-right: 8px;
    }
    .status-dot.active { background: var(--green); box-shadow: 0 0 8px var(--green); }
    .status-dot.ended { background: var(--text-dim); }

    .session-id {
      font-family: 'SF Mono', 'Cascadia Code', monospace;
      font-size: 12px;
      color: var(--accent);
      background: rgba(6, 182, 212, 0.1);
      padding: 2px 8px;
      border-radius: 4px;
    }

    .btn {
      display: inline-flex;
      align-items: center;
      gap: 6px;
      padding: 8px 16px;
      font-size: 12px;
      font-weight: 600;
      font-family: inherit;
      border-radius: 8px;
      cursor: pointer;
      border: 1px solid var(--border);
      background: var(--surface2);
      color: var(--text);
      transition: all 0.15s;
    }
    .btn:hover { background: var(--border); }
    .btn-accent {
      background: var(--accent-dim);
      color: var(--accent);
      border-color: var(--accent-dim);
    }
    .btn-accent:hover { background: var(--accent); color: var(--bg); }

    /* Dashboard preview modal */
    .modal-overlay {
      display: none;
      position: fixed;
      inset: 0;
      background: rgba(0,0,0,0.7);
      z-index: 999;
      align-items: center;
      justify-content: center;
      backdrop-filter: blur(4px);
    }
    .modal-overlay.open { display: flex; }
    .modal {
      background: var(--surface);
      border: 1px solid var(--border);
      border-radius: var(--radius);
      width: 90vw;
      max-width: 900px;
      max-height: 85vh;
      display: flex;
      flex-direction: column;
    }
    .modal-top {
      padding: 16px 20px;
      border-bottom: 1px solid var(--border);
      display: flex;
      align-items: center;
      justify-content: space-between;
    }
    .modal-top h3 { font-size: 15px; }
    .modal-body {
      flex: 1;
      overflow: auto;
      padding: 0;
    }
    .modal-body iframe {
      width: 100%;
      height: 70vh;
      border: none;
      background: #fff;
      border-radius: 0 0 var(--radius) var(--radius);
    }
    .close-btn {
      background: none;
      border: none;
      color: var(--text-dim);
      font-size: 20px;
      cursor: pointer;
      padding: 4px 8px;
      border-radius: 6px;
    }
    .close-btn:hover { background: var(--surface2); color: var(--text); }

    /* Tab content */
    .tab-content { display: none; }
    .tab-content.active { display: block; }

    /* Empty state */
    .empty {
      text-align: center;
      padding: 60px 20px;
      color: var(--text-dim);
    }
    .empty .icon { font-size: 48px; margin-bottom: 16px; opacity: 0.5; }
    .empty p { font-size: 14px; }

    /* Loading */
    .loading {
      text-align: center;
      padding: 40px;
      color: var(--text-dim);
      font-size: 13px;
    }

    @media (max-width: 768px) {
      .header { padding: 12px 16px; }
      .tabs { padding: 12px 16px 0; }
      .main { padding: 16px; }
      .stats-row { grid-template-columns: repeat(2, 1fr); }
    }
  </style>
</head>
<body>

  <!-- Header -->
  <div class="header">
    <div class="header-brand">
      <div class="logo">bf</div>
      <h1>Browser<span>Friend</span></h1>
    </div>
    <div class="header-meta" id="userEmail">Loading...</div>
  </div>

  <!-- Tabs -->
  <div class="tabs">
    <button class="tab active" data-tab="sessions">Sessions</button>
    <button class="tab" data-tab="dashboards">Dashboards</button>
  </div>

  <!-- Main Content -->
  <div class="main">

    <!-- Stats -->
    <div class="stats-row" id="statsRow">
      <div class="stat-card">
        <div class="label">Total Sessions</div>
        <div class="value accent" id="statSessions">—</div>
      </div>
      <div class="stat-card">
        <div class="label">Total Visits</div>
        <div class="value green" id="statVisits">—</div>
      </div>
      <div class="stat-card">
        <div class="label">Total Time</div>
        <div class="value purple" id="statTime">—</div>
      </div>
      <div class="stat-card">
        <div class="label">Dashboards Sent</div>
        <div class="value yellow" id="statDashboards">—</div>
      </div>
    </div>

    <!-- Sessions Tab -->
    <div class="tab-content active" id="tab-sessions">
      <div class="table-wrapper">
        <div class="table-header">
          <h2>Browsing Sessions</h2>
          <span class="badge" id="sessionsCount">0</span>
        </div>
        <div id="sessionsTable"><div class="loading">Loading sessions...</div></div>
      </div>
    </div>

    <!-- Dashboards Tab -->
    <div class="tab-content" id="tab-dashboards">
      <div class="table-wrapper">
        <div class="table-header">
          <h2>Generated Dashboards</h2>
          <span class="badge" id="dashboardsCount">0</span>
        </div>
        <div id="dashboardsTable"><div class="loading">Loading dashboards...</div></div>
      </div>
    </div>
  </div>

  <!-- Modal for dashboard preview -->
  <div class="modal-overlay" id="modalOverlay">
    <div class="modal">
      <div class="modal-top">
        <h3 id="modalTitle">Dashboard Preview</h3>
        <button class="close-btn" id="modalClose">&times;</button>
      </div>
      <div class="modal-body">
        <iframe id="modalIframe" sandbox="allow-same-origin"></iframe>
      </div>
    </div>
  </div>

  <script>
    const API = '';

    // ─── Tab switching ───
    document.querySelectorAll('.tab').forEach(tab => {
      tab.addEventListener('click', () => {
        document.querySelectorAll('.tab').forEach(t => t.classList.remove('active'));
        document.querySelectorAll('.tab-content').forEach(c => c.classList.remove('active'));
        tab.classList.add('active');
        document.getElementById('tab-' + tab.dataset.tab).classList.add('active');
      });
    });

    // ─── Modal ───
    const overlay = document.getElementById('modalOverlay');
    const modalIframe = document.getElementById('modalIframe');
    const modalTitle = document.getElementById('modalTitle');
    document.getElementById('modalClose').addEventListener('click', () => {
      overlay.classList.remove('open');
      modalIframe.srcdoc = '';
    });
    overlay.addEventListener('click', (e) => {
      if (e.target === overlay) { overlay.classList.remove('open'); modalIframe.srcdoc = ''; }
    });

    function openDashboardPreview(id, sessionId) {
      modalTitle.textContent = 'Dashboard — Session ' + sessionId.slice(0, 8) + '…';
      modalIframe.srcdoc = '<p style="text-align:center;padding:40px;color:#888">Loading…</p>';
      overlay.classList.add('open');
      fetch(API + '/api/admin/dashboards/' + id + '/html')
        .then(r => r.text())
        .then(html => { modalIframe.srcdoc = html; })
        .catch(() => { modalIframe.srcdoc = '<p style="text-align:center;padding:40px;color:red">Failed to load</p>'; });
    }

    // ─── Helpers ───
    function fmtDuration(sec) {
      if (sec == null) return '—';
      sec = Math.round(sec);
      const h = Math.floor(sec / 3600);
      const m = Math.floor((sec % 3600) / 60);
      const s = sec % 60;
      if (h > 0) return h + 'h ' + m + 'm';
      if (m > 0) return m + 'm ' + s + 's';
      return s + 's';
    }
    function fmtDate(iso) {
      if (!iso) return '—';
      const d = new Date(iso);
      return d.toLocaleDateString(undefined, { month: 'short', day: 'numeric', year: 'numeric' })
        + ' ' + d.toLocaleTimeString(undefined, { hour: 'numeric', minute: '2-digit' });
    }

    // ─── Fetch & Render Sessions ───
    async function loadSessions() {
      try {
        const res = await fetch(API + '/api/admin/sessions');
        const data = await res.json();

        document.getElementById('userEmail').textContent = data.user_email || '';
        document.getElementById('statSessions').textContent = data.sessions.length;
        document.getElementById('statVisits').textContent = data.total_visits;
        document.getElementById('statTime').textContent = fmtDuration(data.total_time);
        document.getElementById('sessionsCount').textContent = data.sessions.length;

        if (data.sessions.length === 0) {
          document.getElementById('sessionsTable').innerHTML =
            '<div class="empty"><div class="icon">📭</div><p>No sessions yet. Run <code>bf start</code> to begin tracking.</p></div>';
          return;
        }

        let html = '<table><thead><tr>' +
          '<th>Status</th><th>Session ID</th><th>Started</th><th>Ended</th><th>Duration</th><th>Visits</th>' +
          '</tr></thead><tbody>';

        for (const s of data.sessions) {
          const active = !s.end_time;
          html += '<tr>' +
            '<td><span class="status-dot ' + (active ? 'active' : 'ended') + '"></span>' + (active ? 'Active' : 'Ended') + '</td>' +
            '<td><span class="session-id">' + s.session_id.slice(0, 8) + '…</span></td>' +
            '<td>' + fmtDate(s.start_time) + '</td>' +
            '<td>' + (s.end_time ? fmtDate(s.end_time) : '<span style="color:var(--green)">now</span>') + '</td>' +
            '<td>' + fmtDuration(s.duration) + '</td>' +
            '<td>' + s.visit_count + '</td>' +
            '</tr>';
        }
        html += '</tbody></table>';
        document.getElementById('sessionsTable').innerHTML = html;
      } catch (e) {
        document.getElementById('sessionsTable').innerHTML =
          '<div class="empty"><div class="icon">⚠️</div><p>Failed to load sessions.</p></div>';
      }
    }

    // ─── Fetch & Render Dashboards ───
    async function loadDashboards() {
      try {
        const res = await fetch(API + '/api/admin/dashboards');
        const data = await res.json();

        document.getElementById('statDashboards').textContent = data.dashboards.length;
        document.getElementById('dashboardsCount').textContent = data.dashboards.length;

        if (data.dashboards.length === 0) {
          document.getElementById('dashboardsTable').innerHTML =
            '<div class="empty"><div class="icon">📊</div><p>No dashboards yet. Run <code>bf dashboard</code> after a session.</p></div>';
          return;
        }

        let html = '<table><thead><tr>' +
          '<th>#</th><th>Session</th><th>Generated</th><th>Emailed</th><th></th>' +
          '</tr></thead><tbody>';

        for (const d of data.dashboards) {
          html += '<tr>' +
            '<td>' + d.id + '</td>' +
            '<td><span class="session-id">' + d.session_id.slice(0, 8) + '…</span></td>' +
            '<td>' + fmtDate(d.sent_at) + '</td>' +
            '<td>' + (d.email_sent ? '<span style="color:var(--green)">✓ Sent</span>' : '<span style="color:var(--red)">✗</span>') + '</td>' +
            '<td><button class="btn btn-accent" onclick="openDashboardPreview(' + d.id + ',\'' + d.session_id + '\')">View</button></td>' +
            '</tr>';
        }
        html += '</tbody></table>';
        document.getElementById('dashboardsTable').innerHTML = html;
      } catch (e) {
        document.getElementById('dashboardsTable').innerHTML =
          '<div class="empty"><div class="icon">⚠️</div><p>Failed to load dashboards.</p></div>';
      }
    }

    // ─── Init ───
    loadSessions();
    loadDashboards();
  </script>
</body>
</html>
