document.addEventListener("DOMContentLoaded", () => {
  const bookList = document.getElementById("bookList");
  const searchInput = document.getElementById("searchInput");
  const categoryFilter = document.getElementById("categoryFilter");
  const statusFilter = document.getElementById("statusFilter");
  let currentMode = "all";

  const getRandomQuote = () => {
    const quotes = [
      "Книга — це мрія, яку ти тримаєш у руках.",
      "Той, хто читає, живе тисячу життів.",
      "Світ належить тим, хто читає.",
      "Читання — це відпочинок для душі.",
      "Кожна книга — це новий світ."
    ];
    return quotes[Math.floor(Math.random() * quotes.length)];
  };

  const renderBooks = (mode = "all") => {
  currentMode = mode;
  const filterText = searchInput.value.toLowerCase();
  const selectedCategory = categoryFilter?.value || "";
  const selectedStatus = statusFilter.value;
  const statuses = getStatuses();
  const favorites = getFavorites();

  // 🧠 Ось цей рядок — додає клас для правильного стилю
  bookList.className = mode === "profile" ? "profile-view" : "books-view";
  bookList.innerHTML = "";

  if (mode === "profile") {
    renderProfile(statuses, favorites);
    return;
  }

  const filtered = books.filter(book => {
    const matchTitle = book.title.toLowerCase().includes(filterText);
    const matchCategory = selectedCategory === "" || book.category === selectedCategory;
    const matchStatus = selectedStatus === "" || statuses[book.id] === selectedStatus;
    const matchFav = mode !== "favorites" || favorites.includes(book.id);
    return matchTitle && matchCategory && matchStatus && matchFav;
  });

  filtered.forEach(book => createBookCard(book, bookList));
};

  const renderProfile = (statuses, favorites) => {
    const ratings = getRatings();
    const totalBooks = books.length;
    const read = Object.values(statuses).filter(s => s === "read").length;
    const reading = Object.values(statuses).filter(s => s === "reading").length;
    const planned = Object.values(statuses).filter(s => s === "planned").length;
    const avgRating = Object.values(ratings).length
      ? (Object.values(ratings).reduce((a, b) => a + b, 0) / Object.values(ratings).length).toFixed(1)
      : "—";

    const ratedBooks = books
      .filter(b => ratings[b.id])
      .map(b => ({ ...b, rating: ratings[b.id] }))
      .sort((a, b) => b.rating - a.rating)
      .slice(0, 3);

    bookList.innerHTML = `
      <div class="profile-container">
        <div class="profile-panel" style="flex: 1;">
          <h2>📊 Статистика користувача</h2>
          <canvas id="statusChart" width="400" height="250" style="margin-top: 20px;"></canvas>

          <ul style="margin-top: 2rem;">
            <li>📚 Усього книг: <strong>${totalBooks}</strong></li>
            <li>❤️ У обраному: <strong>${favorites.length}</strong></li>
            <li>⭐ Середній рейтинг: <strong>${avgRating}</strong></li>
          </ul>

          <div class="top-books">
            <h3>🏆 Топ 3 улюблених книги</h3>
            <div class="top-books-list horizontal">
              ${ratedBooks.length ? ratedBooks.map(book => `
                <div class="top-book-card">
                  <h4>${book.title}</h4>
                  <p>${book.author}</p>
                  <div class="stars">
                    ${[1, 2, 3, 4, 5].map(i =>
                      `<span style="color:${i <= book.rating ? 'gold' : '#ccc'}">&#9733;</span>`
                    ).join("")}
                  </div>
                </div>
              `).join("") : "<p>Немає оцінених книг.</p>"}
            </div>
          </div>
        </div>

        <div class="right-panel" style="flex: 0 0 280px;">
          <h3>📅 Останні прочитані</h3>
          <ul class="recent-read">
            ${books.filter(b => statuses[b.id] === "read").slice(-3).reverse().map(b => `
              <li><strong>${b.title}</strong> — ${b.author}</li>
            `).join("") || "<li>Немає прочитаних книг</li>"}
          </ul>

          <h3 style="margin-top: 1rem;">💡 Цитата дня</h3>
          <blockquote class="quote">
            "${getRandomQuote()}"
          </blockquote>
        </div>
      </div>
    `;

    setTimeout(() => {
      const ctx = document.getElementById("statusChart")?.getContext("2d");
      if (!ctx) return;

      new Chart(ctx, {
        type: "doughnut",
        data: {
          labels: ["Прочитано", "Читається", "В планах"],
          datasets: [{
            data: [read, reading, planned],
            backgroundColor: ["#4caf50", "#2196f3", "#ffc107"],
            borderWidth: 1
          }]
        },
        options: {
          plugins: {
            legend: {
              labels: {
                color: document.body.classList.contains("dark-mode") ? "#eee" : "#111",
                font: { size: 14 }
              }
            }
          }
        }
      });
    }, 0);
  };

  const fillCategoryFilter = () => {
    if (!categoryFilter) return;
    const uniqueCategories = [...new Set(books.map(b => b.category))];
    uniqueCategories.forEach(cat => {
      const opt = document.createElement("option");
      opt.value = cat;
      opt.textContent = cat;
      categoryFilter.appendChild(opt);
    });
  };

  const createBookCard = (book, container) => {
    const statuses = getStatuses();
    const ratingData = getRatings();
    const favorites = getFavorites();

    const card = document.createElement("div");
    card.className = "book-card";

    const currentStatus = statuses[book.id] || "";
    const currentRating = ratingData[book.id] || 0;
    const isFavorite = favorites.includes(book.id);

    card.innerHTML = `
      <h3>${book.title}</h3>
      <p>${book.author}</p>
      <p>${book.category}</p>
      <p>${book.description}</p>

      <div class="stars" data-id="${book.id}">
        ${[1, 2, 3, 4, 5].map(i => `
          <span data-star="${i}" style="color:${i <= currentRating ? "gold" : "#ccc"};">&#9733;</span>`).join("")}
      </div>

      <select class="status-select" data-id="${book.id}">
        <option value="">Без статусу</option>
        <option value="read" ${currentStatus === "read" ? "selected" : ""}>Прочитано</option>
        <option value="reading" ${currentStatus === "reading" ? "selected" : ""}>Читається</option>
        <option value="planned" ${currentStatus === "planned" ? "selected" : ""}>В планах</option>
      </select>

      <div style="display: flex; gap: 8px; margin-top: 6px;">
        <button onclick="location.href='book.html?id=${book.id}'">Читати</button>
        <button class="fav-btn" data-id="${book.id}">
          ${isFavorite ? "★ У обраному" : "☆ У обране"}
        </button>
      </div>
    `;

    container.appendChild(card);
  };

  document.addEventListener("change", (e) => {
    if (e.target.classList.contains("status-select")) {
      const bookId = e.target.getAttribute("data-id");
      const newStatus = e.target.value;
      const statuses = getStatuses();
      statuses[bookId] = newStatus;
      setStatuses(statuses);
      renderBooks(currentMode);
    }
  });

  document.addEventListener("click", (e) => {
    if (e.target.dataset.star) {
      const star = parseInt(e.target.dataset.star);
      const bookId = e.target.closest(".stars").dataset.id;
      const ratings = getRatings();
      ratings[bookId] = star;
      setRatings(ratings);
      renderBooks(currentMode);
    }

    if (e.target.classList.contains("fav-btn")) {
      const bookId = parseInt(e.target.dataset.id);
      let favs = getFavorites();
      if (favs.includes(bookId)) {
        favs = favs.filter(id => id !== bookId);
      } else {
        favs.push(bookId);
      }
      setFavorites(favs);
      renderBooks(currentMode);
    }
  });

  document.querySelectorAll("nav button").forEach(btn => {
    btn.addEventListener("click", () => {
      currentMode = btn.dataset.section || "all";
      renderBooks(currentMode);
    });
  });

  searchInput.addEventListener("input", () => renderBooks(currentMode));
  categoryFilter?.addEventListener("change", () => renderBooks(currentMode));
  statusFilter.addEventListener("change", () => renderBooks(currentMode));

  fillCategoryFilter();
  renderBooks();
});
