/* ============================================
   APP.JS - Fixed Version
   Issues Fixed:
   1. Changed overlay class from 'active' to 'open' for CSS consistency
   2. Added touch event support for mobile
   3. Improved sidebar toggle handling
   4. Fixed event propagation issues
   ============================================ */

document.addEventListener('DOMContentLoaded', function() {
    initSidebar();
    initModals();
    initForms();
    initAnimations();
    initMobileTouch();
});

function initSidebar() {
    const menuToggle = document.querySelector('.menu-toggle');
    const sidebar = document.querySelector('.sidebar');
    
    // Check if overlay already exists (some pages create it in HTML)
    let overlay = document.querySelector('.sidebar-overlay');
    if (!overlay) {
        overlay = document.createElement('div');
        overlay.className = 'sidebar-overlay';
        document.body.appendChild(overlay);
    }
    
    if (menuToggle) {
        menuToggle.addEventListener('click', function(e) {
            e.preventDefault();
            e.stopPropagation();
            if (sidebar) sidebar.classList.toggle('open');
            if (overlay) overlay.classList.toggle('open');
        });
        
        // Add touch support
        menuToggle.addEventListener('touchend', function(e) {
            e.preventDefault();
            if (sidebar) sidebar.classList.toggle('open');
            if (overlay) overlay.classList.toggle('open');
        }, { passive: false });
    }
    
    if (overlay) {
        overlay.addEventListener('click', function(e) {
            e.preventDefault();
            closeSidebar();
        });
        
        overlay.addEventListener('touchend', function(e) {
            e.preventDefault();
            closeSidebar();
        }, { passive: false });
    }
}

function closeSidebar() {
    const sidebar = document.querySelector('.sidebar');
    const staffSidebar = document.querySelector('.staff-sidebar');
    const overlay = document.querySelector('.sidebar-overlay');
    
    if (sidebar) sidebar.classList.remove('open');
    if (staffSidebar) staffSidebar.classList.remove('open');
    if (overlay) {
        overlay.classList.remove('open');
        overlay.classList.remove('active');
    }
}

function toggleSidebar() {
  const sidebar = document.querySelector('.sidebar');
  const overlay = document.querySelector('.sidebar-overlay');

  if (!sidebar || !overlay) return;

  sidebar.classList.toggle('open');
  overlay.classList.toggle('active');
}


function initModals() {
    document.querySelectorAll('[data-modal]').forEach(trigger => {
        trigger.addEventListener('click', function(e) {
            e.preventDefault();
            const modalId = this.getAttribute('data-modal');
            openModal(modalId);
        });
    });
    
    document.querySelectorAll('.modal-close, .modal-cancel').forEach(btn => {
        btn.addEventListener('click', function(e) {
            e.preventDefault();
            const modal = this.closest('.modal-overlay');
            if (modal) closeModal(modal.id);
        });
    });
    
    document.querySelectorAll('.modal-overlay').forEach(overlay => {
        overlay.addEventListener('click', function(e) {
            if (e.target === this) {
                closeModal(this.id);
            }
        });
    });
}

function openModal(modalId) {
    const modal = document.getElementById(modalId);
    if (modal) {
        modal.classList.add('active');
        document.body.style.overflow = 'hidden';
    }
}

function closeModal(modalId) {
    const modal = document.getElementById(modalId);
    if (modal) {
        modal.classList.remove('active');
        document.body.style.overflow = '';
        const form = modal.querySelector('form');
        if (form) form.reset();
    }
}

function initForms() {
    document.querySelectorAll('.form-input').forEach(input => {
        input.addEventListener('focus', function() {
            this.parentElement.classList.add('focused');
        });
        
        input.addEventListener('blur', function() {
            this.parentElement.classList.remove('focused');
        });
    });
}

function initAnimations() {
    const observer = new IntersectionObserver((entries) => {
        entries.forEach(entry => {
            if (entry.isIntersecting) {
                entry.target.classList.add('animate-in');
            }
        });
    }, { threshold: 0.1 });
    
    document.querySelectorAll('.animate-on-scroll').forEach(el => {
        observer.observe(el);
    });
    
    document.querySelectorAll('.ripple').forEach(element => {
        element.addEventListener('click', function(e) {
            const rect = this.getBoundingClientRect();
            const x = e.clientX - rect.left;
            const y = e.clientY - rect.top;
            
            const ripple = document.createElement('span');
            ripple.className = 'ripple-effect';
            ripple.style.left = x + 'px';
            ripple.style.top = y + 'px';
            
            this.appendChild(ripple);
            
            setTimeout(() => ripple.remove(), 600);
        });
    });
}

// FIXED: Initialize mobile touch handling
function initMobileTouch() {
    // Ensure all action buttons respond to touch
    document.querySelectorAll('.action-btn, .btn, button, a[href^="tel:"]').forEach(btn => {
        // Remove any existing touchend handlers and add new ones
        btn.style.touchAction = 'manipulation';
        btn.style.webkitTapHighlightColor = 'transparent';
    });
    
    // Fix tel: links for mobile
    document.querySelectorAll('a[href^="tel:"]').forEach(link => {
        link.addEventListener('click', function(e) {
            // Don't prevent default - let the tel: link work
            e.stopPropagation();
        });
    });
}

function showToast(message, type = 'info') {
    const container = document.querySelector('.toast-container') || createToastContainer();
    
    const toast = document.createElement('div');
    toast.className = `toast ${type}`;
    toast.innerHTML = `
        <span>${message}</span>
        <button onclick="this.parentElement.remove()">&times;</button>
    `;
    
    container.appendChild(toast);
    
    setTimeout(() => {
        toast.style.animation = 'toastSlideIn 0.3s ease reverse';
        setTimeout(() => toast.remove(), 300);
    }, 4000);
}

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

function showLoading() {
    const overlay = document.createElement('div');
    overlay.className = 'loading-overlay';
    overlay.id = 'loading-overlay';
    overlay.innerHTML = '<div class="loading-spinner"></div>';
    document.body.appendChild(overlay);
}

function hideLoading() {
    const overlay = document.getElementById('loading-overlay');
    if (overlay) overlay.remove();
}

function formatDate(dateString) {
    const date = new Date(dateString);
    return date.toLocaleDateString('en-GB', {
        day: '2-digit',
        month: 'short',
        year: 'numeric'
    });
}

function formatCurrency(amount) {
    return new Intl.NumberFormat('en-IN', {
        style: 'currency',
        currency: 'INR'
    }).format(amount);
}

function debounce(func, wait) {
    let timeout;
    return function executedFunction(...args) {
        const later = () => {
            clearTimeout(timeout);
            func(...args);
        };
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
    };
}

function confirmAction(message) {
    return new Promise((resolve) => {
        if (confirm(message)) {
            resolve(true);
        } else {
            resolve(false);
        }
    });
}

// FIXED: WhatsApp redirect helper for mobile compatibility
function openWhatsApp(phone, message) {
    // Clean phone number
    let cleanPhone = phone.replace(/[^0-9+]/g, '');
    
    // Ensure phone starts with country code
    if (!cleanPhone.startsWith('+')) {
        // Assume India if no country code
        if (cleanPhone.startsWith('0')) {
            cleanPhone = '+91' + cleanPhone.substring(1);
        } else if (!cleanPhone.startsWith('91')) {
            cleanPhone = '+91' + cleanPhone;
        } else {
            cleanPhone = '+' + cleanPhone;
        }
    }
    
    // Encode message
    const encodedMessage = encodeURIComponent(message || '');
    
    // Use wa.me for mobile compatibility (works on both mobile and desktop)
    const whatsappUrl = `https://wa.me/${cleanPhone.replace('+', '')}${encodedMessage ? '?text=' + encodedMessage : ''}`;
    
    // Use window.location for better mobile app opening
    // On mobile, this will open WhatsApp app directly
    // On desktop, it will open WhatsApp Web
    window.location.href = whatsappUrl;
}

// FIXED: Call helper for mobile compatibility
function makeCall(phone) {
    let cleanPhone = phone.replace(/[^0-9+]/g, '');
    window.location.href = 'tel:' + cleanPhone;
}


/* =========================
   GLOBAL SIDEBAR TOGGLE
========================= */

document.addEventListener('DOMContentLoaded', function () {

    const sidebar = document.querySelector('.sidebar');
    const overlay = document.querySelector('.sidebar-overlay');
    const menuBtn = document.querySelector('.menu-toggle');

    function toggleSidebar() {
        if (!sidebar || !overlay) return;

        sidebar.classList.toggle('open');
        overlay.classList.toggle('open');
    }

    // Bind menu button
    if (menuBtn) {
        menuBtn.addEventListener('click', toggleSidebar);
    }

    // Bind overlay click
    if (overlay) {
        overlay.addEventListener('click', toggleSidebar);
    }

});

// ===============================
// MOBILE SIDEBAR TOGGLE (COMPANY)
// ===============================

function toggleSidebar() {
  document.body.classList.toggle('sidebar-open');

  const sidebar = document.querySelector('.sidebar');
  const overlay = document.querySelector('.sidebar-overlay');

  if (sidebar) sidebar.classList.toggle('open');
  if (overlay) overlay.classList.toggle('active');
}

document.addEventListener('DOMContentLoaded', function () {
  const hamburger = document.querySelector('.hamburger');
  const overlay = document.querySelector('.sidebar-overlay');

  if (hamburger) {
    hamburger.addEventListener('click', function (e) {
      e.preventDefault();
      e.stopPropagation();
      toggleSidebar();
    });
  }

  if (overlay) {
    overlay.addEventListener('click', function () {
      toggleSidebar();
    });
  }
});
