// Language Management
let currentLanguage = 'ar';
let currentPage = 'home';

function t(key) {
  return translations[currentLanguage][key] || key;
}

function setLanguage(lang) {
  currentLanguage = lang;
  const html = document.documentElement;
  html.setAttribute('lang', lang);
  html.setAttribute('dir', lang === 'ar' ? 'rtl' : 'ltr');
  
  // استدعاء route تغيير اللغة باستخدام AJAX
  fetch(`/switch-language/${lang}`, {
    method: 'GET',
    headers: {
      'X-Requested-With': 'XMLHttpRequest',
      'Content-Type': 'application/json',
      'Accept': 'application/json'
    },
    credentials: 'same-origin'
  })
  .then(response => {
    if (response.ok) {
       return response;
    }
    throw new Error('Network response was not ok');
  })
  .catch(error => {
    console.error('Error changing language:', error);
  });
  
  updateContent();
}

function updateContent() {
  document.querySelectorAll('[data-translate]').forEach(el => {
    const key = el.getAttribute('data-translate');
    el.textContent = t(key);
  });
  
  document.querySelectorAll('[data-translate-html]').forEach(el => {
    const key = el.getAttribute('data-translate-html');
    el.innerHTML = t(key);
  });
}

// Navigation
function navigateTo(page) {
  if (page === 'home') {
    window.location.href = 'index.html';
  } else if (page === 'verify') {
    window.location.href = 'verify.html';
  } else if (page === 'details') {
    const code = sessionStorage.getItem('contractCode');
    if (code) {
      window.location.href = `details.html?code=${code}`;
    }
  }
}

// Header functionality
function initHeader() {
  const menuToggle = document.getElementById('mobile-menu-toggle');
  const mobileMenu = document.getElementById('mobile-menu');
  
  if (menuToggle && mobileMenu) {
    menuToggle.addEventListener('click', () => {
      mobileMenu.classList.toggle('hidden');
    });
  }
  
  // Language toggle
  const langToggle = document.getElementById('language-toggle');
  if (langToggle) {
    langToggle.addEventListener('click', () => {
      setLanguage(currentLanguage === 'ar' ? 'en' : 'ar');
    });
  }

  // Mobile language toggle
  const mobileLangToggle = document.getElementById('mobile-language-toggle');
  if (mobileLangToggle) {
    mobileLangToggle.addEventListener('click', () => {
      setLanguage(currentLanguage === 'ar' ? 'en' : 'ar');
    });
  }
  
  // Smooth scroll for anchor links
  document.querySelectorAll('a[href^="#"]').forEach(anchor => {
    anchor.addEventListener('click', function(e) {
      const href = this.getAttribute('href');
      if (href !== '#' && href !== '#verify') {
        e.preventDefault();
        const target = document.querySelector(href);
        if (target) {
          target.scrollIntoView({ behavior: 'smooth', block: 'start' });
          // Close mobile menu
          if (mobileMenu) mobileMenu.classList.add('hidden');
        }
      }
    });
  });
}

// Scroll to top
function initScrollToTop() {
  const scrollBtn = document.getElementById('scroll-to-top');
  if (!scrollBtn) return;
  
  window.addEventListener('scroll', () => {
    if (window.scrollY > 300) {
      scrollBtn.classList.remove('hidden');
    } else {
      scrollBtn.classList.add('hidden');
    }
  });
  
  scrollBtn.addEventListener('click', () => {
    window.scrollTo({ top: 0, behavior: 'smooth' });
  });
}

// FAQ Accordion
function initFAQ() {
  const faqItems = document.querySelectorAll('.faq-item');
  faqItems.forEach((item, index) => {
    const button = item.querySelector('.faq-button');
    const content = item.querySelector('.faq-content');
    
    button.addEventListener('click', () => {
      const isOpen = !item.classList.contains('faq-open');
      
      // Close all other items
      faqItems.forEach(otherItem => {
        if (otherItem !== item) {
          otherItem.classList.remove('faq-open');
          const otherContent = otherItem.querySelector('.faq-content');
          if (otherContent) {
            otherContent.style.maxHeight = null;
          }
        }
      });
      
      // Toggle current item
      if (isOpen) {
        item.classList.add('faq-open');
        if (content) {
          content.style.maxHeight = content.scrollHeight + 'px';
        }
      } else {
        item.classList.remove('faq-open');
        if (content) {
          content.style.maxHeight = null;
        }
      }
    });
  });
}

// Verify Contract
function initVerifyContract() {
  const form = document.getElementById('verify-form');
  const inputs = document.querySelectorAll('.code-input');
  
  if (!form) return;
  
  inputs.forEach((input, index) => {
    input.addEventListener('input', (e) => {
      const value = e.target.value.replace(/[^0-9]/g, '');
      if (value.length > 1) {
        e.target.value = value[0];
      } else {
        e.target.value = value;
      }
      
      if (value && index < inputs.length - 1) {
        inputs[index + 1].focus();
      }
      
      checkCodeComplete();
    });
    
    input.addEventListener('keydown', (e) => {
      if (e.key === 'Backspace' && !e.target.value && index > 0) {
        inputs[index - 1].focus();
      }
    });
  });
  
  // Paste handling
  form.addEventListener('paste', (e) => {
    e.preventDefault();
    const pastedData = e.clipboardData.getData('text').trim();
    if (/^\d{6}$/.test(pastedData)) {
      const digits = pastedData.split('');
      inputs.forEach((input, index) => {
        input.value = digits[index] || '';
      });
      inputs[5].focus();
      checkCodeComplete();
    }
  });
  
  function checkCodeComplete() {
    const code = Array.from(inputs).map(input => input.value).join('');
    const submitBtn = document.getElementById('verify-submit');
    if (submitBtn) {
      submitBtn.disabled = code.length !== 6;
      submitBtn.classList.toggle('disabled', code.length !== 6);
    }
  }
  
  form.addEventListener('submit', (e) => {
    e.preventDefault();
    const code = Array.from(inputs).map(input => input.value).join('');
    if (code.length === 6) {
      sessionStorage.setItem('contractCode', code);
      window.location.href = 'details.html';
    }
  });
}

// Contract Details
function initContractDetails() {
  const urlParams = new URLSearchParams(window.location.search);
  const code = urlParams.get('code') || sessionStorage.getItem('contractCode');
  
  if (!code) {
    window.location.href = 'verify.html';
    return;
  }
  
  const approveBtn = document.getElementById('approve-btn');
  const rejectBtn = document.getElementById('reject-btn');
  const confirmDialog = document.getElementById('confirm-dialog');
  const confirmYes = document.getElementById('confirm-yes');
  const confirmCancel = document.getElementById('confirm-cancel');
  const successDialog = document.getElementById('success-dialog');
  
  let pendingAction = null; // 'approve' or 'reject'
  
  if (approveBtn) {
    approveBtn.addEventListener('click', () => {
      pendingAction = 'approve';
      if (confirmDialog) {
        confirmDialog.classList.remove('hidden');
        const confirmYes = document.getElementById('confirm-yes');
        if (confirmYes) {
          confirmYes.className = 'confirm-btn yes';
        }
        const confirmMessage = document.getElementById('confirm-message-text');
        if (confirmMessage) {
          confirmMessage.textContent = t('confirmApproval');
        }
      }
    });
  }

  if (rejectBtn) {
    rejectBtn.addEventListener('click', () => {
      pendingAction = 'reject';
      if (confirmDialog) {
        confirmDialog.classList.remove('hidden');
        const confirmMessage = document.getElementById('confirm-message-text');
        if (confirmMessage) {
          confirmMessage.textContent = t('confirmRejection');
        }
        const confirmYes = document.getElementById('confirm-yes');
        if (confirmYes) {
          confirmYes.className = 'confirm-btn reject';
        }
      }
    });
  }
  
  if (confirmYes) {
    confirmYes.addEventListener('click', () => {
      if (pendingAction === 'approve' || pendingAction === 'reject') {
        if (confirmDialog) confirmDialog.classList.add('hidden');
        if (successDialog) {
          const isApproved = pendingAction === 'approve';
          successDialog.classList.remove('hidden');
          const title = successDialog.querySelector('.success-title');
          const message = successDialog.querySelector('.success-message');
          const icon = successDialog.querySelector('.success-icon');
          
          if (title) title.textContent = t(isApproved ? 'approvedSuccessfully' : 'contractRejected');
          if (message) message.textContent = t(isApproved ? 'approvalMessage' : 'rejectionMessage');
          if (icon) {
            icon.className = isApproved ? 'success-icon text-green-600' : 'success-icon text-red-600';
            icon.innerHTML = isApproved 
              ? '<svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"></path><polyline points="22 4 12 14.01 9 11.01"></polyline></svg>'
              : '<svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"></circle><line x1="15" y1="9" x2="9" y2="15"></line><line x1="9" y1="9" x2="15" y2="15"></line></svg>';
          }
        }
      }
    });
  }
  
  if (confirmCancel) {
    confirmCancel.addEventListener('click', () => {
      if (confirmDialog) confirmDialog.classList.add('hidden');
      pendingAction = null;
    });
  }
}

// Initialize icons helper
function initIcons() {
  if (typeof lucide !== 'undefined' && lucide.createIcons) {
    try {
      lucide.createIcons();
    } catch (e) {
      console.error('Error initializing icons:', e);
    }
  }
}

// Initialize on page load
document.addEventListener('DOMContentLoaded', () => {
  // Set initial language from HTML lang attribute (set by Laravel)
  const htmlLang = document.documentElement.getAttribute('lang') || 'ar';
  setLanguage(htmlLang);
  
  // Initialize components based on page
  const path = window.location.pathname;
  const page = path.includes('verify') ? 'verify' : path.includes('details') ? 'details' : 'home';
  currentPage = page;
  
  initHeader();
  initScrollToTop();
  
  if (page === 'home') {
    initFAQ();
  } else if (page === 'verify') {
    initVerifyContract();
  } else if (page === 'details') {
    initContractDetails();
  }
  
  // Initialize icons - try multiple times to ensure Lucide is loaded
  initIcons();
  setTimeout(initIcons, 100);
  setTimeout(initIcons, 300);
  setTimeout(initIcons, 500);
});

// Also initialize on window load as backup
window.addEventListener('load', function() {
  initIcons();
  setTimeout(initIcons, 100);
});

// Add smooth scroll behavior
document.documentElement.style.scrollBehavior = 'smooth';
