const togglePassword = document.getElementById('togglePassword');
const password = document.getElementById('password');
const form = document.getElementById('loginForm');
const themeToggleBtn = document.getElementById('themeToggleBtn');
const languageToggleBtn = document.getElementById('languageToggleBtn');
const htmlTag = document.getElementById('htmlTag');

const expiryDateText = document.getElementById('expiryDateText');
const remainingTime = document.getElementById('remainingTime');
const expiryNote = document.getElementById('expiryNote');

const expiryDate = new Date(window.posConfig.expiryDateTime).getTime();

let currentLanguage = localStorage.getItem('posLanguage') || 'en';
let currentTheme = localStorage.getItem('posTheme') || 'light';

function applyLanguage(lang) {
    currentLanguage = lang;
    localStorage.setItem('posLanguage', lang);

    document.querySelectorAll('[data-en]').forEach(el => {
        el.textContent = lang === 'ur' ? el.getAttribute('data-ur') : el.getAttribute('data-en');
    });

    document.querySelectorAll('[data-placeholder-en]').forEach(el => {
        el.placeholder = lang === 'ur'
            ? el.getAttribute('data-placeholder-ur')
            : el.getAttribute('data-placeholder-en');
    });

    if (lang === 'ur') {
        htmlTag.setAttribute('lang', 'ur');
        htmlTag.setAttribute('dir', 'rtl');
        languageToggleBtn.innerHTML = '<i class="bi bi-translate me-1"></i> English';
    } else {
        htmlTag.setAttribute('lang', 'en');
        htmlTag.setAttribute('dir', 'ltr');
        languageToggleBtn.innerHTML = '<i class="bi bi-translate me-1"></i> اردو';
    }

    updateExpiryCountdown();
}

function applyTheme(theme) {
    currentTheme = theme;
    localStorage.setItem('posTheme', theme);

    if (theme === 'dark') {
        document.body.classList.add('dark-mode');
        themeToggleBtn.innerHTML = '<i class="bi bi-sun-fill me-1"></i> Light Mode';
    } else {
        document.body.classList.remove('dark-mode');
        themeToggleBtn.innerHTML = '<i class="bi bi-moon-stars-fill me-1"></i> Dark Mode';
    }
}

function formatExpiryDate() {
    const date = new Date(expiryDate);

    if (currentLanguage === 'ur') {
        expiryDateText.textContent =
            date.getDate() + "-" +
            String(date.getMonth() + 1).padStart(2, '0') + "-" +
            date.getFullYear() + " " +
            String(date.getHours()).padStart(2, '0') + ":" +
            String(date.getMinutes()).padStart(2, '0');
    } else {
        expiryDateText.textContent = date.toLocaleString('en-GB', {
            day: '2-digit',
            month: 'short',
            year: 'numeric',
            hour: '2-digit',
            minute: '2-digit'
        });
    }
}

function updateExpiryCountdown() {
    formatExpiryDate();

    const now = new Date().getTime();
    const distance = expiryDate - now;

    if (distance <= 0) {
        remainingTime.textContent = currentLanguage === 'ur'
            ? 'مدت ختم ہو چکی ہے'
            : 'Expired';

        expiryNote.textContent = currentLanguage === 'ur'
            ? 'براہ کرم فوری تجدید کروائیں تاکہ سسٹم دوبارہ فعال ہو سکے۔'
            : 'Please renew now to restore uninterrupted system access.';
        return;
    }

    const days = Math.floor(distance / (1000 * 60 * 60 * 24));
    const hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
    const minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
    const seconds = Math.floor((distance % (1000 * 60)) / 1000);

    if (currentLanguage === 'ur') {
        remainingTime.textContent = `${days} دن ${hours} گھنٹے ${minutes} منٹ ${seconds} سیکنڈ`;
        expiryNote.textContent = days <= 7
            ? 'توجہ: آپ کی سروس جلد ختم ہونے والی ہے، وقت پر ریچارج کروائیں۔'
            : 'وقت پر تجدید کروائیں تاکہ استعمال میں کوئی رکاوٹ نہ آئے۔';
    } else {
        remainingTime.textContent = `${days}d ${hours}h ${minutes}m ${seconds}s`;
        expiryNote.textContent = days <= 7
            ? 'Attention: Your service is close to expiry. Please renew on time.'
            : 'Please renew before expiry to avoid any interruption in access.';
    }
}

applyLanguage(currentLanguage);
applyTheme(currentTheme);
updateExpiryCountdown();
setInterval(updateExpiryCountdown, 1000);

languageToggleBtn.addEventListener('click', function () {
    applyLanguage(currentLanguage === 'en' ? 'ur' : 'en');
});

themeToggleBtn.addEventListener('click', function () {
    applyTheme(currentTheme === 'light' ? 'dark' : 'light');
});

togglePassword.addEventListener('click', function () {
    const type = password.getAttribute('type') === 'password' ? 'text' : 'password';
    password.setAttribute('type', type);
    this.innerHTML = type === 'password'
        ? '<i class="bi bi-eye-fill"></i>'
        : '<i class="bi bi-eye-slash-fill"></i>';
});

form.addEventListener('submit', function (e) {
    const username = document.getElementById('username').value.trim();
    const pass = password.value.trim();

    if (username === '' || pass === '') {
        e.preventDefault();
        alert(currentLanguage === 'ur'
            ? 'براہ کرم تمام فیلڈز بھریں۔'
            : 'Please fill in all fields.');
    }
});