<?php
// ─────────────────────────────────────────────
// hq/content.php  —  Landing Page Content Editor
// Alle Texte, Preise und Labels der Website
// administrieren — direkt im Browser
// ─────────────────────────────────────────────

require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/db.php';
require_hq_auth();

$db = C2CDatabase::get();

// Alle Inhalte laden — als section → key → row
$stmt = $db->query(
    "SELECT section, `key`, `value`, type, label FROM site_content
     WHERE section != '_meta'
     ORDER BY section, id"
);
$allRows = $stmt->fetchAll();

// Gruppieren
$content = [];
foreach ($allRows as $row) {
    $content[$row['section']][$row['key']] = $row;
}

// Letzter Speicher-Zeitpunkt
$stmt = $db->prepare("SELECT value FROM site_content WHERE section='_meta' AND `key`='last_saved'");
$stmt->execute();
$lastSaved = $stmt->fetchColumn();

// Sektionen-Definition (Reihenfolge + Titel + Icon)
$sections = [
    'seo'        => ['icon' => '🔍', 'label' => 'SEO & Meta-Tags'],
    'nav'        => ['icon' => '🔗', 'label' => 'Navigation'],
    'hero'       => ['icon' => '🏔️', 'label' => 'Hero — Hauptbanner'],
    'services'   => ['icon' => '🗂️', 'label' => 'Services & Preise'],
    'how'        => ['icon' => '🗺️', 'label' => 'Wie es funktioniert'],
    'quote'      => ['icon' => '💬', 'label' => 'Zitat-Band'],
    'about'      => ['icon' => '👤', 'label' => 'SwissChris — Über mich'],
    'disclaimer' => ['icon' => '⚖️', 'label' => 'Disclaimer'],
    'footer'     => ['icon' => '📍', 'label' => 'Footer'],
];
?>
<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Content Editor — HQ come2canada.life</title>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&family=Fraunces:ital,wght@0,700;1,400&display=swap" rel="stylesheet">
<style>
:root {
  --bg:         #0F1410;
  --surface:    #1A2018;
  --surface2:   #222B20;
  --surface3:   #2A342A;
  --border:     #344030;
  --border2:    #405040;
  --red:        #D0271D;
  --red-soft:   rgba(208,39,29,0.15);
  --green:      #3CA85A;
  --green-soft: rgba(60,168,90,0.15);
  --gold:       #C8A96E;
  --white:      #F5F2EC;
  --muted:      #8A9280;
  --radius:     10px;
  --sidebar-w:  260px;
}
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
html, body { height: 100%; }
body {
  font-family: Inter, sans-serif;
  background: var(--bg);
  color: var(--white);
  display: flex;
  flex-direction: column;
  font-size: 14px;
  line-height: 1.5;
}

/* ── TOP BAR ── */
.topbar {
  height: 54px;
  background: var(--surface);
  border-bottom: 1px solid var(--border);
  display: flex;
  align-items: center;
  padding: 0 24px;
  gap: 16px;
  flex-shrink: 0;
  position: sticky;
  top: 0;
  z-index: 100;
}
.topbar-logo {
  font-family: 'Fraunces', serif;
  font-size: 17px;
  font-weight: 700;
  color: var(--white);
  display: flex;
  align-items: center;
  gap: 8px;
}
.topbar-logo span { color: var(--red); }
.topbar-sep {
  width: 1px; height: 20px;
  background: var(--border);
}
.topbar-title {
  font-size: 14px;
  font-weight: 500;
  color: var(--muted);
}
.topbar-actions {
  margin-left: auto;
  display: flex;
  align-items: center;
  gap: 12px;
}
.last-saved {
  font-size: 12px;
  color: var(--muted);
}
.last-saved.just-saved { color: var(--green); }

.btn-save {
  background: var(--red);
  color: #fff;
  padding: 9px 24px;
  border-radius: var(--radius);
  border: none;
  cursor: pointer;
  font-size: 14px;
  font-weight: 700;
  font-family: Inter, sans-serif;
  transition: background 0.15s, transform 0.15s;
  display: flex;
  align-items: center;
  gap: 7px;
}
.btn-save:hover { background: #b01f16; }
.btn-save:active { transform: scale(0.97); }
.btn-save.saving { opacity: 0.6; pointer-events: none; }
.btn-save .save-icon { font-size: 16px; }

.btn-preview {
  background: var(--surface3);
  color: var(--white);
  padding: 9px 18px;
  border-radius: var(--radius);
  border: 1px solid var(--border2);
  cursor: pointer;
  font-size: 13px;
  font-weight: 600;
  font-family: Inter, sans-serif;
  transition: background 0.15s;
  text-decoration: none;
  display: inline-flex;
  align-items: center;
  gap: 6px;
}
.btn-preview:hover { background: var(--border); }

/* ── LAYOUT ── */
.layout {
  display: flex;
  flex: 1;
  overflow: hidden;
  min-height: 0;
}

/* ── SIDEBAR ── */
.sidebar {
  width: var(--sidebar-w);
  background: var(--surface);
  border-right: 1px solid var(--border);
  flex-shrink: 0;
  overflow-y: auto;
  padding: 16px 0;
}
.sidebar-section {
  padding: 4px 12px;
}
.sidebar-section-label {
  font-size: 10px;
  font-weight: 700;
  letter-spacing: 1.2px;
  text-transform: uppercase;
  color: var(--muted);
  padding: 12px 8px 6px;
}
.nav-item {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 10px 12px;
  border-radius: 8px;
  cursor: pointer;
  transition: background 0.15s;
  border: none;
  background: transparent;
  color: var(--muted);
  font-family: Inter, sans-serif;
  font-size: 13px;
  font-weight: 500;
  width: 100%;
  text-align: left;
  position: relative;
}
.nav-item:hover { background: var(--surface2); color: var(--white); }
.nav-item.active {
  background: var(--red-soft);
  color: var(--white);
  border-left: 2px solid var(--red);
  padding-left: 10px;
}
.nav-item .nav-icon { font-size: 16px; width: 20px; text-align: center; }
.nav-item .nav-badge {
  margin-left: auto;
  background: var(--border);
  color: var(--muted);
  font-size: 10px;
  padding: 1px 6px;
  border-radius: 10px;
}
.nav-item.active .nav-badge { background: var(--red-soft); color: var(--red); }
.nav-item.has-changes::after {
  content: '';
  width: 6px; height: 6px;
  background: var(--gold);
  border-radius: 50%;
  position: absolute;
  right: 12px; top: 50%;
  transform: translateY(-50%);
}

/* ── MAIN EDITOR ── */
.editor-main {
  flex: 1;
  overflow-y: auto;
  padding: 32px 40px;
  max-width: 860px;
}

/* Section panels */
.section-panel { display: none; }
.section-panel.active { display: block; }

.section-header {
  display: flex;
  align-items: center;
  gap: 14px;
  margin-bottom: 32px;
  padding-bottom: 20px;
  border-bottom: 1px solid var(--border);
}
.section-emoji { font-size: 28px; }
.section-header h2 {
  font-family: 'Fraunces', serif;
  font-size: 22px;
  font-weight: 700;
  color: var(--white);
}
.section-header p {
  font-size: 13px;
  color: var(--muted);
  margin-top: 3px;
}

/* Field groups */
.fields { display: flex; flex-direction: column; gap: 0; }

.field-group-title {
  font-size: 11px;
  font-weight: 700;
  letter-spacing: 1px;
  text-transform: uppercase;
  color: var(--muted);
  margin: 28px 0 14px;
  padding-bottom: 8px;
  border-bottom: 1px solid var(--border);
  display: flex;
  align-items: center;
  gap: 8px;
}

.field {
  margin-bottom: 20px;
}
.field-label {
  display: flex;
  align-items: baseline;
  gap: 8px;
  margin-bottom: 7px;
}
.field-label label {
  font-size: 13px;
  font-weight: 600;
  color: var(--white);
}
.field-label .field-key {
  font-size: 11px;
  color: var(--muted);
  font-family: 'Courier New', monospace;
  background: var(--surface3);
  padding: 1px 6px;
  border-radius: 4px;
}

input[type="text"],
input[type="number"],
textarea {
  width: 100%;
  background: var(--surface2);
  border: 1.5px solid var(--border);
  border-radius: var(--radius);
  color: var(--white);
  font-family: Inter, sans-serif;
  font-size: 14px;
  padding: 11px 14px;
  transition: border-color 0.15s, box-shadow 0.15s;
  outline: none;
  resize: vertical;
}
input[type="text"]:focus,
input[type="number"]:focus,
textarea:focus {
  border-color: var(--red);
  box-shadow: 0 0 0 3px var(--red-soft);
}
input[type="text"].changed,
input[type="number"].changed,
textarea.changed {
  border-color: var(--gold);
  box-shadow: 0 0 0 3px rgba(200,169,110,0.15);
}
textarea { min-height: 90px; line-height: 1.6; }
textarea.tall { min-height: 140px; }
input[type="number"] { max-width: 160px; }

/* Price field */
.price-wrap {
  display: flex;
  align-items: center;
  gap: 10px;
}
.price-prefix {
  font-size: 16px;
  font-weight: 700;
  color: var(--muted);
  white-space: nowrap;
}
.price-preview {
  font-family: 'Fraunces', serif;
  font-size: 20px;
  font-weight: 700;
  color: var(--red);
  min-width: 80px;
}

/* Card previews for services */
.service-preview-row {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 14px;
  margin: 24px 0 32px;
}
.svc-preview {
  background: var(--surface2);
  border: 1px solid var(--border);
  border-radius: 12px;
  padding: 16px;
  font-size: 12px;
  text-align: center;
}
.svc-preview.active-svc { border-color: var(--red); background: var(--red-soft); }
.svc-preview-icon { font-size: 24px; margin-bottom: 6px; }
.svc-preview-name { font-weight: 700; margin-bottom: 4px; color: var(--white); }
.svc-preview-price { color: var(--red); font-weight: 700; font-size: 16px; }

/* Character counter */
.char-counter {
  font-size: 11px;
  color: var(--muted);
  text-align: right;
  margin-top: 4px;
}
.char-counter.warn { color: var(--gold); }
.char-counter.over { color: var(--red); }

/* Hint boxes */
.hint {
  background: var(--surface2);
  border: 1px solid var(--border);
  border-radius: 8px;
  padding: 12px 16px;
  font-size: 12px;
  color: var(--muted);
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
  align-items: flex-start;
  line-height: 1.6;
}
.hint-icon { font-size: 16px; flex-shrink: 0; }

/* Toast */
#toast {
  position: fixed;
  bottom: 28px;
  right: 28px;
  padding: 14px 22px;
  border-radius: 10px;
  font-size: 14px;
  font-weight: 600;
  opacity: 0;
  transform: translateY(10px);
  transition: all 0.25s ease;
  pointer-events: none;
  z-index: 999;
  display: flex;
  align-items: center;
  gap: 8px;
}
#toast.success { background: var(--green); color: #fff; }
#toast.error   { background: var(--red);   color: #fff; }
#toast.visible { opacity: 1; transform: translateY(0); }

/* Unsaved indicator */
.unsaved-bar {
  display: none;
  background: rgba(200,169,110,0.12);
  border: 1px solid rgba(200,169,110,0.3);
  border-radius: 8px;
  padding: 10px 16px;
  font-size: 13px;
  color: var(--gold);
  margin-bottom: 24px;
  align-items: center;
  gap: 8px;
}
.unsaved-bar.visible { display: flex; }

/* Scrollbar */
::-webkit-scrollbar { width: 6px; }
::-webkit-scrollbar-track { background: var(--surface); }
::-webkit-scrollbar-thumb { background: var(--border2); border-radius: 3px; }
</style>
</head>
<body>

<!-- TOP BAR -->
<div class="topbar">
  <div class="topbar-logo">🍁 <span>C2C</span> HQ</div>
  <div class="topbar-sep"></div>
  <span class="topbar-title">Landing Page — Content Editor</span>
  <div class="topbar-actions">
    <span class="last-saved" id="lastSavedLabel">
      <?= $lastSaved ? 'Zuletzt: ' . date('d.m.Y H:i', strtotime($lastSaved)) : 'Noch nicht gespeichert' ?>
    </span>
    <a href="<?= C2C_PUBLIC_URL ?>formular.php" target="_blank" class="btn-preview">
      👁 Vorschau
    </a>
    <button class="btn-save" id="saveBtn" onclick="saveAll()">
      <span class="save-icon">💾</span>
      Alles speichern
    </button>
  </div>
</div>

<!-- MAIN LAYOUT -->
<div class="layout">

  <!-- SIDEBAR -->
  <nav class="sidebar">
    <div class="sidebar-section">
      <div class="sidebar-section-label">Seiten-Inhalte</div>
      <?php foreach ($sections as $sectionKey => $sectionMeta):
        $fieldCount = count($content[$sectionKey] ?? []);
      ?>
        <button class="nav-item <?= $sectionKey === 'hero' ? 'active' : '' ?>"
                id="nav-<?= $sectionKey ?>"
                onclick="showSection('<?= $sectionKey ?>')">
          <span class="nav-icon"><?= $sectionMeta['icon'] ?></span>
          <?= htmlspecialchars($sectionMeta['label']) ?>
          <span class="nav-badge"><?= $fieldCount ?></span>
        </button>
      <?php endforeach; ?>
    </div>

    <div class="sidebar-section">
      <div class="sidebar-section-label">Navigation</div>
      <a href="index.php" style="display:flex;align-items:center;gap:10px;padding:10px 12px;
        border-radius:8px;color:var(--muted);text-decoration:none;font-size:13px;font-weight:500;
        transition:background 0.15s;" onmouseover="this.style.background='#222B20'"
        onmouseout="this.style.background='transparent'">
        <span>←</span> Zurück zum HQ
      </a>
    </div>
  </nav>

  <!-- EDITOR MAIN -->
  <main class="editor-main" id="editorMain">

    <!-- Unsaved changes warning -->
    <div class="unsaved-bar" id="unsavedBar">
      ✏️ Sie haben ungespeicherte Änderungen — bitte speichern Sie vor dem Verlassen.
    </div>

    <?php
    // ── Hilfe-Texte pro Sektion ──────────────
    $hints = [
      'seo'     => ['🔍', 'Diese Felder erscheinen nicht auf der Website, aber in Google-Suchergebnissen und beim Teilen auf Social Media.'],
      'nav'     => ['🔗', 'Die Navigation erscheint oben auf jeder Seite. Halten Sie die Labels kurz.'],
      'hero'    => ['🏔️', 'Der Hero-Bereich ist das Erste, was Besucher sehen. Klar, direkt und einladend.'],
      'services'=> ['🗂️', 'Features: Eine Leistung pro Zeile (Enter-Taste trennt). Der Preis wird als "CHF 299" angezeigt.'],
      'how'     => ['🗺️', 'Maximal 4 Schritte. Kurze, aktive Formulierungen — keine langen Erklärungen.'],
      'quote'   => ['💬', 'Das Zitat erscheint auf rotem Hintergrund über die volle Breite. Authentisch und persönlich halten.'],
      'about'   => ['👤', 'Die letzte Zeile der Headline wird automatisch rot-kursiv dargestellt.'],
      'disclaimer'=>['⚖️','Rechtlich notwendig. Bitte keine wesentlichen Änderungen ohne Rücksprache.'],
      'footer'  => ['📍', 'Erscheint ganz unten auf der Seite.'],
    ];

    foreach ($sections as $sectionKey => $sectionMeta):
      $sFields = $content[$sectionKey] ?? [];
    ?>

    <!-- Section: <?= $sectionKey ?> -->
    <div class="section-panel <?= $sectionKey === 'hero' ? 'active' : '' ?>"
         id="panel-<?= $sectionKey ?>">

      <div class="section-header">
        <span class="section-emoji"><?= $sectionMeta['icon'] ?></span>
        <div>
          <h2><?= htmlspecialchars($sectionMeta['label']) ?></h2>
          <p><?= count($sFields) ?> editierbare Felder</p>
        </div>
      </div>

      <?php if (isset($hints[$sectionKey])): ?>
        <div class="hint">
          <span class="hint-icon"><?= $hints[$sectionKey][0] ?></span>
          <span><?= $hints[$sectionKey][1] ?></span>
        </div>
      <?php endif; ?>

      <!-- Service preview row -->
      <?php if ($sectionKey === 'services'): ?>
        <div class="service-preview-row">
          <?php foreach ([1,2,3] as $i): ?>
            <div class="svc-preview" id="svc-preview-<?= $i ?>">
              <div class="svc-preview-icon" id="prev-icon-<?= $i ?>"><?= htmlspecialchars($sFields["s{$i}_icon"]['value'] ?? '') ?></div>
              <div class="svc-preview-name" id="prev-name-<?= $i ?>"><?= htmlspecialchars($sFields["s{$i}_name"]['value'] ?? '') ?></div>
              <div class="svc-preview-price" id="prev-price-<?= $i ?>">CHF <?= htmlspecialchars($sFields["s{$i}_price"]['value'] ?? '') ?></div>
            </div>
          <?php endforeach; ?>
        </div>
      <?php endif; ?>

      <div class="fields">
        <?php
        // Felder in Gruppen für Services + How anzeigen
        $groupedFields = [];
        if ($sectionKey === 'services') {
            $groupedFields = [
                'Abschnitt' => ['section_tag', 'title'],
                'Service 1 — Geschichte Starter' => ['s1_icon','s1_name','s1_desc','s1_features','s1_price'],
                'Service 2 — Vollständiges Portfolio' => ['s2_icon','s2_name','s2_desc','s2_features','s2_price','s2_badge'],
                'Service 3 — Familien-Geschichte' => ['s3_icon','s3_name','s3_desc','s3_features','s3_price'],
            ];
        } elseif ($sectionKey === 'how') {
            $groupedFields = [
                'Abschnitt' => ['section_tag','title'],
                'Schritt 1' => ['step1_icon','step1_title','step1_text'],
                'Schritt 2' => ['step2_icon','step2_title','step2_text'],
                'Schritt 3' => ['step3_icon','step3_title','step3_text'],
                'Schritt 4' => ['step4_icon','step4_title','step4_text'],
            ];
        } elseif ($sectionKey === 'hero') {
            $groupedFields = [
                'Texte'      => ['eyebrow','h1_line1','h1_accent','h2','body'],
                'Buttons'    => ['cta_primary','cta_secondary'],
                'Info-Karten'=> ['stat1_label','stat1_sub','stat1_num',
                                 'stat2_label','stat2_sub','stat2_num',
                                 'stat3_label','stat3_sub','stat3_num'],
            ];
        }

        if (!empty($groupedFields)):
            foreach ($groupedFields as $groupTitle => $keys):
        ?>
            <div class="field-group-title"><?= htmlspecialchars($groupTitle) ?></div>
            <?php
            foreach ($keys as $k):
              if (!isset($sFields[$k])) continue;
              $f = $sFields[$k];
              renderField($sectionKey, $k, $f);
            endforeach;
          endforeach;
        else:
          // Alle Felder ungrouped
          foreach ($sFields as $k => $f):
            renderField($sectionKey, $k, $f);
          endforeach;
        endif;
        ?>
      </div>
    </div>

    <?php endforeach; // sections ?>

  </main>
</div><!-- /layout -->

<!-- Toast -->
<div id="toast"></div>

<?php
// ── Hilfs-Funktion: Feld rendern ──────────────
function renderField(string $section, string $key, array $f): void {
    $id    = "f-{$section}-{$key}";
    $val   = htmlspecialchars($f['value'] ?? '');
    $label = $f['label'] ?? ucfirst(str_replace('_', ' ', $key));
    $type  = $f['type'] ?? 'text';

    $maxLen = match($key) {
        'title','description','og_description' => 160,
        'h2','body','body1','body2','text','desc' => 0,
        default => 0,
    };
    ?>
    <div class="field" id="field-<?= $id ?>">
      <div class="field-label">
        <label for="<?= $id ?>"><?= htmlspecialchars($label) ?></label>
        <span class="field-key"><?= htmlspecialchars("{$section}.{$key}") ?></span>
      </div>

      <?php if ($type === 'number'): ?>
        <div class="price-wrap">
          <span class="price-prefix">CHF</span>
          <input type="number" id="<?= $id ?>" min="0" step="1"
                 data-section="<?= $section ?>" data-key="<?= $key ?>"
                 value="<?= $val ?>"
                 oninput="markChanged(this); updatePricePreview('<?= $section ?>','<?= $key ?>', this.value)">
          <span class="price-preview" id="pp-<?= $section ?>-<?= $key ?>">CHF <?= $val ?></span>
        </div>

      <?php elseif ($type === 'textarea' || str_contains($key, 'features') || str_contains($key, 'body') || str_contains($key, 'text') || $key === 'title' || $key === 'h2' || $key === 'quote'): ?>
        <textarea id="<?= $id ?>" class="<?= strlen($f['value'] ?? '') > 200 ? 'tall' : '' ?>"
                  data-section="<?= $section ?>" data-key="<?= $key ?>"
                  oninput="markChanged(this)"
                  <?= $maxLen ? "maxlength=\"$maxLen\"" : '' ?>
                  ><?= $val ?></textarea>
        <?php if ($maxLen): ?>
          <div class="char-counter" id="cc-<?= $id ?>"><?= strlen($f['value'] ?? '') ?> / <?= $maxLen ?></div>
        <?php endif; ?>

      <?php else: ?>
        <input type="text" id="<?= $id ?>"
               data-section="<?= $section ?>" data-key="<?= $key ?>"
               value="<?= $val ?>"
               oninput="markChanged(this)"
               <?= $maxLen ? "maxlength=\"$maxLen\"" : '' ?>>
        <?php if ($maxLen): ?>
          <div class="char-counter" id="cc-<?= $id ?>"><?= strlen($f['value'] ?? '') ?> / <?= $maxLen ?></div>
        <?php endif; ?>
      <?php endif; ?>

    </div>
    <?php
}
?>

<script>
const API  = '<?= C2C_API_BASE ?>';
const TOKEN= '<?= C2C_SECRET ?>';
let hasChanges = false;

// ── Section navigation ──────────────────────
function showSection(key) {
  document.querySelectorAll('.section-panel').forEach(p => p.classList.remove('active'));
  document.querySelectorAll('.nav-item').forEach(n => n.classList.remove('active'));
  document.getElementById('panel-' + key)?.classList.add('active');
  document.getElementById('nav-' + key)?.classList.add('active');
  document.getElementById('editorMain').scrollTo({ top: 0, behavior: 'smooth' });
}

// ── Mark field as changed ───────────────────
function markChanged(el) {
  el.classList.add('changed');
  hasChanges = true;
  document.getElementById('unsavedBar').classList.add('visible');

  // Update nav badge dot
  const section = el.dataset.section;
  const navItem = document.getElementById('nav-' + section);
  if (navItem) navItem.classList.add('has-changes');

  // Character counter
  const id = el.id;
  const cc = document.getElementById('cc-' + id);
  if (cc && el.maxLength > 0) {
    const len = el.value.length;
    const max = el.maxLength;
    cc.textContent = len + ' / ' + max;
    cc.className = 'char-counter' + (len > max * 0.9 ? ' warn' : '') + (len >= max ? ' over' : '');
  }

  // Service live preview
  updateServicePreview(el.dataset.section, el.dataset.key, el.value);
}

// ── Service card live preview ───────────────
function updateServicePreview(section, key, value) {
  if (section !== 'services') return;
  const match = key.match(/^s([123])_(icon|name|price)$/);
  if (!match) return;
  const [, i, field] = match;
  if (field === 'icon')  { const el = document.getElementById('prev-icon-' + i);  if (el) el.textContent = value; }
  if (field === 'name')  { const el = document.getElementById('prev-name-' + i);  if (el) el.textContent = value; }
  if (field === 'price') { const el = document.getElementById('prev-price-' + i); if (el) el.textContent = 'CHF ' + value; }
}

function updatePricePreview(section, key, value) {
  const pp = document.getElementById('pp-' + section + '-' + key);
  if (pp) pp.textContent = 'CHF ' + value;
}

// ── Collect all field values ────────────────
function collectAll() {
  const items = [];
  document.querySelectorAll('[data-section][data-key]').forEach(el => {
    items.push({
      section: el.dataset.section,
      key:     el.dataset.key,
      value:   el.value,
    });
  });
  return items;
}

// ── Save all to API ─────────────────────────
async function saveAll() {
  const btn = document.getElementById('saveBtn');
  btn.classList.add('saving');
  btn.querySelector('.save-icon').textContent = '⏳';

  const content = collectAll();

  try {
    const res = await fetch(API + 'content.php', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'X-C2C-Token': TOKEN,
      },
      body: JSON.stringify({ content }),
    });

    const data = await res.json();

    if (data.success) {
      // Clear changed states
      document.querySelectorAll('.changed').forEach(el => el.classList.remove('changed'));
      document.querySelectorAll('.nav-item.has-changes').forEach(el => el.classList.remove('has-changes'));
      document.getElementById('unsavedBar').classList.remove('visible');
      hasChanges = false;

      // Update timestamp
      const now = new Date();
      const label = document.getElementById('lastSavedLabel');
      label.textContent = 'Gespeichert um ' + now.toLocaleTimeString('de-CH', {hour:'2-digit', minute:'2-digit'});
      label.classList.add('just-saved');
      setTimeout(() => label.classList.remove('just-saved'), 3000);

      toast('✓ ' + data.saved + ' Felder gespeichert', 'success');
    } else {
      toast('Fehler: ' + (data.error || 'Unbekannt'), 'error');
    }
  } catch (e) {
    toast('Verbindungsfehler — bitte erneut versuchen', 'error');
    console.error(e);
  }

  btn.classList.remove('saving');
  btn.querySelector('.save-icon').textContent = '💾';
}

// ── Toast ───────────────────────────────────
function toast(msg, type = 'success') {
  const el = document.getElementById('toast');
  el.textContent = msg;
  el.className = type + ' visible';
  setTimeout(() => el.className = type, 3200);
}

// ── Keyboard shortcut: Cmd/Ctrl + S ─────────
document.addEventListener('keydown', e => {
  if ((e.metaKey || e.ctrlKey) && e.key === 's') {
    e.preventDefault();
    saveAll();
  }
});

// ── Warn on page leave with unsaved changes ──
window.addEventListener('beforeunload', e => {
  if (hasChanges) {
    e.preventDefault();
    e.returnValue = '';
  }
});
</script>
</body>
</html>
