/* =============================================
   Rig N Dig - Main JavaScript
   ============================================= */

'use strict';

// ── Mobile Menu ──────────────────────────────────────────────
const menuBtn = document.getElementById('mobile-menu-btn');
const mobileMenu = document.getElementById('mobile-menu');
if (menuBtn && mobileMenu) {
  menuBtn.addEventListener('click', () => mobileMenu.classList.toggle('hidden'));
}

// ── Sticky Header ────────────────────────────────────────────
const header = document.getElementById('header-inner');
if (header) {
  window.addEventListener('scroll', () => {
    if (window.scrollY > 50) {
      header.style.borderBottomColor = 'rgba(42,49,71,0.8)';
      header.style.boxShadow = '0 4px 20px rgba(0,0,0,0.4)';
    } else {
      header.style.borderBottomColor = 'transparent';
      header.style.boxShadow = 'none';
    }
  });
}

// ── Hero Particle Canvas ─────────────────────────────────────
function initParticles(canvasId) {
  const canvas = document.getElementById(canvasId);
  if (!canvas) return;
  const ctx = canvas.getContext('2d');
  let W = canvas.width = canvas.offsetWidth;
  let H = canvas.height = canvas.offsetHeight;
  const particles = [];
  const N = Math.floor((W * H) / 12000);

  class Particle {
    constructor() { this.reset(); }
    reset() {
      this.x = Math.random() * W;
      this.y = Math.random() * H;
      this.vx = (Math.random() - 0.5) * 0.4;
      this.vy = (Math.random() - 0.5) * 0.4;
      this.r = Math.random() * 1.5 + 0.5;
      this.alpha = Math.random() * 0.5 + 0.15;
    }
    update() {
      this.x += this.vx; this.y += this.vy;
      if (this.x < 0 || this.x > W || this.y < 0 || this.y > H) this.reset();
    }
    draw() {
      ctx.beginPath();
      ctx.arc(this.x, this.y, this.r, 0, Math.PI * 2);
      ctx.fillStyle = `rgba(255,107,0,${this.alpha})`;
      ctx.fill();
    }
  }

  for (let i = 0; i < N; i++) particles.push(new Particle());

  // Draw connecting lines
  function drawLines() {
    for (let i = 0; i < particles.length; i++) {
      for (let j = i + 1; j < particles.length; j++) {
        const dx = particles[i].x - particles[j].x;
        const dy = particles[i].y - particles[j].y;
        const dist = Math.sqrt(dx*dx + dy*dy);
        if (dist < 100) {
          ctx.beginPath();
          ctx.strokeStyle = `rgba(255,107,0,${0.12 * (1 - dist/100)})`;
          ctx.lineWidth = 0.5;
          ctx.moveTo(particles[i].x, particles[i].y);
          ctx.lineTo(particles[j].x, particles[j].y);
          ctx.stroke();
        }
      }
    }
  }

  function loop() {
    ctx.clearRect(0, 0, W, H);
    particles.forEach(p => { p.update(); p.draw(); });
    drawLines();
    requestAnimationFrame(loop);
  }
  loop();

  window.addEventListener('resize', () => {
    W = canvas.width = canvas.offsetWidth;
    H = canvas.height = canvas.offsetHeight;
  });
}

initParticles('hero-canvas');

// ── Scroll Fade-in Animations ────────────────────────────────
const fadeEls = document.querySelectorAll('.fade-in');
const observer = new IntersectionObserver((entries) => {
  entries.forEach(entry => {
    if (entry.isIntersecting) {
      entry.target.classList.add('visible');
      observer.unobserve(entry.target);
    }
  });
}, { threshold: 0.1 });
fadeEls.forEach(el => observer.observe(el));

// ── Counter Animation ─────────────────────────────────────────
function animateCounter(el) {
  const target = parseInt(el.dataset.target, 10);
  const dur = 2000;
  const step = target / (dur / 16);
  let current = 0;
  const timer = setInterval(() => {
    current = Math.min(current + step, target);
    el.textContent = Math.floor(current).toLocaleString() + (el.dataset.suffix || '');
    if (current >= target) clearInterval(timer);
  }, 16);
}

const counterObserver = new IntersectionObserver((entries) => {
  entries.forEach(entry => {
    if (entry.isIntersecting) {
      animateCounter(entry.target);
      counterObserver.unobserve(entry.target);
    }
  });
}, { threshold: 0.5 });
document.querySelectorAll('[data-target]').forEach(el => counterObserver.observe(el));

// ── Add to Cart (AJAX) ────────────────────────────────────────
function addToQuote(productId, btn) {
  if (btn) {
    btn.setAttribute('data-original', btn.innerHTML);
    btn.disabled = true;
    btn.innerHTML = '⏳ Sourcing...';
  }
  const basePrefix = (window.SITE_URL || '').replace(/\/$/, '');
  const apiUrl = basePrefix + (basePrefix ? '/api/cart.php' : 'api/cart.php');
  
  fetch(apiUrl, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'X-CSRF-TOKEN': window.CSRF_TOKEN || ''
    },
    body: JSON.stringify({ action: 'add', product_id: productId, quantity: 1 })
  })
  .then(async r => {
    const isJson = r.headers.get('content-type')?.includes('application/json');
    const data = isJson ? await r.json() : null;
    
    if (!r.ok) {
        throw new Error(data?.error || `Server responded with ${r.status}`);
    }
    if (!data) {
        throw new Error('Server returned non-JSON response. Check your database connection.');
    }
    return data;
  })
  .then(data => {
    if (data.success) {
      // Update cart badge
      const badges = document.querySelectorAll('.cart-badge');
      badges.forEach(b => {
        b.textContent = data.count;
        b.style.display = data.count > 0 ? 'flex' : 'none';
        b.classList.add('animate-ping');
        setTimeout(() => b.classList.remove('animate-ping'), 1000);
      });
      showToast('Successfully added to your RFQ cart!', 'success');
    } else {
      showToast(data.error || 'Unable to add item. Please try again.', 'error');
    }
    if (btn) {
      btn.innerHTML = '✓ Added to RFQ';
      btn.classList.add('bg-green-600', 'border-green-600');
      setTimeout(() => {
        btn.innerHTML = btn.getAttribute('data-original');
        btn.classList.remove('bg-green-600', 'border-green-600');
        btn.disabled = false;
      }, 2000);
    }
  })
  .catch(err => {
    console.error('Cart Error Detail:', err);
    showToast('Add to RFQ failed: ' + (err.message || 'Check connection'), 'error');
    if (btn) {
      btn.disabled = false;
      btn.innerHTML = btn.getAttribute('data-original');
    }
    // Debug info for the user
    console.warn('Backend API URL used:', apiUrl);
  });
}

// ── Toast Notification ────────────────────────────────────────
function showToast(msg, type = 'success') {
  const existing = document.getElementById('toast-container');
  if (!existing) {
    const tc = document.createElement('div');
    tc.id = 'toast-container';
    tc.className = 'fixed top-4 right-4 z-[200] flex flex-col gap-2';
    document.body.appendChild(tc);
  }
  const tc = document.getElementById('toast-container');
  const toast = document.createElement('div');
  const bg = type === 'success' ? 'bg-green-800 border-green-600' : 'bg-red-900 border-red-600';
  toast.className = `${bg} border text-white text-sm px-4 py-3 rounded-lg shadow-xl flex items-center gap-2 animate-fade-in`;
  toast.innerHTML = `<span>${type === 'success' ? '✓' : '✕'}</span><span>${msg}</span>`;
  tc.appendChild(toast);
  setTimeout(() => { toast.remove(); }, 3500);
}

// ── Quick View Modal ──────────────────────────────────────────
function openQuickView(productId) {
  const overlay = document.getElementById('quick-view-overlay');
  const content = document.getElementById('quick-view-content');
  if (!overlay || !content) return;
  content.innerHTML = '<div class="flex justify-center py-10"><div class="spinner"></div></div>';
  overlay.classList.remove('hidden');
  document.body.style.overflow = 'hidden';

  const basePrefix = (window.SITE_URL || '').replace(/\/$/, '');
  const apiUrl = basePrefix + (basePrefix ? `/api/product.php?id=${productId}` : `api/product.php?id=${productId}`);
  fetch(apiUrl)
    .then(r => r.json())
    .then(data => {
      if (data.error) { content.innerHTML = `<p class="text-red-400 p-6">${data.error}</p>`; return; }
      content.innerHTML = `
        <button onclick="closeQuickView()" class="absolute top-4 right-4 text-gray-400 hover:text-white text-xl z-10">✕</button>
        <div class="grid grid-cols-1 md:grid-cols-2 gap-6 p-6">
          <div>
            ${data.image ? `<img src="/uploads/${data.image}" class="rounded-lg w-full object-cover" alt="${data.name}">` : '<div class="rounded-lg bg-navy-600 h-48 flex items-center justify-center text-5xl">⚙️</div>'}
          </div>
          <div>
            <div class="text-xs text-orange-500 mb-1">${data.category_name || ''}</div>
            <h3 class="text-xl font-bold mb-2">${data.name}</h3>
            ${data.sku ? `<div class="text-xs text-gray-400 mb-3">SKU: ${data.sku}</div>` : ''}
            <p class="text-sm text-gray-300 mb-4">${data.short_description || ''}</p>
            ${data.standards ? `<div class="text-xs bg-navy-600 rounded px-2 py-1 inline-block mb-4">📋 ${data.standards}</div>` : ''}
            <button onclick="addToQuote(${data.id}, this)" class="btn-primary w-full">
              📋 Add to RFQ Cart
            </button>
            <a href="/product-detail.php?slug=${data.slug}" class="btn-outline w-full mt-2 text-center block">View Full Details</a>
          </div>
        </div>`;
    });
}

function closeQuickView() {
  const overlay = document.getElementById('quick-view-overlay');
  if (overlay) overlay.classList.add('hidden');
  document.body.style.overflow = '';
}

// ── Confirm Dialogs ───────────────────────────────────────────
function confirmAction(msg, callback) {
  if (confirm(msg)) callback();
}

// ── Filter Form Live Submit ───────────────────────────────────
document.querySelectorAll('.auto-submit').forEach(el => {
  el.addEventListener('change', () => el.closest('form').submit());
});

// ── Image Preview on Upload ───────────────────────────────────
document.querySelectorAll('input[type="file"][data-preview]').forEach(input => {
  input.addEventListener('change', () => {
    const preview = document.getElementById(input.dataset.preview);
    if (!preview || !input.files[0]) return;
    const reader = new FileReader();
    reader.onload = e => { preview.src = e.target.result; preview.classList.remove('hidden'); };
    reader.readAsDataURL(input.files[0]);
  });
});

// ── Admin Sidebar Toggle ──────────────────────────────────────
const sidebarToggle = document.getElementById('sidebar-toggle');
const adminSidebar = document.getElementById('admin-sidebar');
if (sidebarToggle && adminSidebar) {
  sidebarToggle.addEventListener('click', () => adminSidebar.classList.toggle('open'));
}

// ── Clipboard Copy ────────────────────────────────────────────
document.querySelectorAll('[data-copy]').forEach(btn => {
  btn.addEventListener('click', () => {
    navigator.clipboard.writeText(btn.dataset.copy).then(() => {
      showToast('Copied to clipboard!');
    });
  });
});

// ── Wishlist Toggle ───────────────────────────────────────────
function toggleWishlist(productId, btn) {
  const basePrefix = (window.SITE_URL || '').replace(/\/$/, '');
  const apiUrl = basePrefix + (basePrefix ? '/api/wishlist-toggle.php' : 'api/wishlist-toggle.php');
  fetch(apiUrl, {
    method: 'POST',
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        'X-CSRF-TOKEN': window.CSRF_TOKEN || ''
    },
    body: 'product_id=' + productId
  })
  .then(r => r.json())
  .then(data => {
    if (data.redirect) { window.location.href = data.redirect; return; }
    if (data.success) {
      if (data.action === 'added') {
        btn.innerHTML = '❤️ Saved';
        btn.className = btn.className.replace('text-gray-400','text-orange-400').replace('border-navy-500','border-orange-600');
        showToast('Saved to wishlist!');
      } else {
        btn.innerHTML = '🤍 Save';
        btn.className = btn.className.replace('text-orange-400','text-gray-400').replace('border-orange-600','border-navy-500');
        showToast('Removed from wishlist.');
      }
    }
  })
  .catch(() => showToast('Error updating wishlist.'));
}

// ── Product Compare Bar ───────────────────────────────────────
let compareList = JSON.parse(sessionStorage.getItem('rnd_compare') || '[]');

function handleCompareCheck(checkbox) {
  const id   = parseInt(checkbox.value);
  const name = checkbox.dataset.name;
  if (checkbox.checked) {
    if (compareList.length >= 4) {
      checkbox.checked = false;
      showToast('You can compare up to 4 products at a time.');
      return;
    }
    if (!compareList.find(x => x.id === id)) compareList.push({ id, name });
  } else {
    compareList = compareList.filter(x => x.id !== id);
  }
  sessionStorage.setItem('rnd_compare', JSON.stringify(compareList));
  renderCompareBar();
}

function addToCompare(id, name) {
  if (compareList.length >= 4) { showToast('Max 4 products for comparison.'); return; }
  if (compareList.find(x => x.id === id)) { showToast('Already in compare list.'); return; }
  compareList.push({ id, name });
  sessionStorage.setItem('rnd_compare', JSON.stringify(compareList));
  renderCompareBar();
  showToast('Added to compare. ' + compareList.length + '/4');
}

function removeFromCompare(id) {
  compareList = compareList.filter(x => x.id !== id);
  sessionStorage.setItem('rnd_compare', JSON.stringify(compareList));
  renderCompareBar();
  document.querySelectorAll('.compare-check').forEach(cb => {
    if (parseInt(cb.value) === id) cb.checked = false;
  });
}

function renderCompareBar() {
  let bar = document.getElementById('compare-bar');
  if (!compareList.length) {
    if (bar) bar.remove();
    return;
  }
  if (!bar) {
    bar = document.createElement('div');
    bar.id = 'compare-bar';
    bar.style.cssText = 'position:fixed;bottom:0;left:0;right:0;z-index:100;background:#111827;border-top:2px solid #ff6b00;padding:12px 20px;display:flex;align-items:center;gap:12px;flex-wrap:wrap;';
    document.body.appendChild(bar);
  }
  bar.innerHTML = '<span style="font-size:12px;font-weight:700;color:#ff8c30;white-space:nowrap;">⚖️ Compare (' + compareList.length + '/4)</span>';
  compareList.forEach(item => {
    const tag = document.createElement('span');
    tag.style.cssText = 'background:#1a1f2e;border:1px solid #2a3147;color:#e5e7eb;padding:4px 10px;border-radius:6px;font-size:12px;display:flex;align-items:center;gap:6px;';
    tag.innerHTML = `<span style="max-width:120px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;">${item.name}</span><button onclick="removeFromCompare(${item.id})" style="color:#f87171;background:none;border:none;cursor:pointer;padding:0;line-height:1;">✕</button>`;
    bar.appendChild(tag);
  });
  const ids = compareList.map(x => x.id).join(',');
  bar.innerHTML += `<a href="/compare.php?ids=${ids}" style="margin-left:auto;background:#ff6b00;color:white;padding:8px 18px;border-radius:8px;font-size:13px;font-weight:700;text-decoration:none;">Compare Now →</a>`;
  bar.innerHTML += `<button onclick="compareList=[];sessionStorage.removeItem('rnd_compare');renderCompareBar();" style="background:none;border:none;color:#9ca3af;cursor:pointer;font-size:12px;">Clear</button>`;
}

// Init compare bar on page load
document.addEventListener('DOMContentLoaded', function() {
  if (compareList.length) renderCompareBar();
});
