import React, { createContext, useContext, useState, useCallback } from 'react';

const LanguageContext = createContext(null);

// Traducciones estáticas de la UI
export const T = {
  es: {
    dashboard: 'Dashboard', projects: 'Proyectos', gantt: 'Gantt & CP',
    wbs: 'EDT / WBS', risks: 'Riesgos', evm: 'EVM', portfolio: 'Portafolio',
    burndown: 'Burndown', simulator: 'Simulador', nps: 'NPS Cliente',
    exports: 'Exportar PDF', budget: 'Presupuesto', reports: 'Reportes',
    accounting: 'Contabilidad', billing: 'Facturación',
    team: 'Equipo', workOrders: 'Órd. Trabajo', procurement: 'Abastecimiento',
    resources: 'Recursos', documents: 'Documentos', quality: 'Calidad (QC)',
    hse: 'HSE / SSOMA', bids: 'Licitaciones', reception: 'Recepción',
    timeTracking: 'Control Horas', meetings: 'Actas Reunión',
    lessons: 'Lecc. Aprendidas', standup: 'Standup Board',
    messages: 'Mensajes', contracts: 'Contratos', vendors: 'Proveedores',
    changes: 'Gest. Cambios', closure: 'Cierre Proyecto',
    clientPortal: 'Portal Cliente', settings: 'Configuración', users: 'Usuarios y Roles',
    newProject: 'Nuevo proyecto', createProject: 'Crear proyecto',
    save: 'Guardar', cancel: 'Cancelar', search: 'Buscar',
    status: 'Estado', priority: 'Prioridad', assignee: 'Responsable',
    dueDate: 'Fecha límite', progress: 'Avance', hours: 'Horas',
    pending: 'PENDIENTE', inProgress: 'EN PROCESO', done: 'COMPLETADA',
    blocked: 'BLOQUEADA', active: 'Activo', paused: 'Pausado',
    atRisk: 'En riesgo', completed: 'Completado',
    loading: 'Cargando...', noData: 'Sin datos',
    importProject: 'Importar anteproyecto con IA',
    translateContent: 'Traducir contenido',
  },
  en: {
    dashboard: 'Dashboard', projects: 'Projects', gantt: 'Gantt & CP',
    wbs: 'WBS / EDT', risks: 'Risks', evm: 'EVM', portfolio: 'Portfolio',
    burndown: 'Burndown', simulator: 'Simulator', nps: 'Client NPS',
    exports: 'Export PDF', budget: 'Budget', reports: 'Reports',
    accounting: 'Accounting', billing: 'Billing',
    team: 'Team', workOrders: 'Work Orders', procurement: 'Procurement',
    resources: 'Resources', documents: 'Documents', quality: 'Quality (QC)',
    hse: 'HSE / SSOMA', bids: 'Bids', reception: 'Reception',
    timeTracking: 'Time Tracking', meetings: 'Meeting Minutes',
    lessons: 'Lessons Learned', standup: 'Standup Board',
    messages: 'Messages', contracts: 'Contracts', vendors: 'Vendors',
    changes: 'Change Mgmt', closure: 'Project Closure',
    clientPortal: 'Client Portal', settings: 'Settings', users: 'Users & Roles',
    newProject: 'New project', createProject: 'Create project',
    save: 'Save', cancel: 'Cancel', search: 'Search',
    status: 'Status', priority: 'Priority', assignee: 'Assignee',
    dueDate: 'Due date', progress: 'Progress', hours: 'Hours',
    pending: 'PENDING', inProgress: 'IN PROGRESS', done: 'COMPLETED',
    blocked: 'BLOCKED', active: 'Active', paused: 'Paused',
    atRisk: 'At risk', completed: 'Completed',
    loading: 'Loading...', noData: 'No data',
    importProject: 'Import pre-project with AI',
    translateContent: 'Translate content',
  },
};

// Traduce texto dinámico con la IA configurada
export async function translateWithAI(text, targetLang) {
  if (!text || !text.trim()) return text;
  try {
    const config = JSON.parse(localStorage.getItem('arpm_settings') || '{}');
    const provider = config.aiProvider || 'none';
    const langName = targetLang === 'en' ? 'English' : 'Spanish';
    const prompt = `Translate the following project management text to ${langName}. Return ONLY the translated text, no explanations:\n\n${text}`;

    if (provider === 'ollama') {
      const base = (config.aiLocalUrl || 'http://localhost:11434').replace(/\/$/, '');
      const model = config.aiLocalModel || 'llama3';
      const res = await fetch(`${base}/api/generate`, {
        method: 'POST', headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ model, prompt, stream: false }),
      });
      if (!res.ok) return text;
      return (await res.json()).response?.trim() || text;
    }
    if (provider === 'claude') {
      const res = await fetch('https://api.anthropic.com/v1/messages', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', 'x-api-key': config.claudeApiKey || '', 'anthropic-version': '2023-06-01' },
        body: JSON.stringify({ model: config.claudeModel || 'claude-haiku-4-5-20251001', max_tokens: 1024, messages: [{ role: 'user', content: prompt }] }),
      });
      if (!res.ok) return text;
      return (await res.json()).content[0].text?.trim() || text;
    }
    if (provider === 'openai') {
      const res = await fetch('https://api.openai.com/v1/chat/completions', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${config.openaiApiKey || ''}` },
        body: JSON.stringify({ model: config.openaiModel || 'gpt-4o-mini', messages: [{ role: 'user', content: prompt }], max_tokens: 1024 }),
      });
      if (!res.ok) return text;
      return (await res.json()).choices[0].message.content?.trim() || text;
    }
  } catch { /* sin IA, devolver original */ }
  return text;
}

export function LanguageProvider({ children }) {
  const [lang, setLang] = useState(() => localStorage.getItem('arpm_lang') || 'es');

  const toggleLang = useCallback(() => {
    setLang(l => {
      const next = l === 'es' ? 'en' : 'es';
      localStorage.setItem('arpm_lang', next);
      return next;
    });
  }, []);

  const t = useCallback((key) => T[lang]?.[key] || T.es[key] || key, [lang]);

  return (
    <LanguageContext.Provider value={{ lang, toggleLang, t, translateWithAI }}>
      {children}
    </LanguageContext.Provider>
  );
}

export const useLang = () => {
  const ctx = useContext(LanguageContext);
  if (!ctx) throw new Error('useLang must be inside LanguageProvider');
  return ctx;
};
