/* ==========================================================================
   TeknoTok AI Translator Pro - Interactivity Script
   ========================================================================== */

document.addEventListener('DOMContentLoaded', () => {
  // Initialize the cost calculator if present on the page
  initCalculator();
});

/**
 * FAQ Accordion Toggler
 * Adds/removes active class and manages ARIA states for accessibility
 * @param {number} id - The FAQ item index
 */
function toggleFaq(id) {
  const faqItem = document.getElementById(`faq-item-${id}`);
  const faqBtn = document.getElementById(`faq-btn-${id}`);
  
  if (!faqItem) return;
  
  const isActive = faqItem.classList.contains('active');
  
  // Close all other FAQs for clean presentation
  const allItems = document.querySelectorAll('.faq-item');
  allItems.forEach(item => {
    item.classList.remove('active');
    const btn = item.querySelector('.faq-trigger');
    if (btn) {
      btn.setAttribute('aria-expanded', 'false');
      const icon = btn.querySelector('.faq-icon');
      if (icon) icon.textContent = '+';
    }
  });
  
  // Toggle the clicked one
  if (!isActive) {
    faqItem.classList.add('active');
    if (faqBtn) {
      faqBtn.setAttribute('aria-expanded', 'true');
      const icon = faqBtn.querySelector('.faq-icon');
      if (icon) icon.textContent = '−';
    }
  }
}

/**
 * Cost Savings & ROI Calculator
 */
function initCalculator() {
  const postsSlider = document.getElementById('posts-slider');
  const languagesSlider = document.getElementById('languages-slider');
  const updatesSlider = document.getElementById('updates-slider');
  
  // Verify calculator elements are present on the current page
  if (!postsSlider || !languagesSlider || !updatesSlider) return;
  
  const postsVal = document.getElementById('posts-val');
  const languagesVal = document.getElementById('languages-val');
  const updatesVal = document.getElementById('updates-val');
  
  const costNoCache = document.getElementById('cost-no-cache');
  const costWithCache = document.getElementById('cost-with-cache');
  
  function calculate() {
    const P = parseInt(postsSlider.value, 10);
    const L = parseInt(languagesSlider.value, 10);
    const U = parseInt(updatesSlider.value, 10);
    
    // Update value bubbles
    postsVal.textContent = P.toLocaleString();
    languagesVal.textContent = L.toString();
    updatesVal.textContent = U.toString();
    
    /* 
       --- Pricing Model Copy Rationale ---
       An average page/product is around 600 words (including header, menu, title, body, widgets).
       With OpenAI translation API, that's roughly 800 tokens per language.
       Without cache:
       Initial translation = P * L * 800 tokens.
       At an average blended prompt/completion cost of $0.005 per 1,000 tokens:
       Initial Cost = P * L * 0.004
       Ongoing edits = P * U * 0.1 (10% of pages edited monthly) * L * 800 tokens * 0.005.
       Monthly operational cost model:
       No Cache = (P * L * 0.04) + (U * P * 0.05 * L * 0.004)
       With Cache (TeknoTok translates only what changed, saving ~88% on initial and ~92% on edits):
       With Cache = No Cache * 0.11
    */
    
    const initialNoCache = P * L * 0.05;
    const monthlyUpdatesNoCache = U * (P * 0.08) * L * 0.004;
    const totalNoCache = initialNoCache + monthlyUpdatesNoCache;
    
    // 88% cache hit efficiency for redundant layout structures
    const totalWithCache = totalNoCache * 0.12; 
    
    // Format to 2 decimal places
    costNoCache.textContent = `$${totalNoCache.toFixed(2)}`;
    costWithCache.textContent = `$${totalWithCache.toFixed(2)}`;
  }
  
  // Attach listeners
  postsSlider.addEventListener('input', calculate);
  languagesSlider.addEventListener('input', calculate);
  updatesSlider.addEventListener('input', calculate);
  
  // Initial run
  calculate();
}

/* --- License Domain Registration Dialog Handling --- */
document.addEventListener('DOMContentLoaded', () => {
  const dialog = document.getElementById('domain-dialog');
  const domainForm = document.getElementById('domain-form');
  const domainInput = document.getElementById('modal-domain-input');
  const errorSpan = document.getElementById('modal-domain-error');
  
  if (!dialog || !domainForm || !domainInput) return;

  let activeCheckoutUrl = '';

  // Intercept all add-to-cart clicks
  const purchaseLinks = document.querySelectorAll('a[href*="add-to-cart="]');
  purchaseLinks.forEach(link => {
    link.addEventListener('click', (e) => {
      e.preventDefault();
      activeCheckoutUrl = link.getAttribute('href');
      
      // Clear errors and input before showing modal
      domainInput.value = '';
      if (errorSpan) errorSpan.style.display = 'none';
      
      dialog.showModal();
    });
  });

  // Handle dialog form submission
  domainForm.addEventListener('submit', (e) => {
    e.preventDefault();
    const rawValue = domainInput.value.trim();

    if (validateDomainName(rawValue)) {
      if (errorSpan) errorSpan.style.display = 'none';
      dialog.close();

      // Normalize domain name to host format
      const normalizedDomain = rawValue.replace(/^(?:https?:\/\/)?(?:www\.)?/i, '').split('/')[0];
      
      // Build destination URL by appending license_domain parameter
      const separator = activeCheckoutUrl.includes('?') ? '&' : '?';
      const checkoutUrl = `${activeCheckoutUrl}${separator}license_domain=${encodeURIComponent(normalizedDomain)}`;
      
      window.location.href = checkoutUrl;
    } else {
      if (errorSpan) {
        errorSpan.textContent = 'Please enter a valid website domain name (e.g., mysite.com).';
        errorSpan.style.display = 'block';
      }
      domainInput.focus();
    }
  });

  // Fallback for browsers (like Safari) without native closedby (light-dismiss) support
  if (!('closedBy' in HTMLDialogElement.prototype)) {
    dialog.addEventListener('click', (event) => {
      if (event.target !== dialog) return;
      const rect = dialog.getBoundingClientRect();
      const isDialogContent = (
        rect.top <= event.clientY &&
        event.clientY <= rect.top + rect.height &&
        rect.left <= event.clientX &&
        event.clientX <= rect.left + rect.width
      );
      if (isDialogContent) return;
      dialog.close();
    });
  }
});

/**
 * Validates a domain name format.
 * @param {string} domain 
 * @returns {boolean}
 */
function validateDomainName(domain) {
  const normalized = domain.replace(/^(?:https?:\/\/)?(?:www\.)?/i, '').split('/')[0];
  const domainRegex = /^[a-zA-Z0-9][a-zA-Z0-9-]{0,61}[a-zA-Z0-9](?:\.[a-zA-Z]{2,})+$/;
  return domainRegex.test(normalized);
}

