// ---- CRM I18N runtime helpers ----
function crmNormalizeText(s){ return String(s == null ? '' : s).replace(/\s+/g,' ').trim(); }
function crmT(s){
  const original = String(s == null ? '' : s);
  const clean = crmNormalizeText(original);
  if (!clean || !window.CRM_I18N) return original;
  if (window.CRM_I18N[clean]) return window.CRM_I18N[clean];
  // Replace known English chunks inside dynamic messages
  let out = original;
  Object.keys(window.CRM_I18N).sort((a,b)=>b.length-a.length).forEach(k=>{
    if (k.length < 3) return;
    out = out.split(k).join(window.CRM_I18N[k]);
  });
  return out;
}

function crmTranslateDom(root){
  if (!window.CRM_I18N || window.CRM_LANG !== 'ar') return;
  const scope = root || document.body;
  if (!scope) return;
  const attrs = ['title','placeholder','aria-label','data-confirm','alt'];
  const els = scope.nodeType === 1 ? [scope, ...scope.querySelectorAll('*')] : Array.from(scope.querySelectorAll ? scope.querySelectorAll('*') : []);
  els.forEach(el => {
    if (!el || ['SCRIPT','STYLE','TEXTAREA'].includes(el.tagName)) return;
    attrs.forEach(a => { if (el.hasAttribute && el.hasAttribute(a)) el.setAttribute(a, crmT(el.getAttribute(a))); });
  });
  const walker = document.createTreeWalker(scope, NodeFilter.SHOW_TEXT, {
    acceptNode(node){
      const p = node.parentElement;
      if (!p || ['SCRIPT','STYLE','TEXTAREA','INPUT'].includes(p.tagName)) return NodeFilter.FILTER_REJECT;
      const clean = crmNormalizeText(node.nodeValue);
      if (!clean || !/[A-Za-z]/.test(clean)) return NodeFilter.FILTER_REJECT;
      return NodeFilter.FILTER_ACCEPT;
    }
  });
  const nodes=[]; while(walker.nextNode()) nodes.push(walker.currentNode);
  nodes.forEach(n => {
    const old = n.nodeValue;
    const leading = old.match(/^\s*/)[0];
    const trailing = old.match(/\s*$/)[0];
    const translated = crmT(crmNormalizeText(old));
    if (translated && translated !== crmNormalizeText(old)) n.nodeValue = leading + translated + trailing;
  });
}
document.addEventListener('DOMContentLoaded', function(){
  crmTranslateDom(document.body);
  const obs = new MutationObserver(ms => ms.forEach(m => m.addedNodes.forEach(n => { if (n.nodeType === 1) crmTranslateDom(n); })));
  if (document.body) obs.observe(document.body, {childList:true, subtree:true});
});

(function(){
  const nativeAlert = window.alert.bind(window);
  const nativeConfirm = window.confirm.bind(window);
  window.alert = function(msg){ return nativeAlert(crmT(msg)); };
  window.confirm = function(msg){ return nativeConfirm(crmT(msg)); };
})();

// =============================================
// 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>${crmT(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: crmT('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(crmT(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);
});

// ---- Simple request button loading state ----
let __crmLastClickedButton = null;
document.addEventListener('click', function(e){
  const btn = e.target.closest('button, .btn');
  if (btn && !btn.disabled) __crmLastClickedButton = btn;
}, true);
function __crmLoadingText(txt){
  const t = (txt || '').replace(/^[^A-Za-z+]+/,'').trim().toLowerCase();
  if (t.includes('create')) return crmT('Creating...');
  if (t.includes('add')) return crmT('Adding...');
  if (t.includes('update')) return crmT('Updating...');
  if (t.includes('save')) return crmT('Saving...');
  if (t.includes('send')) return crmT('Sending...');
  if (t.includes('delete') || t.includes('remove')) return crmT('Removing...');
  if (t.includes('filter') || t.includes('search')) return crmT('Loading...');
  return crmT('Working...');
}
function __crmSetButtonLoading(btn, loading){
  if (!btn || btn.dataset.noLoading === '1') return;
  if (loading) {
    if (btn.dataset.loading === '1') return;
    btn.dataset.loading = '1';
    btn.dataset.originalHtml = btn.innerHTML;
    btn.disabled = true;
    btn.classList.add('is-loading');
    btn.innerHTML = __crmLoadingText(btn.textContent);
  } else {
    if (btn.dataset.loading !== '1') return;
    btn.innerHTML = btn.dataset.originalHtml || btn.innerHTML;
    btn.disabled = false;
    btn.classList.remove('is-loading');
    delete btn.dataset.loading;
  }
}
if (typeof apiCall === 'function' && !apiCall.__crmWrapped) {
  const __crmOriginalApiCall = apiCall;
  apiCall = async function(url, data = null, method = 'POST') {
    const btn = __crmLastClickedButton;
    __crmSetButtonLoading(btn, true);
    try { return await __crmOriginalApiCall(url, data, method); }
    finally { __crmSetButtonLoading(btn, false); __crmLastClickedButton = null; }
  };
  apiCall.__crmWrapped = true;
}
document.addEventListener('submit', function(e){
  const btn = e.submitter || e.target.querySelector('button[type="submit"], .btn-primary');
  __crmSetButtonLoading(btn, true);
  setTimeout(()=>__crmSetButtonLoading(btn,false), 8000);
}, true);
