// ═══════════════════════════════════════════════════════════════════════
// Admin panel — passcode login + Cloudflare status helper.
// Dark studio theme.
// ═══════════════════════════════════════════════════════════════════════

function LoginModal({ onSubmit, onClose }) {
  const [pw, setPw] = React.useState("");
  const [error, setError] = React.useState("");
  const [busy, setBusy] = React.useState(false);
  const firstRef = React.useRef(null);

  React.useEffect(() => { firstRef.current?.focus(); }, []);

  const submit = async (e) => {
    e?.preventDefault();
    setError("");
    setBusy(true);
    const result = await onSubmit(pw);
    setBusy(false);
    if (!result.ok) {
      setError("// " + (result.error || "Try again."));
      setPw("");
    }
  };

  return (
    <div className="login-backdrop" onClick={onClose}>
      <form className="login-card" onClick={(e) => e.stopPropagation()} onSubmit={submit}>
        <div className="login-corner tl" />
        <div className="login-corner tr" />
        <div className="login-corner bl" />
        <div className="login-corner br" />

        <div className="login-glyph">
          <BrandGlyph letter="A" size={40} />
        </div>
        <div className="login-tag">[ STUDIO ACCESS · v2.6 ]</div>
        <h3>Authenticate</h3>
        <p className="login-sub">// Enter your admin password to edit</p>

        <input
          ref={firstRef}
          type="password"
          value={pw}
          onChange={(e) => { setPw(e.target.value); setError(""); }}
          placeholder="••••••••"
          autoComplete="current-password"
        />

        {error && <div className="login-error">{error}</div>}

        <div className="login-actions">
          <button type="button" className="btn-mini" onClick={onClose} disabled={busy}>Cancel</button>
          <button type="submit" className="btn-mini primary" disabled={busy}>
            {busy ? "// signing in…" : "→ Enter"}
          </button>
        </div>

        <p className="login-hint">
          // Local mode · default passcode: <code>changeme</code><br />
          Edit <code>index.html</code> → <code>ADMIN_PASSCODE</code>, or set the
          <code>ADMIN_PASSWORD</code> secret once deployed to Cloudflare
        </p>
      </form>
    </div>
  );
}

function AdminToolbar({ status, onLogout, onConfigOpen, onSettingsOpen }) {
  return (
    <div className="admin-toolbar" data-noncommentable>
      <div className="at-status">
        <span className={`at-dot ${status.mode}`} />
        <span className="at-text">
          {status.mode === "cloud" ? "LIVE · CLOUDFLARE" : "LOCAL · BROWSER"}
        </span>
      </div>
      <div className="at-hint">
        <span>Click anything to edit</span>
      </div>
      <div className="at-actions">
        {onSettingsOpen && <button onClick={onSettingsOpen} title="Site settings (link preview)">Settings</button>}
        <button onClick={onConfigOpen} title="Cloudflare status">⚙</button>
        <button onClick={onLogout}>Sign out</button>
      </div>
    </div>
  );
}

function ConfigModal({ status, onClose }) {
  const configured = window.isCloudConfigured();
  return (
    <div className="login-backdrop" onClick={onClose}>
      <div className="config-card" onClick={(e) => e.stopPropagation()}>
        <div className="login-corner tl" />
        <div className="login-corner tr" />
        <div className="login-corner bl" />
        <div className="login-corner br" />

        <div className="login-tag">[ CLOUDFLARE / STATUS ]</div>
        <h3>Cloud sync</h3>
        <div className={`config-status ${status.mode}`}>
          <span className="led" /> {configured ? "// Connected — content, media and login all run on Cloudflare" : "// Not deployed yet — using browser storage"}
        </div>
        {status.error && <div className="config-error">// {status.error}</div>}

        <ol className="config-steps">
          <li>Install <a href="https://developers.cloudflare.com/workers/wrangler/install-and-update/" target="_blank" rel="noreferrer">Wrangler</a>, Cloudflare's CLI, and run <code>wrangler login</code>.</li>
          <li>Create the KV namespace and R2 bucket, and set the <code>ADMIN_PASSWORD</code> / <code>SESSION_SECRET</code> secrets.</li>
          <li>Run <code>wrangler pages deploy .</code> to publish this site, its API, and its media store.</li>
        </ol>

        <p className="config-hint">
          // Full steps are in <code>SETUP_CLOUDFLARE.md</code>. Without Cloudflare, edits save only on this browser. Once deployed, edits and uploads sync everywhere.
        </p>

        <div className="login-actions">
          <button className="btn-mini primary" onClick={onClose}>→ Got it</button>
        </div>
      </div>
    </div>
  );
}

// ── styles (dark studio) ────────────────────────────────────────────────

const ADMIN_STYLES = `
  .login-backdrop {
    position: fixed;
    inset: 0;
    background: rgba(0, 0, 0, 0.75);
    backdrop-filter: blur(6px);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 1000;
    animation: backdrop-in 0.25s ease;
  }
  @keyframes backdrop-in { from { opacity: 0; } to { opacity: 1; } }

  .login-card, .config-card {
    background: var(--bg-2);
    padding: 40px;
    width: min(440px, 92vw);
    box-shadow: 0 24px 80px -16px rgba(0,0,0,0.8);
    border: 1px solid var(--line);
    position: relative;
    font-family: var(--sans);
    color: var(--ink);
    animation: card-in 0.3s cubic-bezier(0.2,0.7,0.2,1);
  }
  .config-card { width: min(560px, 92vw); max-height: 86vh; overflow-y: auto; }
  @keyframes card-in {
    from { transform: translateY(20px) scale(0.96); opacity: 0; }
    to   { transform: none; opacity: 1; }
  }

  .login-corner {
    position: absolute;
    width: 18px; height: 18px;
    border: 1.5px solid var(--accent);
    pointer-events: none;
  }
  .login-corner.tl { top: 10px; left: 10px;    border-right: 0; border-bottom: 0; }
  .login-corner.tr { top: 10px; right: 10px;   border-left: 0;  border-bottom: 0; }
  .login-corner.bl { bottom: 10px; left: 10px; border-right: 0; border-top: 0; }
  .login-corner.br { bottom: 10px; right: 10px;border-left: 0;  border-top: 0; }

  .login-glyph {
    display: flex; justify-content: center;
    margin-bottom: 14px;
  }
  .login-tag {
    text-align: center;
    font-family: var(--mono);
    font-size: 10.5px;
    letter-spacing: 0.16em;
    color: var(--accent);
    margin-bottom: 14px;
  }

  .login-card h3, .config-card h3 {
    font-family: var(--display);
    font-weight: 500;
    font-size: 32px;
    margin: 0 0 4px;
    text-align: center;
    letter-spacing: -0.02em;
    color: var(--ink);
  }

  .login-sub {
    font-family: var(--mono);
    font-size: 11px;
    letter-spacing: 0.06em;
    color: var(--mute);
    text-align: center;
    margin: 8px 0 24px;
  }

  .login-card input {
    width: 100%;
    padding: 14px 16px;
    border: 1px solid var(--line);
    background: var(--bg);
    color: var(--ink);
    font-family: var(--mono);
    font-size: 18px;
    text-align: center;
    letter-spacing: 0.4em;
    outline: none;
  }
  .login-card input:focus { border-color: var(--accent); }

  .login-error {
    margin-top: 12px;
    color: var(--red);
    font-family: var(--mono);
    font-size: 11px;
    text-align: center;
    letter-spacing: 0.06em;
  }

  .login-actions {
    display: flex;
    justify-content: flex-end;
    gap: 8px;
    margin-top: 24px;
  }

  .login-hint {
    margin-top: 20px;
    padding-top: 16px;
    border-top: 1px solid var(--line);
    font-family: var(--mono);
    font-size: 10.5px;
    color: var(--mute);
    line-height: 1.7;
    text-align: center;
    letter-spacing: 0.04em;
  }
  .login-hint code, .config-card code {
    font-family: var(--mono);
    background: var(--bg);
    padding: 1px 6px;
    border: 1px solid var(--line);
    font-size: 11px;
    color: var(--accent);
  }

  /* btn-mini override for dark theme */
  .btn-mini {
    padding: 8px 14px;
    border: 1px solid var(--line);
    background: transparent;
    color: var(--ink);
    font-family: var(--mono);
    font-size: 11px;
    letter-spacing: 0.06em;
    text-transform: uppercase;
    cursor: pointer;
    transition: all 0.15s ease;
  }
  .btn-mini:hover { background: var(--bg-3); border-color: var(--line-2); }
  .btn-mini.primary { background: var(--accent); color: var(--bg); border-color: var(--accent); }
  .btn-mini.primary:hover { background: var(--ink); color: var(--bg); border-color: var(--ink); }
  .btn-mini.danger { color: var(--red); border-color: var(--red); }
  .btn-mini.danger:hover { background: var(--red); color: var(--bg); }

  /* Admin toolbar (bottom-center, dark) */
  .admin-toolbar {
    position: fixed;
    bottom: 24px;
    left: 50%;
    transform: translateX(-50%);
    background: var(--bg-2);
    border: 1px solid var(--accent);
    color: var(--ink);
    padding: 10px 14px 10px 18px;
    display: flex;
    align-items: center;
    gap: 18px;
    z-index: 90;
    font-family: var(--mono);
    font-size: 11px;
    letter-spacing: 0.06em;
    box-shadow: 0 12px 32px -8px rgba(0,0,0,0.6), 0 0 32px color-mix(in oklab, var(--accent) 20%, transparent);
    animation: tb-in 0.4s cubic-bezier(0.2,0.7,0.2,1);
  }
  @keyframes tb-in {
    from { transform: translate(-50%, 20px); opacity: 0; }
    to   { transform: translateX(-50%); opacity: 1; }
  }
  .at-status { display: flex; align-items: center; gap: 8px; }
  .at-dot {
    width: 8px; height: 8px; border-radius: 50%;
    background: var(--warn);
    box-shadow: 0 0 8px var(--warn);
  }
  .at-dot.cloud { background: var(--accent); box-shadow: 0 0 8px var(--accent); animation: pulse-dot 2s infinite; }
  @keyframes pulse-dot {
    0%, 100% { opacity: 0.7; }
    50% { opacity: 1; }
  }
  .at-hint > span {
    font-family: var(--mono);
    font-size: 11px;
    color: var(--accent);
    letter-spacing: 0.04em;
    text-transform: uppercase;
  }
  .at-actions { display: flex; gap: 6px; }
  .at-actions button {
    background: transparent;
    color: var(--ink);
    border: 1px solid var(--line);
    padding: 5px 10px;
    cursor: pointer;
    font-family: var(--mono);
    font-size: 11px;
    transition: all 0.15s ease;
    letter-spacing: 0.04em;
    text-transform: uppercase;
  }
  .at-actions button:hover { background: var(--accent); color: var(--bg); border-color: var(--accent); }

  /* Config modal */
  .config-status {
    text-align: center;
    margin: 0 0 16px;
    font-family: var(--mono);
    font-size: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
    color: var(--ink-2);
  }
  .config-status .led {
    width: 8px; height: 8px;
    border-radius: 50%;
    background: var(--warn);
    box-shadow: 0 0 8px var(--warn);
  }
  .config-status.cloud { color: var(--accent); }
  .config-status.cloud .led { background: var(--accent); box-shadow: 0 0 8px var(--accent); }

  .config-error {
    background: color-mix(in oklab, var(--red) 12%, transparent);
    color: var(--red);
    padding: 10px 14px;
    margin-bottom: 16px;
    font-family: var(--mono);
    font-size: 11.5px;
    border-left: 3px solid var(--red);
    letter-spacing: 0.04em;
  }

  .config-steps {
    padding-left: 22px;
    margin: 0 0 16px;
    line-height: 1.7;
    font-family: var(--sans);
    font-size: 14px;
    color: var(--ink-2);
  }
  .config-steps li { margin-bottom: 6px; }
  .config-steps a { color: var(--accent); text-decoration: underline; }

  .config-details {
    margin: 12px 0;
    padding: 10px 14px;
    background: var(--bg);
    border: 1px solid var(--line);
  }
  .config-details summary {
    cursor: pointer;
    color: var(--mute);
    font-family: var(--mono);
    letter-spacing: 0.06em;
    font-size: 11px;
    text-transform: uppercase;
  }
  .config-details pre {
    margin: 10px 0 0;
    font-family: var(--mono);
    font-size: 11px;
    white-space: pre-wrap;
    word-break: break-all;
    color: var(--ink-2);
  }

  .config-hint {
    margin: 16px 0 0;
    padding: 14px;
    background: color-mix(in oklab, var(--accent) 8%, transparent);
    border-left: 3px solid var(--accent);
    font-family: var(--mono);
    font-size: 11.5px;
    line-height: 1.6;
    color: var(--ink-2);
    letter-spacing: 0.02em;
  }
`;

function AdminStyles() {
  return <style>{ADMIN_STYLES}</style>;
}

window.LoginModal = LoginModal;
window.AdminToolbar = AdminToolbar;
window.ConfigModal = ConfigModal;
window.AdminStyles = AdminStyles;
