// API Configuration
// For production: https://the.shayantraders.com/api
// For local development: http://localhost:3000/api
const API_BASE_URL = (() => {
    // If opened from file:// or localhost, use localhost
    if (window.location.protocol === 'file:' ||
        window.location.hostname === 'localhost' ||
        window.location.hostname === '127.0.0.1') {
        return 'http://localhost:3000/api';
    }
    // Production - shayantraders.com calls the.shayantraders.com
    if (window.location.hostname === 'shayantraders.com' ||
        window.location.hostname === 'www.shayantraders.com') {
        return 'https://the.shayantraders.com/api';
    }
    // Default - use current origin
    return window.location.origin + '/api';
})();

// Utility Functions
const formatCurrency = (amount) => {
    return `PKR ${parseFloat(amount).toLocaleString('en-PK', { minimumFractionDigits: 0, maximumFractionDigits: 2 })}`;
};

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

const getCurrentDate = () => {
    const date = new Date();
    return date.toISOString().split('T')[0];
};

const getCurrentDateTime = () => {
    const date = new Date();
    return date.toLocaleString('en-PK', {
        weekday: 'long',
        year: 'numeric',
        month: 'long',
        day: 'numeric',
        hour: '2-digit',
        minute: '2-digit'
    });
};

// API Helper Functions
const apiGet = async (endpoint) => {
    try {
        const response = await fetch(`${API_BASE_URL}${endpoint}`);
        if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
        return await response.json();
    } catch (error) {
        console.error('API GET Error:', error);
        throw error;
    }
};

const apiPost = async (endpoint, data) => {
    try {
        const response = await fetch(`${API_BASE_URL}${endpoint}`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(data),
        });
        if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
        return await response.json();
    } catch (error) {
        console.error('API POST Error:', error);
        throw error;
    }
};

const apiPut = async (endpoint, data) => {
    try {
        const response = await fetch(`${API_BASE_URL}${endpoint}`, {
            method: 'PUT',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(data),
        });
        if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
        return await response.json();
    } catch (error) {
        console.error('API PUT Error:', error);
        throw error;
    }
};

const apiDelete = async (endpoint) => {
    try {
        const response = await fetch(`${API_BASE_URL}${endpoint}`, {
            method: 'DELETE',
        });
        if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
        return await response.json();
    } catch (error) {
        console.error('API DELETE Error:', error);
        throw error;
    }
};

// Show notification
const showNotification = (message, type = 'success') => {
    const notification = document.createElement('div');
    notification.className = `notification notification-${type}`;
    notification.textContent = message;
    notification.style.cssText = `
        position: fixed;
        top: 20px;
        right: 20px;
        padding: 1rem 1.5rem;
        background: ${type === 'success' ? 'var(--success)' : 'var(--danger)'};
        color: white;
        border-radius: var(--radius-md);
        box-shadow: var(--shadow-lg);
        z-index: 9999;
        animation: slideIn 0.3s ease;
    `;

    document.body.appendChild(notification);

    setTimeout(() => {
        notification.style.animation = 'slideOut 0.3s ease';
        setTimeout(() => notification.remove(), 300);
    }, 3000);
};

// Add animation styles
const style = document.createElement('style');
style.textContent = `
    @keyframes slideIn {
        from {
            transform: translateX(400px);
            opacity: 0;
        }
        to {
            transform: translateX(0);
            opacity: 1;
        }
    }
    
    @keyframes slideOut {
        from {
            transform: translateX(0);
            opacity: 1;
        }
        to {
            transform: translateX(400px);
            opacity: 0;
        }
    }
`;
document.head.appendChild(style);

// Set active navigation item
const setActiveNav = () => {
    const currentPath = window.location.pathname;
    const navItems = document.querySelectorAll('.nav-item');

    navItems.forEach(item => {
        const href = item.getAttribute('href');
        if (currentPath.includes(href) || (currentPath.endsWith('/') && href === 'index.html')) {
            item.classList.add('active');
        } else {
            item.classList.remove('active');
        }
    });
};

// Authentication functions
// Authentication functions
const checkAuth = async () => {
    // Skip check if we are on the login page
    if (window.location.href.includes('login.html')) return;

    const isLoggedIn = localStorage.getItem('isLoggedIn') === 'true';
    const username = localStorage.getItem('user');

    if (!isLoggedIn || !username) {
        redirectToLogin();
        return;
    }

    try {
        // Verify status with backend
        const response = await fetch(`${API_BASE_URL}/users/status/${username}`);
        if (response.ok) {
            const data = await response.json();
            if (data.status === 'Disabled') {
                alert('Your account has been disabled. Please contact the administrator.');
                logout();
                return;
            }
            // Update local storage to match server
            localStorage.setItem('status', data.status);
        } else if (response.status === 404) {
            // User deleted?
            logout();
            return;
        }
    } catch (error) {
        console.error('Auth verification failed:', error);
        // Fallback to local storage check if offline/error
        const localStatus = localStorage.getItem('status');
        if (localStatus === 'Disabled') {
            alert('Your account has been disabled. Please contact the administrator.');
            logout();
            return;
        }
    }

    const userRole = localStorage.getItem('role');
    const userPermsStr = localStorage.getItem('permissions');

    // Permission Check logic continues...

    // Permission Check
    const path = window.location.pathname;
    const pageName = path.split('/').pop();

    // If we are on index.html (dashboard), check permissions
    // Note: login check sets 'dashboard.html' or 'index.html'? 
    // Usually 'dashboard.html' permission covers root index.html

    let requiredPerm = pageName;
    if (pageName === 'index.html' || pageName === '') requiredPerm = 'dashboard.html';

    // Parse permissions
    let permissions = [];
    try {
        permissions = JSON.parse(userPermsStr) || [];
    } catch (e) {
        permissions = [];
    }

    // Admin has full access
    if (userRole === 'Admin') return; // Access granted

    // Check specific page permission
    if (!permissions.includes(requiredPerm) && !permissions.includes('*')) {
        // Access Denied
        alert('Access Denied. You do not have permission to view this page.');
        // If trying to access dashboard without permission, redirect to login
        if (requiredPerm === 'dashboard.html') {
            logout(); // This will clear local storage and redirect to login
        } else {
            // For other pages, redirect to dashboard if user has access, otherwise to login
            if (permissions.includes('dashboard.html') || permissions.includes('*')) {
                window.location.href = path.includes('/pages/') ? '../index.html' : 'index.html';
            } else {
                logout(); // User doesn't have dashboard access either, so redirect to login
            }
        }
    }
};

const redirectToLogin = () => {
    const path = window.location.pathname;
    if (path.includes('/pages/')) {
        window.location.href = '../login.html';
    } else {
        if (!path.endsWith('login.html')) {
            window.location.href = 'login.html';
        }
    }
};

const logout = () => {
    localStorage.removeItem('isLoggedIn');
    localStorage.removeItem('user');
    localStorage.removeItem('role');
    localStorage.removeItem('permissions');
    localStorage.removeItem('status');

    // Redirect to login
    const path = window.location.pathname;
    if (path.includes('/pages/')) {
        window.location.href = '../login.html';
    } else {
        window.location.href = 'login.html';
    }
};

// Initialize on page load
document.addEventListener('DOMContentLoaded', () => {
    checkAuth(); // Check authentication first
    setActiveNav();
    updateSidebarVisibility(); // Update sidebar based on permissions

    // Update date display if element exists
    const dateDisplay = document.getElementById('currentDate');
    if (dateDisplay) {
        dateDisplay.textContent = getCurrentDateTime();
    }
    
    // Initialize password toggles
    app.initPasswordToggles();
});

// Update sidebar visibility based on user permissions
const updateSidebarVisibility = () => {
    const userRole = localStorage.getItem('role');
    const userPermsStr = localStorage.getItem('permissions');

    // Parse permissions
    let permissions = [];
    try {
        permissions = JSON.parse(userPermsStr) || [];
    } catch (e) {
        permissions = [];
    }

    // Admin has full access - show everything
    if (userRole === 'Admin' || permissions.includes('*')) {
        showAllSidebarItems();
        return;
    }

    // Map of page links to their permission requirements
    const pagePermissions = {
        'dashboard': 'dashboard.html',
        'inventory': 'inventory.html',
        'billing': 'billing.html',
        'invoices': 'invoices.html',
        'returns': 'returns.html',
        'damage_items': 'damage_items.html',
        'credit': 'credit.html',
        'expenses': 'expenses.html',
        'reports': 'reports.html',
        'admin': 'admin.html'
    };

    // Get all navigation links
    const navItems = document.querySelectorAll('.nav-item');

    navItems.forEach(item => {
        const href = item.getAttribute('href');
        if (!href || href === '#') return; // Skip logout and other non-page links

        // Extract page name from href
        const pageName = href.split('/').pop();

        // Check if user has permission for this page
        if (pageName === 'index.html' || pageName === '../index.html') {
            // Dashboard access requires explicit 'dashboard.html' permission
            if (permissions.includes('dashboard.html') || permissions.includes('*')) {
                item.style.display = 'flex';
            } else {
                item.style.display = 'none';
            }
            return;
        }

        // Check if user has permission for this page
        if (permissions.includes(pageName) || permissions.includes('*')) {
            item.style.display = 'flex';
        } else {
            item.style.display = 'none';
        }
    });

    // Handle special cases with IDs
    const adminLink = document.getElementById('adminLink');
    const reportsLink = document.getElementById('reportsLink');

    if (adminLink) {
        adminLink.style.display = permissions.includes('admin.html') || permissions.includes('*') ? 'flex' : 'none';
    }

    if (reportsLink) {
        reportsLink.style.display = permissions.includes('reports.html') || permissions.includes('*') ? 'flex' : 'none';
    }
};

// Helper function to show all sidebar items (for Admin)
const showAllSidebarItems = () => {
    const navItems = document.querySelectorAll('.nav-item');
    navItems.forEach(item => {
        item.style.display = 'flex';
    });
};

// Password toggle functionality
const togglePasswordVisibility = (inputId) => {
    const passwordInput = document.getElementById(inputId);
    const toggleButton = document.querySelector(`#${inputId}-toggle`);
    
    if (passwordInput.type === 'password') {
        passwordInput.type = 'text';
        if (toggleButton) {
            toggleButton.innerHTML = `
                <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-eye-off">
                    <path d="M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19m-5.77 3.23a12.86 12.86 0 0 1-5.65-5.69M1 1l22 22"></path>
                </svg>`;
        }
    } else {
        passwordInput.type = 'password';
        if (toggleButton) {
            toggleButton.innerHTML = `
                <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-eye">
                    <path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"></path>
                    <circle cx="12" cy="12" r="3"></circle>
                </svg>`;
        }
    }
};

// Function to add password toggle to an input field
const addPasswordToggle = (inputId) => {
    const input = document.getElementById(inputId);
    if (!input) return;
    
    // Check if toggle is already added
    if (input.classList.contains('password-input')) return;
    
    // Add CSS classes
    input.classList.add('password-input');
    
    // Create wrapper div
    const wrapper = document.createElement('div');
    wrapper.className = 'password-toggle-wrapper';
    
    // Move the input inside the wrapper
    input.parentNode.insertBefore(wrapper, input);
    wrapper.appendChild(input);
    
    // Create toggle button
    const toggleButton = document.createElement('button');
    toggleButton.type = 'button';
    toggleButton.id = `${inputId}-toggle`;
    toggleButton.className = 'password-toggle-btn';
    toggleButton.innerHTML = `
        <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-eye">
            <path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"></path>
            <circle cx="12" cy="12" r="3"></circle>
        </svg>`;
    toggleButton.onclick = () => togglePasswordVisibility(inputId);
    
    // Add toggle button to wrapper
    wrapper.appendChild(toggleButton);
};

// Initialize password toggles when DOM is loaded
const initPasswordToggles = () => {
    // Add toggles to all password inputs on the page
    const passwordInputs = document.querySelectorAll('input[type="password"]');
    passwordInputs.forEach(input => {
        if (input.id) {
            addPasswordToggle(input.id);
        }
    });
};

// Export for use in other scripts
window.app = {
    API_BASE_URL,
    formatCurrency,
    formatDate,
    getCurrentDate,
    getCurrentDateTime,
    apiGet,
    apiPost,
    apiPut,
    apiDelete,
    showNotification,
    logout,
    togglePasswordVisibility,
    addPasswordToggle,
    initPasswordToggles
};
