<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Norskly - Home</title>
    <style>
        body {
            display: flex;
            flex-direction: column; /* Stack content vertically */
            min-height: 100vh; /* Ensure the page takes the full height of the viewport */
            margin: 0;
            font-family: Arial, sans-serif;
            background-color: rgb(253, 253, 253); 
            padding: 0;
            display: flex;
            flex-direction: column;
            align-items: center;
            height: 100vh;
        } 
        
        #loading-container {
    min-height: calc(100vh - 150px);
    display: flex;
    align-items: center;
    justify-content: center;
}

.card.read {
    background-color:rgb(202, 234, 255); /* Light green for read files */
}

#content-wrapper {
    position: relative; /* Position relative for arrows */
    flex: 1; /* Allow this container to grow and push the footer down */
    display: flex;
    justify-content: center; /* Center cards horizontally */
    align-items: stretch; /* Prevent height alignment issues */
    width: 100%; 
    margin: 0 auto; /* Center the wrapper */
    background-color: rgb(255, 255, 255); 
}

.card.locked {
    position: relative;
}
.card.locked:hover {
    cursor: pointer;
}

.lock-icon {
  font-size: 20px;      /* or whatever size you prefer */
  color: #333;          /* adjust color */
  vertical-align: middle;
}

.darken-image {
    filter: brightness(50%); /* Darkens the image */
    transition: filter 0.3s ease; /* Smooth transition for hover effects */
}







@media (max-width: 1572px) {
    #content-wrapper {
        max-width: 1400px; /* Reduce the width */
    }
    #content {
        grid-template-columns: repeat(3, 300px) !important; /* Fixed column width */

    }
    .arrow-left,
    .arrow-right {
        top: 49% !important; /* Vertically center the arrows relative to the container */
}
}

@media (max-width: 1250px) {
    #content-wrapper {
        max-width: 100%; /* Allow full width for small devices */
        padding: 0 10px; /* Add some padding for spacing 
        */
    }
    #content {
        grid-template-columns: repeat(2, 300px) !important; /* Fixed column width */

    }
    .arrow-left,
    .arrow-right {
        top: 47.28% !important; /* Vertically center the arrows relative to the container */
    }
}

/* Media query: Further reduce width for very small screens */
@media (max-width: 800px) {
    #content-wrapper {
        max-width: 100.5%; /* Allow full width for small devices */
        padding: 0 10px; /* Add some padding for spacing 
        */
    }
    #content {
        grid-template-columns: repeat(1, 300px) !important; /* Fixed column width */

    }
    .arrow-left,
    .arrow-right {
        top: 101% !important; /* Vertically center the arrows relative to the container */
    }
}

.arrow-left,
.arrow-right {
    position: absolute;
    top: 50%; /* Vertically center the arrows relative to the container */
    transform: translateY(-50%);
    font-size: 3.5rem; /* Adjust the size of the icons */
    color: #333; /* Icon color */
    cursor: pointer;
    z-index: 10; /* Ensure icons appear above the content */
    color:rgb(125, 203, 255); /* Set the custom color (e.g., blue) */
    transition: color 0.3s; /* Smooth color transition */
}

.arrow-left {
    left: 100px; /* Position on the left side */
}

.arrow-right {
    right: 100px; /* Position on the right side */
}

.arrow-left:hover,
.arrow-right:hover {
    color:rgb(0, 153, 255); /* Hover color */
}



#content {
    flex: 1; /* Makes the content area grow and push the footer down */
    display: grid;
    grid-template-columns: repeat(4, 300px); /* Fixed column width */
    grid-template-rows: repeat(3, 300px); 
    grid-auto-rows: 0; /* Prevent additional implicit rows */
    gap: 20px; /* Consistent spacing between cards */
    justify-content: center; /* Center the grid in the container */
    padding: 50px;
    box-sizing: border-box;
    width: 100%; /* Ensure the grid stretches across the container */
    max-width: 1200px; /* Optional: Limit the grid's width */
    margin: 0 auto;
}

.card.hidden {
    display: none; /* Hide extra cards dynamically */
}


.card {
    width: 300px; /* Fixed card width */
    height: 300px; /* Fixed card height */
    border-radius: 12px;
    overflow: hidden;
    box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
    cursor: pointer;
    display: flex;
    flex-direction: column;
    justify-content: flex-end;
    position: relative;
    text-decoration: none;
    background-color: white;
    opacity: 0;
    transition: opacity 0.3s ease;
}

.card.fade-in {
    opacity: 1;
}

.card:hover {
    transform: translateY(-1px);
    box-shadow: 0 8px 10px rgba(0, 0, 0, 0.07);
}

.card img {
    width: 100%;
    height: calc(100% - 30px);
    object-fit: cover;
    display: block;
}

.card-text {
    text-align: left; /* Aligns text to the left */
    padding: 10px; /* Adds spacing inside the text container */
    padding-top: 20px;
    padding-bottom: 20px; 
}

.card-title {
    padding: 10px;
    display: flex; 
    align-items: center; /* Vertically centers the text */
    justify-content: flex-start; /* Aligns text to the left */
    height: 15px; 
    margin-top: 0px;
    margin-bottom: 4px;
    font-size: 22px;
    font-weight: bold;
    color: rgb(65, 65, 65);
    background-color: rgba(255, 255, 255, 0); /* For testing purposes */
}
    
.card-level {
    font-size: 14px;
    font-weight: bold;
    margin-left: 8px;
    margin-top: 5px;
    padding: 1px 8px;
    color: white;
    border-radius: 100px;
    display: inline-flex;
    height: 20px;
    justify-content: center;
    align-items: center;
    
}

footer {
    text-align: center;
    padding: 10px;
    background-color: #333;
    color: white;
    width: 100%;
    position: relative; /* Keep footer in the flow of the document */
    margin-top: 200px; /* Add some space between content and footer */
}

    </style>
</head>
<body>
<div id="content-wrapper">
        <!-- Left Arrow -->
        <div class="arrow-left">
            <i class="fa-solid fa-circle-chevron-left"></i>
        </div>

        
        <!-- Card Content -->
        <div id="content">
            <!-- Cards will be dynamically added here -->
        </div>

        <!-- Right Arrow -->
        <div class="arrow-right">
            <i class="fa-solid fa-circle-chevron-right"></i>
        </div>
    </div>

    <?php
// PHP script to list JSON files in the /texts directory
$directory = '/var/www/html/texts';
$files = array_values(array_filter(scandir($directory), function($file) use ($directory) {
    return is_file("$directory/$file") && pathinfo($file, PATHINFO_EXTENSION) === 'json';
}));
?>

<script>
    // 1) Expose readFiles from PHP so we can highlight them
    const readFiles = <?php echo json_encode($readFiles); ?>;

    let currentPage = 1;
    let cardsPerPage = 12; 
    let totalFiles = 0;
    let currentFilter = null; 
    let currentBreakpoint = null;

    // -- ADDED: a helper to update the URL
    function updateURL(page, difficulty) {
      // Create a new URL object from current location
      const newURL = new URL(window.location);

      // Set or update the 'page' parameter
      newURL.searchParams.set('page', page);

      // If you want to keep track of difficulty, set that param, otherwise remove it
      if (difficulty) {
        newURL.searchParams.set('difficulty', difficulty);
      } else {
        newURL.searchParams.delete('difficulty');
      }

      // Push the new state into the browser's history
      window.history.pushState({ page, difficulty }, '', newURL);
    }

    // -- ADDED: handle back/forward button clicks
    window.onpopstate = function(event) {
      if (event.state) {
        // event.state has {page, difficulty} if we pushState with them
        currentPage = event.state.page || 1;
        currentFilter = event.state.difficulty || null;
      } else {
        // fallback if no state, read from URL again
        const urlParams = new URLSearchParams(window.location.search);
        currentPage = parseInt(urlParams.get('page') || '1', 10);
        currentFilter = urlParams.get('difficulty') || null;
      }
      // Actually load that page
      loadPage(currentPage, currentFilter);
    };

    // 2) Adjust cardsPerPage based on screen size
    function updateCardsPerPage() {
      const screenWidth = window.innerWidth;
      if (screenWidth <= 800) {
          cardsPerPage = 3;
      } else if (screenWidth <= 1250) {
          cardsPerPage = 6;
      } else if (screenWidth <= 1572) {
          cardsPerPage = 9;
      } else {
          cardsPerPage = 12;
      }
    }

    // 3) Determine current breakpoint
    function getBreakpoint() {
      const w = window.innerWidth;
      if (w <= 800) return 800;
      if (w <= 1250) return 1250;
      if (w <= 1572) return 1572;
      return Infinity;
    }

    // 4) Debounce
    function debounce(func, delay) {
      let timeout;
      return function(...args) {
        clearTimeout(timeout);
        timeout = setTimeout(() => func.apply(this, args), delay);
      };
    }

    // 5) Handle resize
    function handleResize() {
      const newBP = getBreakpoint();
      if (newBP !== currentBreakpoint) {
        currentBreakpoint = newBP;
        updateCardsPerPage();
        loadPage(currentPage, currentFilter);
      }
    }
    window.addEventListener('resize', debounce(handleResize, 100));

    // 6) Fetch from texts_api
    async function fetchTexts(page, limit, difficulty = null, hideRead = false) {
      let url = `/texts_api.php?page=${page}&limit=${limit}`;
      if (difficulty) {
        url += `&difficulty=${encodeURIComponent(difficulty)}`;
      }
      if (hideRead) {
        url += `&hide_read=1`;
      }

      const res = await fetch(url);
      if (!res.ok) {
        throw new Error("Failed to fetch texts.");
      }
      const result = await res.json(); 
      totalFiles = result.total; 
      return result.data; 
    }

    // 7) Load page
    async function loadPage(page, difficulty = null) {
      const contentDiv = document.getElementById('content');
      contentDiv.innerHTML = '';

      // Check if "Hide read" is toggled
      const toggleEl = document.querySelector('.toggle-switch input[type="checkbox"]');
      const isHideRead = localStorage.getItem('hideReadToggle') === 'true';

      try {
        const data = await fetchTexts(page, cardsPerPage, difficulty, isHideRead);

        if (!data || data.length === 0) {
          contentDiv.innerHTML = '<p>No more texts to display.</p>';
          updateArrowVisibility();
          return;
        }

        // Create & append the card for each item
        data.forEach(item => {
          const card = createCard(item);
          contentDiv.appendChild(card);
        });

        updateArrowVisibility();
      } catch (error) {
        console.error(error);
        contentDiv.innerHTML = '<p style="color: red;">Failed to load texts. Please try again later.</p>';
      }
    }

    // 8) Update arrow visibility
    function updateArrowVisibility() {
      const leftArrow  = document.querySelector('.arrow-left');
      const rightArrow = document.querySelector('.arrow-right');

      const totalPages = Math.ceil(totalFiles / cardsPerPage);

      leftArrow.style.display  = (currentPage > 1) ? 'block' : 'none';
      rightArrow.style.display = (currentPage < totalPages) ? 'block' : 'none';
    }

    // 9) Arrows
    document.querySelector('.arrow-left').addEventListener('click', () => {
      if (currentPage > 1) {
        currentPage--;
        loadPage(currentPage, currentFilter);
        updateURL(currentPage, currentFilter); // <-- ADDED
      }
    });
    document.querySelector('.arrow-right').addEventListener('click', () => {
      if (currentPage * cardsPerPage < totalFiles) {
        currentPage++;
        loadPage(currentPage, currentFilter);
        updateURL(currentPage, currentFilter); // <-- ADDED
      }
    });

    // 10) Create a card
    function createCard(data) {
  // 1) Create the main card element
  const card = document.createElement('div');
  card.className = 'card';
  card.style.position = 'relative'; // For absolute positioning of the lock icon

  // 2) Check if user has read this file
  const normalizedFile = normalizeFilename(`${data.title.replace(/\s+/g, '_')}.json`);
  if (readFiles.some(r => normalizeFilename(r) === normalizedFile)) {
    card.classList.add('read');
  }

  // 3) Handle locked vs unlocked
  const locked = !!data.locked;
  if (locked) {
    card.classList.add('locked');
    card.onclick = () => {
      alert("This text is locked. Upgrade to premium to unlock!");
    };
  } else {
    card.onclick = () => {
      const fileName = `${data.title.replace(/\s+/g, '_')}.json`;
      window.location.href = `learn.php?file=${encodeURIComponent(fileName)}`;
    };
  }

  // 4) Create and append the image
  const img = document.createElement('img');
  img.src = `/text_images/${encodeURIComponent(data.image)}`;
  img.alt = data.title;
  if (locked) {
    setTimeout(() => {
        img.classList.add('darken-image'); // Dynamically add after card is added to DOM
    }, 50);
}

  card.appendChild(img);

  // 5) If locked, add a centered white lock icon
  if (locked) {
    const lockIcon = document.createElement('i');
    lockIcon.className = 'fa-solid fa-lock';
    lockIcon.style.position = 'absolute';
    lockIcon.style.top = '36%';
    lockIcon.style.left = '50%';
    lockIcon.style.transform = 'translate(-50%, -50%)';
    lockIcon.style.fontSize = '38px';   // Adjust to preferred size
    lockIcon.style.color = '#fff';      // White color
    lockIcon.style.zIndex = '5';        // Ensure it displays above the image
    card.appendChild(lockIcon);
  }

  // 6) Create the text container (title + level)
  const textDiv = document.createElement('div');
  textDiv.className = 'card-text';

  // Title
  const title = document.createElement('div');
  title.className = 'card-title';
  title.textContent = data.title;
  textDiv.appendChild(title);

  // Level
  const level = document.createElement('div');
  level.className = 'card-level';
  level.textContent = `Level ${data.difficulty.replace('L', '')}`;
  level.style.backgroundColor = getLevelColor(data.difficulty);
  textDiv.appendChild(level);

  card.appendChild(textDiv);

  // 7) Fade-in animation
  setTimeout(() => {
    card.classList.add('fade-in');
  }, 50);

  return card;
}





    // 11) Helper: normalize filename
    function normalizeFilename(str) {
      return str.trim().toLowerCase().normalize("NFC");
    }

    // 12) Difficulty color
    function getLevelColor(diff) {
      switch (diff) {
        case 'L1': return 'rgb(109,180,255)';
        case 'L2': return 'rgb(81,255,75)';
        case 'L3': return 'rgb(174,255,44)';
        case 'L4': return 'rgb(255,95,234)';
        case 'L5': return 'rgb(141,68,0)';
        default:   return 'gray';
      }
    }

    // 13) "Hide read" toggle
    document.querySelector('.toggle-switch input[type="checkbox"]')
      .addEventListener('change', function() {
        localStorage.setItem('hideReadToggle', this.checked);
        currentPage = 1;
        loadPage(currentPage, currentFilter);
        updateURL(currentPage, currentFilter); // <-- ADDED (optional if you want ?page=1 when toggling
      });

    // 14) Optional: load difficulty
    function loadTexts(difficulty) {
      currentFilter = difficulty;
      currentPage = 1;
      loadPage(currentPage, difficulty);
      updateURL(currentPage, difficulty); // <-- ADDED
    }
    function loadAllTexts() {
      currentFilter = null;
      currentPage = 1;
      loadPage(currentPage, null);
      updateURL(currentPage, null); // <-- ADDED
    }

    // 15) Onload
    window.onload = () => {
      currentBreakpoint = getBreakpoint();
      updateCardsPerPage();

      // <-- ADDED: read ?page= from URL on load
      const urlParams = new URLSearchParams(window.location.search);
      const pageParam = parseInt(urlParams.get('page') || '1', 10);
      currentPage = isNaN(pageParam) ? 1 : pageParam;

      // If you want to also read ?difficulty= from URL
      const diffParam = urlParams.get('difficulty');
      currentFilter = diffParam || null;

      // Restore hide toggle
      const savedToggle = localStorage.getItem('hideReadToggle') === 'true';
      const toggleEl = document.querySelector('.toggle-switch input[type="checkbox"]');
      if (toggleEl) {
        toggleEl.checked = savedToggle;
      }

      loadPage(currentPage, currentFilter);
    };
</script>



   <?php include 'includes/footer.php'; ?>
</body>
</html>

