<?php
require __DIR__ . '/Login/config.php';

// === Buku Sedang Tren (berdasarkan favorit terbanyak) ===
$stmt_tren = $pdo->query("
    SELECT b.id, b.judul, b.gambar, COUNT(f.id) AS total_fav
    FROM favorites f
    JOIN books b ON f.book_id = b.id
    GROUP BY b.id
    ORDER BY total_fav DESC, b.created_at DESC
    LIMIT 5
");
$trending_books = $stmt_tren->fetchAll(PDO::FETCH_ASSOC);

// === Buku Terbaru (berdasarkan tanggal ditambahkan) ===
$stmt_terbaru = $pdo->query("
    SELECT id, judul, gambar 
    FROM books 
    ORDER BY created_at DESC 
    LIMIT 5
");
$new_books = $stmt_terbaru->fetchAll(PDO::FETCH_ASSOC);
$rating_data = [];

$stmt_rating = $pdo->query("
    SELECT book_id, rating, COUNT(*) AS jumlah
    FROM reviews
    GROUP BY book_id, rating
");

while ($row = $stmt_rating->fetch(PDO::FETCH_ASSOC)) {
    $bookId = $row['book_id'];
    $rating = $row['rating'];
    $count = $row['jumlah'];
    $rating_data[$bookId][$rating] = $count;
}
// === Buku Terlaris (berdasarkan jumlah peminjaman terbanyak) ===
$stmt_terlaris = $pdo->query("
    SELECT 
        b.id,
        b.judul,
        b.gambar,
        COUNT(DISTINCT br.user_id) AS total_peminjam
    FROM borrowings br
    JOIN book_items bi ON br.book_item_id = bi.id
    JOIN books b ON bi.book_id = b.id
    WHERE br.status = 'dikembalikan'
    GROUP BY b.id
    ORDER BY total_peminjam DESC, b.created_at DESC
    LIMIT 5
");
$best_books = $stmt_terlaris->fetchAll(PDO::FETCH_ASSOC);

?>
<!DOCTYPE html>
<html lang="id">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Pustakaia</title>
  <style>
    /* GLOBAL */
    body {
      margin: 0;
      font-family: "Poppins", Arial, sans-serif;
      line-height: 1.6;
      background: linear-gradient(135deg, #f9f9f9, #e9f5ec);
      color: #222;
    }

    a {
      text-decoration: none;
      color: inherit;
    }

    /* HEADER */
    header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 20px 40px;
      background: #fff;
      border-bottom: 1px solid #ddd;
      position: sticky;
      top: 0;
      z-index: 100;
    }

    header .logo {
      font-size: 22px;
      font-weight: bold;
      color: #069797;
    }

    nav a {
      margin: 0 15px;
      font-weight: 500;
      transition: color 0.3s;
      color: #333;
    }

    nav a:hover {
      color: #069797;
    }
/* HERO SECTION */
.hero {
  position: relative;
  height: 480px; /* 🔹 Ubah tinggi hero di sini (bisa disesuaikan) */
  overflow: hidden;
  color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  text-align: center;
}

/* SLIDES */
.hero-slides {
  position: absolute;
  inset: 0;
  width: 100%;
  height: 100%;
}

.hero-slides .slide {
  position: absolute;
  inset: 0;
  background-size: cover;
  background-position: center;
  opacity: 0;
  transition: opacity 1.5s ease-in-out;
}

.hero-slides .slide.active {
  opacity: 1;
}

/* Overlay agar teks tetap terbaca */
.hero::after {
  content: "";
  position: absolute;
  inset: 0;
  background: rgba(0, 0, 0, 0.6);
}

/* TEKS DI HERO */
.hero-content {
  position: relative;
  z-index: 2;
  max-width: 800px;
  padding: 0 20px;
}

.hero-content h1 {
  font-size: 48px;
  font-weight: 700;
  margin-bottom: 10px;
}

.hero-content span {
  color: #06b6b6;
}

.hero-content p {
  font-size: 18px;
  color: #eee;
}
    /* SECTION */
    .section {
      padding: 40px 40px;
      max-width: 1200px;
      margin: auto;
    }

    .section-title {
      font-size: 28px;
      font-weight: bold;
      margin-bottom: 25px;
      text-align: center;
      color: #069797;
    }

    /* CARD STYLE */
    .card {
      background: #fff;
      border-radius: 0;
      padding: 25px;
      margin-bottom: 30px;
      box-shadow: 0 4px 12px rgba(0,0,0,0.08);
    }

    .favorite {
      display: flex;
      gap: 30px;
      align-items: flex-start;
    }

    .favorite img {
      width: 200px;
      border-radius: 0;
      box-shadow: 0 4px 12px rgba(0,0,0,0.15);
      flex-shrink: 0;
    }

    .info {
      flex: 1;
    }

    .info h2 {
      margin-top: 0;
      font-size: 24px;
    }

    .info strong {
      color: #069797;
    }

    .info p {
      font-size: 15px;
      color: #444;
    }

    /* TRENDING & TERBARU */
    .trending-row {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  gap: 25px; /* Jarak antar card lebih besar */
  margin: 30px 0;
}

.trend-card {
  display: flex;
  flex-direction: column;
  align-items: center;
  background: #ffffff;
  border-radius: 14px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  width: 190px; /* Lebih besar */
  transition: transform 0.2s ease, box-shadow 0.2s ease;
  text-decoration: none;
}

.trend-card:hover {
  transform: translateY(-6px);
  box-shadow: 0 8px 18px rgba(0, 0, 0, 0.15);
}

.trend-card img {
  width: 100%;
  height: 260px; /* Lebih tinggi agar proporsional */
  object-fit: cover;
  border-bottom: 3px solid #1a8917; /* Garis hijau pemisah */
}

.trend-card p {
  font-weight: 600;
  font-size: 15px;
  text-align: center;
  color: #111;
  padding: 10px;
  background-color: #f5f7f6;
  width: 100%;
  border-radius: 0 0 14px 14px;
}

    /* FOOTER */
    footer {
      background: #fff;
      margin-top: 40px;
      padding: 20px 40px;
      font-size: 14px;
      color: #222;
    }

    .footer-top {
      display: flex;
      justify-content: space-between;
      align-items: flex-start;
      flex-wrap: wrap;
    }

    .footer-left h3,
    .footer-right h3 {
      font-size: 18px;
      margin: 0 0 15px 0;
    }

    .contacts {
      display: flex;
      gap: 40px;
      flex-wrap: wrap;
    }

    .contact-card {
      display: flex;
      align-items: center;
      gap: 10px;
    }

    .contact-card p {
      margin: 0;
      font-size: 14px;
    }

    .avatar {
      width: 40px;
      height: 40px;
      border-radius: 50%;
      object-fit: cover;
    }

    .footer-bottom {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-top: 15px;
      font-size: 13px;
      flex-wrap: wrap;
    }

    .footer-links a {
      margin-left: 15px;
      color: #222;
      font-weight: 500;
    }

    .footer-links a:hover {
      text-decoration: underline;
    }
    .book-section {
  margin: 60px auto;
  text-align: center;
}

.section-title {
  font-size: 28px;
  font-weight: 700;
  margin-bottom: 30px;
  color: #069797;
  text-transform: uppercase;
  letter-spacing: 1px;
}

/* Gaya grid buku mirip category.php */
.book-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));
  gap: 30px;
  justify-items: center;
  max-width: 1200px;
  margin: 0 auto;
}

/* Kartu buku putih, bersih, elegan */
.book-card {
  background: #ffffff;
  border-radius: 10px;
  box-shadow: 0 2px 10px rgba(0,0,0,0.08);
  text-align: center;
  width: 190px;
  padding: 15px;
  transition: transform 0.2s ease, box-shadow 0.2s ease;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.book-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 18px rgba(0,0,0,0.15);
}

.book-card img {
  width: 100%;
  height: 250px;
  object-fit: cover;
  border-radius: 6px;
  margin-bottom: 10px;
}

/* Info buku (judul dan rating) */
.book-info {
  text-align: center;
  padding: 0;
  color: #222;
}

.book-info h4 {
  font-size: 15px;
  margin-bottom: 6px;
  font-weight: 600;
}

.rating-detail {
  font-size: 13px;
  color: #666;
  line-height: 1.4;
}

.rating-detail div {
  margin: 2px 0;
}

/* --- Search Bar Styling --- */
.search-bar {
  display: flex;
  align-items: center;
  background: #ffffff;
  border: 2px solid #069797;
  border-radius: 10px;        /* Tidak oval, agak tumpul */
  overflow: hidden;
  width: 1000px;               /* Lebih panjang */
  height: 40px;               /* Lebih besar dan tinggi */
  position: relative;
  box-shadow: 0 2px 6px rgba(0,0,0,0.05);
}

/* Dropdown kategori */
.search-bar select {
  border: none;
  background: #e7f7f7;       /* Sedikit tosca muda biar lembut */
  padding: 0 14px;
  font-size: 15px;
  outline: none;
  color: #069797;
  cursor: pointer;
  font-weight: 500;
  height: 100%;
}

/* Input pencarian */
.search-bar input {
  flex: 1;
  border: none;
  outline: none;
  padding: 0 16px;
  font-size: 15px;
  color: #333;
  background: #ffffff;
  height: 100%;
}

.search-bar input::placeholder {
  color: #aaa;
}

/* Tombol cari */
.search-bar button {
  background: #069797;
  color: #fff;
  border: none;
  padding: 0 20px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  transition: background 0.3s ease;
}

.search-bar button:hover {
  background: #048787;
}

/* Saran (autocomplete) */


#suggestions .suggest-item {
  padding: 10px 14px;
  cursor: pointer;
  transition: background 0.2s;
}

#suggestions .suggest-item:hover {
  background: #e7f7f7;
}

.search-bar {
  position: relative;
}

#suggestions {
  background: #ffffff;
  border: 2px solid #069797;
  border-radius: 8px;
  position: absolute;
  top: 100%;
  left: 0;
  right: 0;
  z-index: 9999;
  box-shadow: 0 4px 10px rgba(0,0,0,0.1);
  max-height: 250px;
  overflow-y: auto;
  display: none; /* ini nanti diubah jadi block lewat JS */
}
/* Grid */
.book-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));
    gap: 25px;
    justify-items: center;
    overflow: visible; /* penting agar popover tidak terpotong */
  }

 /* Ganti ini: */
.book-card {
  background: #fff;
  border-radius: 8px;
  /* overflow: hidden;  <-- HAPUS / KOMENTARI */
  overflow: visible;      /* <-- TAMBAHKAN */
  box-shadow: 0 3px 12px rgba(0,0,0,.1);
  transition: transform .2s, box-shadow .2s;
  position: relative;     /* anchor popover */
}
  .book-card:hover {
    transform: translateY(-5px);
    box-shadow: 0 8px 20px rgba(0,0,0,.15);
  }

  /* Cover */
  .cover-wrapper { position: relative; width: 100%; height: 260px; overflow: hidden; }
  .cover-btn { border: none; background: transparent; padding: 0; width: 100%; height: 100%; cursor: pointer; }
  .cover-wrapper img { width: 100%; height: 100%; object-fit: cover; display: block; transition: transform .3s ease; }
  .cover-wrapper:hover img { transform: scale(1.05); }

  /* Tombol bintang kecil */
  .star-toggle {
    position: absolute; bottom: 8px; right: 8px;
    width: 28px; height: 28px; border: none; border-radius: 50%;
    background: rgba(255,255,255,.9); cursor: pointer; font-size: 16px; line-height: 1;
    transition: background .2s;
  }
  .star-toggle:hover { background: #ffe89a; }

  /* Judul strip hitam: tinggi seragam 2 baris */
  .book-title{
    background:#111; color:#fff;
    display:flex; align-items:center; justify-content:center;
    height:56px; padding:6px 10px; text-align:center;
  }
  .book-title a{
    color:inherit; text-decoration:none;
    display:-webkit-box; -webkit-line-clamp:2; -webkit-box-orient:vertical;
    overflow:hidden; line-height:1.2; max-height:2.4em;
  }
  .book-title a:hover{ text-decoration:underline; }

  /* Popover rating: overlay muncul di bawah card */
  .rating-popover{
    position: absolute;
    top: calc(100% + 8px); left: 50%;
    transform: translateX(-50%) translateY(-6px);
    width: 220px; background: #181818; color: #f2f2f2;
    border: 1px solid #2a2a2a; border-radius: 10px; padding: 10px;
    box-shadow: 0 10px 24px rgba(0,0,0,.25);
    opacity: 0; visibility: hidden; pointer-events: none;
    transition: opacity .18s ease, transform .18s ease, visibility 0s linear .18s;
    z-index: 50;
  }
  .rating-popover.open{
    opacity: 1; visibility: visible; pointer-events: auto;
    transform: translateX(-50%) translateY(0);
    transition: opacity .18s ease, transform .18s ease;
  }
  .rating-popover::before{
    content: ""; position: absolute; top: -8px; left: 50%; transform: translateX(-50%);
    border: 8px solid transparent; border-bottom-color: #181818;
  }
  .rating-popover div{ font-size: 13px; margin: 6px 0; }

  /* Saat popover terbuka, taruh card di atas elemen lain */
  .book-card.popover-open{ z-index: 100; }

  /* Modal login (kalau belum ada di file) */
  .modal-backdrop { position:fixed; inset:0; background:rgba(0,0,0,.55); display:none; z-index:99999; }
  .modal { position:fixed; left:50%; top:50%; transform:translate(-50%,-50%);
    background:#fff; width:min(92vw,420px); border-radius:12px; padding:20px;
    box-shadow:0 10px 30px rgba(0,0,0,.2); display:none; z-index:100000; }
  .modal h3 { margin:0 0 8px 0; color:#069797; }
  .modal p { margin:0 0 16px 0; color:#333; }
  .modal .actions { display:flex; gap:10px; justify-content:flex-end; }
  .modal .btn { padding:10px 14px; border-radius:8px; border:1px solid #ddd; cursor:pointer; background:#fff; }
  .modal .btn-primary { background:#069797; color:#fff; border-color:#069797; }
/* Popover rating: putih, bersih, bayangan lembut */
.rating-popover {
  position: absolute;
  top: calc(100% + 8px);
  left: 50%;
  transform: translateX(-50%) translateY(-6px);
  width: 220px;
  background: #ffffff;             /* 🔹 ganti ke putih */
  color: #111;                     /* 🔹 teks hitam */
  border: 1px solid #ddd;          /* 🔹 garis lembut abu muda */
  border-radius: 10px;
  padding: 10px;
  box-shadow: 0 8px 20px rgba(0,0,0,.2); /* 🔹 lembut tapi kontras */
  opacity: 0;
  visibility: hidden;
  pointer-events: none;
  transition: opacity .18s ease, transform .18s ease, visibility 0s linear .18s;
  z-index: 999;
}

.rating-popover.open {
  opacity: 1;
  visibility: visible;
  pointer-events: auto;
  transform: translateX(-50%) translateY(0);
  transition: opacity .18s ease, transform .18s ease;
}

.rating-popover::before {
  content: "";
  position: absolute;
  top: -8px;
  left: 50%;
  transform: translateX(-50%);
  border: 8px solid transparent;
  border-bottom-color: #ffffff; /* 🔹 panahnya putih juga */
}

.rating-popover div {
  font-size: 13px;
  margin: 6px 0;
}
/* Strip judul full hitam, tidak ada putih sama sekali */
.book-title {
  background: #fff;
  color: #111;
  text-align: center;
  font-weight: 600;
  font-size: 14px;
  display: flex;
  align-items: center;
  justify-content: center;
  height: 56px;
  padding: 0 10px;
  margin: 0;                  /* 🔹 pastikan gak ada jarak ke bawah */
  width: 100%;                /* 🔹 lebar penuh card */
  box-sizing: border-box;
}

.book-title a {
  color: inherit;
  text-decoration: none;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  line-height: 1.2;
  max-height: 2.4em;
}

.book-title a:hover {
  text-decoration: underline;
}

  </style>
</head>
<body>
  <!-- HEADER -->
  <header>
  <div class="logo" data-translate="text">📚 Pustaka Ilium Academy</div>
    </div>
    <!-- 🔍 Search bar (di tengah header) -->
  <form id="searchForm" method="get" action="search_results.php" class="search-bar">
  <select name="kategori" id="kategori" class="search-select">
    <option value="">Kategori</option>
    <option value="Novel"data-translate="text">Novel</option>
    <option value="Sains"data-translate="text">Sains</option>
    <option value="Teknologi"data-translate="text">Teknologi</option>
    <option value="Komputer"data-translate="text">Komputer</option>
    <option value="Matematika"data-translate="text">Matematika</option>
    <option value="Fisika"data-translate="text">Fisika</option>
    <option value="Kimia"data-translate="text">Kimia</option>
    <option value="Biologi"data-translate="text">Biologi</option>
    <option value="Psikologi"data-translate="text">Psikologi</option>
    <option value="Ekonomi"data-translate="text">Ekonomi</option>
    <option value="Bisnis"data-translate="text">Bisnis</option>
    <option value="Sejarah"data-translate="text">Sejarah</option>
    <option value="Agama"data-translate="text">Agama</option>
    <option value="Sastra"data-translate="text">Sastra</option>
    <option value="Politik"data-translate="text">Politik</option>
    <option value="Pendidikan"data-translate="text">Pendidikan</option>
    <option value="Anak-anak"data-translate="text">Anak-anak</option>
    <option value="Remaja"data-translate="text">Remaja</option>
    <option value="Inspiratif"data-translate="text">Inspiratif</option>
    <option value="Hukum"data-translate="text">Hukum</option>
    <option value="Geografi"data-translate="text">Geografi</option>
    <option value="Kesehatan"data-translate="text">Kesehatan</option>
    <option value="Komik"data-translate="text">Komik</option>
    <option value="Ensiklopedia"data-translate="text">Ensiklopedia</option>
    <option value="Filsafat"data-translate="text">Filsafat</option>
  </select>

  <input type="text" id="searchInput" name="search"
       data-translate="placeholder"
       placeholder="Cari buku apa...?" autocomplete="off" />

  <button type="submit">
    <i class="fa fa-search"></i>
  </button>

  <div id="suggestions"></div>
</form>
    <nav>
      <a href="Login/Login.php"data-translate="text">Login</a>
    </nav>


  </header>

  <!-- HERO -->
<section class="hero">
  <div class="hero-slides">
    <div class="slide" style="background-image: url('images/bud11.png');"></div>
    <div class="slide" style="background-image: url('images/bud21.png');"></div>
    <div class="slide" style="background-image: url('images/bud31.png');"></div>
  </div>

  <div class="hero-content">
    <h1 data-translate="text">Membaca <span>adalah </span>Jendela <span>Dunia</span></h1>
    <p data-translate="text">Temukan buku favoritmu dan tren terbaru di Pustakaia</p>
  </div>
</section>


  <!-- TERFAVORITE -->
  <div class="section">
    <div class="card favorite">
      <img src="images/book.png" alt="Filosofi Teras">
      <div class="info">
      <h2>FILOSOFI TERAS</h2>
<p><strong data-translate="text">PENULIS:</strong> Henry Manampiring</p>
<p><strong data-translate="text">TAHUN TERBIT:</strong> 2016</p>
<p><strong data-translate="text">PENERBIT:</strong> Gramedia</p>
        <p>
          Filosofi Teras karya Henry Manampiring adalah sebuah buku pengembangan diri
          yang memaparkan konsep filsafat Stoa (Stoikisme) dari Yunani-Romawi kuno
          dengan bahasa yang ringan dan relevan untuk kehidupan modern.
          Tujuannya adalah membantu pembaca mengatasi emosi negatif
          dan mencapai ketenangan batin dalam menghadapi berbagai tantangan hidup.
        </p>
      </div>
    </div>
  </div>
<!-- 🌟 SEDANG TREN -->
<section class="book-section">
  <h2 class="section-title"data-translate="text">Sedang Tren</h2>
  <div class="book-grid">
    <?php if (!empty($trending_books)): ?>
      <?php foreach ($trending_books as $book): ?>
        <div class="book-card" data-book-id="<?= $book['id'] ?>">
          <div class="cover-wrapper">
            <!-- Cover -> modal login -->
            <button class="cover-btn" type="button" aria-label="Buka login">
              <img src="<?= htmlspecialchars($book['gambar']) ?>" alt="<?= htmlspecialchars($book['judul']) ?>">
            </button>
            <!-- Bintang kecil -->
            <button class="star-toggle" type="button" aria-expanded="false" title="Lihat rating">⭐</button>
          </div>

          <!-- Judul -> ke detail -->
          <div class="book-title">
            <a href="detail_guest.php?id=<?= $book['id'] ?>">
              <?= htmlspecialchars($book['judul']) ?>
            </a>
          </div>

          <!-- Popover rating -->
          <div class="rating-popover" role="dialog" aria-label="Rating buku" aria-hidden="true">
            <?php
              $bookId = $book['id'];
              for ($i = 5; $i >= 1; $i--) {
                  $jumlah = $rating_data[$bookId][$i] ?? 0;
                  echo '<div data-translate="text">⭐'.$i.': '.$jumlah.' orang</div>';
              }
            ?>
          </div>
        </div>
      <?php endforeach; ?>
    <?php else: ?>
      <p style="text-align:center;">Belum ada buku yang sedang tren.</p>
    <?php endif; ?>
  </div>
</section>

<!-- 🆕 TERBARU -->
<section class="book-section">
  <h2 class="section-title"data-translate="text">Terbaru</h2>
  <div class="book-grid">
    <?php if (!empty($new_books)): ?>
      <?php foreach ($new_books as $book): ?>
        <div class="book-card" data-book-id="<?= $book['id'] ?>">
          <div class="cover-wrapper">
            <button class="cover-btn" type="button" aria-label="Buka login">
              <img src="<?= htmlspecialchars($book['gambar']) ?>" alt="<?= htmlspecialchars($book['judul']) ?>">
            </button>
            <button class="star-toggle" type="button" aria-expanded="false" title="Lihat rating">⭐</button>
          </div>

          <div class="book-title">
            <a href="detail_guest.php?id=<?= $book['id'] ?>">
              <?= htmlspecialchars($book['judul']) ?>
            </a>
          </div>

          <div class="rating-popover" role="dialog" aria-label="Rating buku" aria-hidden="true">
            <?php
              $bookId = $book['id'];
              for ($i = 5; $i >= 1; $i--) {
                  $jumlah = $rating_data[$bookId][$i] ?? 0;
                  echo '<div data-translate="text">⭐'.$i.': '.$jumlah.' orang</div>';
              }
            ?>
          </div>
        </div>
      <?php endforeach; ?>
    <?php else: ?>
      <p style="text-align:center;">Belum ada buku terbaru.</p>
    <?php endif; ?>
  </div>
</section>

<!-- 🏆 TERLARIS -->
<section class="book-section">
  <h2 class="section-title"data-translate="text">Terlaris</h2>
  <div class="book-grid">
    <?php if (!empty($best_books)): ?>
      <?php foreach ($best_books as $book): ?>
        <div class="book-card" data-book-id="<?= $book['id'] ?>">
          <div class="cover-wrapper">
            <button class="cover-btn" type="button" aria-label="Buka login">
              <img src="<?= htmlspecialchars($book['gambar']) ?>" alt="<?= htmlspecialchars($book['judul']) ?>">
            </button>
            <button class="star-toggle" type="button" aria-expanded="false" title="Lihat rating">⭐</button>
          </div>

          <div class="book-title">
            <a href="detail_guest.php?id=<?= $book['id'] ?>">
              <?= htmlspecialchars($book['judul']) ?>
            </a>
          </div>

          <div class="rating-popover" role="dialog" aria-label="Rating buku" aria-hidden="true">
            <?php
              $bookId = $book['id'];
              for ($i = 5; $i >= 1; $i--) {
                  $jumlah = $rating_data[$bookId][$i] ?? 0;
                  echo '<div data-translate="text">⭐'.$i.': '.$jumlah.' orang</div>';
              }
            ?>
          </div>
        </div>
      <?php endforeach; ?>
    <?php else: ?>
      <p style="text-align:center;">Belum ada buku terlaris.</p>
    <?php endif; ?>
  </div>
</section>

  <!-- FOOTER -->
  <footer>
    <div class="footer-top">
      <!-- Kiri -->
      <div class="footer-left">
        <h3 style="color:#069797;">Pustakaia</h3>
      </div>

      <!-- Kanan -->
      <div class="footer-right">
      <h3 data-translate="text">Contact Us</h3>
        <div class="contacts">
          <div class="contact-card">
            <img src="images/dwi.jpeg" alt="Dwi Putri B" class="avatar">
            <div>
              <p><strong>Dwi Putri B</strong></p>
              <p>+62 8222 2222 2222</p>
            </div>
          </div>
          <div class="contact-card">
            <img src="images/dihya.jpeg" alt="M Dihya Al Hanif" class="avatar">
            <div>
              <p><strong>M Dihya Al Hanif</strong></p>
              <p>+62 8111 1111 1111</p>
            </div>
          </div>
          <div class="contact-card">
            <img src="images/wilo.jpg" alt="Wilo Antika" class="avatar">
            <div>
              <p><strong>Wilo Antika</strong></p>
              <p>+62 8333 3333 3333</p>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- Garis full width -->
    <hr style="border: none; border-top: 1px solid #ddd; margin: 20px 0 10px 0; width: 100%;">

    <div class="footer-bottom">
    <p data-translate="text">© 2025, Pustakaia | Website developed by Grup 3</p>
      <div class="footer-links">
      <a href="#" data-translate="text">Terms of Use</a>
<a href="#" data-translate="text">Privacy Policy</a>
      </div>
    </div>
  </footer>

  <div class="modal-backdrop" id="loginBackdrop"></div>
<div class="modal" id="loginModal" role="dialog" aria-modal="true" aria-labelledby="loginTitle">
<h3 id="loginTitle" data-translate="text">Anda belum login</h3>
<p data-translate="text">Silakan login untuk meminjam buku.</p>
<button type="button" class="btn" id="modalClose" data-translate="text">Tutup</button>
<a href="Login/Login.php" class="btn btn-primary" id="modalLoginBtn" data-translate="text">Ke Halaman Login</a>
  </div>
</div>


<script>
/* ======= Helper translate functions (collect/apply) ======= */
function genKey(el, type) {
  const raw = (type === 'text') ? (el.textContent || '') : (el.getAttribute(type) || '');
  const snippet = raw.trim().slice(0, 60);
  return (el.tagName + '|' + type + '|' + snippet).toLowerCase();
}

function collectTranslatables() {
  const items = [];
  document.querySelectorAll('[data-translate]').forEach(el => {
    const type = el.getAttribute('data-translate') || 'text';
    let text = '';
    if (type === 'text') text = (el.textContent || '').trim();
    else text = (el.getAttribute(type) || '').trim();
    if (text) items.push({ key: genKey(el, type), type, text });
  });
  return items;
}

function applyTranslations(map) {
  document.querySelectorAll('[data-translate]').forEach(el => {
    const type = el.getAttribute('data-translate') || 'text';
    const key = genKey(el, type);
    const translated = map[key];
    if (!translated) return;
    if (type === 'text') el.textContent = translated;
    else el.setAttribute(type, translated);
  });
}

/* translatePage: kirim batch ke backend translate.php dan apply hasilnya */
async function translatePage(targetLang) {
  if (!targetLang) targetLang = localStorage.getItem('preferred_lang') || 'auto';
  localStorage.setItem('preferred_lang', targetLang);

  if (targetLang === 'auto') {
    document.documentElement.removeAttribute('lang');
  } else {
    document.documentElement.setAttribute('lang', targetLang);
  }

  const items = collectTranslatables();
  if (!items.length) return;

  try {
    const res = await fetch('translate.php', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ target: targetLang, items })
    });
    const data = await res.json();
    if (data && data.ok && data.map) {
      applyTranslations(data.map);
      // handle RTL languages
      if (['ar','he','fa','ur'].includes(targetLang)) {
        document.documentElement.setAttribute('dir', 'rtl');
      } else {
        document.documentElement.removeAttribute('dir');
      }
    } else {
      // nothing critical, just log
      console.warn('translate response:', data);
    }
  } catch (err) {
    console.error('translatePage error', err);
  }
}

/* ======= Live search + floating suggestions + modal/popover handlers ======= */
document.addEventListener('DOMContentLoaded', () => {
  // ---- Hero slides (kept minimal) ----
  let currentSlide = 0;
  const slides = document.querySelectorAll('.hero-slides .slide');
  if (slides && slides.length) {
    const totalSlides = slides.length;
    function showSlide(index) {
      slides.forEach((slide, i) => slide.classList.toggle('active', i === index));
    }
    showSlide(currentSlide);
    setInterval(() => {
      currentSlide = (currentSlide + 1) % totalSlides;
      showSlide(currentSlide);
    }, 7000);
  }

  // ---- Floating suggestions container (global) ----
  const input = document.getElementById('searchInput');
  if (!input) {
    console.warn('searchInput not found');
  } else {
    let floating = document.getElementById('floating-suggestions');
    if (!floating) {
      floating = document.createElement('div');
      floating.id = 'floating-suggestions';
      document.body.appendChild(floating);
      Object.assign(floating.style, {
        position: 'absolute',
        display: 'none',
        background: '#fff',
        border: '2px solid #069797',
        borderRadius: '8px',
        boxShadow: '0 6px 18px rgba(0,0,0,0.15)',
        zIndex: 999999,
        maxHeight: '300px',
        overflowY: 'auto',
        color: '#000',
        padding: '4px'
      });
    }

    // positioning helper
    function positionFloating() {
      const r = input.getBoundingClientRect();
      const docEl = document.documentElement;
      const scrollTop = window.pageYOffset || docEl.scrollTop || document.body.scrollTop;
      const scrollLeft = window.pageXOffset || docEl.scrollLeft || document.body.scrollLeft;
      floating.style.width = Math.max(260, r.width) + 'px';
      floating.style.left = (r.left + scrollLeft) + 'px';
      floating.style.top = (r.bottom + scrollTop + 6) + 'px';
    }

    window.addEventListener('resize', positionFloating);
    window.addEventListener('scroll', positionFloating, true);

    // hide when click outside
    document.addEventListener('click', (ev) => {
      if (ev.target === input || floating.contains(ev.target)) return;
      floating.style.display = 'none';
    }, true);

    // live-search fetch logic
    let lastController = null;
    input.addEventListener('input', () => {
      const q = input.value.trim();
      if (!q) {
        floating.style.display = 'none';
        return;
      }

      if (lastController) lastController.abort();
      lastController = new AbortController();

      fetch('live_search.php?search=' + encodeURIComponent(q), { signal: lastController.signal })
        .then(res => res.json())
        .then(data => {
          if (!Array.isArray(data) || data.length === 0) {
            floating.innerHTML = `
              <div class="fs-empty" data-translate="text" style="padding:10px;color:#666">
                Tidak ada hasil...
              </div>`;
            // translate the newly added element if needed
            translatePage(localStorage.getItem('preferred_lang') || 'auto');
          } else {
            let html = '';
            data.forEach(book => {
              const safeId      = String(book.id ?? '').replace(/"/g, '&quot;');
              const safeTitle   = String(book.judul ?? '').replace(/</g, '&lt;');
              const safeAuthor  = String(book.penulis ?? '').replace(/</g, '&lt;');
              const safeIsbn    = String(book.isbn ?? '').replace(/</g, '&lt;');
              const safeSnippet = String(book.sinopsis_snippet ?? '').replace(/</g, '&lt;');

              html += '<div class="fs-item" data-id="' + safeId + '" style="padding:10px;cursor:pointer;border-bottom:1px solid #eee;">'
                   + '<div style="font-weight:600">' + safeTitle + '</div>'
                   + '<div style="font-size:12px;color:#555">'
                   + (safeAuthor ? safeAuthor : '')
                   + ((safeAuthor && safeIsbn) ? ' • ' : '')
                   + (safeIsbn ? '<span data-translate="text">ISBN:</span> ' + safeIsbn : '')
                   + '</div>'
                   + (safeSnippet ? '<div style="font-size:12px;color:#666;margin-top:4px;">' + safeSnippet + '</div>' : '')
                   + '</div>';
            });

            floating.innerHTML = html;

            // attach click handlers
            floating.querySelectorAll('.fs-item').forEach(el => {
              el.addEventListener('click', () => {
                const id = el.getAttribute('data-id');
                window.location.href = 'detail_guest.php?id=' + encodeURIComponent(id);
              });
            });

            // translate newly created nodes (ISBN:, etc.)
            translatePage(localStorage.getItem('preferred_lang') || 'auto');

            positionFloating();
            floating.style.display = 'block';
          }
        })
        .catch(err => {
          if (err.name === 'AbortError') return;
          console.error('live search error', err);
          floating.style.display = 'none';
        });
    });

    // enter key behavior
    input.addEventListener('keydown', (e) => {
      if (e.key === 'Enter') {
        const first = floating.querySelector('.fs-item');
        if (first && floating.style.display === 'block') {
          e.preventDefault();
          first.click();
          return;
        }
      }
    });
  }

  // kategori change handler (existing)
  const kategoriEl = document.getElementById('kategori');
  if (kategoriEl) {
    kategoriEl.addEventListener('change', function() {
      const category = this.value;
      if (category !== '') {
        window.location.href = 'category.php?kategori=' + encodeURIComponent(category);
      }
    });
  }

  // search form submit (existing)
  const searchForm = document.getElementById('searchForm');
  if (searchForm) {
    searchForm.addEventListener('submit', function(e) {
      e.preventDefault();
      const search = (document.getElementById('searchInput') || {}).value || '';
      if (search.trim() !== '') {
        window.location.href = 'search_results.php?search=' + encodeURIComponent(search.trim());
      }
    });
  }

  // modal login handlers (existing logic kept)
  const modal = document.getElementById('loginModal');
  const backdrop = document.getElementById('loginBackdrop');
  const closeBtn = document.getElementById('modalClose');
  function openModal(){
    if(!modal||!backdrop) return;
    modal.style.display='block';
    backdrop.style.display='block';
    document.getElementById('modalLoginBtn')?.focus();
  }
  function closeModal(){
    if(!modal||!backdrop) return;
    modal.style.display='none';
    backdrop.style.display='none';
  }
  closeBtn?.addEventListener('click', closeModal);
  backdrop?.addEventListener('click', closeModal);
  document.addEventListener('keydown', e => {
    if (e.key === 'Escape'){ closeModal(); closeAllPopovers(); }
  });

  // rating popover handlers (kept, no change)
  function closeAllPopovers(except){
    document.querySelectorAll('.rating-popover.open').forEach(p => {
      if (p !== except){
        p.classList.remove('open');
        p.setAttribute('aria-hidden','true');
        const card = p.closest('.book-card');
        card?.classList.remove('popover-open');
        const star = card?.querySelector('.star-toggle');
        star?.setAttribute('aria-expanded','false');
      }
    });
  }

  document.addEventListener('click', function(e){
    const coverBtn = e.target.closest('.cover-btn');
    if (coverBtn){ e.preventDefault(); openModal(); return; }

    const starBtn = e.target.closest('.star-toggle');
    if (starBtn){
      const card = starBtn.closest('.book-card');
      const pop = card.querySelector('.rating-popover');
      const isOpen = pop.classList.contains('open');
      closeAllPopovers(isOpen ? null : pop);
      if (isOpen){
        pop.classList.remove('open');
        pop.setAttribute('aria-hidden','true');
        starBtn.setAttribute('aria-expanded','false');
        card.classList.remove('popover-open');
      } else {
        pop.classList.add('open');
        pop.setAttribute('aria-hidden','false');
        starBtn.setAttribute('aria-expanded','true');
        card.classList.add('popover-open');
      }
      return;
    }
    if (!e.target.closest('.rating-popover')){
      closeAllPopovers();
    }
  });

  window.addEventListener('scroll', () => closeAllPopovers(), true);
  window.addEventListener('resize', () => closeAllPopovers());

  // language switcher: hook to #langSwitch if exists
  const langSelect = document.getElementById('langSwitch');
  if (langSelect) {
    langSelect.value = localStorage.getItem('preferred_lang') || 'auto';
    langSelect.addEventListener('change', (e) => translatePage(e.target.value));
    // run initial translate once DOM ready
    translatePage(langSelect.value || 'auto');
  } else {
    // still try to run automatic translate if preferred saved
    translatePage(localStorage.getItem('preferred_lang') || 'auto');
  }
});
</script>


</body>
</html>
