// =============================================
// SHARK CRM - Main JavaScript
// =============================================

// ---- Toast Notifications ----
function showToast(message, type = 'info') {
  const container = document.getElementById('toast-container') || createToastContainer();
  const icons = { success: '✓', error: '✗', warning: '⚠', info: 'ℹ' };
  const toast = document.createElement('div');
  toast.className = `toast ${type}`;
  toast.innerHTML = `<span style="font-size:16px">${icons[type]||'ℹ'}</span><span>${message}</span>`;
  container.appendChild(toast);
  setTimeout(() => {
    toast.style.animation = 'toastIn 0.3s ease reverse';
    setTimeout(() => toast.remove(), 300);
  }, 3500);
}

function createToastContainer() {
  const div = document.createElement('div');
  div.id = 'toast-container';
  document.body.appendChild(div);
  return div;
}

// ---- Modal Helpers ----
function openModal(id) {
  const overlay = document.getElementById(id);
  if (overlay) { overlay.classList.add('open'); document.body.style.overflow = 'hidden'; }
}

function closeModal(id) {
  const overlay = document.getElementById(id);
  if (overlay) { overlay.classList.remove('open'); document.body.style.overflow = ''; }
}

// Close modal on overlay click
document.addEventListener('click', function(e) {
  if (e.target.classList.contains('modal-overlay')) {
    e.target.classList.remove('open');
    document.body.style.overflow = '';
  }
});

// Close buttons
document.addEventListener('click', function(e) {
  if (e.target.classList.contains('modal-close') || e.target.closest('.modal-close')) {
    const modal = e.target.closest('.modal-overlay');
    if (modal) { modal.classList.remove('open'); document.body.style.overflow = ''; }
  }
});

// ---- Tabs ----
function initTabs(container) {
  const btns = (container || document).querySelectorAll('.tab-btn');
  btns.forEach(btn => {
    btn.addEventListener('click', function() {
      const group = this.closest('.tabs');
      const target = this.dataset.tab;
      group.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('active'));
      this.classList.add('active');
      const panes = (container || document).querySelectorAll('.tab-pane');
      panes.forEach(p => p.classList.toggle('active', p.id === target));
    });
  });
}

// ---- Dropdown menus ----
document.addEventListener('click', function(e) {
  const trigger = e.target.closest('[data-dropdown]');
  if (trigger) {
    e.stopPropagation();
    const menu = document.getElementById(trigger.dataset.dropdown);
    if (!menu) return;
    document.querySelectorAll('.dropdown-menu.open').forEach(m => { if (m !== menu) m.classList.remove('open'); });
    menu.classList.toggle('open');
    return;
  }
  document.querySelectorAll('.dropdown-menu.open').forEach(m => m.classList.remove('open'));
});

// ---- AJAX Helper ----
async function apiCall(url, data = null, method = 'POST') {
  try {
    const opts = { method, headers: {} };
    if (data) {
      if (data instanceof FormData) { opts.body = data; }
      else { opts.headers['Content-Type'] = 'application/json'; opts.body = JSON.stringify(data); }
    }
    const res = await fetch(url, opts);
    return await res.json();
  } catch (err) {
    console.error('API Error:', err);
    return { success: false, message: 'Request failed' };
  }
}

// ---- Star Rating ----
function initStarRating(container) {
  const stars = container.querySelectorAll('.star-input');
  const input = container.querySelector('input[type=hidden]');
  stars.forEach((star, i) => {
    star.addEventListener('mouseover', () => highlightStars(stars, i));
    star.addEventListener('mouseout', () => highlightStars(stars, parseInt(input?.value || 0) - 1));
    star.addEventListener('click', () => {
      if (input) input.value = i + 1;
      highlightStars(stars, i);
    });
  });
}

function highlightStars(stars, upTo) {
  stars.forEach((s, i) => s.classList.toggle('filled', i <= upTo));
}

// ---- Priority display helper ----
function renderPriority(val) {
  let html = '';
  for (let i = 1; i <= 5; i++) {
    html += `<span class="star${i <= val ? ' filled' : ''}">★</span>`;
  }
  return `<span class="stars">${html}</span>`;
}

// ---- Opportunity bar ----
function renderOpportunity(val) {
  const color = val >= 70 ? '#10b981' : val >= 40 ? '#f59e0b' : '#ef4444';
  return `<div class="progress-wrap"><div class="progress-bar" style="width:${val}%;background:${color}"></div></div>
          <div class="progress-label">${val}%</div>`;
}

// ---- Confirm Dialog ----
function confirmAction(msg, cb) {
  if (confirm(msg)) cb();
}

// ---- Format currency ----
function formatCurrency(amount, currency = 'USD') {
  return new Intl.NumberFormat('en-US', { style: 'currency', currency }).format(amount);
}

// ---- Format date ----
function formatDate(dt) {
  if (!dt) return 'N/A';
  return new Date(dt).toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' });
}

// ---- Search filter ----
function initTableSearch(inputId, tableId, cols = null) {
  const input = document.getElementById(inputId);
  const tbody = document.querySelector(`#${tableId} tbody`);
  if (!input || !tbody) return;
  input.addEventListener('input', function() {
    const q = this.value.toLowerCase();
    tbody.querySelectorAll('tr').forEach(row => {
      const text = (cols ? cols.map(c => row.cells[c]?.textContent).join(' ') : row.textContent).toLowerCase();
      row.style.display = text.includes(q) ? '' : 'none';
    });
  });
}

// ---- On page load ----
document.addEventListener('DOMContentLoaded', function() {
  initTabs();
  document.querySelectorAll('.star-rating-wrap').forEach(initStarRating);
});
