<?php
// ============================================================
// FILE: admin/hero_histori.php
// Kelola Hero Background + Histori/Timeline Toko
// Tab 1: Hero Section (bg, gambar, teks)
// Tab 2: Histori Timeline (CRUD milestone)
// ============================================================
require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/functions.php';
require_once __DIR__ . '/../includes/auth.php';
requireAdmin();

$pdo    = db();
$tab    = $_GET['tab'] ?? 'hero';
$errors = [];

// ══════════════════════════════════════════════════════════════
// POST HANDLER
// ══════════════════════════════════════════════════════════════
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $aksi = $_POST['aksi'] ?? '';

    // ── Simpan pengaturan hero ────────────────────────────────
    if ($aksi === 'simpan_hero') {
        $fields = [
            'hero_badge', 'hero_judul_baris1', 'hero_judul_baris2',
            'hero_subtitle', 'hero_cta1_text', 'hero_cta2_text',
        ];

        // Handle upload hero_bg (background)
        if (!empty($_FILES['hero_bg_file']['name']) && $_FILES['hero_bg_file']['error'] === UPLOAD_ERR_OK) {
            $namaFile = uploadGambar($_FILES['hero_bg_file'], 'hero');
            if ($namaFile) {
                // Hapus file lama
                $lama = $pdo->prepare("SELECT nilai FROM pengaturan_hero WHERE kunci='hero_bg_url'");
                $lama->execute();
                $lamaVal = $lama->fetchColumn();
                if ($lamaVal && !str_starts_with($lamaVal, 'http')) {
                    hapusGambar(basename($lamaVal), 'hero');
                }
                $pdo->prepare("UPDATE pengaturan_hero SET nilai=? WHERE kunci='hero_bg_url'")
                    ->execute([UPLOAD_URL . '/hero/' . $namaFile]);
            } else {
                $errors[] = 'Upload background gagal. Pastikan format JPG/PNG/WEBP dan maks 5MB.';
            }
        } elseif (!empty($_POST['hero_bg_url'])) {
            $pdo->prepare("UPDATE pengaturan_hero SET nilai=? WHERE kunci='hero_bg_url'")
                ->execute([trim($_POST['hero_bg_url'])]);
        }

        // Handle upload hero_img_utama (gambar kanan)
        if (!empty($_FILES['hero_img_file']['name']) && $_FILES['hero_img_file']['error'] === UPLOAD_ERR_OK) {
            $namaFile = uploadGambar($_FILES['hero_img_file'], 'hero');
            if ($namaFile) {
                $lama = $pdo->prepare("SELECT nilai FROM pengaturan_hero WHERE kunci='hero_img_utama'");
                $lama->execute();
                $lamaVal = $lama->fetchColumn();
                if ($lamaVal && !str_starts_with($lamaVal, 'http')) {
                    hapusGambar(basename($lamaVal), 'hero');
                }
                $pdo->prepare("UPDATE pengaturan_hero SET nilai=? WHERE kunci='hero_img_utama'")
                    ->execute([UPLOAD_URL . '/hero/' . $namaFile]);
            } else {
                $errors[] = 'Upload gambar utama gagal.';
            }
        } elseif (!empty($_POST['hero_img_utama'])) {
            $pdo->prepare("UPDATE pengaturan_hero SET nilai=? WHERE kunci='hero_img_utama'")
                ->execute([trim($_POST['hero_img_utama'])]);
        }

        // Update field teks
        if (empty($errors)) {
            $stmt = $pdo->prepare("UPDATE pengaturan_hero SET nilai=? WHERE kunci=?");
            foreach ($fields as $k) {
                if (isset($_POST[$k])) {
                    $stmt->execute([trim($_POST[$k]), $k]);
                }
            }
            setFlash('success', 'Pengaturan Hero berhasil disimpan!');
            redirect(BASE_URL . '/admin/hero_histori.php?tab=hero');
        }
        $tab = 'hero';
    }

    // ── Tambah milestone histori ──────────────────────────────
    if ($aksi === 'tambah_histori') {
        $tahun  = (int)($_POST['tahun']    ?? 0);
        $judul  = trim($_POST['judul']     ?? '');
        $desk   = trim($_POST['deskripsi'] ?? '');
        $urutan = (int)($_POST['urutan']   ?? 0);

        if (!$tahun || !$judul) {
            $errors[] = 'Tahun dan judul wajib diisi.';
        } else {
            $pdo->prepare("INSERT INTO histori_toko (tahun, judul, deskripsi, urutan) VALUES (?,?,?,?)")
                ->execute([$tahun, $judul, $desk ?: null, $urutan]);
            setFlash('success', 'Milestone baru berhasil ditambahkan!');
            redirect(BASE_URL . '/admin/hero_histori.php?tab=histori');
        }
        $tab = 'histori';
    }

    // ── Edit milestone histori ────────────────────────────────
    if ($aksi === 'edit_histori') {
        $id     = (int)($_POST['id']       ?? 0);
        $tahun  = (int)($_POST['tahun']    ?? 0);
        $judul  = trim($_POST['judul']     ?? '');
        $desk   = trim($_POST['deskripsi'] ?? '');
        $urutan = (int)($_POST['urutan']   ?? 0);
        $aktif  = isset($_POST['is_aktif']) ? 1 : 0;

        if (!$id || !$tahun || !$judul) {
            $errors[] = 'Tahun dan judul wajib diisi.';
        } else {
            $pdo->prepare("UPDATE histori_toko SET tahun=?, judul=?, deskripsi=?, urutan=?, is_aktif=? WHERE id=?")
                ->execute([$tahun, $judul, $desk ?: null, $urutan, $aktif, $id]);
            setFlash('success', 'Milestone berhasil diperbarui!');
            redirect(BASE_URL . '/admin/hero_histori.php?tab=histori');
        }
        $tab = 'histori';
    }

    // ── Hapus milestone histori ───────────────────────────────
    if ($aksi === 'hapus_histori') {
        $id = (int)($_POST['id'] ?? 0);
        if ($id) {
            $pdo->prepare("DELETE FROM histori_toko WHERE id=?")->execute([$id]);
            setFlash('success', 'Milestone berhasil dihapus.');
        }
        redirect(BASE_URL . '/admin/hero_histori.php?tab=histori');
    }
}

// ══════════════════════════════════════════════════════════════
// AMBIL DATA
// ══════════════════════════════════════════════════════════════
$hero = [];
foreach ($pdo->query("SELECT kunci, nilai FROM pengaturan_hero")->fetchAll() as $r) {
    $hero[$r['kunci']] = $r['nilai'];
}

$historiList = $pdo->query("SELECT * FROM histori_toko ORDER BY urutan ASC, tahun ASC")->fetchAll();

// Edit mode histori
$editHistori = null;
if (isset($_GET['edit_id'])) {
    $s = $pdo->prepare("SELECT * FROM histori_toko WHERE id=? LIMIT 1");
    $s->execute([(int)$_GET['edit_id']]);
    $editHistori = $s->fetch();
}

$pageTitle = 'Hero & Histori';
include __DIR__ . '/admin_layout.php';
?>

<!-- Tabs -->
<div class="adm-page-header mb-4">
  <div>
    <h4 class="adm-page-title"><i class="bi bi-palette2 me-2"></i>Kelola Hero & Histori</h4>
    <p class="adm-page-sub mb-0">Atur tampilan halaman utama dan timeline sejarah toko</p>
  </div>
</div>

<div class="adm-tabs mb-4">
  <a href="?tab=hero"
     class="adm-tab <?= $tab==='hero' ? 'adm-tab--active' : '' ?>">
    <i class="bi bi-image me-1"></i>Hero Section
  </a>
  <a href="?tab=histori"
     class="adm-tab <?= $tab==='histori' ? 'adm-tab--active' : '' ?>">
    <i class="bi bi-clock-history me-1"></i>Histori Timeline
    <span class="adm-tab-badge"><?= count($historiList) ?></span>
  </a>
</div>

<?php if (!empty($errors)): ?>
  <div class="alert alert-danger alert-dismissible fade show mb-4">
    <strong><i class="bi bi-exclamation-triangle-fill me-2"></i>Gagal menyimpan:</strong>
    <ul class="mb-0 mt-1 ps-3">
      <?php foreach ($errors as $e): ?>
        <li><?= $e ?></li>
      <?php endforeach; ?>
    </ul>
    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
  </div>
<?php endif; ?>

<?php if ($tab === 'hero'): ?>
<!-- ══════════════════════════════════════════════════════════
     TAB 1: HERO SECTION
══════════════════════════════════════════════════════════ -->

<!-- Preview Hero -->
<div class="admin-card mb-4">
  <div class="admin-card-header">
    <h6 class="mb-0"><i class="bi bi-eye me-2"></i>Preview Hero Saat Ini</h6>
    <a href="<?= BASE_URL ?>/" target="_blank" class="btn btn-sm btn-outline-secondary">
      <i class="bi bi-box-arrow-up-right me-1"></i>Lihat di Website
    </a>
  </div>
  <div class="hero-preview-box" style="
    background: linear-gradient(135deg,#2D1B0E 0%,#1A0F07 100%);
    border-radius: 0 0 12px 12px;
    padding: 2rem;
    position: relative;
    overflow: hidden;
    min-height: 180px;
  ">
    <!-- BG Preview -->
    <div style="
      position:absolute;inset:0;
      background-image:url('<?= e($hero['hero_bg_url'] ?? '') ?>');
      background-size:cover;background-position:center;
      opacity:.2;
    "></div>
    <div style="position:relative;z-index:1;color:white">
      <div style="font-size:.75rem;color:#D4A853;font-weight:700;margin-bottom:.5rem">
        ✦ <?= e($hero['hero_badge'] ?? '') ?>
      </div>
      <h3 style="font-size:1.5rem;font-weight:900;margin:0;line-height:1.2">
        <?= e($hero['hero_judul_baris1'] ?? '') ?><br>
        <span style="color:#D4A853"><?= e($hero['hero_judul_baris2'] ?? '') ?></span>
      </h3>
      <p style="font-size:.8rem;color:rgba(255,255,255,.7);margin:.5rem 0 0">
        <?= e(mb_substr($hero['hero_subtitle'] ?? '', 0, 80)) ?>...
      </p>
    </div>
    <?php if ($hero['hero_img_utama'] ?? ''): ?>
      <img src="<?= e($hero['hero_img_utama']) ?>"
           style="position:absolute;right:2rem;top:50%;transform:translateY(-50%);
                  height:140px;width:140px;object-fit:cover;border-radius:12px;
                  box-shadow:0 8px 24px rgba(0,0,0,.4);"
           alt="Hero Image">
    <?php endif; ?>
  </div>
</div>

<form method="POST" enctype="multipart/form-data" id="frmHero">
  <input type="hidden" name="aksi" value="simpan_hero">

  <div class="row g-4">

    <!-- Kolom Kiri: Background -->
    <div class="col-lg-6">
      <div class="admin-card h-100">
        <div class="admin-card-header">
          <h6 class="mb-0"><i class="bi bi-image-fill me-2 text-primary"></i>Background Hero</h6>
        </div>
        <div class="p-4">

          <!-- Preview BG -->
          <div class="mb-3">
            <div class="hh-img-preview" id="prevBg"
                 style="background-image:url('<?= e($hero['hero_bg_url'] ?? '') ?>')">
              <span class="hh-img-label">Background Saat Ini</span>
            </div>
          </div>

          <!-- Upload file -->
          <div class="mb-3">
            <label class="ck-label">Upload Gambar Baru</label>
            <div class="multi-upload-zone" id="dzBg" onclick="document.getElementById('iBgFile').click()">
              <i class="bi bi-cloud-arrow-up-fill adm-dz-icon"></i>
              <p class="mb-0 small">Klik atau drag gambar di sini</p>
              <p class="text-muted" style="font-size:.75rem">JPG / PNG / WEBP · Maks 5MB · Resolusi min 1600×900px</p>
            </div>
            <input type="file" id="iBgFile" name="hero_bg_file"
                   accept="image/jpeg,image/png,image/webp" class="d-none"
                   onchange="previewImg(this,'prevBg');updateDzLabel('dzBg',this)">
          </div>

          <!-- Atau URL -->
          <div class="mb-0">
            <label class="ck-label">— Atau isi URL gambar —</label>
            <input type="url" name="hero_bg_url" class="form-control ck-input"
                   value="<?= e($hero['hero_bg_url'] ?? '') ?>"
                   placeholder="https://..."
                   oninput="previewUrl(this,'prevBg')">
            <div class="ck-hint">Kosongkan jika upload file di atas.</div>
          </div>
        </div>
      </div>
    </div>

    <!-- Kolom Kanan: Gambar Utama -->
    <div class="col-lg-6">
      <div class="admin-card h-100">
        <div class="admin-card-header">
          <h6 class="mb-0"><i class="bi bi-card-image me-2 text-success"></i>Gambar Utama (Kanan Hero)</h6>
        </div>
        <div class="p-4">

          <!-- Preview -->
          <div class="mb-3">
            <div class="hh-img-preview hh-img-preview--sm" id="prevImg">
              <img src="<?= e($hero['hero_img_utama'] ?? '') ?>" id="prevImgTag"
                   onerror="this.style.display='none'"
                   style="width:100%;height:100%;object-fit:cover;border-radius:8px">
              <span class="hh-img-label">Gambar Kanan Saat Ini</span>
            </div>
          </div>

          <!-- Upload -->
          <div class="mb-3">
            <label class="ck-label">Upload Gambar Baru</label>
            <div class="multi-upload-zone" id="dzImg" onclick="document.getElementById('iImgFile').click()">
              <i class="bi bi-cloud-arrow-up-fill adm-dz-icon"></i>
              <p class="mb-0 small">Klik atau drag gambar di sini</p>
              <p class="text-muted" style="font-size:.75rem">Rasio 4:3 atau 1:1 disarankan</p>
            </div>
            <input type="file" id="iImgFile" name="hero_img_file"
                   accept="image/jpeg,image/png,image/webp" class="d-none"
                   onchange="previewImgTag(this);updateDzLabel('dzImg',this)">
          </div>

          <!-- URL -->
          <div class="mb-0">
            <label class="ck-label">— Atau isi URL gambar —</label>
            <input type="url" name="hero_img_utama" class="form-control ck-input"
                   value="<?= e($hero['hero_img_utama'] ?? '') ?>"
                   placeholder="https://..."
                   oninput="document.getElementById('prevImgTag').src=this.value">
          </div>
        </div>
      </div>
    </div>

    <!-- Teks Hero -->
    <div class="col-12">
      <div class="admin-card">
        <div class="admin-card-header">
          <h6 class="mb-0"><i class="bi bi-fonts me-2 text-warning"></i>Teks Hero</h6>
        </div>
        <div class="p-4">
          <div class="row g-3">

            <div class="col-md-6">
              <label class="ck-label">Badge (teks kecil di atas judul)</label>
              <input type="text" name="hero_badge" class="form-control ck-input"
                     value="<?= e($hero['hero_badge'] ?? '') ?>"
                     placeholder="Terpercaya Sejak 2005">
            </div>

            <div class="col-md-6">
              <label class="ck-label">Judul Baris 1</label>
              <input type="text" name="hero_judul_baris1" class="form-control ck-input"
                     value="<?= e($hero['hero_judul_baris1'] ?? '') ?>"
                     placeholder="Kusen & Gypsum">
            </div>

            <div class="col-md-6">
              <label class="ck-label">Judul Baris 2 <span class="text-warning small">(ditampilkan dengan warna emas)</span></label>
              <input type="text" name="hero_judul_baris2" class="form-control ck-input"
                     value="<?= e($hero['hero_judul_baris2'] ?? '') ?>"
                     placeholder="Terbaik untuk Hunian Anda">
            </div>

            <div class="col-md-3">
              <label class="ck-label">Teks Tombol 1 (CTA Utama)</label>
              <input type="text" name="hero_cta1_text" class="form-control ck-input"
                     value="<?= e($hero['hero_cta1_text'] ?? '') ?>"
                     placeholder="Lihat Katalog">
            </div>

            <div class="col-md-3">
              <label class="ck-label">Teks Tombol 2</label>
              <input type="text" name="hero_cta2_text" class="form-control ck-input"
                     value="<?= e($hero['hero_cta2_text'] ?? '') ?>"
                     placeholder="Tentang Kami">
            </div>

            <div class="col-12">
              <label class="ck-label">Subtitel / Deskripsi</label>
              <textarea name="hero_subtitle" class="form-control ck-input" rows="3"
                        placeholder="Dari kusen kayu premium..."><?= e($hero['hero_subtitle'] ?? '') ?></textarea>
            </div>

          </div>
        </div>
      </div>
    </div>

  </div><!-- /row -->

  <div class="d-flex gap-3 mt-4">
    <button type="submit" class="btn btn-primary-brand btn-lg flex-grow-1" id="btnSimpanHero">
      <i class="bi bi-save me-2"></i>Simpan Perubahan Hero
    </button>
    <a href="<?= BASE_URL ?>/" target="_blank" class="btn btn-outline-secondary btn-lg">
      <i class="bi bi-eye me-1"></i>Preview
    </a>
  </div>
</form>

<?php else: ?>
<!-- ══════════════════════════════════════════════════════════
     TAB 2: HISTORI TIMELINE
══════════════════════════════════════════════════════════ -->

<div class="row g-4">

  <!-- Form Tambah / Edit -->
  <div class="col-lg-4">
    <div class="admin-card" style="position:sticky;top:80px">
      <div class="admin-card-header">
        <h6 class="mb-0">
          <?php if ($editHistori): ?>
            <i class="bi bi-pencil-fill me-2 text-warning"></i>Edit Milestone
          <?php else: ?>
            <i class="bi bi-plus-circle me-2 text-success"></i>Tambah Milestone Baru
          <?php endif; ?>
        </h6>
        <?php if ($editHistori): ?>
          <a href="?tab=histori" class="btn btn-sm btn-outline-secondary">Batal</a>
        <?php endif; ?>
      </div>
      <div class="p-4">
        <form method="POST">
          <input type="hidden" name="aksi"
                 value="<?= $editHistori ? 'edit_histori' : 'tambah_histori' ?>">
          <?php if ($editHistori): ?>
            <input type="hidden" name="id" value="<?= $editHistori['id'] ?>">
          <?php endif; ?>

          <div class="mb-3">
            <label class="ck-label">Tahun <span class="text-danger">*</span></label>
            <input type="number" name="tahun" class="form-control ck-input"
                   value="<?= $editHistori ? $editHistori['tahun'] : date('Y') ?>"
                   min="1900" max="<?= date('Y') + 10 ?>" required>
          </div>

          <div class="mb-3">
            <label class="ck-label">Judul Milestone <span class="text-danger">*</span></label>
            <input type="text" name="judul" class="form-control ck-input"
                   value="<?= e($editHistori['judul'] ?? '') ?>"
                   placeholder="Berdiri & Pertama Buka" required>
          </div>

          <div class="mb-3">
            <label class="ck-label">Deskripsi</label>
            <textarea name="deskripsi" class="form-control ck-input" rows="3"
                      placeholder="Ceritakan peristiwa penting ini..."><?= e($editHistori['deskripsi'] ?? '') ?></textarea>
          </div>

          <div class="mb-3">
            <label class="ck-label">Urutan Tampil</label>
            <input type="number" name="urutan" class="form-control ck-input"
                   value="<?= $editHistori ? $editHistori['urutan'] : (count($historiList) + 1) ?>"
                   min="0">
            <div class="ck-hint">Angka kecil tampil lebih awal.</div>
          </div>

          <?php if ($editHistori): ?>
            <div class="mb-3">
              <div class="form-check form-switch">
                <input type="checkbox" name="is_aktif" id="cbAktif"
                       class="form-check-input" value="1"
                       <?= $editHistori['is_aktif'] ? 'checked' : '' ?>>
                <label class="form-check-label ck-label mb-0" for="cbAktif">
                  Tampilkan di website
                </label>
              </div>
            </div>
          <?php endif; ?>

          <button type="submit" class="btn btn-primary-brand w-100">
            <?php if ($editHistori): ?>
              <i class="bi bi-check-lg me-1"></i>Simpan Perubahan
            <?php else: ?>
              <i class="bi bi-plus-lg me-1"></i>Tambah Milestone
            <?php endif; ?>
          </button>
        </form>
      </div>
    </div>
  </div>

  <!-- Daftar Timeline -->
  <div class="col-lg-8">
    <div class="admin-card">
      <div class="admin-card-header">
        <h6 class="mb-0"><i class="bi bi-list-ol me-2"></i><?= count($historiList) ?> Milestone</h6>
        <small class="text-muted">Drag urutan lewat kolom "Urutan"</small>
      </div>

      <?php if (empty($historiList)): ?>
        <div class="p-5 text-center">
          <i class="bi bi-clock-history fs-1 text-muted d-block mb-3"></i>
          <p class="text-muted">Belum ada milestone. Tambahkan di form kiri.</p>
        </div>
      <?php else: ?>
        <div class="table-responsive">
          <table class="table table-hover admin-table mb-0">
            <thead>
              <tr>
                <th style="width:70px">Urutan</th>
                <th style="width:80px">Tahun</th>
                <th>Judul & Deskripsi</th>
                <th style="width:80px" class="text-center">Status</th>
                <th style="width:100px" class="text-center">Aksi</th>
              </tr>
            </thead>
            <tbody>
              <?php foreach ($historiList as $h): ?>
                <tr class="<?= !$h['is_aktif'] ? 'adm-row--inactive' : '' ?>">
                  <td class="text-center">
                    <span class="badge bg-secondary"><?= $h['urutan'] ?></span>
                  </td>
                  <td>
                    <span class="fw-bold text-primary"><?= $h['tahun'] ?></span>
                  </td>
                  <td>
                    <div class="fw-semibold"><?= e($h['judul']) ?></div>
                    <?php if ($h['deskripsi']): ?>
                      <div class="small text-muted"><?= e(mb_substr($h['deskripsi'], 0, 80)) ?>...</div>
                    <?php endif; ?>
                  </td>
                  <td class="text-center">
                    <?php if ($h['is_aktif']): ?>
                      <span class="badge bg-success-subtle text-success border border-success-subtle">Aktif</span>
                    <?php else: ?>
                      <span class="badge bg-secondary-subtle text-secondary border border-secondary-subtle">Nonaktif</span>
                    <?php endif; ?>
                  </td>
                  <td class="text-center">
                    <div class="d-flex gap-1 justify-content-center">
                      <a href="?tab=histori&edit_id=<?= $h['id'] ?>"
                         class="btn btn-xs btn-warning" title="Edit">
                        <i class="bi bi-pencil"></i>
                      </a>
                      <form method="POST" class="d-inline">
                        <input type="hidden" name="aksi" value="hapus_histori">
                        <input type="hidden" name="id"   value="<?= $h['id'] ?>">
                        <button class="btn btn-xs btn-outline-danger"
                                onclick="return confirm('Hapus milestone <?= $h['tahun'] ?> - <?= e(addslashes($h['judul'])) ?>?')"
                                title="Hapus">
                          <i class="bi bi-trash3"></i>
                        </button>
                      </form>
                    </div>
                  </td>
                </tr>
              <?php endforeach; ?>
            </tbody>
          </table>
        </div>

        <!-- Preview Timeline -->
        <div class="p-4 border-top">
          <p class="small fw-bold text-muted mb-3">
            <i class="bi bi-eye me-1"></i>Preview Timeline di Website:
          </p>
          <div class="hh-timeline-preview">
            <?php foreach ($historiList as $h): if (!$h['is_aktif']) continue; ?>
              <div class="hh-tl-item">
                <div class="hh-tl-dot"></div>
                <div class="hh-tl-year"><?= $h['tahun'] ?></div>
                <div class="hh-tl-title"><?= e($h['judul']) ?></div>
                <?php if ($h['deskripsi']): ?>
                  <div class="hh-tl-desc"><?= e(mb_substr($h['deskripsi'],0,70)) ?>...</div>
                <?php endif; ?>
              </div>
            <?php endforeach; ?>
          </div>
        </div>

      <?php endif; ?>
    </div>
  </div>

</div><!-- /row histori -->
<?php endif; ?>

<style>
/* ── Hero Preview ──────────────────────────────────────── */
.hh-img-preview {
  width: 100%; height: 160px;
  background-size: cover; background-position: center;
  border-radius: 10px; border: 2px dashed #D1D5DB;
  position: relative; overflow: hidden;
  background-color: #F8FAFC;
}
.hh-img-preview--sm { height: 160px; }
.hh-img-label {
  position: absolute; bottom: 6px; left: 8px;
  background: rgba(0,0,0,.55); color: white;
  font-size: .7rem; padding: 2px 8px; border-radius: 10px;
}

/* ── Timeline Preview ──────────────────────────────────── */
.hh-timeline-preview {
  display: flex; flex-direction: column; gap: 0;
  border-left: 3px solid #D4A853;
  padding-left: 1.5rem; margin-left: .75rem;
}
.hh-tl-item { position: relative; padding: .6rem 0; }
.hh-tl-dot {
  position: absolute; left: -1.85rem; top: .75rem;
  width: 14px; height: 14px;
  background: #8B5E3C; border: 3px solid white;
  border-radius: 50%; box-shadow: 0 0 0 2px #D4A853;
}
.hh-tl-year { font-size: .7rem; color: #D4A853; font-weight: 800; margin-bottom: .1rem; }
.hh-tl-title { font-size: .88rem; font-weight: 700; color: #2D1B0E; }
.hh-tl-desc { font-size: .75rem; color: #64748B; margin-top: .1rem; }
</style>

<script>
/* ── Preview image from file input ───────────────────── */
function previewImg(input, divId) {
  const file = input.files?.[0];
  if (!file) return;
  const r = new FileReader();
  r.onload = e => {
    document.getElementById(divId).style.backgroundImage = `url('${e.target.result}')`;
  };
  r.readAsDataURL(file);
}

function previewImgTag(input) {
  const file = input.files?.[0];
  if (!file) return;
  const r = new FileReader();
  r.onload = e => {
    const img = document.getElementById('prevImgTag');
    img.src = e.target.result;
    img.style.display = 'block';
  };
  r.readAsDataURL(file);
}

function previewUrl(input, divId) {
  document.getElementById(divId).style.backgroundImage = `url('${input.value}')`;
}

function updateDzLabel(dzId, input) {
  const file = input.files?.[0];
  if (!file) return;
  const dz = document.getElementById(dzId);
  dz.querySelector('p').textContent = '✓ ' + file.name;
  dz.style.borderColor = '#8B5E3C';
}

/* ── Drag & Drop ─────────────────────────────────────── */
['dzBg','dzImg'].forEach(id => {
  const dz  = document.getElementById(id);
  const inp = document.getElementById(id === 'dzBg' ? 'iBgFile' : 'iImgFile');
  if (!dz || !inp) return;
  dz.addEventListener('dragover',  e => { e.preventDefault(); dz.classList.add('drag-over'); });
  dz.addEventListener('dragleave', ()  => dz.classList.remove('drag-over'));
  dz.addEventListener('drop', e => {
    e.preventDefault(); dz.classList.remove('drag-over');
    const dt = new DataTransfer();
    if (e.dataTransfer.files[0]) {
      dt.items.add(e.dataTransfer.files[0]);
      inp.files = dt.files;
      inp.dispatchEvent(new Event('change'));
    }
  });
});

/* ── Loading state submit ────────────────────────────── */
document.getElementById('frmHero')?.addEventListener('submit', () => {
  const btn = document.getElementById('btnSimpanHero');
  btn.disabled = true;
  btn.innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span>Menyimpan...';
});
</script>

<?php include __DIR__ . '/admin_footer.php'; ?>