const searchInput = document.getElementById('search');
const contentType = document.getElementById('contentType');
const PEXELS_API_KEY = '2bFMHHYJrdMdyyRFDVeVvdgi9yzHe3KeN1XctYoJvzcySM6qiPgbXfyD';

let scrollBatch = [];
let isLoading = false;
let scrollPage = 0;

// Fetch a batch of items for scrolling
async function fetchBatch(type, count = 5) {
  let batch = [];
  if (type === "quote") {
    const localQuotes = [
      {q: "Education is the most powerful weapon which you can use to change the world.", a: "Nelson Mandela"},
      {q: "The beautiful thing about learning is nobody can take it away from you.", a: "B.B. King"},
      {q: "Science is a way of thinking much more than it is a body of knowledge.", a: "Carl Sagan"},
      {q: "The important thing is not to stop questioning.", a: "Albert Einstein"},
      {q: "Poetry is when an emotion has found its thought and the thought has found words.", a: "Robert Frost"},
      {q: "Tell me and I forget. Teach me and I remember. Involve me and I learn.", a: "Benjamin Franklin"},
      {q: "Learning never exhausts the mind.", a: "Leonardo da Vinci"},
      {q: "The roots of education are bitter, but the fruit is sweet.", a: "Aristotle"},
      {q: "Live as if you were to die tomorrow. Learn as if you were to live forever.", a: "Mahatma Gandhi"},
      {q: "Wisdom is not a product of schooling but of the lifelong attempt to acquire it.", a: "Albert Einstein"},
      {q: "Success is not the key to happiness. Happiness is the key to success.", a: "Albert Schweitzer"},
      {q: "The only way to do great work is to love what you do.", a: "Steve Jobs"},
      {q: "It does not matter how slowly you go as long as you do not stop.", a: "Confucius"},
      {q: "You are never too old to set another goal or to dream a new dream.", a: "C.S. Lewis"},
      {q: "The mind is not a vessel to be filled, but a fire to be kindled.", a: "Plutarch"},
      {q: "Change is the end result of all true learning.", a: "Leo Buscaglia"},
      {q: "Education is not preparation for life; education is life itself.", a: "John Dewey"},
      {q: "A person who never made a mistake never tried anything new.", a: "Albert Einstein"},
      {q: "The expert in anything was once a beginner.", a: "Helen Hayes"},
      {q: "Learning is a treasure that will follow its owner everywhere.", a: "Chinese Proverb"}
    ];
    for (let i = 0; i < count; i++) {
      const q = localQuotes[Math.floor(Math.random() * localQuotes.length)];
      batch.push({
        text: `"${q.q}"`,
        author: `— ${q.a}`,
        type: "quote"
      });
    }
  } else if (type === "science") {
    for (let i = 0; i < count; i++) {
      try {
        const res = await fetch('https://fun-facts-api.onrender.com/facts/random');
        const data = await res.json();
        batch.push({
          text: data.fact,
          author: "🔬 Science Fact",
          type: "science"
        });
      } catch {
        batch.push({ text: "❌ Failed to load science fact.", author: "", type: "science" });
      }
    }
  } else if (type === "poem") {
    for (let i = 0; i < Math.max(3, count); i++) {
      try {
        const res = await fetch('https://poetrydb.org/random');
        const data = await res.json();
        const poem = data[0];
        batch.push({
          text: `${poem.title} by ${poem.author}\n\n${poem.lines.join("\n")}`,
          author: "",
          type: "poem"
        });
      } catch {
        batch.push({ text: "❌ Failed to load poem.", author: "", type: "poem" });
      }
    }
  }
  return batch;
}

async function loadInitialScrollList() {
  scrollPage = 0;
  scrollBatch = [];
  const scrollList = document.getElementById('scroll-list');
  scrollList.innerHTML = '';
  scrollList.scrollLeft = 0;
  await loadMoreScrollList();
}

async function loadMoreScrollList() {
  if (isLoading) return;
  isLoading = true;
  const type = contentType.value;
  const newBatch = await fetchBatch(type, 5);
  const startIdx = scrollBatch.length;
  scrollBatch = scrollBatch.concat(newBatch);
  renderScrollList(newBatch, startIdx);
  scrollPage++;
  isLoading = false;
}

function renderScrollList(newBatch, startIdx) {
  const scrollList = document.getElementById('scroll-list');
  newBatch.forEach(async (item, idx) => {
    const globalIdx = startIdx + idx;
    const card = document.createElement('div');
    card.className = 'scroll-card';
    card.innerHTML = `
      <div class="card-img-wrap">
        <img class="card-img" src="https://via.placeholder.com/400x120?text=Loading..." alt="Loading image">
      </div>
      <div>${item.text}</div>
      <div class="output-meta">${item.author}</div>
      <div class="scroll-actions">
        <button class="action-btn" onclick="saveScrollFavorite(${globalIdx})">❤️ Save</button>
        <button class="action-btn" onclick="shareScrollContent(${globalIdx})">📤 Share</button>
      </div>
    `;
    scrollList.appendChild(card);

    // Fetch a relevant image for this card
    let imgQuery = "education,inspiration";
    if (item.type === "science") imgQuery = "science,technology,space";
    if (item.type === "poem") imgQuery = "poetry,nature";
    try {
      const res = await fetch(`https://api.pexels.com/v1/search?query=${encodeURIComponent(imgQuery)}&per_page=10`, {
        headers: { Authorization: PEXELS_API_KEY }
      });
      const data = await res.json();
      if (data.photos && data.photos.length > 0) {
        const photo = data.photos[Math.floor(Math.random() * data.photos.length)];
        const img = card.querySelector('.card-img');
        img.src = photo.src.landscape;
        img.alt = imgQuery + " image";
      }
    } catch {
      // If image fails, keep placeholder
    }
  });
  window._scrollBatch = scrollBatch;
}

// Infinite horizontal scroll: load more when near right end
document.addEventListener('DOMContentLoaded', () => {
  const scrollList = document.getElementById('scroll-list');
  scrollList.addEventListener('scroll', async function() {
    // Hide scroll hint after user scrolls a bit
    if (scrollList.scrollLeft > 30) {
      document.getElementById('scrollHint').classList.add('hide');
    } else {
      document.getElementById('scrollHint').classList.remove('hide');
    }
    // Infinite scroll
    if (scrollList.scrollLeft + scrollList.clientWidth >= scrollList.scrollWidth - 40) {
      await loadMoreScrollList();
    }
  });
  contentType.addEventListener('change', loadInitialScrollList);
  loadInitialScrollList();
});

// Back to Top Button
const backToTopBtn = document.getElementById('backToTopBtn');
window.addEventListener('scroll', function() {
  if (window.scrollY > 200) {
    backToTopBtn.style.display = 'flex';
  } else {
    backToTopBtn.style.display = 'none';
  }
});
backToTopBtn.onclick = function() {
  window.scrollTo({ top: 0, behavior: 'smooth' });
  document.getElementById('scroll-list').scrollTo({ left: 0, behavior: 'smooth' });
};

function refreshScrollList() {
  loadInitialScrollList();
}

// Save favorite from scroll
function saveScrollFavorite(idx) {
  const batch = window._scrollBatch || [];
  if (!batch[idx]) return;
  const item = {
    text: batch[idx].text,
    author: batch[idx].author,
    timestamp: new Date().toLocaleString(),
    type: contentType.value
  };
  let favorites = JSON.parse(localStorage.getItem('favorites') || '[]');
  favorites.unshift(item);
  localStorage.setItem('favorites', JSON.stringify(favorites));
  showFavorites();
}

// Share from scroll
function shareScrollContent(idx) {
  const batch = window._scrollBatch || [];
  if (!batch[idx]) return;
  const text = batch[idx].text;
  const authorText = batch[idx].author;
  const shareUrl = window.location.origin + window.location.pathname;
  const shareMessage = `${text}\n${authorText}\n\nRead more at: ${shareUrl}`;

  if (navigator.share) {
    navigator.share({
      title: 'Learn & Inspire',
      text: `${text}\n${authorText}`,
      url: shareUrl
    }).catch(() => {
      openSocialShare(shareMessage, shareUrl);
    });
  } else {
    openSocialShare(shareMessage, shareUrl);
  }
}

// Delete favorite
function deleteFavorite(index) {
  let favorites = JSON.parse(localStorage.getItem('favorites') || '[]');
  favorites.splice(index, 1);
  localStorage.setItem('favorites', JSON.stringify(favorites));
  showFavorites();
}

// Show favorites
function showFavorites() {
  const container = document.getElementById('favorites');
  const searchTerm = searchInput.value.toLowerCase();
  let favorites = JSON.parse(localStorage.getItem('favorites') || '[]');
  if (searchTerm) {
    favorites = favorites.filter(f =>
      f.text.toLowerCase().includes(searchTerm) || f.author.toLowerCase().includes(searchTerm)
    );
  }
  if (favorites.length === 0) {
    container.innerHTML = `<div class="empty-favs"><em>No favorites saved.</em></div>`;
    return;
  }
  container.innerHTML = "<h3>⭐ Saved Favorites</h3>" +
    favorites.map((fav, index) => `
      <div class="favorite-card">
        <button class="delete-btn" onclick="deleteFavorite(${index})" title="Delete">🗑️</button>
        <div>${fav.text}</div>
        <div class="fav-meta">${fav.author}
          <span class="fav-type">| ${fav.type}</span>
        </div>
        <div class="fav-meta">📅 ${fav.timestamp}</div>
      </div>
    `).join("");
}

// Dark mode toggle
function toggleDarkMode() {
  document.body.classList.toggle('dark-mode');
}

// Social share fallback: Twitter, Facebook, WhatsApp
function openSocialShare(message, url) {
  const encodedMsg = encodeURIComponent(message);
  const encodedUrl = encodeURIComponent(url);

  // Simple popup with options
  const popup = window.open('', '', 'width=420,height=320');
  popup.document.write(`
    <div style="font-family:sans-serif;padding:1.2em;">
      <h3>Share on:</h3>
      <a href="https://twitter.com/intent/tweet?text=${encodedMsg}" target="_blank" style="display:block;margin-bottom:1em;">🐦 Twitter</a>
      <a href="https://www.facebook.com/sharer/sharer.php?u=${encodedUrl}" target="_blank" style="display:block;margin-bottom:1em;">📘 Facebook</a>
      <a href="https://wa.me/?text=${encodedMsg}" target="_blank" style="display:block;margin-bottom:1em;">💬 WhatsApp</a>
      <button onclick="window.close()" style="margin-top:1em;padding:0.5em 1em;">Close</button>
    </div>
  `);
}

// Make functions global for inline onclick
window.saveScrollFavorite = saveScrollFavorite;
window.shareScrollContent = shareScrollContent;
window.deleteFavorite = deleteFavorite;
window.showFavorites = showFavorites;
window.toggleDarkMode = toggleDarkMode;
window.refreshScrollList = refreshScrollList;