<!DOCTYPE html>
<html lang="en">
  {% load static %}

  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>TAYAPROMEDIVERSE Dashboard</title>
    <link rel="stylesheet" href="{% static 'css/dashboard.css' %}" />
    <link
      href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600&display=swap"
      rel="stylesheet"
    />

    <!-- Toastify CSS -->
    <link
      rel="stylesheet"
      type="text/css"
      href="https://cdn.jsdelivr.net/npm/toastify-js/src/toastify.min.css"
    />
  </head>

  <body>
    <!-- Card Modal Overlay -->
    <div class="card-modal-overlay" id="cardModalOverlay">
      <div class="card-modal" id="cardModal">
        <button class="card-modal-close" id="cardModalClose">&times;</button>
        <div id="cardModalContent"></div>
      </div>
    </div>

    <!-- Mobile Menu Overlay -->
    <div class="mobile-menu-overlay" id="mobileMenuOverlay"></div>

    <!-- Mobile Menu -->
    <div class="mobile-menu" id="mobileMenu">
      <div class="mobile-menu-header">TAYAPROMEDIVERSE</div>
      <div class="mobile-menu-items">
        <div class="mobile-menu-item active">
          <div class="mobile-menu-item-icon">🏠</div>
          <span>Home</span>
        </div>
        <div class="mobile-menu-item">
          <div class="mobile-menu-item-icon">⚙️</div>
          <span>Settings</span>
        </div>
        <div class="mobile-menu-item">
          <div class="mobile-menu-item-icon">💳</div>
          <span>Subscription</span>
        </div>
      </div>
    </div>

    <div class="sidebar">
      <div class="sidebar-top">
        <div class="logo">TAYAPROMEDIVERSE</div>

        <div class="nav-item home active">
          <div class="nav-icon"></div>
          <span>Home</span>
        </div>

        <div
          class="settings-item"
          id="settingsNav"
          onclick="handleSettings()"
          style="cursor: pointer"
        >
          <div class="settings-icon"></div>
          <span>Setting</span>
        </div>

        <div
          class="nav-item subscription"
          id="subscriptionNav"
          onclick="handleSubscription()"
          style="cursor: pointer; margin-top: 10px"
        >
          <div class="nav-icon">💳</div>
          <span>Subscription</span>
        </div>
      </div>

      <!-- Support Card -->
      <div class="support-card">
        <div class="support-icon"></div>
        <div class="support-title">Support</div>
        <div class="support-description">
          Having trouble with TAYAPROMEDIVERSE? Please contact us for more
          questions.
        </div>

        <div class="contact-frame">
          <div class="contact-label">Cell:</div>
          <div class="contact-value-phone">8553728266</div>
        </div>

        <div class="contact-frame">
          <div class="contact-label">Mail:</div>
          <div class="contact-value-email">tayaprolibrary@gmail.com</div>
        </div>
      </div>
    </div>

    <div class="main-content">
      <!-- Desktop Header -->
      <div class="header">
        <div class="page-title" id="pageTitle">Home</div>

        <div class="auth-buttons">
          {% if user %}
          <div class="user-account">
            <div class="user-avatar" id="headerAvatar">
              {{ user.first_name|first|upper }}{{ user.last_name|first|upper }}
            </div>
            <div class="user-info">
              <div class="user-name" id="headerUserName">
                {{ user.first_name }} {{ user.last_name }}
              </div>
            </div>
            <a href="{% url 'logout' %}" class="logout-link">Logout</a>
          </div>
          {% else %}
          <button class="login-btn" onclick="handleLogin()">Login</button>
          <button class="signup-btn" onclick="handleSignup()">Sign Up</button>
          {% endif %}
        </div>
      </div>

      <!-- Mobile Header -->
      <div class="mobile-header">
        <div class="mobile-logo">TAYAPROMEDIVERSE</div>
        <div class="hamburger-menu" id="hamburgerMenu">
          <div class="hamburger-line"></div>
          <div class="hamburger-line"></div>
          <div class="hamburger-line"></div>
        </div>
      </div>

      <div class="dashboard-content" id="dashboardContent">
        <div class="content-rectangle">
          <div class="search-filter-bar">
            <div class="search-container">
              <input
                type="text"
                class="search-input"
                placeholder="Search card..."
              />
              <div class="search-icon">🔍</div>
            </div>
            <div class="filter-container">
              <button class="filter-button">
                <span>Filter</span>
                <span>▼</span>
              </button>
            </div>
          </div>

          <!-- ✅ Dynamic Dashboard Items -->
          <div class="grid-container">
            {% for item in dashboard_items %}
            <div class="card" data-title="{{ item.title }}" data-link="{{ item.link }}">
               {% if item.has_video %}
               <div class="card-media-container video-container">
                 <!-- Thumbnail image shown by default -->
                 <img
                   class="card-image video-thumbnail"
                   src="{% if item.image %}{{ item.image }}{% else %}{% static 'images/bigdeal.png' %}{% endif %}"
                   alt="{{ item.title }}"
                 />
                 <!-- Video element (initially hidden) -->
                 <video 
                   class="card-video" 
                   preload="metadata"
                   muted
                   loop
                 >
                   {% if item.video %}
                   <source src="{{ item.video }}" type="video/mp4">
                   {% elif item.video_url %}
                   <source src="{{ item.video_url }}" type="video/mp4">
                   {% endif %}
                   Your browser does not support the video tag.
                 </video>
                 <!-- Video play indicator -->
                 <div class="video-play-indicator">
                   <span>▶</span>
                 </div>
               </div>
              {% else %}
              <div class="card-media-container">
                <img
                  class="card-image"
                  src="{{ item.image }}"
                  alt="{{ item.title }}"
                />
              </div>
              {% endif %}
              <div class="card-content">
                <div class="card-title">{{ item.title }}</div>
                <button
                  class="view-details-btn"
                  onclick="viewDetails('{{ item.title }}', '{{ item.link }}'); event.stopPropagation();"
                >
                  View Details
                </button>
              </div>
            </div>
            {% empty %}
            <p>No items available.</p>
            {% endfor %}
          </div>
        </div>
      </div>
    </div>

    <script>
      function handleLogin() {
        window.location.href = "{% url 'signin' %}";
      }

      function handleSignup() {
        window.location.href = "{% url 'signup' %}";
      }

      function handleSettings() {
        // Check if user is logged in
        {% if user %}
          // User is logged in, proceed to settings
          window.location.href = "{% url 'settings' %}";
        {% else %}
          // User is not logged in, show notification
          if (window.ToastifyUtils) {
            window.ToastifyUtils.warning("Please login to access settings. Click the Login button to proceed.");
          } else {
            alert("Please login to access settings.");
          }
        {% endif %}
      }

      function handleSubscription() {
        // Check if user is logged in
        {% if user %}
          // User is logged in, proceed to subscription
          window.location.href = "{% url 'subscription' %}";
        {% else %}
          // User is not logged in, show notification
          if (window.ToastifyUtils) {
            window.ToastifyUtils.warning("Please login to access subscription. Click the Login button to proceed.");
          } else {
            alert("Please login to access subscription.");
          }
        {% endif %}
      }

      function viewDetails(title, link) {
        // Check if user is logged in
        {% if user %}
          // User is logged in, check for active subscription
          {% if has_active_subscription %}
            // User has active subscription, allow access
            if (link) {
              window.open(link, '_blank');
            } else {
              alert(`No link available for: ${title}`);
            }
          {% else %}
            // User is logged in but no active subscription
            if (window.ToastifyUtils) {
              window.ToastifyUtils.warning("Please subscribe to access this content. Click the Subscription button to choose a plan.");
            } else {
              alert("Please subscribe to access this content.");
            }
            // Optionally redirect to subscription page after a short delay
            setTimeout(function() {
              window.location.href = "{% url 'subscription' %}";
            }, 2000);
          {% endif %}
        {% else %}
          // User is not logged in, show notification
          if (window.ToastifyUtils) {
            window.ToastifyUtils.warning("Please login to view details. Click the Login button to proceed.");
          } else {
            alert("Please login to view details.");
          }
        {% endif %}
      }

      // Mobile menu functionality
      const hamburgerMenu = document.getElementById("hamburgerMenu");
      const mobileMenu = document.getElementById("mobileMenu");
      const mobileMenuOverlay = document.getElementById("mobileMenuOverlay");

      function toggleMobileMenu() {
        mobileMenu.classList.toggle("active");
        mobileMenuOverlay.style.display = mobileMenu.classList.contains(
          "active"
        )
          ? "block"
          : "none";
      }

      if (hamburgerMenu) {
        hamburgerMenu.addEventListener("click", toggleMobileMenu);
      }

      if (mobileMenuOverlay) {
        mobileMenuOverlay.addEventListener("click", toggleMobileMenu);
      }

      // Mobile menu item clicks
      document.querySelectorAll(".mobile-menu-item").forEach((item) => {
        item.addEventListener("click", function () {
          const menuText = this.querySelector("span").textContent;
          if (menuText === "Home") {
            // Already on home page
            toggleMobileMenu();
          } else if (menuText === "Settings") {
            handleSettings();
            toggleMobileMenu();
          } else if (menuText === "Subscription") {
            handleSubscription();
            toggleMobileMenu();
          }
        });
      });

      // Navigation functionality
      document
        .querySelector(".nav-item.home")
        .addEventListener("click", function () {
          // Already on home page, do nothing
        });

       // Search filtering
       document.addEventListener("DOMContentLoaded", () => {
         const searchInput = document.querySelector(".search-input");
         const cards = document.querySelectorAll(".card");

         searchInput.addEventListener("input", (e) => {
           const term = e.target.value.toLowerCase();
           cards.forEach((card) => {
             const title = card
               .querySelector(".card-title")
               .textContent.toLowerCase();
             card.style.display = title.includes(term) ? "block" : "none";
           });
         });

         // Card Modal Popup Functionality
         const cardModalOverlay = document.getElementById('cardModalOverlay');
         const cardModal = document.getElementById('cardModal');
         const cardModalContent = document.getElementById('cardModalContent');
         const cardModalClose = document.getElementById('cardModalClose');

         // Function to show modal with card content
         function showCardModal(cardElement) {
           // Clone the card content
           const cardClone = cardElement.cloneNode(true);
           
           // Clear previous content
           cardModalContent.innerHTML = '';
           cardModalContent.appendChild(cardClone);
           
           // Re-initialize video functionality for the cloned card
           const videoContainer = cardClone.querySelector('.video-container');
           if (videoContainer) {
             const video = videoContainer.querySelector('video');
             
             if (video) {
               // Enable video controls in modal
               video.setAttribute('controls', 'controls');
               video.removeAttribute('muted');
               video.preload = "auto";
               
               // Set volume to a reasonable level
               video.volume = 0.7;
               
               // Optional: Auto-play when modal opens (can be removed if not desired)
               if (video.readyState >= 2) {
                 video.play().catch(err => {
                   // Auto-play might be blocked by browser, that's okay
                   console.log('Auto-play prevented:', err);
                 });
               } else {
                 video.addEventListener('loadeddata', () => {
                   video.play().catch(err => {
                     console.log('Auto-play prevented:', err);
                   });
                 }, { once: true });
               }
             }
           }
           
           // Show the modal
           cardModalOverlay.classList.add('active');
           document.body.style.overflow = 'hidden'; // Prevent background scrolling
         }

         // Function to hide modal
         function hideCardModal() {
           cardModalOverlay.classList.remove('active');
           document.body.style.overflow = ''; // Restore scrolling
           cardModalContent.innerHTML = '';
         }

         // Add click event to all cards
         cards.forEach((card) => {
           card.addEventListener('click', function(e) {
             // Don't open modal if clicking on the View Details button
             if (e.target.classList.contains('view-details-btn')) {
               return;
             }
             showCardModal(this);
           });
         });

         // Close modal when clicking outside the card
         cardModalOverlay.addEventListener('click', function(e) {
           if (e.target === cardModalOverlay) {
             hideCardModal();
           }
         });

         // Close modal when clicking close button
         cardModalClose.addEventListener('click', function(e) {
           e.stopPropagation();
           hideCardModal();
         });

         // Prevent modal from closing when clicking on the card itself
         cardModal.addEventListener('click', function(e) {
           e.stopPropagation();
         });

         // Close modal with Escape key
         document.addEventListener('keydown', function(e) {
           if (e.key === 'Escape' && cardModalOverlay.classList.contains('active')) {
             hideCardModal();
           }
         });
         
         // Handle video hover and touch functionality
         const videoContainers = document.querySelectorAll('.video-container');
         
         // Detect if device has hover capability
         const hasHoverSupport = window.matchMedia('(hover: hover)').matches;
         
         videoContainers.forEach(container => {
           const video = container.querySelector('video');
           const playIndicator = container.querySelector('.video-play-indicator');
           let isPlaying = false;
           
           // Function to play video
           const playVideo = () => {
             if (video.readyState >= 2) { // Check if video is loaded enough to play
               video.play();
               isPlaying = true;
               container.classList.add('playing');
             } else {
               // If video is not loaded yet, set up an event listener
               video.addEventListener('loadeddata', () => {
                 video.play();
                 isPlaying = true;
                 container.classList.add('playing');
               }, { once: true });
             }
           };
           
           // Function to pause video
           const pauseVideo = () => {
             video.pause();
             isPlaying = false;
             container.classList.remove('playing');
             // Reset video to beginning
             video.currentTime = 0;
           };
           
           if (hasHoverSupport) {
             // Desktop hover behavior
             container.addEventListener('mouseenter', playVideo);
             container.addEventListener('mouseleave', pauseVideo);
           } else {
             // Touch device behavior - toggle on tap
             playIndicator.addEventListener('click', (e) => {
               e.stopPropagation(); // Prevent card click event
               if (isPlaying) {
                 pauseVideo();
               } else {
                 playVideo();
               }
             });
             
             // Stop video when clicking elsewhere
             document.addEventListener('click', (e) => {
               if (isPlaying && !container.contains(e.target)) {
                 pauseVideo();
               }
             });
           }
           
           // Preload video
           video.preload = "auto";
         });
       });
    </script>

    <!-- Toastify JS -->
    <script
      type="text/javascript"
      src="https://cdn.jsdelivr.net/npm/toastify-js"
    ></script>

    <!-- Toastify Utils -->
    <script src="{% static 'js/toastify-utils.js' %}"></script>

    <!-- Django Messages with Toastify -->
    {% if messages %}
    <div id="django-messages" style="display: none">
      {% for message in messages %}
      <div
        data-type="{{ message.tags }}"
        data-message="{{ message|escapejs }}"
      ></div>
      {% endfor %}
    </div>
    {% endif %}
  </body>
</html>
