---
export const prerender = false;
import '../../../styles/global.css';
import { loadContent } from '../../../lib/content';
import { CONTENT_SCHEMAS, type ContentKey } from '../../../content/schemas';

const { section } = Astro.params;

if (!section || !(section in CONTENT_SCHEMAS)) {
  return Astro.redirect('/admin');
}

const key = section as ContentKey;
const data = await loadContent(key);
const jsonString = JSON.stringify(data, null, 2);
---

<!doctype html>
<html lang="fr">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Admin — Édition {section}</title>
    <link
      href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600&family=Space+Grotesk:wght@500;700&family=JetBrains+Mono:wght@400;500&display=swap"
      rel="stylesheet"
    />
  </head>
  <body class="aurora-bg min-h-screen">
    <header class="border-b border-[color:var(--color-border)] backdrop-blur-xl bg-[rgba(10,10,15,0.7)] sticky top-0 z-40">
      <div class="container mx-auto px-4 h-16 flex items-center justify-between">
        <div class="flex items-center gap-3">
          <a href="/admin" class="font-mono text-sm text-[color:var(--color-text-muted)] hover:text-[color:var(--color-cyan)]">
            ← dashboard
          </a>
          <span class="text-[color:var(--color-text-dim)]">/</span>
          <span class="font-display uppercase tracking-wider text-[color:var(--color-cyan)]">
            {section}
          </span>
        </div>

        <div class="flex items-center gap-3">
          <span id="save-status" class="text-xs font-mono text-[color:var(--color-text-dim)]"></span>
          <button id="format-btn" class="btn-ghost text-xs py-1.5">Formater</button>
          <button id="save-btn" class="btn-primary text-xs py-1.5">Enregistrer</button>
        </div>
      </div>
    </header>

    <main class="container mx-auto px-4 py-6">
      <p class="text-xs font-mono text-[color:var(--color-text-dim)] mb-2">
        Édition libre en JSON. Le contenu est validé contre le schéma Zod avant sauvegarde.
      </p>
      <textarea
        id="editor"
        class="w-full h-[calc(100vh-200px)] bg-[color:var(--color-surface)] border border-[color:var(--color-border)] focus:border-[color:var(--color-cyan)] focus:outline-none p-4 rounded text-sm font-mono text-[color:var(--color-text)] resize-none"
        spellcheck="false"
      >{jsonString}</textarea>
    </main>

    <script define:vars={{ section }}>
      const editor = document.getElementById('editor');
      const saveBtn = document.getElementById('save-btn');
      const formatBtn = document.getElementById('format-btn');
      const status = document.getElementById('save-status');

      formatBtn.addEventListener('click', () => {
        try {
          const parsed = JSON.parse(editor.value);
          editor.value = JSON.stringify(parsed, null, 2);
          status.textContent = 'formaté';
          status.style.color = 'var(--color-cyan)';
        } catch (e) {
          status.textContent = 'JSON invalide';
          status.style.color = 'var(--color-magenta)';
        }
      });

      saveBtn.addEventListener('click', async () => {
        status.textContent = 'enregistrement…';
        status.style.color = 'var(--color-text-muted)';
        let body;
        try {
          body = JSON.parse(editor.value);
        } catch (e) {
          status.textContent = 'JSON invalide';
          status.style.color = 'var(--color-magenta)';
          return;
        }
        const res = await fetch(`/api/content/${section}`, {
          method: 'PUT',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(body),
        });
        const result = await res.json();
        if (res.ok) {
          status.textContent = '✓ enregistré';
          status.style.color = 'var(--color-cyan)';
          setTimeout(() => { status.textContent = ''; }, 3000);
        } else {
          status.textContent = `✗ ${result.message || result.error}`;
          status.style.color = 'var(--color-magenta)';
        }
      });

      editor.addEventListener('keydown', (e) => {
        if ((e.metaKey || e.ctrlKey) && e.key === 's') {
          e.preventDefault();
          saveBtn.click();
        }
      });
    </script>
  </body>
</html>
