---
import { SITE } from "../../lib/blog-data.js";
// Public page (NOT gated — you must be able to reach it to log in). It reveals
// the console only after a successful admin login sets the session. The gate
// lives on /devconsole + /_preview, not here.
---

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>Admin — {SITE.name}</title>
    <meta name="robots" content="noindex, nofollow" />
    <link rel="stylesheet" href="/styles-admin.css" />
    <link rel="icon" href="/favicon.svg" type="image/svg+xml" />
    <style is:global>
      :root {
        --paper: #f6f5f2; --ink: #14151a; --ink3: #6e7078; --ink4: #9a9ca3;
        --rule: #dfddd7; --seal: #d0342c; --card: #efeeea;
        --serif: "Fraunces", ui-serif, Georgia, serif;
        --sans: "Inter", ui-sans-serif, system-ui, sans-serif;
        --mono: "JetBrains Mono", ui-monospace, monospace;
      }
      @media (prefers-color-scheme: dark) {
        :root { --paper:#121317; --ink:#edece8; --ink3:#8b8d95; --ink4:#5e606a;
                --rule:#2a2c33; --seal:#e8564a; --card:#191a1f; }
      }
      * { box-sizing: border-box; }
      /* .panel sets display:flex, which would otherwise beat the [hidden]
         attribute's UA display:none — force hidden to win so the login and
         signed-in panels actually toggle. */
      [hidden] { display: none !important; }
      body {
        margin: 0; min-height: 100dvh; display: grid; place-items: center;
        background: var(--paper); color: var(--ink); font-family: var(--sans);
        padding: 2rem;
      }
      .card {
        width: 100%; max-width: 24rem; display: flex; flex-direction: column; gap: 1.5rem;
      }
      .seal {
        display: inline-flex; align-items: center; justify-content: center;
        width: 2rem; height: 2rem; border-radius: 2px; background: var(--seal);
        color: #fff; font-family: var(--serif); font-size: 1rem;
      }
      h1 { font-family: var(--serif); font-weight: 400; font-size: 1.6rem; margin: 0; letter-spacing: -0.01em; }
      .sub { margin: 0; font-size: 0.85rem; color: var(--ink3); line-height: 1.5; }
      label { font-family: var(--mono); font-size: 0.62rem; letter-spacing: 0.14em;
              text-transform: uppercase; color: var(--ink4); display: block; margin-bottom: 0.4rem; }
      input {
        width: 100%; border: 0; border-bottom: 1px solid var(--rule); background: transparent;
        padding: 0.6rem 0; font-size: 1rem; color: var(--ink); font-family: var(--sans);
      }
      input:focus { outline: none; border-bottom-color: var(--seal); }
      .field { display: flex; flex-direction: column; }
      .field + .field { margin-top: 1.1rem; }
      button {
        margin-top: 1.4rem; width: 100%; border: 1px solid var(--ink); background: var(--ink);
        color: var(--paper); border-radius: 2px; padding: 0.8rem; font-size: 0.9rem; font-weight: 500;
        cursor: pointer; font-family: var(--sans); transition: opacity .2s;
      }
      button:disabled { opacity: 0.55; cursor: default; }
      .msg { font-size: 0.82rem; min-height: 1.2em; }
      .msg.error { color: var(--seal); }
      .panel { display: flex; flex-direction: column; gap: 1rem; }
      .panel .row { display: flex; align-items: baseline; gap: 0.6rem; font-size: 0.9rem; }
      .steps { margin: 0; padding: 0; list-style: none; display: flex; flex-direction: column; gap: 0.6rem; }
      .steps li { position: relative; padding-left: 1.1rem; font-size: 0.88rem; line-height: 1.5; color: var(--ink3); }
      .steps li::before { content:""; position:absolute; left:0; top:0.62em; width:0.5rem; height:1px; background:var(--seal); }
      a.link { color: var(--ink); border-bottom: 1px solid var(--ink4); text-decoration: none; }
      .links { display: flex; flex-direction: column; gap: 0.7rem; }
      .links a { align-self: flex-start; font-size: 0.95rem; }
      .links a:hover { border-bottom-color: var(--seal); }
      .ghost { background: transparent; color: var(--ink); border-color: var(--rule); }
      .mono-note { font-family: var(--mono); font-size: 0.6rem; letter-spacing: 0.1em;
                   text-transform: uppercase; color: var(--ink4); }
    </style>
  </head>
  <body>
    <div class="card">
      <div style="display:flex;align-items:center;gap:.75rem">
        <span class="seal" aria-hidden="true">印</span>
        <span class="mono-note">Carlos Arias · Admin</span>
      </div>

      <!-- login -->
      <form id="login" class="panel" hidden>
        <div>
          <h1>Sign in</h1>
          <p class="sub">Admin access to the editing console.</p>
        </div>
        <div class="field">
          <label for="u">Username</label>
          <input id="u" name="username" autocomplete="username" autofocus />
        </div>
        <div class="field">
          <label for="p">Password</label>
          <input id="p" name="password" type="password" autocomplete="current-password" />
        </div>
        <button type="submit" id="go">Sign in</button>
        <p class="msg" id="loginMsg" role="status" aria-live="polite"></p>
      </form>

      <!-- signed in -->
      <div id="in" class="panel" hidden>
        <div>
          <h1>You&rsquo;re in.</h1>
          <p class="sub">Signed in as <strong id="who"></strong>. The editing console is now active across the site.</p>
        </div>
        <div class="links">
          <a class="link" href="/admin/designer">Web Designer &rarr;</a>
          <a class="link" href="/admin/projects">Manage projects &rarr;</a>
          <a class="link" href="/">Go to the site &rarr;</a>
        </div>
        <ul class="steps">
          <li>Or open any page and click the <strong>▲ astroagent</strong> handle to edit it in place.</li>
        </ul>
        <button class="ghost" id="out" type="button" style="margin-top:.4rem">Sign out</button>
      </div>

      <p class="msg" id="boot">Checking session…</p>
    </div>

    <script>
      const $ = (id) => document.getElementById(id);
      const login = $("login"), panel = $("in"), boot = $("boot");

      const show = (authed, username) => {
        boot.hidden = true;
        login.hidden = authed;
        panel.hidden = !authed;
        if (authed) $("who").textContent = username || "admin";
      };

      const check = async () => {
        try {
          const r = await fetch("/api/adminauth/me", { credentials: "same-origin" });
          const d = await r.json();
          show(Boolean(d?.data?.admin), d?.data?.username);
        } catch {
          show(false);
        }
        // invalid/expired secret link -> /admin?e=1
        if (new URLSearchParams(location.search).get("e") === "1") {
          const m = $("loginMsg");
          m.textContent = "That login link is invalid or expired.";
          m.className = "msg error";
        }
      };

      $("login").addEventListener("submit", async (e) => {
        e.preventDefault();
        const btn = $("go"), msg = $("loginMsg");
        msg.textContent = ""; msg.className = "msg";
        btn.disabled = true; btn.textContent = "Signing in…";
        try {
          const r = await fetch("/api/adminauth/login", {
            method: "POST",
            credentials: "same-origin",
            headers: { "content-type": "application/json" },
            body: JSON.stringify({ username: $("u").value.trim(), password: $("p").value }),
          });
          const d = await r.json();
          if (r.ok && d?.data?.admin) {
            show(true, d.data.username);
          } else {
            msg.textContent = d?.error?.message || "Sign-in failed.";
            msg.className = "msg error";
          }
        } catch {
          msg.textContent = "Couldn't reach the server.";
          msg.className = "msg error";
        } finally {
          btn.disabled = false; btn.textContent = "Sign in";
        }
      });

      $("out").addEventListener("click", async () => {
        try { await fetch("/api/adminauth/logout", { method: "POST", credentials: "same-origin" }); } catch {}
        show(false);
      });

      check();
    </script>
  </body>
</html>
