// Navigation Handler
function initNavigation() {
  var navToggle = document.querySelector('.nav-toggle');
  var navWrap = document.querySelector('.nav-wrap');
  
  if (navToggle && navWrap) {
    navToggle.addEventListener('click', function() {
      navWrap.classList.toggle('expanded');
      navToggle.classList.toggle('active');
      var isExpanded = navWrap.classList.contains('expanded');
      navToggle.setAttribute('aria-expanded', isExpanded);
    });
  }
}

// Load site settings from localStorage
function getSiteSettings() {
  return JSON.parse(localStorage.getItem('huemanSiteSettings')) || {
    logo: '',
    siteName: 'Hueman',
    siteDescription: 'Platform Berbagi Pemikiran',
    profilePhoto: '',
    headerImage: '',
    headerBanner: '',
    headerColor1: '#667eea',
    headerColor2: '#764ba2',
    fontFamily: 'Inter, sans-serif',
    textColor: '#333333',
    fontSize: 16,
    headingSize: 24
  };
}

// Apply site settings to the page
function applySiteSettings() {
  const settings = getSiteSettings();
  
  // Update header background (image or gradient)
  const header = document.getElementById('header');
  if (header) {
    if (settings.headerImage) {
      header.style.background = `url('${settings.headerImage}') center/cover no-repeat`;
      header.style.position = 'relative';
    } else {
      header.style.background = `linear-gradient(135deg, ${settings.headerColor1} 0%, ${settings.headerColor2} 100%)`;
    }
  }
  
  // Update site name
  const siteTitle = document.querySelector('.site-title a');
  if (siteTitle && settings.siteName) {
    siteTitle.textContent = settings.siteName;
  }
  
  // Update site description
  const siteDescription = document.querySelector('.site-description');
  if (siteDescription && settings.siteDescription) {
    siteDescription.textContent = settings.siteDescription;
  }
  
  // Update logo if provided
  if (settings.logo) {
    const logoPlaceholder = document.querySelector('.logo-placeholder');
    if (logoPlaceholder) {
      logoPlaceholder.innerHTML = `<img src="${settings.logo}" alt="Logo" style="width: 100%; height: 100%; object-fit: contain;">`;
    }
  }
  
  // Update profile photo if provided
  if (settings.profilePhoto) {
    const profilePhoto = document.querySelector('.profile-photo img');
    if (profilePhoto) {
      profilePhoto.src = settings.profilePhoto;
    }
  }
  
  // Apply typography settings
  document.body.style.fontFamily = settings.fontFamily || 'Inter, sans-serif';
  document.body.style.color = settings.textColor || '#333333';
  document.body.style.fontSize = (settings.fontSize || 16) + 'px';
  
  // Update heading sizes
  const headings = document.querySelectorAll('h1, h2, h3, h4, h5, h6');
  headings.forEach(h => {
    h.style.fontSize = (settings.headingSize || 24) + 'px';
  });
  
  // Apply header banner image
  if (settings.headerBanner) {
    const headerBanner = document.getElementById('header-banner');
    const headerBannerImg = document.getElementById('header-banner-img');
    if (headerBanner && headerBannerImg) {
      headerBannerImg.src = settings.headerBanner;
      headerBanner.style.display = 'block';
    }
  }
}

// Load data from localStorage
function getData() {
  return JSON.parse(localStorage.getItem('huemanData')) || { 
    aktivitas: [], 
    artikel: [], 
    diskusi: [], 
    galeri: [] 
  };
}

// Save changes function
function saveChanges() {
  const data = getData();
  localStorage.setItem('huemanData', JSON.stringify(data));
  
  // Show save confirmation
  const saveBtn = document.querySelector('button[onclick="saveChanges()"]');
  const originalText = saveBtn.innerHTML;
  saveBtn.innerHTML = '<i class="fas fa-check"></i> Tersimpan!';
  saveBtn.style.background = '#4CAF50';
  saveBtn.style.color = 'white';
  
  setTimeout(() => {
    saveBtn.innerHTML = originalText;
    saveBtn.style.background = 'white';
    saveBtn.style.color = '#667eea';
  }, 2000);
}

// Render content from admin dashboard
function renderContent() {
  const data = getData();
  
  // Render featured posts (from artikel)
  const featuredSection = document.querySelector('.featured .group');
  if (featuredSection && data.artikel.length > 0) {
    const featuredPost = data.artikel[0];
    featuredSection.innerHTML = `
      <article class="post">
        <div class="post-inner">
          <div class="post-thumbnail">
            <div style="width:100%; height:200px; background:#16cfc1; display:flex; align-items:center; justify-content:center; color:white; font-size:24px;">${featuredPost.title.substring(0, 20)}</div>
          </div>
          <div class="post-header">
            <h2 class="post-title"><a href="#">${featuredPost.title}</a></h2>
            <div class="post-meta">
              <span class="post-date">${featuredPost.date}</span>
              <span class="post-author">By ${featuredPost.author}</span>
            </div>
          </div>
          <div class="post-content">
            <p>${featuredPost.content}</p>
          </div>
        </div>
      </article>
    `;
  }
  
  // Render recent posts widget
  const recentPostsWidget = document.querySelectorAll('.widget')[2];
  if (recentPostsWidget && data.artikel.length > 0) {
    const recentPostsUl = recentPostsWidget.querySelector('ul');
    recentPostsUl.innerHTML = data.artikel.slice(0, 3).map(post => `<li><a href="#">${post.title}</a></li>`).join('');
  }
}

// Render aktivitas content with video and photo support
function renderAktivitas() {
  const data = getData();
  const listContainer = document.getElementById('aktivitas-list');
  
  if (data.aktivitas.length === 0) {
    listContainer.innerHTML = '<p class="text-center">Belum ada aktivitas.</p>';
    return;
  }

  let html = '';
  data.aktivitas.forEach(item => {
    let mediaContent = '';
    
    // Check if item has video
    if (item.video) {
      mediaContent = `
        <div class="post-thumbnail" style="margin-bottom: 15px;">
          <video controls style="width: 100%; border-radius: 8px;">
            <source src="${item.video}" type="video/mp4">
            Browser Anda tidak mendukung tag video.
          </video>
        </div>
      `;
    } else if (item.image) {
      mediaContent = `
        <div class="post-thumbnail" style="margin-bottom: 15px;">
          <img src="${item.image}" alt="${item.title}" style="width: 100%; height: auto; border-radius: 8px;">
        </div>
      `;
    } else {
      mediaContent = `
        <div class="post-thumbnail">
          <div style="width:100%; height:150px; background:#16cfc1; display:flex; align-items:center; justify-content:center; color:white; font-size:18px; border-radius: 8px;">${item.title.substring(0, 15)}</div>
        </div>
      `;
    }
    
    html += `
      <article class="post" style="margin-bottom: 30px;">
        <div class="post-inner">
          ${mediaContent}
          <div class="post-header">
            <h2 class="post-title"><a href="#">${item.title}</a></h2>
            <div class="post-meta">
              <span class="post-date">${item.date}</span>
              <span class="post-author">Oleh Admin</span>
            </div>
          </div>
          <div class="post-content">
            <p>${item.description}</p>
          </div>
        </div>
      </article>
    `;
  });
  
  listContainer.innerHTML = html;
}

// Render artikel content
function renderArtikel() {
  const data = getData();
  const listContainer = document.getElementById('artikel-list');
  
  if (data.artikel.length === 0) {
    listContainer.innerHTML = '<p class="text-center">Belum ada artikel.</p>';
    return;
  }

  let html = '';
  data.artikel.forEach(item => {
    let mediaContent = '';
    
    // Check if item has video
    if (item.video) {
      mediaContent = `
        <div class="post-thumbnail" style="margin-bottom: 15px;">
          <video controls style="width: 100%; border-radius: 8px;">
            <source src="${item.video}" type="video/mp4">
            Browser Anda tidak mendukung tag video.
          </video>
        </div>
      `;
    } else if (item.image) {
      mediaContent = `
        <div class="post-thumbnail" style="margin-bottom: 15px;">
          <img src="${item.image}" alt="${item.title}" style="width: 100%; height: auto; border-radius: 8px;">
        </div>
      `;
    } else {
      mediaContent = `
        <div class="post-thumbnail">
          <div style="width:100%; height:150px; background:#3498db; display:flex; align-items:center; justify-content:center; color:white; font-size:18px; border-radius: 8px;">${item.category}</div>
        </div>
      `;
    }
    
    html += `
      <article class="post" style="margin-bottom: 30px;">
        <div class="post-inner">
          ${mediaContent}
          <div class="post-header">
            <h2 class="post-title"><a href="#">${item.title}</a></h2>
            <div class="post-meta">
              <span class="post-date">${item.date}</span>
              <span class="post-author">Oleh ${item.author}</span>
              <span class="post-category"><a href="#">${item.category}</a></span>
            </div>
          </div>
          <div class="post-content">
            <p>${item.content}</p>
            <a href="#" class="more-link">Baca Selengkapnya →</a>
          </div>
        </div>
      </article>
    `;
  });
  
  listContainer.innerHTML = html;

  // Update sidebar categories
  const categoriesWidget = document.querySelector('.widget ul');
  if (categoriesWidget && data.artikel.length > 0) {
    const categories = [...new Set(data.artikel.map(a => a.category))];
    categoriesWidget.innerHTML = categories.map(cat => `<li><a href="#">${cat}</a></li>`).join('');
  }

  // Update sidebar popular posts
  const popularWidget = document.querySelectorAll('.widget')[1];
  if (popularWidget && data.artikel.length > 0) {
    const popularUl = popularWidget.querySelector('ul');
    popularUl.innerHTML = data.artikel.slice(0, 3).map(post => `<li><a href="#">${post.title}</a></li>`).join('');
  }
}

// Render diskusi content
function renderDiskusi() {
  const data = getData();
  const listContainer = document.getElementById('diskusi-list');
  
  if (data.diskusi.length === 0) {
    listContainer.innerHTML = '<p class="text-center">Belum ada diskusi.</p>';
    return;
  }

  let html = '';
  data.diskusi.forEach(item => {
    let mediaContent = '';
    
    // Check if item has video
    if (item.video) {
      mediaContent = `
        <div style="margin-bottom: 15px;">
          <video controls style="width: 100%; border-radius: 8px;">
            <source src="${item.video}" type="video/mp4">
            Browser Anda tidak mendukung tag video.
          </video>
        </div>
      `;
    } else if (item.image) {
      mediaContent = `
        <div style="margin-bottom: 15px;">
          <img src="${item.image}" alt="${item.title}" style="width: 100%; height: auto; border-radius: 8px;">
        </div>
      `;
    }
    
    html += `
      <div class="discussion-item" style="margin-bottom: 30px;">
        ${mediaContent}
        <h3>${item.title}</h3>
        <div class="meta">
          <span>Oleh: ${item.author}</span> | <span>${item.date}</span> | <span>${item.replies || 0} Balasan</span>
        </div>
        <div class="content">
          <p>${item.content || 'Diskusi ini dibuat oleh ' + item.author + '. Silakan berpartisipasi dalam pembahasan ini.'}</p>
        </div>
      </div>
    `;
  });
  
  listContainer.innerHTML = html;

  // Update sidebar statistics
  const statsWidget = document.querySelectorAll('.widget')[1];
  if (statsWidget) {
    statsWidget.innerHTML = `
      <h3 class="widget-title">Statistik</h3>
      <p>Total Diskusi: ${data.diskusi.length}</p>
      <p>Artikel: ${data.artikel.length}</p>
      <p>Aktivitas: ${data.aktivitas.length}</p>
    `;
  }
}

// Render galeri content
function renderGaleri() {
  const data = getData();
  const listContainer = document.getElementById('galeri-list');
  
  if (data.galeri.length === 0) {
    listContainer.innerHTML = '<p class="text-center">Belum ada galeri.</p>';
    return;
  }

  let html = '';
  data.galeri.forEach(item => {
    let mediaContent = '';
    
    // Check if item has video
    if (item.video) {
      mediaContent = `
        <video controls style="width: 100%; height: 200px; object-fit: cover;">
          <source src="${item.video}" type="video/mp4">
          Browser Anda tidak mendukung tag video.
        </video>
      `;
    } else if (item.image) {
      mediaContent = `
        <img src="${item.image}" alt="${item.title}" style="width: 100%; height: 200px; object-fit: cover;">
      `;
    } else {
      mediaContent = `<div class="gallery-placeholder" style="background: #3498db;">${item.category}</div>`;
    }
    
    html += `
      <div class="gallery-item">
        ${mediaContent}
        <div class="gallery-info">
          <h3>${item.title}</h3>
          <p>${item.date}</p>
        </div>
      </div>
    `;
  });
  
  listContainer.innerHTML = html;

  // Update sidebar categories
  const categoriesWidget = document.querySelector('.widget ul');
  if (categoriesWidget && data.galeri.length > 0) {
    const categories = [...new Set(data.galeri.map(g => g.category))];
    categoriesWidget.innerHTML = categories.map(cat => `<li><a href="#">${cat}</a></li>`).join('');
  }

  // Update sidebar statistics
  const statsWidget = document.querySelectorAll('.widget')[1];
  if (statsWidget) {
    statsWidget.innerHTML = `
      <h3 class="widget-title">Statistik</h3>
      <p>Total Galeri: ${data.galeri.length}</p>
      <p>Artikel: ${data.artikel.length}</p>
      <p>Aktivitas: ${data.aktivitas.length}</p>
    `;
  }
}

// Initialize on DOM ready
document.addEventListener('DOMContentLoaded', function() {
  initNavigation();
  applySiteSettings();
  renderContent();
});
