const translations = {
    en: {
        dashboard: "Dashboard",
        overview: "Overview",
        service_records: "Service Records",
        repairs: "Repairs",
        fuel: "Fuel",
        taxes: "Taxes",
        notes: "Notes",
        reminders: "Reminders",
        settings: "Settings",
        logout: "Logout",
        toggle_theme: "Toggle Theme",
        your_garage: "Your Garage",
        add_vehicle: "Add Vehicle",
        add_fuel_record: "Add Fuel Record",
        add_service_record: "Add Service Record",
        add_repair: "Add Repair",
        add_tax_record: "Add Tax Record",
        add_note: "Add Note",
        add_reminder: "Add Reminder",
        export_csv: "Export CSV",
        export_all_data: "Export All Data",
        back_to_vehicle: "Back to Vehicle",
        date: "Date",
        odometer: "Odometer",
        description: "Description",
        category: "Category",
        cost: "Cost",
        notes: "Notes",
        attachment: "Attachment",
        download: "Download",
        fuel_amount: "Fuel Amount",
        distance: "Distance",
        economy: "Economy",
        total_fuel_cost: "Total Fuel Cost",
        average_fuel_economy: "Average Fuel Economy",
        recurring: "Recurring",
        type: "Type",
        amount: "Amount",
        save: "Save All Changes",
        cancel: "Cancel",
        edit: "Edit",
        delete: "Delete",
        add_record: "Add Record",
        update: "Update",
        create_backup: "Create Backup",
        restore_backup: "Restore Backup",
        language: "Language",
        select_language: "Select Language",
        save_language: "Save Language",
        measurement_system: "Measurement System",
        currency: "Currency",
        user_management: "User Management",
        change_password: "Change Password",
        current_password: "Current Password",
        new_password: "New Password",
        confirm_password: "Confirm New Password",
        year: "Year",
        make: "Make",
        model: "Model",
        vin: "VIN",
        license_plate: "Registration Number",
        vehicle_photo: "Vehicle Photo",
        edit_vehicle: "Edit Vehicle",
        delete_vehicle: "Delete Vehicle",
        last_odometer_reading: "Last Odometer Reading",
        total_distance_traveled: "Total Distance Travelled",
        total_cost: "Total Cost",
        fuel_cost: "Fuel Cost",
        service_cost: "Service Cost",
        repairs_cost: "Repairs Cost",
        taxes_cost: "Taxes Cost",
        upgrades_cost: "Upgrades Cost",
        recent_service_records: "Recent Service Records",
        recent_fuel_records: "Recent Fuel Records",
        active_reminders: "Active Reminders",
        no_active_reminders: "No active reminders",
        urgency: "Urgency",
        due_date: "Due Date",
        due_odometer: "Due Odometer",
        registration: "Registration",
        license: "Licence",
        property_tax: "Road Tax",
        insurance: "Insurance",
        inspection: "MOT",
        other: "Other",
        maintenance: "Maintenance",
        repair: "Repair",
        upgrade: "Upgrade",
        tax: "Tax",
        note: "Note",
        monthly: "Monthly",
        quarterly: "Quarterly",
        yearly: "Yearly",
        metric: "Metric (km, litres)",
        imperial: "Imperial (miles, gallons)",
        us_dollar: "US Dollar (USD)",
        british_pound: "British Pound (GBP)",
        romanian_leu: "Romanian Leu (RON)",
        euro: "Euro (EUR)",
        supported_files: "Supported: PDF, Images, Text, Word, Excel",
        no_file_selected: "No file selected",
        upload_failed: "Upload failed",
        save_successful: "Saved successfully",
        delete_confirmation: "Are you sure you want to delete this?",
        title: "Title",
        content: "Content",
        optional: "Optional",
        mileage: "Mileage",
        litres: "Litres",
        gallons: "Gallons",
        petrol: "Petrol",
        diesel: "Diesel",
        backup_restore_title: "Backup & Restore",
        backup_restore_desc: "Create a complete backup of all your data or restore from a previous backup.",
        units_currency: "Units & Currency",
        manage_account: "Manage your account settings and password.",
        app_info: "Application Info",
        version: "Version",
        database: "Database",
        current_user: "Current User",
        save_units: "Save Settings"
    },
    ro: {
        dashboard: "Tablou de bord",
        overview: "Prezentare generala",
        service_records: "Inregistrari service",
        repairs: "Reparatii",
        fuel: "Combustibil",
        taxes: "Taxe",
        notes: "Notite",
        reminders: "Memento-uri",
        settings: "Setari",
        logout: "Deconectare",
        toggle_theme: "Schimba tema",
        your_garage: "Garajul tau",
        add_vehicle: "Adauga vehicul",
        add_fuel_record: "Adauga alimentare",
        add_service_record: "Adauga service",
        add_repair: "Adauga reparatie",
        add_tax_record: "Adauga taxa",
        add_note: "Adauga notita",
        add_reminder: "Adauga memento",
        export_csv: "Exporta CSV",
        export_all_data: "Exporta toate datele",
        back_to_vehicle: "Inapoi la vehicul",
        date: "Data",
        odometer: "Kilometraj",
        description: "Descriere",
        category: "Categorie",
        cost: "Cost",
        notes: "Notite",
        attachment: "Atasament",
        download: "Descarca",
        fuel_amount: "Cantitate combustibil",
        distance: "Distanta",
        economy: "Consum",
        total_fuel_cost: "Cost total combustibil",
        average_fuel_economy: "Consum mediu",
        recurring: "Recurent",
        type: "Tip",
        amount: "Suma",
        save: "Salveaza toate modificarile",
        cancel: "Anuleaza",
        edit: "Editeaza",
        delete: "Sterge",
        add_record: "Adauga inregistrare",
        update: "Actualizeaza",
        create_backup: "Creeaza backup",
        restore_backup: "Restaureaza backup",
        language: "Limba",
        select_language: "Selecteaza limba",
        save_language: "Salveaza limba",
        measurement_system: "Sistem de masura",
        currency: "Moneda",
        user_management: "Gestionare utilizator",
        change_password: "Schimba parola",
        current_password: "Parola curenta",
        new_password: "Parola noua",
        confirm_password: "Confirma parola noua",
        year: "An",
        make: "Marca",
        model: "Model",
        vin: "VIN",
        license_plate: "Numar inmatriculare",
        vehicle_photo: "Fotografie vehicul",
        edit_vehicle: "Editeaza vehicul",
        delete_vehicle: "Sterge vehicul",
        last_odometer_reading: "Ultima citire kilometraj",
        total_distance_traveled: "Distanta totala parcursa",
        total_cost: "Cost total",
        fuel_cost: "Cost combustibil",
        service_cost: "Cost service",
        repairs_cost: "Cost reparatii",
        taxes_cost: "Cost taxe",
        upgrades_cost: "Cost imbunatatiri",
        recent_service_records: "Inregistrari service recente",
        recent_fuel_records: "Alimentari recente",
        active_reminders: "Memento-uri active",
        no_active_reminders: "Niciun memento activ",
        urgency: "Urgenta",
        due_date: "Data scadenta",
        due_odometer: "Kilometraj scadent",
        registration: "Inmatriculare",
        license: "Licenta",
        property_tax: "Taxa proprietate",
        insurance: "Asigurare",
        inspection: "Inspectie tehnica",
        other: "Altele",
        maintenance: "Intretinere",
        repair: "Reparatie",
        upgrade: "Imbunatatire",
        tax: "Taxa",
        note: "Notita",
        monthly: "Lunar",
        quarterly: "Trimestrial",
        yearly: "Anual",
        metric: "Metric (km, litri)",
        imperial: "Imperial (mile, galoane)",
        us_dollar: "Dolar american (USD)",
        british_pound: "Lira sterlina (GBP)",
        romanian_leu: "Leu romanesc (RON)",
        euro: "Euro (EUR)",
        supported_files: "Suportat: PDF, Imagini, Text, Word, Excel",
        no_file_selected: "Niciun fisier selectat",
        upload_failed: "Incarcare esuata",
        save_successful: "Salvat cu succes",
        delete_confirmation: "Sigur doriti sa stergeti?",
        title: "Titlu",
        content: "Continut",
        optional: "Optional",
        mileage: "Kilometraj",
        litres: "Litri",
        gallons: "Galoane",
        petrol: "Benzina",
        diesel: "Motorina",
        backup_restore_title: "Backup & Restaurare",
        backup_restore_desc: "Creaza un backup complet al datelor tale sau restaureaza dintr-un backup anterior.",
        units_currency: "Unitati & Moneda",
        manage_account: "Gestioneaza setarile contului si parola.",
        app_info: "Informatii aplicatie",
        version: "Versiune",
        database: "Baza de date",
        current_user: "Utilizator curent",
        save_units: "Salveaza setari"
    }
};

function getTranslation(key, lang = null) {
    if (!lang) {
        const settings = JSON.parse(localStorage.getItem('userSettings') || '{"language":"en"}');
        lang = settings.language || 'en';
    }
    return translations[lang]?.[key] || translations['en'][key] || key;
}

function translatePage() {
    const settings = JSON.parse(localStorage.getItem('userSettings') || '{"language":"en"}');
    const lang = settings.language || 'en';
    
    document.querySelectorAll('[data-translate]').forEach(element => {
        const key = element.getAttribute('data-translate');
        const translation = getTranslation(key, lang);
        
        if (element.tagName === 'INPUT' && (element.type === 'button' || element.type === 'submit')) {
            element.value = translation;
        } else if (element.tagName === 'INPUT' || element.tagName === 'TEXTAREA') {
            element.placeholder = translation;
        } else if (element.tagName === 'OPTION') {
            element.textContent = translation;
        } else {
            element.textContent = translation;
        }
    });
    
    document.querySelectorAll('label[data-translate]').forEach(label => {
        const key = label.getAttribute('data-translate');
        const translation = getTranslation(key, lang);
        
        const checkbox = label.querySelector('input[type="checkbox"]');
        if (checkbox) {
            label.childNodes.forEach(node => {
                if (node.nodeType === 3) {
                    node.textContent = translation;
                }
            });
        }
    });
}

document.addEventListener('DOMContentLoaded', () => {
    setTimeout(() => {
        translatePage();
    }, 100);
});
