---
import Layout from "../../components/Layout.astro";
const user = Astro.locals.user as any;
import events from "../../content/events.json";
import images from "../../content/gallery.json";
import texts from "../../content/texts.json";
---

<!-- Guard: if not logged in, show login link only -->
{!user && (
  <Layout>
    <section style="padding:2rem; text-align:center">
      <h1>Admin Login</h1>
      <p>Bitte mit Gitea anmelden, um Inhalte zu bearbeiten.</p>
      <p><a class="button" href="/api/auth/login">Mit Gitea anmelden</a></p>
    </section>
  </Layout>
)}

{user && (
  <Layout>
    <section class="admin" style="padding:2rem;">
      <h1>Admin Bereich</h1>
      <p>Eingeloggt als <b>{user.username}</b></p>
      <form id="editor">
        <h2>Welcome/Textbausteine (JSON)</h2>
        <textarea id="texts" style="width:100%;height:240px">{JSON.stringify(texts, null, 2)}</textarea>

        <h2>Events (JSON)</h2>
        <textarea id="events" style="width:100%;height:220px">{JSON.stringify(events, null, 2)}</textarea>

        <h2>Gallerie (JSON)</h2>
        <textarea id="gallery" style="width:100%;height:160px">{JSON.stringify(images, null, 2)}</textarea>

        <h2>Bild hochladen</h2>
        <input id="imageInput" type="file" accept="image/*" multiple />

        <div style="margin-top:1rem; display:flex; gap:1rem;">
          <button type="button" id="saveBtn">Speichern</button>
          <button type="button" id="logoutBtn">Logout</button>
        </div>
      </form>
    </section>

    <script>
      async function getCsrf() {
        const m = document.cookie.match(/(?:^|; )gp_csrf=([^;]+)/);
        return m ? decodeURIComponent(m[1]) : '';
      }

      async function save() {
        const files = [];
        try {
          const textsText = (document.getElementById('texts')).value;
          const textsJson = JSON.stringify(JSON.parse(textsText), null, 2);
          files.push({ path: 'src/content/texts.json', content: textsJson, encoding: 'utf8' });
        } catch (e) {
          alert('Texts JSON ist ungültig: ' + e.message);
          return;
        }
        try {
          const eventsText = (document.getElementById('events')).value;
          const eventsJson = JSON.stringify(JSON.parse(eventsText), null, 2);
          files.push({ path: 'src/content/events.json', content: eventsJson, encoding: 'utf8' });
        } catch (e) {
          alert('Events JSON ist ungültig: ' + e.message);
          return;
        }
        try {
          const galleryText = (document.getElementById('gallery')).value;
          const galleryJson = JSON.stringify(JSON.parse(galleryText), null, 2);
          files.push({ path: 'src/content/gallery.json', content: galleryJson, encoding: 'utf8' });
        } catch (e) {
          alert('Galerie JSON ist ungültig: ' + e.message);
          return;
        }

        // handle image uploads
        const input = document.getElementById('imageInput');
        const toUpload = Array.from(input.files || []);
        for (const f of toUpload) {
          const buf = await f.arrayBuffer();
          const base64 = btoa(String.fromCharCode(...new Uint8Array(buf)));
          files.push({ path: `public/images/${f.name}`, content: base64, encoding: 'base64' });
        }

        const res = await fetch('/api/save', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'X-CSRF': await getCsrf(),
          },
          body: JSON.stringify({ message: 'Admin content update', files })
        });
        if (!res.ok) {
          const t = await res.text();
          alert('Fehler beim Speichern: ' + t);
        } else {
          alert('Änderungen gespeichert. Build/Deploy wird ausgelöst.');
          location.reload();
        }
      }

      document.getElementById('saveBtn').addEventListener('click', save);
      document.getElementById('logoutBtn').addEventListener('click', async () => {
        await fetch('/api/auth/logout', { method: 'POST' });
        location.href = '/';
      });
    </script>
  </Layout>
)}
