---
export const prerender = false;

import { isAuthenticated, ADMIN_COOKIE } from '@admin/lib/admin-auth';

interface Env { DB: D1Database }
const runtime = Astro.locals.runtime as { env: Env } | undefined;
const db = runtime?.env?.DB;
if (!db || !await isAuthenticated(Astro.cookies.get(ADMIN_COOKIE)?.value, db)) {
  return Astro.redirect('/admin/login', 302);
}

interface ScraperRun {
  id: number; chain_id: string; city_id: string;
  started_at: string; finished_at: string | null; status: string;
  movies_found: number; showtimes_found: number; error_message: string | null;
}

let runs: ScraperRun[] = [];
let dbError: string | null = null;
const page = Number(Astro.url.searchParams.get('page') ?? '1');
const limit = 100;
const offset = (page - 1) * limit;

if (db) {
  try {
    const result = await db.prepare('SELECT * FROM scraper_runs ORDER BY id DESC LIMIT ? OFFSET ?').bind(limit, offset).all();
    runs = result.results as ScraperRun[];
  } catch (e) {
    dbError = String(e);
  }
} else {
  dbError = 'D1 database binding not available.';
}

function duration(started: string, finished: string | null): string {
  if (!finished) return '—';
  const ms = new Date(finished).getTime() - new Date(started).getTime();
  if (ms < 0) return '—';
  const s = Math.round(ms / 1000);
  return s < 60 ? `${s}s` : `${Math.floor(s / 60)}m ${s % 60}s`;
}

function relativeTime(dt: string | null): string {
  if (!dt) return '—';
  const m = Math.floor((Date.now() - new Date(dt).getTime()) / 60000);
  if (m < 1) return 'just now';
  if (m < 60) return `${m}m ago`;
  const h = Math.floor(m / 60);
  if (h < 24) return `${h}h ago`;
  return `${Math.floor(h / 24)}d ago`;
}
---
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <title>All Runs — CultRoll Admin</title>
  <link rel="icon" href="/favicon.svg" type="image/svg+xml" />
  <style>
    *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
    body { background: #0a0a0a; color: #e6e6e6; font-family: system-ui, sans-serif; font-size: 0.9rem; }
    a { color: #b78a3c; text-decoration: none; }
    a:hover { text-decoration: underline; }
    .sidebar { position: fixed; top: 0; left: 0; width: 220px; height: 100vh; background: #111; border-right: 1px solid #222; padding: 1.5rem 1rem; display: flex; flex-direction: column; gap: 0.25rem; overflow-y: auto; }
    .main { margin-left: 220px; padding: 2rem; }
    .logo { display: flex; align-items: center; gap: 0.5rem; font-weight: 700; letter-spacing: 0.1em; color: #fff; font-size: 0.95rem; margin-bottom: 1.5rem; }
    .nav-section { font-size: 0.7rem; font-weight: 600; color: #555; text-transform: uppercase; letter-spacing: 0.1em; padding: 0.75rem 0.5rem 0.25rem; }
    .nav-link { display: block; padding: 0.5rem 0.75rem; border-radius: 6px; color: #aaa; font-size: 0.85rem; }
    .nav-link:hover, .nav-link.active { background: #1a1a1a; color: #fff; text-decoration: none; }
    .page-header { display: flex; align-items: center; gap: 1rem; margin-bottom: 1.5rem; }
    .page-header h1 { font-size: 1.3rem; font-weight: 700; color: #fff; }
    .badge { display: inline-block; padding: 0.2em 0.55em; border-radius: 4px; font-size: 0.7rem; font-weight: 700; text-transform: uppercase; letter-spacing: 0.05em; }
    .badge-success { background: #0d2e1e; color: #34d399; }
    .badge-failed { background: #2a1010; color: #f87171; }
    .badge-running { background: #1a200a; color: #facc15; }
    .badge-partial { background: #1a160a; color: #fb923c; }
    .db-error { background: #2a1010; border: 1px solid #5a2020; border-radius: 8px; padding: 1rem; color: #f87171; margin-bottom: 1.5rem; }
    .table-wrap { overflow-x: auto; }
    table { width: 100%; border-collapse: collapse; font-size: 0.82rem; }
    thead th { background: #111; color: #666; font-size: 0.7rem; font-weight: 700; text-transform: uppercase; letter-spacing: 0.08em; padding: 0.5rem 0.75rem; text-align: left; border-bottom: 1px solid #222; }
    tbody tr { border-bottom: 1px solid #1a1a1a; }
    tbody tr:hover { background: #141414; }
    tbody td { padding: 0.55rem 0.75rem; color: #ccc; vertical-align: middle; }
    .mono { font-family: 'Courier New', monospace; font-size: 0.78rem; }
    .error-cell { color: #f87171; font-size: 0.75rem; max-width: 200px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
    .pagination { display: flex; gap: 1rem; margin-top: 1.5rem; font-size: 0.85rem; }
  </style>
</head>
<body>
  <nav class="sidebar">
    <div class="logo">
      <svg viewBox="0 0 32 32" width="22" height="22" xmlns="http://www.w3.org/2000/svg">
        <rect width="32" height="32" rx="6" fill="#0a0a0a"/>
        <circle cx="16" cy="16" r="10" fill="none" stroke="#e6e6e6" stroke-width="1.5"/>
        <circle cx="16" cy="16" r="3.5" fill="#e6e6e6"/>
        <circle cx="16" cy="7" r="1.5" fill="#0a0a0a"/>
        <circle cx="16" cy="25" r="1.5" fill="#0a0a0a"/>
        <circle cx="7" cy="16" r="1.5" fill="#0a0a0a"/>
        <circle cx="25" cy="16" r="1.5" fill="#0a0a0a"/>
        <circle cx="9.7" cy="9.7" r="1.5" fill="#0a0a0a"/>
        <circle cx="22.3" cy="22.3" r="1.5" fill="#0a0a0a"/>
        <circle cx="22.3" cy="9.7" r="1.5" fill="#0a0a0a"/>
        <circle cx="9.7" cy="22.3" r="1.5" fill="#0a0a0a"/>
      </svg>
      CULTROLL
    </div>
    <div class="nav-section">Overview</div>
    <a href="/admin" class="nav-link">Dashboard</a>
    <div class="nav-section">Scraper</div>
    <a href="/admin/runs" class="nav-link active">All Runs</a>
    <div class="nav-section">Account</div>
    <a href="/admin/password" class="nav-link">Change Password</a>
    <div class="nav-section">Data</div>
    <a href="/admin/titles" class="nav-link">Titles</a>
    <a href="/admin/cast" class="nav-link">Cast</a>
    <a href="/" class="nav-link" target="_blank">↗ Live Site</a>
  </nav>

  <main class="main">
    <div class="page-header">
      <h1>All Scraper Runs</h1>
      <span style="font-size:0.78rem;color:#555">page {page}</span>
    </div>

    {dbError && <div class="db-error">⚠ DB error: {dbError}</div>}

    <div class="table-wrap">
      <table>
        <thead>
          <tr>
            <th>#</th>
            <th>Chain</th>
            <th>City</th>
            <th>Status</th>
            <th>Started</th>
            <th>Duration</th>
            <th>Movies</th>
            <th>Showtimes</th>
            <th>Error</th>
          </tr>
        </thead>
        <tbody>
          {runs.length === 0 && (
            <tr><td colspan="9" style="color:#555;text-align:center;padding:1.5rem">No runs found.</td></tr>
          )}
          {runs.map(run => (
            <tr>
              <td><a href={`/admin/runs/${run.id}`} class="mono">#{run.id}</a></td>
              <td class="mono">{run.chain_id}</td>
              <td class="mono">{run.city_id ?? '—'}</td>
              <td><span class={`badge badge-${run.status}`}>{run.status}</span></td>
              <td title={run.started_at}>{relativeTime(run.started_at)}</td>
              <td>{duration(run.started_at, run.finished_at)}</td>
              <td>{run.movies_found ?? 0}</td>
              <td>{run.showtimes_found ?? 0}</td>
              <td class="error-cell" title={run.error_message ?? ''}>{run.error_message ?? ''}</td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>

    <div class="pagination">
      {page > 1 && <a href={`/admin/runs?page=${page - 1}`}>← Previous</a>}
      {runs.length === limit && <a href={`/admin/runs?page=${page + 1}`}>Next →</a>}
    </div>
  </main>
</body>
</html>
