---
export const prerender = false;

import AdminLayout from '../../layouts/AdminLayout.astro';
import { getSession, SESSION_COOKIE } from '../../lib/auth';

// Redirect if already logged in
const sessionId = Astro.cookies.get(SESSION_COOKIE)?.value;
const session = sessionId ? getSession(sessionId) : undefined;
if (session) {
  return Astro.redirect('/admin');
}

const tokenAuthEnabled = Boolean(process.env.ADMIN_SECRET_TOKEN?.trim());
const tokenError = Astro.url.searchParams.get('tokenError') === '1';
---

<AdminLayout title="Login">
  <div class="login-wrap">
    <h1>admin access</h1>

    {tokenAuthEnabled ? (
      <div class="card">
        <h2>Token login</h2>
        <p class="info-text">
          Enter your admin token to access moderation.
        </p>
        {tokenError && (
          <p class="warning-text">Invalid token. Try again.</p>
        )}
        <form method="post" action="/api/admin/token-login" class="token-form">
          <label for="token-input" class="token-label">Admin token</label>
          <input
            id="token-input"
            name="token"
            type="password"
            autocomplete="current-password"
            required
            class="token-input"
          />
          <button type="submit" class="btn btn-primary">Sign in with token</button>
        </form>
      </div>
    ) : (
      <div class="card">
        <h2>Token not configured</h2>
        <p class="warning-text">
          <code>ADMIN_SECRET_TOKEN</code> is not set. Configure it in your environment, then reload this page.
        </p>
      </div>
    )}
  </div>

  <style>
  .login-wrap {
    max-width: 480px;
    margin: 0 auto;
  }

  h1 {
    margin-bottom: var(--space-md);
  }

  .info-text {
    color: var(--color-text-dim);
    font-size: 0.88rem;
    margin-bottom: var(--space-sm);
  }

  .warning-text {
    color: var(--color-peach);
    font-size: 0.82rem;
    margin-bottom: var(--space-md);
    padding: var(--space-xs) var(--space-sm);
    border-left: 2px solid var(--color-peach);
  }

  .btn {
    display: inline-block;
    padding: 8px 20px;
    border-radius: 4px;
    border: 1px solid currentColor;
    background: none;
    font-family: inherit;
    font-size: 0.9rem;
    cursor: pointer;
    transition: opacity 0.15s;
  }
  .btn:hover { opacity: 0.8; }
  .btn:disabled { opacity: 0.5; cursor: not-allowed; }
  .btn-primary { color: var(--color-accent); }

  .token-form {
    display: grid;
    gap: var(--space-xs);
  }

  .token-label {
    color: var(--color-text-dim);
    font-size: 0.82rem;
  }

  .token-input {
    width: 100%;
    max-width: 360px;
  }
  </style>
</AdminLayout>
