import React, { useState, useEffect } from 'react';
import { NavLink, useLocation } from 'react-router-dom';
import { useAuth } from '../../context/AuthContext';
import { usePermissions } from '../../context/PermissionsContext';
import { useLang } from '../../context/LanguageContext';

function useBranding() {
  const [branding, setBranding] = useState(() => {
    try {
      const s = localStorage.getItem('arpm_branding');
      return s ? JSON.parse(s) : {};
    } catch { return {}; }
  });
  useEffect(() => {
    const handler = () => {
      try {
        const s = localStorage.getItem('arpm_branding');
        setBranding(s ? JSON.parse(s) : {});
      } catch { setBranding({}); }
    };
    window.addEventListener('arpm_branding_updated', handler);
    return () => window.removeEventListener('arpm_branding_updated', handler);
  }, []);
  return branding;
}

const GROUPS_EN = { 'PM':'PM', 'Análisis':'Analysis', 'Finanzas':'Finance', 'Operaciones':'Operations', 'Equipo':'Team', 'Comunicación':'Communication', 'Contratos':'Contracts', 'Sistema':'System' };

const NAV = [
  { to: '/',         label: 'Dashboard',        en: 'Dashboard',        end: true,  icon: <GridIcon />,        group: null },
  { to: '/projects', label: 'Proyectos',         en: 'Projects',         end: false, icon: <FolderIcon />,      group: null },
  { to: '/gantt',    label: 'Gantt & CP',        en: 'Gantt & CP',       end: false, icon: <GanttIcon />,       group: 'PM' },
  { to: '/wbs',      label: 'EDT / WBS',         en: 'WBS',              end: false, icon: <WBSIcon />,         group: 'PM' },
  { to: '/risks',    label: 'Riesgos',           en: 'Risks',            end: false, icon: <RiskIcon />,        group: 'PM' },
  { to: '/evm',      label: 'EVM',               en: 'EVM',              end: false, icon: <EVMIcon />,         group: 'PM' },
  { to: '/portfolio',      label: 'Portafolio',       en: 'Portfolio',        end: false, icon: <PortfolioIcon />,   group: 'Análisis' },
  { to: '/burndown',       label: 'Burndown',          en: 'Burndown',         end: false, icon: <BurndownIcon />,    group: 'Análisis' },
  { to: '/simulator',      label: 'Simulador',         en: 'Simulator',        end: false, icon: <SimulatorIcon />,   group: 'Análisis' },
  { to: '/nps',            label: 'NPS Cliente',       en: 'Client NPS',       end: false, icon: <NPSIcon />,         group: 'Análisis' },
  { to: '/exports',        label: 'Exportar PDF',      en: 'Export PDF',       end: false, icon: <ExportIcon />,      group: 'Análisis' },
  { to: '/budget',         label: 'Presupuesto',       en: 'Budget',           end: false, icon: <BudgetIcon />,      group: 'Finanzas' },
  { to: '/reports',        label: 'Reportes',          en: 'Reports',          end: false, icon: <ChartIcon />,       group: 'Finanzas' },
  { to: '/accounting',     label: 'Contabilidad',      en: 'Accounting',       end: false, icon: <AccountingIcon />,  group: 'Finanzas', perm: 'ACCOUNTING_PAYMENTS' },
  { to: '/billing',        label: 'Facturación',       en: 'Billing',          end: false, icon: <BillingIcon />,     group: 'Finanzas', perm: 'REPORTS_FINANCIAL' },
  { to: '/financial-report',label:'Rep. Financiero',   en: 'Financial Report', end: false, icon: <FinancialIcon />,   group: 'Finanzas', perm: 'REPORTS_FINANCIAL' },
  { to: '/work-orders',    label: 'Órd. Trabajo',      en: 'Work Orders',      end: false, icon: <WrenchIcon />,      group: 'Operaciones' },
  { to: '/procurement',    label: 'Abastecimiento',    en: 'Procurement',      end: false, icon: <TruckIcon />,       group: 'Operaciones' },
  { to: '/team',           label: 'Equipo',            en: 'Team',             end: false, icon: <TeamIcon />,        group: 'Equipo' },
  { to: '/resources',      label: 'Recursos',          en: 'Resources',        end: false, icon: <ResourcesIcon />,   group: 'Equipo' },
  { to: '/resource-calendar', label: 'Cal. Recursos',  en: 'Resource Cal.',    end: false, icon: <CalendarIcon />,    group: 'Equipo' },
  { to: '/documents',      label: 'Documentos',        en: 'Documents',        end: false, icon: <DocumentsIcon />,   group: 'Operaciones' },
  { to: '/quality',        label: 'Calidad (QC)',      en: 'Quality (QC)',     end: false, icon: <QualityIcon />,     group: 'Operaciones' },
  { to: '/hse',            label: 'HSE / SSOMA',       en: 'HSE / SSOMA',     end: false, icon: <HSEIcon />,         group: 'Operaciones' },
  { to: '/bids',           label: 'Licitaciones',      en: 'Bids',             end: false, icon: <BidsIcon />,        group: 'Operaciones', perm: 'REPORTS_FINANCIAL' },
  { to: '/reception',      label: 'Recepción',         en: 'Reception',        end: false, icon: <ReceptionIcon />,   group: 'Operaciones' },
  { to: '/time-tracking',  label: 'Control Horas',     en: 'Time Tracking',    end: false, icon: <TimeIcon />,        group: 'Equipo' },
  { to: '/meetings',       label: 'Actas Reunión',     en: 'Meeting Minutes',  end: false, icon: <MeetingIcon />,     group: 'Equipo' },
  { to: '/lessons',        label: 'Lecc. Aprendidas',  en: 'Lessons Learned',  end: false, icon: <LessonsIcon />,     group: 'Equipo' },
  { to: '/standup',        label: 'Standup Board',     en: 'Standup Board',    end: false, icon: <StandupIcon />,     group: 'Equipo' },
  { to: '/messages',       label: 'Mensajes',          en: 'Messages',         end: false, icon: <MessageIcon />,     group: 'Comunicación' },
  { to: '/contracts',      label: 'Contratos',         en: 'Contracts',        end: false, icon: <ContractsIcon />,   group: 'Contratos', perm: 'REPORTS_FINANCIAL' },
  { to: '/vendors',        label: 'Proveedores',       en: 'Vendors',          end: false, icon: <VendorsIcon />,     group: 'Contratos', perm: 'REPORTS_FINANCIAL' },
  { to: '/changes',        label: 'Gest. Cambios',     en: 'Change Mgmt',      end: false, icon: <ChangesIcon />,     group: 'Contratos', perm: 'REPORTS_FINANCIAL' },
  { to: '/project-closure',label: 'Cierre Proyecto',   en: 'Project Closure',  end: false, icon: <ClosureIcon />,     group: 'Sistema', perm: 'SETTINGS' },
  { to: '/client-portal',  label: 'Portal Cliente',    en: 'Client Portal',    end: false, icon: <PortalIcon />,      group: 'Sistema', perm: 'SETTINGS' },
  { to: '/settings',       label: 'Configuración',     en: 'Settings',         end: false, icon: <SettingsIcon />,    group: 'Sistema', perm: 'SETTINGS' },
  { to: '/admin/users',    label: 'Usuarios y Roles',  en: 'Users & Roles',    end: false, icon: <UsersAdminIcon />,  group: 'Sistema', perm: 'USERS_ROLES' },
];

function GridIcon() {
  return <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><rect x="3" y="3" width="7" height="7" rx="1"/><rect x="14" y="3" width="7" height="7" rx="1"/><rect x="3" y="14" width="7" height="7" rx="1"/><rect x="14" y="14" width="7" height="7" rx="1"/></svg>;
}
function FolderIcon() {
  return <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><path strokeLinecap="round" strokeLinejoin="round" d="M3 7a2 2 0 012-2h4l2 2h8a2 2 0 012 2v8a2 2 0 01-2 2H5a2 2 0 01-2-2V7z"/></svg>;
}
function ChartIcon() {
  return <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><path strokeLinecap="round" strokeLinejoin="round" d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z"/></svg>;
}
function GanttIcon() {
  return <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><path strokeLinecap="round" strokeLinejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-3 7h3m-3 4h3m-6-4h.01M9 16h.01"/></svg>;
}
function BudgetIcon() {
  return <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><path strokeLinecap="round" strokeLinejoin="round" d="M12 8c-1.657 0-3 .895-3 2s1.343 2 3 2 3 .895 3 2-1.343 2-3 2m0-8c1.11 0 2.08.402 2.599 1M12 8V7m0 1v8m0 0v1m0-1c-1.11 0-2.08-.402-2.599-1M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/></svg>;
}
function TeamIcon() {
  return <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><path strokeLinecap="round" strokeLinejoin="round" d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0z"/></svg>;
}
function WBSIcon() {
  return <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><path strokeLinecap="round" strokeLinejoin="round" d="M4 6h16M4 10h10M4 14h6M4 18h4"/></svg>;
}
function RiskIcon() {
  return <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><path strokeLinecap="round" strokeLinejoin="round" d="M12 9v2m0 4h.01M10.29 3.86L1.82 18a2 2 0 001.71 3h16.94a2 2 0 001.71-3L13.71 3.86a2 2 0 00-3.42 0z"/></svg>;
}
function EVMIcon() {
  return <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><path strokeLinecap="round" strokeLinejoin="round" d="M7 12l3-3 3 3 4-4M8 21l4-4 4 4M3 4h18M4 4h16v12a1 1 0 01-1 1H5a1 1 0 01-1-1V4z"/></svg>;
}
function MessageIcon() {
  return <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><path strokeLinecap="round" strokeLinejoin="round" d="M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z"/></svg>;
}
function WrenchIcon() {
  return <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><path strokeLinecap="round" strokeLinejoin="round" d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z"/><path strokeLinecap="round" strokeLinejoin="round" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"/></svg>;
}
function TruckIcon() {
  return <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><path strokeLinecap="round" strokeLinejoin="round" d="M9 17a2 2 0 11-4 0 2 2 0 014 0zM19 17a2 2 0 11-4 0 2 2 0 014 0z"/><path strokeLinecap="round" strokeLinejoin="round" d="M13 16V6a1 1 0 00-1-1H4a1 1 0 00-1 1v10a1 1 0 001 1h1m8-1a1 1 0 01-1 1H9m4-1V8a1 1 0 011-1h2.586a1 1 0 01.707.293l3.414 3.414a1 1 0 01.293.707V16a1 1 0 01-1 1h-1m-6-1a1 1 0 001 1h1M5 17a2 2 0 104 0m-4 0a2 2 0 114 0m6 0a2 2 0 104 0m-4 0a2 2 0 114 0"/></svg>;
}
function ResourcesIcon() {
  return <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><path strokeLinecap="round" strokeLinejoin="round" d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0z"/></svg>;
}
function AccountingIcon() {
  return <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><path strokeLinecap="round" strokeLinejoin="round" d="M9 7h6m0 10v-3m-3 3h.01M9 17h.01M9 14h.01M12 14h.01M15 11h.01M12 11h.01M9 11h.01M7 21h10a2 2 0 002-2V5a2 2 0 00-2-2H7a2 2 0 00-2 2v14a2 2 0 002 2z"/></svg>;
}
function SettingsIcon() {
  return <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><path strokeLinecap="round" strokeLinejoin="round" d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z"/><path strokeLinecap="round" strokeLinejoin="round" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"/></svg>;
}
function FinancialIcon() {
  return <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><path strokeLinecap="round" strokeLinejoin="round" d="M9 17v-2m3 2v-4m3 4v-6m2 10H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"/></svg>;
}
function BillingIcon() {
  return <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><path strokeLinecap="round" strokeLinejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-3 7h3m-3 4h3m-6-4h.01M9 16h.01"/></svg>;
}
function DocumentsIcon() {
  return <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><path strokeLinecap="round" strokeLinejoin="round" d="M7 21h10a2 2 0 002-2V9.414a1 1 0 00-.293-.707l-5.414-5.414A1 1 0 0012.586 3H7a2 2 0 00-2 2v14a2 2 0 002 2z"/></svg>;
}
function QualityIcon() {
  return <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><path strokeLinecap="round" strokeLinejoin="round" d="M9 12l2 2 4-4M7.835 4.697a3.42 3.42 0 001.946-.806 3.42 3.42 0 014.438 0 3.42 3.42 0 001.946.806 3.42 3.42 0 013.138 3.138 3.42 3.42 0 00.806 1.946 3.42 3.42 0 010 4.438 3.42 3.42 0 00-.806 1.946 3.42 3.42 0 01-3.138 3.138 3.42 3.42 0 00-1.946.806 3.42 3.42 0 01-4.438 0 3.42 3.42 0 00-1.946-.806 3.42 3.42 0 01-3.138-3.138 3.42 3.42 0 00-.806-1.946 3.42 3.42 0 010-4.438 3.42 3.42 0 00.806-1.946 3.42 3.42 0 013.138-3.138z"/></svg>;
}
function HSEIcon() {
  return <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><path strokeLinecap="round" strokeLinejoin="round" d="M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z"/></svg>;
}
function BidsIcon() {
  return <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><path strokeLinecap="round" strokeLinejoin="round" d="M19 21V5a2 2 0 00-2-2H7a2 2 0 00-2 2v16m14 0h2m-2 0h-5m-9 0H3m2 0h5M9 7h1m-1 4h1m4-4h1m-1 4h1m-2 10v-5a1 1 0 011-1h2a1 1 0 011 1v5m-4 0h4"/></svg>;
}
function UsersAdminIcon() {
  return <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><path strokeLinecap="round" strokeLinejoin="round" d="M12 4.354a4 4 0 110 5.292M15 21H3v-1a6 6 0 0112 0v1zm0 0h6v-1a6 6 0 00-9-5.197M13 7a4 4 0 11-8 0 4 4 0 018 0z"/></svg>;
}
function ContractsIcon() {
  return <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><path strokeLinecap="round" strokeLinejoin="round" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"/></svg>;
}
function VendorsIcon() {
  return <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><path strokeLinecap="round" strokeLinejoin="round" d="M19 21V5a2 2 0 00-2-2H7a2 2 0 00-2 2v16m14 0h2m-2 0h-5m-9 0H3m2 0h5M9 7h1m-1 4h1m4-4h1m-1 4h1m-5 10v-5a1 1 0 011-1h2a1 1 0 011 1v5m-4 0h4"/></svg>;
}
function ChangesIcon() {
  return <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><path strokeLinecap="round" strokeLinejoin="round" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"/></svg>;
}
function ReceptionIcon() {
  return <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><path strokeLinecap="round" strokeLinejoin="round" d="M9 13h6m-3-3v6m-9 1V7a2 2 0 012-2h6l2 2h6a2 2 0 012 2v8a2 2 0 01-2 2H5a2 2 0 01-2-2z"/></svg>;
}
function ClosureIcon() {
  return <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><path strokeLinecap="round" strokeLinejoin="round" d="M3 3h2l.4 2M7 13h10l4-8H5.4M7 13L5.4 5M7 13l-2.293 2.293c-.63.63-.184 1.707.707 1.707H17m0 0a2 2 0 100 4 2 2 0 000-4zm-8 2a2 2 0 11-4 0 2 2 0 014 0z"/></svg>;
}
function PortalIcon() {
  return <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><path strokeLinecap="round" strokeLinejoin="round" d="M5.121 17.804A13.937 13.937 0 0112 16c2.5 0 4.847.655 6.879 1.804M15 10a3 3 0 11-6 0 3 3 0 016 0M19 10a7 7 0 11-14 0 7 7 0 0114 0z"/></svg>;
}
function PortfolioIcon() {
  return <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><path strokeLinecap="round" strokeLinejoin="round" d="M4 6a2 2 0 012-2h2a2 2 0 012 2v2a2 2 0 01-2 2H6a2 2 0 01-2-2V6zm10 0a2 2 0 012-2h2a2 2 0 012 2v2a2 2 0 01-2 2h-2a2 2 0 01-2-2V6zM4 16a2 2 0 012-2h2a2 2 0 012 2v2a2 2 0 01-2 2H6a2 2 0 01-2-2v-2zm10 0a2 2 0 012-2h2a2 2 0 012 2v2a2 2 0 01-2 2h-2a2 2 0 01-2-2v-2z"/></svg>;
}
function BurndownIcon() {
  return <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><path strokeLinecap="round" strokeLinejoin="round" d="M13 17h8m0 0V9m0 8l-8-8-4 4-6-6"/></svg>;
}
function TimeIcon() {
  return <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><path strokeLinecap="round" strokeLinejoin="round" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"/></svg>;
}
function MeetingIcon() {
  return <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><path strokeLinecap="round" strokeLinejoin="round" d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0zm6 3a2 2 0 11-4 0 2 2 0 014 0zM7 10a2 2 0 11-4 0 2 2 0 014 0z"/></svg>;
}
function LessonsIcon() {
  return <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><path strokeLinecap="round" strokeLinejoin="round" d="M12 6.253v13m0-13C10.832 5.477 9.246 5 7.5 5S4.168 5.477 3 6.253v13C4.168 18.477 5.754 18 7.5 18s3.332.477 4.5 1.253m0-13C13.168 5.477 14.754 5 16.5 5c1.747 0 3.332.477 4.5 1.253v13C19.832 18.477 18.247 18 16.5 18c-1.746 0-3.332.477-4.5 1.253"/></svg>;
}
function LogoutIcon() {
  return <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><path strokeLinecap="round" strokeLinejoin="round" d="M17 16l4-4m0 0l-4-4m4 4H7m6 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h4a3 3 0 013 3v1"/></svg>;
}
function SimulatorIcon() {
  return <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><path strokeLinecap="round" strokeLinejoin="round" d="M9 7h6m0 10v-3m-3 3h.01M9 17h.01M9 11h.01M12 11h.01M15 11h.01M12 7v10m-7 4h14a2 2 0 002-2V5a2 2 0 00-2-2H5a2 2 0 00-2 2v14a2 2 0 002 2z"/></svg>;
}
function CalendarIcon() {
  return <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><path strokeLinecap="round" strokeLinejoin="round" d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z"/></svg>;
}
function StandupIcon() {
  return <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><path strokeLinecap="round" strokeLinejoin="round" d="M17 8h2a2 2 0 012 2v6a2 2 0 01-2 2h-2v4l-4-4H9a1.994 1.994 0 01-1.414-.586m0 0L11 14h4a2 2 0 002-2V6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2v4l.586-.586z"/></svg>;
}
function NPSIcon() {
  return <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><path strokeLinecap="round" strokeLinejoin="round" d="M11.049 2.927c.3-.921 1.603-.921 1.902 0l1.519 4.674a1 1 0 00.95.69h4.915c.969 0 1.371 1.24.588 1.81l-3.976 2.888a1 1 0 00-.363 1.118l1.518 4.674c.3.922-.755 1.688-1.538 1.118l-3.976-2.888a1 1 0 00-1.176 0l-3.976 2.888c-.783.57-1.838-.197-1.538-1.118l1.518-4.674a1 1 0 00-.363-1.118l-3.976-2.888c-.784-.57-.38-1.81.588-1.81h4.914a1 1 0 00.951-.69l1.519-4.674z"/></svg>;
}
function ExportIcon() {
  return <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><path strokeLinecap="round" strokeLinejoin="round" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4"/></svg>;
}

// Group metadata: icon color + emoji label
const GROUP_META = {
  'PM':           { color: 'text-blue-600 dark:text-blue-400',    bg: 'bg-blue-50 dark:bg-blue-500/10'    },
  'Análisis':     { color: 'text-violet-600 dark:text-violet-400', bg: 'bg-violet-50 dark:bg-violet-500/10' },
  'Finanzas':     { color: 'text-emerald-600 dark:text-emerald-400', bg: 'bg-emerald-50 dark:bg-emerald-500/10' },
  'Operaciones':  { color: 'text-orange-600 dark:text-orange-400', bg: 'bg-orange-50 dark:bg-orange-500/10' },
  'Equipo':       { color: 'text-pink-600 dark:text-pink-400',     bg: 'bg-pink-50 dark:bg-pink-500/10'    },
  'Comunicación': { color: 'text-cyan-600 dark:text-cyan-400',     bg: 'bg-cyan-50 dark:bg-cyan-500/10'    },
  'Contratos':    { color: 'text-amber-600 dark:text-amber-400',   bg: 'bg-amber-50 dark:bg-amber-500/10'  },
  'Sistema':      { color: 'text-slate-600 dark:text-slate-400',   bg: 'bg-slate-50 dark:bg-slate-500/10'  },
};

function NavGroup({ groupName, items, can, lang = 'es' }) {
  const { pathname } = useLocation();
  const hasActive = items.some(i => pathname === i.to || (!i.end && pathname.startsWith(i.to + '/')));
  const [open, setOpen] = useState(hasActive);
  const meta = GROUP_META[groupName] || { color: 'text-slate-500', bg: 'bg-slate-50' };

  // Auto-open if a child becomes active
  useEffect(() => { if (hasActive) setOpen(true); }, [hasActive]);

  const visibleItems = items.filter(i => !i.perm || can(i.perm));
  if (visibleItems.length === 0) return null;

  return (
    <div className="mb-0.5">
      <button onClick={() => setOpen(v => !v)}
        className={`w-full flex items-center justify-between px-3 py-2 rounded-lg text-xs font-semibold uppercase tracking-widest transition-all cursor-pointer ${
          open || hasActive
            ? `${meta.color} ${meta.bg}`
            : 'text-slate-400 dark:text-gray-500 hover:text-slate-700 dark:hover:text-gray-300 hover:bg-slate-50 dark:hover:bg-surface-700'
        }`}>
        <span>{groupName}</span>
        <svg className={`w-3 h-3 transition-transform duration-200 ${open ? 'rotate-90' : ''}`}
          fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2.5}>
          <path strokeLinecap="round" strokeLinejoin="round" d="M9 5l7 7-7 7"/>
        </svg>
      </button>

      {open && (
        <div className="mt-0.5 ml-2 pl-2 border-l-2 border-slate-100 dark:border-surface-700 space-y-0.5">
          {visibleItems.map((item) => (
            <NavLink key={item.to} to={item.to} end={item.end}
              className={({ isActive }) =>
                `flex items-center gap-2.5 px-3 py-1.5 rounded-lg text-sm transition-all cursor-pointer ${
                  isActive
                    ? 'bg-blue-50 dark:bg-primary-500/15 text-blue-700 dark:text-blue-400 font-medium'
                    : 'text-slate-500 dark:text-gray-400 hover:text-slate-900 dark:hover:text-white hover:bg-slate-100 dark:hover:bg-surface-700'
                }`
              }>
              {item.icon}
              <span className="truncate">{lang === 'en' ? (item.en || item.label) : item.label}</span>
            </NavLink>
          ))}
        </div>
      )}
    </div>
  );
}

export default function Sidebar() {
  const { user, logout } = useAuth();
  const { can } = usePermissions();
  const { lang } = useLang();
  const initials = `${user?.firstName?.[0] ?? ''}${user?.lastName?.[0] ?? ''}`;
  const { logo, appName, appSubtitle } = useBranding();
  const lbl = (item) => lang === 'en' ? (item.en || item.label) : item.label;

  // Separate top-level items (no group) from grouped items
  const topItems  = NAV.filter(i => !i.group);
  const groups    = [...new Set(NAV.filter(i => i.group).map(i => i.group))];

  return (
    <aside className="w-60 h-screen flex flex-col bg-white dark:bg-surface-800 border-r border-slate-200 dark:border-surface-700 transition-colors">
      {/* Logo */}
      <div className="flex items-center gap-3 px-5 h-16 border-b border-slate-200 dark:border-surface-700 flex-shrink-0">
        <div className="w-8 h-8 rounded-lg flex items-center justify-center flex-shrink-0 shadow-sm overflow-hidden bg-slate-900">
          <img src={logo || '/logo-ar.png'} alt="Logo" className="w-full h-full object-cover" />
        </div>
        <div className="min-w-0">
          <p className="text-slate-900 dark:text-white font-semibold text-sm leading-tight truncate">{appName || 'AR Project'}</p>
          <p className="text-slate-400 dark:text-gray-500 text-xs truncate">{appSubtitle || 'Manager'}</p>
        </div>
      </div>

      {/* Nav */}
      <nav className="flex-1 px-3 py-3 overflow-y-auto space-y-0.5">
        {/* Top-level links (Dashboard, Proyectos) */}
        {topItems.filter(i => !i.perm || can(i.perm)).map((item) => (
          <NavLink key={item.to} to={item.to} end={item.end}
            className={({ isActive }) =>
              `flex items-center gap-2.5 px-3 py-2 rounded-lg text-sm transition-all cursor-pointer ${
                isActive
                  ? 'bg-blue-50 dark:bg-primary-500/15 text-blue-700 dark:text-blue-400 font-medium'
                  : 'text-slate-500 dark:text-gray-400 hover:text-slate-900 dark:hover:text-white hover:bg-slate-100 dark:hover:bg-surface-700'
              }`
            }>
            {item.icon}
            <span>{lbl(item)}</span>
          </NavLink>
        ))}

        {/* Divider */}
        {topItems.length > 0 && groups.length > 0 && (
          <div className="h-px bg-slate-100 dark:bg-surface-700 my-2" />
        )}

        {/* Collapsible groups */}
        {groups.map(g => (
          <NavGroup key={g} groupName={lang === 'en' ? (GROUPS_EN[g] || g) : g}
            items={NAV.filter(i => i.group === g)}
            can={can} lang={lang} />
        ))}
      </nav>

      {/* User */}
      <div className="px-3 py-4 border-t border-slate-200 dark:border-surface-700 flex-shrink-0">
        <div className="flex items-center gap-2.5">
          <div className="w-8 h-8 rounded-full bg-blue-100 dark:bg-primary-500/20 flex items-center justify-center flex-shrink-0">
            <span className="text-blue-700 dark:text-blue-400 text-xs font-semibold">{initials}</span>
          </div>
          <div className="flex-1 min-w-0">
            <p className="text-sm font-medium text-slate-900 dark:text-white truncate">{user?.firstName} {user?.lastName}</p>
            <p className="text-xs text-slate-400 dark:text-gray-500 truncate">{user?.role?.replace(/_/g,' ')}</p>
          </div>
          <button onClick={logout} title="Cerrar sesión"
            className="text-slate-400 dark:text-gray-500 hover:text-red-500 dark:hover:text-red-400 transition-colors cursor-pointer p-1 rounded">
            <LogoutIcon />
          </button>
        </div>
      </div>
    </aside>
  );
}
