import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
import LanguageDetector from 'i18next-browser-languagedetector';

// English translations
const enTranslations = {
    common: {
        loading: 'Loading...',
        save: 'Save',
        cancel: 'Cancel',
        delete: 'Delete',
        edit: 'Edit',
        add: 'Add',
        search: 'Search',
        filter: 'Filter',
        export: 'Export',
        close: 'Close',
        confirm: 'Confirm',
        back: 'Back',
        next: 'Next',
        submit: 'Submit',
        yes: 'Yes',
        no: 'No',
        ok: 'OK',
        error: 'Error',
        success: 'Success',
        warning: 'Warning',
        info: 'Info',
        required: 'Required',
        optional: 'Optional',
        noData: 'No data available',
        selectAll: 'Select all',
        clearAll: 'Clear all',
    },
    nav: {
        dashboard: 'Dashboard',
        walkthrough: 'Walkthrough',
        ipm: 'IPM',
        tasks: 'Tasks',
        reports: 'Reports',
        inventory: 'Inventory',
        timeclock: 'Time Clock',
        rooms: 'Rooms',
        batches: 'Batches',
        quickActions: 'Quick Actions',
        layout: 'Layout Designer',
        visitors: 'Visitors',
        roles: 'Roles',
        settings: 'Settings',
        logout: 'Logout',
    },
    auth: {
        login: 'Login',
        logout: 'Logout',
        email: 'Email',
        password: 'Password',
        forgotPassword: 'Forgot password?',
        rememberMe: 'Remember me',
        loginFailed: 'Login failed. Please check your credentials.',
        sessionExpired: 'Your session has expired. Please login again.',
    },
    dashboard: {
        welcome: 'Welcome back',
        todaysTasks: "Today's Tasks",
        activeBatches: 'Active Batches',
        upcomingHarvests: 'Upcoming Harvests',
        recentActivity: 'Recent Activity',
        quickStats: 'Quick Stats',
        plantsTotal: 'Total Plants',
        roomsActive: 'Active Rooms',
    },
    batches: {
        title: 'Batches',
        createBatch: 'Create Batch',
        batchName: 'Batch Name',
        strain: 'Strain',
        stage: 'Stage',
        plantCount: 'Plant Count',
        startDate: 'Start Date',
        harvestDate: 'Harvest Date',
        status: 'Status',
        stages: {
            clone: 'Clone',
            veg: 'Vegetative',
            flower: 'Flowering',
            dry: 'Drying',
            cure: 'Curing',
            harvest: 'Harvested',
        },
    },
    tasks: {
        title: 'Tasks',
        createTask: 'Create Task',
        taskName: 'Task Name',
        assignee: 'Assignee',
        dueDate: 'Due Date',
        priority: 'Priority',
        status: 'Status',
        description: 'Description',
        priorities: {
            low: 'Low',
            medium: 'Medium',
            high: 'High',
            urgent: 'Urgent',
        },
        statuses: {
            pending: 'Pending',
            inProgress: 'In Progress',
            completed: 'Completed',
            cancelled: 'Cancelled',
        },
    },
    visitors: {
        title: 'Visitor Management',
        checkIn: 'Check In',
        checkOut: 'Check Out',
        onSite: 'On-Site',
        badge: 'Badge',
        purpose: 'Purpose of Visit',
        escort: 'Escort',
        company: 'Company',
        types: {
            visitor: 'Visitor',
            contractor: 'Contractor',
            inspector: 'Inspector',
            vendor: 'Vendor',
            delivery: 'Delivery',
        },
    },
    compliance: {
        title: 'Compliance',
        auditLog: 'Audit Log',
        documents: 'Documents',
        acknowledge: 'Acknowledge',
        acknowledged: 'Acknowledged',
        pending: 'Pending',
        sopLibrary: 'SOP Library',
        policies: 'Policies',
    },
    messaging: {
        announcements: 'Announcements',
        shiftNotes: 'Shift Notes',
        newAnnouncement: 'New Announcement',
        priority: {
            info: 'Info',
            warning: 'Warning',
            critical: 'Critical',
        },
    },
    settings: {
        title: 'Settings',
        profile: 'Profile',
        language: 'Language',
        theme: 'Theme',
        notifications: 'Notifications',
        accessibility: 'Accessibility',
        themes: {
            light: 'Light',
            dark: 'Dark',
            system: 'System',
        },
    },
    errors: {
        generic: 'Something went wrong. Please try again.',
        network: 'Network error. Please check your connection.',
        notFound: 'Page not found.',
        unauthorized: 'You are not authorized to perform this action.',
        validation: 'Please check your input and try again.',
    },
    time: {
        today: 'Today',
        yesterday: 'Yesterday',
        tomorrow: 'Tomorrow',
        thisWeek: 'This Week',
        lastWeek: 'Last Week',
        thisMonth: 'This Month',
        lastMonth: 'Last Month',
    },
};

// Spanish translations
const esTranslations = {
    common: {
        loading: 'Cargando...',
        save: 'Guardar',
        cancel: 'Cancelar',
        delete: 'Eliminar',
        edit: 'Editar',
        add: 'Agregar',
        search: 'Buscar',
        filter: 'Filtrar',
        export: 'Exportar',
        close: 'Cerrar',
        confirm: 'Confirmar',
        back: 'Atrás',
        next: 'Siguiente',
        submit: 'Enviar',
        yes: 'Sí',
        no: 'No',
        ok: 'OK',
        error: 'Error',
        success: 'Éxito',
        warning: 'Advertencia',
        info: 'Información',
        required: 'Requerido',
        optional: 'Opcional',
        noData: 'No hay datos disponibles',
        selectAll: 'Seleccionar todo',
        clearAll: 'Limpiar todo',
    },
    nav: {
        dashboard: 'Panel',
        walkthrough: 'Recorrido',
        ipm: 'MIP',
        tasks: 'Tareas',
        reports: 'Informes',
        inventory: 'Inventario',
        timeclock: 'Reloj de Tiempo',
        rooms: 'Cuartos',
        batches: 'Lotes',
        quickActions: 'Acciones Rápidas',
        layout: 'Diseñador de Plano',
        visitors: 'Visitantes',
        roles: 'Roles',
        settings: 'Configuración',
        logout: 'Cerrar Sesión',
    },
    auth: {
        login: 'Iniciar Sesión',
        logout: 'Cerrar Sesión',
        email: 'Correo Electrónico',
        password: 'Contraseña',
        forgotPassword: '¿Olvidaste tu contraseña?',
        rememberMe: 'Recuérdame',
        loginFailed: 'Error al iniciar sesión. Verifica tus credenciales.',
        sessionExpired: 'Tu sesión ha expirado. Por favor inicia sesión nuevamente.',
    },
    dashboard: {
        welcome: 'Bienvenido de nuevo',
        todaysTasks: 'Tareas de Hoy',
        activeBatches: 'Lotes Activos',
        upcomingHarvests: 'Próximas Cosechas',
        recentActivity: 'Actividad Reciente',
        quickStats: 'Estadísticas Rápidas',
        plantsTotal: 'Total de Plantas',
        roomsActive: 'Cuartos Activos',
    },
    batches: {
        title: 'Lotes',
        createBatch: 'Crear Lote',
        batchName: 'Nombre del Lote',
        strain: 'Cepa',
        stage: 'Etapa',
        plantCount: 'Cantidad de Plantas',
        startDate: 'Fecha de Inicio',
        harvestDate: 'Fecha de Cosecha',
        status: 'Estado',
        stages: {
            clone: 'Clon',
            veg: 'Vegetativo',
            flower: 'Floración',
            dry: 'Secado',
            cure: 'Curado',
            harvest: 'Cosechado',
        },
    },
    tasks: {
        title: 'Tareas',
        createTask: 'Crear Tarea',
        taskName: 'Nombre de Tarea',
        assignee: 'Asignado a',
        dueDate: 'Fecha Límite',
        priority: 'Prioridad',
        status: 'Estado',
        description: 'Descripción',
        priorities: {
            low: 'Baja',
            medium: 'Media',
            high: 'Alta',
            urgent: 'Urgente',
        },
        statuses: {
            pending: 'Pendiente',
            inProgress: 'En Progreso',
            completed: 'Completada',
            cancelled: 'Cancelada',
        },
    },
    visitors: {
        title: 'Gestión de Visitantes',
        checkIn: 'Registrar Entrada',
        checkOut: 'Registrar Salida',
        onSite: 'En el Sitio',
        badge: 'Gafete',
        purpose: 'Propósito de la Visita',
        escort: 'Escolta',
        company: 'Empresa',
        types: {
            visitor: 'Visitante',
            contractor: 'Contratista',
            inspector: 'Inspector',
            vendor: 'Proveedor',
            delivery: 'Entrega',
        },
    },
    compliance: {
        title: 'Cumplimiento',
        auditLog: 'Registro de Auditoría',
        documents: 'Documentos',
        acknowledge: 'Reconocer',
        acknowledged: 'Reconocido',
        pending: 'Pendiente',
        sopLibrary: 'Biblioteca de POE',
        policies: 'Políticas',
    },
    messaging: {
        announcements: 'Anuncios',
        shiftNotes: 'Notas de Turno',
        newAnnouncement: 'Nuevo Anuncio',
        priority: {
            info: 'Información',
            warning: 'Advertencia',
            critical: 'Crítico',
        },
    },
    settings: {
        title: 'Configuración',
        profile: 'Perfil',
        language: 'Idioma',
        theme: 'Tema',
        notifications: 'Notificaciones',
        accessibility: 'Accesibilidad',
        themes: {
            light: 'Claro',
            dark: 'Oscuro',
            system: 'Sistema',
        },
    },
    errors: {
        generic: 'Algo salió mal. Por favor intenta de nuevo.',
        network: 'Error de red. Por favor verifica tu conexión.',
        notFound: 'Página no encontrada.',
        unauthorized: 'No estás autorizado para realizar esta acción.',
        validation: 'Por favor verifica tu entrada e intenta de nuevo.',
    },
    time: {
        today: 'Hoy',
        yesterday: 'Ayer',
        tomorrow: 'Mañana',
        thisWeek: 'Esta Semana',
        lastWeek: 'Semana Pasada',
        thisMonth: 'Este Mes',
        lastMonth: 'Mes Pasado',
    },
};

i18n
    .use(LanguageDetector)
    .use(initReactI18next)
    .init({
        resources: {
            en: { translation: enTranslations },
            es: { translation: esTranslations },
        },
        fallbackLng: 'en',
        interpolation: {
            escapeValue: false, // React already escapes
        },
        detection: {
            order: ['localStorage', 'navigator', 'htmlTag'],
            caches: ['localStorage'],
        },
    });

export default i18n;
