/* =====================================================================
 * Navigation latérale + sélecteur de session.
 * ===================================================================== */

const NAV_ITEMS = [
  { id: 'dashboard', label: 'Tableau de bord', icon: LayoutDashboard, perm: null },
  { id: 'nouveau', label: 'Nouveau bilan', icon: FilePlus2, perm: 'sap' },
  { id: 'historique', label: 'Historique', icon: HistoryIcon, perm: 'sap' },
  { id: 'jsp', label: 'Habillement JSP', icon: Shirt, perm: 'jsp' },
  { id: 'admin', label: 'Gestion accès', icon: ShieldCheck, perm: 'admin' },
  { id: 'journal', label: 'Journal', icon: ScrollText, perm: null },
];

const SYNC_LABELS = {
  ok: { label: 'Enregistré', dot: 'bg-emerald-500' },
  saving: { label: 'Enregistrement…', dot: 'bg-amber-400 animate-pulse' },
  error: { label: 'Hors ligne', dot: 'bg-red-500 animate-pulse' },
};

function SyncIndicator({ className }) {
  const { syncStatus } = useApp();
  const s = SYNC_LABELS[syncStatus];
  return (
    <span
      className={cx('inline-flex items-center gap-1.5 text-[11px] text-slate-400', className)}
      title={syncStatus === 'error' ? 'Serveur injoignable : les modifications seront envoyées dès le retour de la connexion. Ne fermez pas la page.' : 'Données enregistrées sur le serveur'}
    >
      <span className={cx('h-2 w-2 rounded-full', s.dot)} />
      {s.label}
    </span>
  );
}

function Sidebar({ page, navigate, open, onClose }) {
  const { can, currentUser, logout, settings, bilans } = useApp();
  const [passwordOpen, setPasswordOpen] = useState(false);
  const drafts = bilans.filter((b) => b.status === 'brouillon').length;
  const activeId = page === 'bilan' ? 'historique' : page;

  return (
    <Fragment>
      {open && <div className="fixed inset-0 z-30 bg-slate-900/50 lg:hidden" onClick={onClose} />}
      <aside
        className={cx(
          'fixed inset-y-0 left-0 z-40 flex w-72 flex-col bg-slate-900 text-slate-300 transition-transform lg:w-64 lg:translate-x-0',
          open ? 'translate-x-0' : '-translate-x-full',
        )}
      >
        <div className="flex items-center gap-3 px-5 py-5">
          <div className="flex h-10 w-10 items-center justify-center rounded-xl bg-red-600 text-white shadow-lg shadow-red-600/30">
            <Siren className="h-6 w-6" />
          </div>
          <div className="min-w-0">
            <p className="font-bold leading-tight text-white">SAP Manager</p>
            <p className="truncate text-xs text-slate-400">{settings.centre}</p>
          </div>
          <IconButton icon={X} title="Fermer le menu" className="ml-auto text-slate-400 hover:bg-slate-800 lg:hidden" onClick={onClose} />
        </div>

        <nav className="flex-1 space-y-1 overflow-y-auto px-3 py-2">
          {NAV_ITEMS.filter((item) => !item.perm || can[item.perm]).map((item) => {
            const active = activeId === item.id;
            return (
              <button
                key={item.id}
                type="button"
                onClick={() => navigate(item.id)}
                className={cx(
                  'flex w-full items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium transition',
                  active ? 'bg-red-600 text-white shadow-md shadow-red-900/40' : 'hover:bg-slate-800 hover:text-white',
                )}
              >
                <item.icon className="h-5 w-5" />
                <span className="flex-1 text-left">{item.label}</span>
                {item.id === 'historique' && drafts > 0 && (
                  <span className={cx('rounded-full px-2 py-0.5 text-xs font-bold', active ? 'bg-white/20' : 'bg-amber-500 text-white')}>{drafts}</span>
                )}
              </button>
            );
          })}
        </nav>

        <div className="border-t border-slate-800 p-4">
          <div className="mb-2 flex items-center justify-between">
            <p className="text-[11px] font-semibold uppercase tracking-wider text-slate-500">Session</p>
            <SyncIndicator />
          </div>
          <div className="flex items-center gap-3">
            <UserAvatar user={currentUser} size="sm" />
            <div className="min-w-0 flex-1">
              <p className="truncate text-sm font-semibold text-white">
                {currentUser.prenom} {currentUser.nom}
              </p>
              <p className="truncate text-xs text-slate-400">{roleOf(currentUser.role).label}</p>
            </div>
          </div>
          <div className="mt-3 grid grid-cols-2 gap-2">
            <button
              type="button"
              onClick={() => setPasswordOpen(true)}
              className="flex items-center justify-center gap-1.5 rounded-lg border border-slate-700 px-2 py-1.5 text-xs text-slate-300 transition hover:bg-slate-800 hover:text-white"
            >
              <LockIcon className="h-3.5 w-3.5" /> Mot de passe
            </button>
            <button
              type="button"
              onClick={logout}
              className="flex items-center justify-center gap-1.5 rounded-lg border border-slate-700 px-2 py-1.5 text-xs text-slate-300 transition hover:bg-red-600 hover:text-white"
            >
              <LogOut className="h-3.5 w-3.5" /> Déconnexion
            </button>
          </div>
        </div>
      </aside>
      {passwordOpen && <ChangePasswordModal onClose={() => setPasswordOpen(false)} />}
    </Fragment>
  );
}
