<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <meta name="theme-color" content="#6366f1" />
  <link rel="icon" type="image/png" sizes="32x32" href="/public/og/favicon-32.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/public/og/favicon-16.png">
  <link rel="apple-touch-icon" sizes="48x48" href="/public/og/favicon-48.png">
  <title>User — takedowns admin</title>
  <link rel="stylesheet" href="/public/css/glass.css?v=2-light" />
  <style>
    .user-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 1rem; }
    @media (max-width: 800px) { .user-grid { grid-template-columns: 1fr; } }
    .stat-row { display: flex; justify-content: space-between; align-items: center; padding: .5rem 0; border-bottom: 1px solid var(--border); }
    .stat-row:last-child { border-bottom: 0; }
    .stat-row .lbl { color: var(--text-3); font-size: .85rem; }
    .stat-row .val { font-weight: 600; }
    .actions-bar { display: flex; gap: .5rem; flex-wrap: wrap; margin-top: 1rem; }
    .back-link { color: var(--text-3); font-size: .85rem; text-decoration: none; margin-bottom: .5rem; display: inline-block; }
    .back-link:hover { color: var(--text-1); }
    .not-found { padding: 3rem; text-align: center; color: var(--text-3); }
    .not-found h2 { color: var(--text-1); }
  </style>
</head>
<body>
  <div class="app">
    <aside>
      <a href="/admin/" class="brand" aria-label="takedowns home">
        <img src="/public/og/logo-mark.png" alt="" width="30" height="30" />
        <span class="brand-wordmark">takedowns<small>admin</small></span>
      </a>
      <nav>
        <a href="/dashboard/">Dashboard</a>
        <a href="/admin/">Admin panel</a>
        <a href="/admin/#users" class="active">Users</a>
        <a href="/admin/#alerts">Alerts</a>
        <a href="/admin/#keys">API keys</a>
        <a href="/admin/#audit">Audit</a>
        <a href="#" id="logout">Sign out</a>
      </nav>
    </aside>
    <main>
      <a href="/admin/#users" class="back-link">← back to users</a>
      <div id="userHeader">
        <div class="muted">loading…</div>
      </div>
      <div id="userBody" style="margin-top:1rem"></div>
    </main>
  </div>
  <script>
  (function () {
    function csrf() { const m = document.cookie.match(/(?:^|; )ncsrf=([^;]+)/); return m ? m[1] : ''; }
    async function api(p, o = {}) {
      const r = await fetch(p, { ...o, headers: { 'content-type': 'application/json', 'x-csrf-token': csrf(), ...(o.headers || {}) } });
      if (r.status === 401) {
        const body = await r.json().catch(() => ({}));
        if (body.error === 'UNAUTHENTICATED' || !body.error) {
          location.href = '/login?next=' + encodeURIComponent(location.pathname);
          return null;
        }
        if (body.error === 'TWO_FA_REQUIRED') {
          alert('2FA required. Redirecting to admin panel.');
          location.href = '/admin/';
          return null;
        }
        return body;
      }
      if (!r.ok) { const t = await r.text().catch(() => ''); return { error: 'ERROR', message: t }; }
      return r.json();
    }
    function esc(s) { return String(s || '').replace(/[&<>"]/g, c => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;'}[c])); }
    function fmt(ms) { return ms ? new Date(ms).toLocaleString() : '—'; }

    const id = parseInt(location.pathname.split('/').pop(), 10);
    if (!id || isNaN(id)) {
      document.getElementById('userHeader').innerHTML = '<div class="not-found"><h2>Invalid user id</h2></div>';
      return;
    }

    (async function init() {
      const d = await api('/admin/users/' + id);
      if (!d) return;
      if (d.error) {
        document.getElementById('userHeader').innerHTML = `<div class="not-found"><h2>${esc(d.message || d.error)}</h2><p>User #${id} not found.</p></div>`;
        return;
      }
      const u = d.user;
      const initial = (u.name || u.email || '?')[0].toUpperCase();
      const status = u.suspended ? 'suspended' : (u.payment_failed ? 'payment_failed' : 'active');
      const statusCls = status === 'suspended' ? 'danger' : status === 'payment_failed' ? 'warn' : 'ok';
      document.getElementById('userHeader').innerHTML = `
        <header class="topbar" style="margin-bottom:0">
          <div style="display:flex;align-items:center;gap:1rem">
            <div class="avatar" style="width:56px;height:56px;font-size:1.4rem">${initial}</div>
            <div>
              <h1 style="margin:0">${esc(u.name || '—')}</h1>
              <div class="muted">${esc(u.email)} · <span class="pill ${statusCls}">${status}</span> · <span class="pill info">${esc(u.role)}</span></div>
            </div>
          </div>
          <div class="actions-bar" style="margin:0">
            <button class="warn" id="suspendBtn">${u.suspended ? 'Unsuspend' : 'Suspend'}</button>
            <button class="secondary" id="impersonateBtn">Impersonate</button>
            <button class="secondary" id="testBtn">Test note</button>
            <button class="secondary danger" id="deleteBtn">Delete</button>
          </div>
        </header>
        <div class="muted small-text" style="margin-top:.3rem">Joined ${fmt(u.created_at)} · last seen ${fmt(u.last_login_at)}</div>`;

      document.getElementById('userBody').innerHTML = `
        <div class="user-grid">
          <section class="panel">
            <h2>Account</h2>
            <div class="stat-row"><span class="lbl">User id</span><span class="val mono">#${u.id}</span></div>
            <div class="stat-row"><span class="lbl">Email</span><span class="val mono">${esc(u.email)}</span></div>
            <div class="stat-row"><span class="lbl">Email verified</span><span class="val">${u.email_verified ? '✓' : '—'}</span></div>
            <div class="stat-row"><span class="lbl">Role</span><span class="val">${esc(u.role)}</span></div>
            <div class="stat-row"><span class="lbl">Plan</span><span class="val">${esc(u.plan)}</span></div>
            <div class="stat-row"><span class="lbl">Plan override</span><span class="val mono small-text">${esc(u.plan_override || '—')}</span></div>
            <div class="stat-row"><span class="lbl">Status</span><span class="val"><span class="pill ${statusCls}">${status}</span></span></div>
            <div class="stat-row"><span class="lbl">Failed logins</span><span class="val">${u.failed_logins || 0}</span></div>
          </section>
          <section class="panel">
            <h2>Activity</h2>
            <div class="stat-row"><span class="lbl">Last login</span><span class="val">${fmt(u.last_login_at)}</span></div>
            <div class="stat-row"><span class="lbl">Last IP</span><span class="val mono small-text">${esc(u.last_login_ip || '—')}</span></div>
            <div class="stat-row"><span class="lbl">Strikes</span><span class="val">${u.failed_logins || 0}</span></div>
            <div class="stat-row"><span class="lbl">Stripe customer</span><span class="val mono small-text">${esc(u.stripe_customer_id || '—')}</span></div>
            <div class="stat-row"><span class="lbl">Stripe subscription</span><span class="val mono small-text">${esc(u.stripe_subscription_id || '—')}</span></div>
            <div class="stat-row"><span class="lbl">Extra credits</span><span class="val">${u.extra_scans || 0} scans, ${u.extra_takedowns || 0} takedowns</span></div>
            <div class="stat-row"><span class="lbl">Seats</span><span class="val">${u.seats || 1}</span></div>
            <div class="stat-row"><span class="lbl">Billing interval</span><span class="val">${esc(u.billing_interval || '—')}</span></div>
          </section>
        </div>`;

      // Action buttons
      document.getElementById('suspendBtn').onclick = async () => {
        if (!confirm(`${u.suspended ? 'Unsuspend' : 'Suspend'} ${u.email}?`)) return;
        const r = await api(`/admin/users/${u.id}/${u.suspended ? 'unsuspend' : 'suspend'}`, { method: 'POST' });
        if (r && r.ok) location.reload(); else alert('Failed.');
      };
      document.getElementById('impersonateBtn').onclick = async () => {
        if (!confirm(`Impersonate ${u.email}?`)) return;
        await api(`/admin/users/${u.id}/impersonate`, { method: 'POST' });
        location.href = '/dashboard/';
      };
      document.getElementById('deleteBtn').onclick = async () => {
        if (!confirm(`Delete ${u.email} permanently?`)) return;
        await api(`/admin/users/${u.id}/delete`, { method: 'POST' });
        location.href = '/admin/#users';
      };
      document.getElementById('testBtn').onclick = () => alert('Notes feature ships separately — see admin → users row for the 📝 action.');
    })();

    document.getElementById('logout').onclick = async (e) => {
      e.preventDefault();
      await api('/auth/logout', { method: 'POST' });
      location.href = '/login';
    };
  })();
  </script>
  <script src="/public/js/siteHealth.js" defer></script>
</body>
</html>