document.addEventListener('DOMContentLoaded', () => {

  // ===============================
  // Main tabs (Profile, Inventory, etc.)
  // ===============================
  const tabs   = document.querySelectorAll('.wcmv-tab[data-tab]');
  const panels = document.querySelectorAll('.wcmv-panel');

  if (!tabs.length || !panels.length) {
    console.warn('WCMV: Tabs or panels not found');
    return;
  }

 tabs.forEach(tab => {
  tab.addEventListener('click', (e) => {
    e.preventDefault();
    e.stopPropagation();

    tabs.forEach(t => t.classList.remove('active'));
    panels.forEach(p => p.classList.remove('active'));

    tab.classList.add('active');

    const target = document.getElementById('wcmv-' + tab.dataset.tab);
    if (target) target.classList.add('active');

    const url = new URL(window.location);
    url.searchParams.set('tab', tab.dataset.tab);
    window.history.pushState({}, '', url);
  });
});


  // ===============================
  // Restore active tab from URL
  // ===============================
  const params = new URLSearchParams(window.location.search);
  const activeTab = params.get('tab');

  if (activeTab) {
    const tabBtn = document.querySelector('[data-tab="' + activeTab + '"]');
    tabBtn?.click();
  } else {
    tabs[0].click(); // default tab
  }

});

document.addEventListener('click', (event) => {
  const trigger = event.target.closest('.wcmv-js-confirm');
  if (!trigger) return;
  const message = trigger.getAttribute('data-confirm') || 'Are you sure?';
  if (!window.confirm(message)) {
    event.preventDefault();
  }
});



document.querySelectorAll('.stat-card').forEach(card => {
  card.style.opacity = 0;
  card.style.transform = 'translateY(20px)';
  setTimeout(() => {
    card.style.transition = 'all .5s ease';
    card.style.opacity = 1;
    card.style.transform = 'translateY(0)';
  }, 100);
});

document.addEventListener('DOMContentLoaded', () => {

  // Require both chart data and Chart.js to be present. If Chart.js isn't
  // loaded (e.g. premium analytics not active), skip gracefully.
  var chartCfg = window.STAKMV_CHART_DATA || window.STAKMV_CHART_DATA || null;
  if (!chartCfg || typeof Chart === 'undefined') return;

  const labels = chartCfg.earnings.map(e => e.day).reverse();
  const earningsData = chartCfg.earnings.map(e => e.total).reverse();
  const bidsData = chartCfg.bids.map(b => b.total).reverse();

  new Chart(document.getElementById('wcmvEarningsChart'), {
    type: 'line',
    data: {
      labels,
      datasets: [{
        label: 'Earnings ($)',
        data: earningsData,
        borderColor: '#16a34a',
        backgroundColor: 'rgba(22,163,74,.15)',
        fill: true,
        tension: .4
      }]
    }
  });

  new Chart(document.getElementById('wcmvBidsChart'), {
    type: 'bar',
    data: {
      labels,
      datasets: [{
        label: 'Bids',
        data: bidsData,
        backgroundColor: '#2563eb'
      }]
    }
  });

  new Chart(document.getElementById('wcmvWatchersChart'), {
    type: 'line',
    data: {
      labels,
      datasets: [{
        label: 'Watchers',
        data: chartCfg.watchers,
        borderColor: '#f97316',
        tension: .4
      }]
    }
  });

});

document.addEventListener('DOMContentLoaded', () => {

  const editBtn   = document.getElementById('wcmv-edit-profile-btn');
  const modal     = document.getElementById('wcmv-edit-profile-modal');
  const formCard  = document.getElementById('wcmv-edit-profile-form');
  const cancelBtn = document.getElementById('wcmv-cancel-edit-profile');
  const closeBtn  = document.getElementById('wcmv-close-edit-profile');

  if (!editBtn || !formCard || !modal) return;

  const openModal = () => {
    modal.classList.remove('wcmv-hidden');
    modal.setAttribute('aria-hidden', 'false');
    document.body.classList.add('wcmv-modal-open');
  };

  const closeModal = () => {
    modal.classList.add('wcmv-hidden');
    modal.setAttribute('aria-hidden', 'true');
    document.body.classList.remove('wcmv-modal-open');
  };

  editBtn.addEventListener('click', openModal);

  cancelBtn?.addEventListener('click', closeModal);
  closeBtn?.addEventListener('click', closeModal);
  modal.addEventListener('click', (event) => {
    if (event.target === modal) {
      closeModal();
    }
  });
  document.addEventListener('keydown', (event) => {
    if (event.key === 'Escape' && !modal.classList.contains('wcmv-hidden')) {
      closeModal();
    }
  });

});

document.addEventListener('DOMContentLoaded', () => {
  const rows = document.querySelectorAll('[data-banner-row]');
  if (!rows.length || typeof wp === 'undefined' || !wp.media) return;

  rows.forEach((row) => {
    const input = row.querySelector('[data-banner-input]');
    const preview = row.querySelector('[data-banner-preview]');
    const uploadBtn = row.querySelector('[data-banner-upload]');
    const removeBtn = row.querySelector('[data-banner-remove]');
    let frame;

    const renderPreview = (url) => {
      if (!preview) return;
      if (!url) {
        preview.innerHTML = '';
        preview.classList.add('is-empty');
        return;
      }
      preview.classList.remove('is-empty');
      preview.innerHTML = `<img src=\"${url}\" alt=\"\">`;
    };

    uploadBtn?.addEventListener('click', (event) => {
      event.preventDefault();
      if (!frame) {
        frame = wp.media({
          title: 'Select banner image',
          button: { text: 'Use image' },
          multiple: false,
          library: { type: 'image' }
        });
        frame.on('select', () => {
          const attachment = frame.state().get('selection').first().toJSON();
          if (!input || !attachment || !attachment.url) return;
          input.value = attachment.url;
          renderPreview(attachment.url);
        });
      }
      frame.open();
    });

    removeBtn?.addEventListener('click', (event) => {
      event.preventDefault();
      if (!input) return;
      input.value = '';
      renderPreview('');
    });
  });
});
