import {
  mdiAccountArrowRight,
  mdiArrowRight,
  mdiBriefcaseVariant,
  mdiCashMultiple,
  mdiClockOutline,
  mdiHandshake,
  mdiLifebuoy,
  mdiPlus,
  mdiStarFourPoints,
  mdiViewDashboardOutline,
} from '@mdi/js';
import axios from 'axios';
import Head from 'next/head';
import Link from 'next/link';
import { ReactElement, ReactNode, useEffect, useMemo, useState } from 'react';
import BaseButton from '../components/BaseButton';
import BaseButtons from '../components/BaseButtons';
import BaseIcon from '../components/BaseIcon';
import CardBox from '../components/CardBox';
import SectionMain from '../components/SectionMain';
import SectionTitleLineWithButton from '../components/SectionTitleLineWithButton';
import { getPageTitle } from '../config';
import { hasPermission } from '../helpers/userPermissions';
import LayoutAuthenticated from '../layouts/Authenticated';
import { useAppSelector } from '../stores/hooks';

type SummaryCollection = {
  count: number;
  rows: any[];
};

type HubState = {
  leads: SummaryCollection;
  deals: SummaryCollection;
  projects: SummaryCollection;
  tickets: SummaryCollection;
  invoices: SummaryCollection;
};

type BoardSectionProps = {
  eyebrow: string;
  title: string;
  icon: string;
  count?: number;
  href?: string;
  actionLabel?: string;
  emptyMessage: string;
  children: ReactNode;
  isEmpty?: boolean;
};

const emptySummary: SummaryCollection = { count: 0, rows: [] };
const emptyHubState: HubState = {
  leads: emptySummary,
  deals: emptySummary,
  projects: emptySummary,
  tickets: emptySummary,
  invoices: emptySummary,
};

const playbooks = [
  { name: 'AI Implementation', duration: '16 sem.', line: 'AI & ML' },
  { name: 'Cybersecurity Audit', duration: '4 sem.', line: 'Cybersécurité' },
  { name: 'Cloud Migration', duration: '8 sem.', line: 'Cloud' },
  { name: 'Hardware Deployment', duration: 'Variable', line: 'Infrastructure' },
  { name: 'Web/Mobile Development', duration: '12 sem.', line: 'Web & Mobile' },
  { name: 'Database Setup', duration: '6 sem.', line: 'Database' },
];

const kpiTone = {
  leads: 'from-[#2563EB] via-[#1D4ED8] to-[#1E40AF]',
  deals: 'from-[#0891B2] via-[#0E7490] to-[#155E75]',
  projects: 'from-[#7C3AED] via-[#6D28D9] to-[#5B21B6]',
  invoices: 'from-[#F97316] via-[#EA580C] to-[#C2410C]',
};

function SectionCard({
  eyebrow,
  title,
  icon,
  count,
  href,
  actionLabel,
  emptyMessage,
  children,
  isEmpty = false,
}: BoardSectionProps) {
  return (
    <CardBox className="h-full border-none shadow-[0_32px_80px_-48px_rgba(15,23,42,0.5)]">
      <div className="mb-5 flex items-start justify-between gap-4">
        <div>
          <p className="text-xs font-semibold uppercase tracking-[0.24em] text-slate-500">{eyebrow}</p>
          <div className="mt-3 flex items-center gap-3">
            <div className="rounded-2xl bg-slate-900 p-3 text-white">
              <BaseIcon path={icon} size={20} />
            </div>
            <div>
              <h2 className="text-xl font-semibold text-slate-900">{title}</h2>
              {typeof count === 'number' && <p className="text-sm text-slate-500">{count} éléments visibles</p>}
            </div>
          </div>
        </div>
        {href && actionLabel && (
          <Link href={href} className="inline-flex items-center rounded-full border border-slate-200 px-4 py-2 text-sm font-semibold text-slate-700 transition hover:border-slate-300 hover:bg-slate-50">
            {actionLabel}
            <BaseIcon path={mdiArrowRight} size={16} className="ml-2" />
          </Link>
        )}
      </div>
      <div className="space-y-3">
        {isEmpty ? (
          <div className="rounded-2xl border border-dashed border-slate-200 bg-slate-50 p-6 text-sm text-slate-500">
            {emptyMessage}
          </div>
        ) : (
          children
        )}
      </div>
    </CardBox>
  );
}

function statusLabel(value?: string) {
  const map: Record<string, string> = {
    new: 'Nouveau',
    qualified: 'Qualifié',
    disqualified: 'Disqualifié',
    converted: 'Converti',
    open: 'Ouvert',
    won: 'Gagné',
    lost: 'Perdu',
    planned: 'Planifié',
    active: 'Actif',
    on_hold: 'En pause',
    completed: 'Terminé',
    cancelled: 'Annulé',
    in_progress: 'En cours',
    waiting: 'En attente',
    resolved: 'Résolu',
    closed: 'Clos',
    draft: 'Brouillon',
    sent: 'Envoyée',
    partial: 'Partielle',
    paid: 'Payée',
    overdue: 'En retard',
    void: 'Annulée',
    p1: 'P1',
    p2: 'P2',
    p3: 'P3',
    p4: 'P4',
    low: 'faible',
    medium: 'moyen',
    high: 'élevé',
    critical: 'critique',
  };

  return map[value || ''] || value || 'N/A';
}

function badgeClass(value?: string) {
  const styles: Record<string, string> = {
    qualified: 'bg-emerald-50 text-emerald-700 border border-emerald-200',
    new: 'bg-blue-50 text-blue-700 border border-blue-200',
    open: 'bg-cyan-50 text-cyan-700 border border-cyan-200',
    active: 'bg-violet-50 text-violet-700 border border-violet-200',
    overdue: 'bg-rose-50 text-rose-700 border border-rose-200',
    paid: 'bg-emerald-50 text-emerald-700 border border-emerald-200',
    resolved: 'bg-emerald-50 text-emerald-700 border border-emerald-200',
    closed: 'bg-slate-100 text-slate-700 border border-slate-200',
    p1: 'bg-rose-50 text-rose-700 border border-rose-200',
    p2: 'bg-amber-50 text-amber-700 border border-amber-200',
    p3: 'bg-sky-50 text-sky-700 border border-sky-200',
    p4: 'bg-slate-100 text-slate-700 border border-slate-200',
  };

  return styles[value || ''] || 'bg-slate-100 text-slate-700 border border-slate-200';
}

function scoreClass(score?: number) {
  if (!score && score !== 0) {
    return 'bg-slate-100 text-slate-700 border border-slate-200';
  }

  if (score >= 70) {
    return 'bg-emerald-50 text-emerald-700 border border-emerald-200';
  }

  if (score >= 55) {
    return 'bg-amber-50 text-amber-700 border border-amber-200';
  }

  return 'bg-slate-100 text-slate-700 border border-slate-200';
}

function formatDate(value?: string | null) {
  if (!value) {
    return 'À planifier';
  }

  return new Intl.DateTimeFormat('fr-FR', {
    day: '2-digit',
    month: 'short',
    year: 'numeric',
  }).format(new Date(value));
}

function formatCurrency(value?: string | number | null, currency = 'USD') {
  if (value === null || value === undefined || value === '') {
    return 'À qualifier';
  }

  return new Intl.NumberFormat('fr-FR', {
    style: 'currency',
    currency,
    maximumFractionDigits: 0,
  }).format(Number(value));
}

function KpiCard({
  title,
  value,
  subtitle,
  icon,
  href,
  tone,
}: {
  title: string;
  value: string | number;
  subtitle: string;
  icon: string;
  href?: string;
  tone: string;
}) {
  const card = (
    <div className={`rounded-[28px] bg-gradient-to-br p-6 text-white shadow-[0_24px_80px_-36px_rgba(15,23,42,0.75)] ${tone}`}>
      <div className="flex items-start justify-between gap-4">
        <div>
          <p className="text-xs font-semibold uppercase tracking-[0.24em] text-white/75">{title}</p>
          <p className="mt-3 text-4xl font-semibold">{value}</p>
          <p className="mt-2 text-sm text-white/75">{subtitle}</p>
        </div>
        <div className="rounded-2xl bg-white/10 p-3 text-white backdrop-blur-sm">
          <BaseIcon path={icon} size={22} />
        </div>
      </div>
    </div>
  );

  return href ? <Link href={href}>{card}</Link> : card;
}

const FleetOsHub = () => {
  const { currentUser } = useAppSelector((state) => state.auth);
  const [hubData, setHubData] = useState<HubState>(emptyHubState);
  const [loading, setLoading] = useState(true);
  const [partialError, setPartialError] = useState('');

  useEffect(() => {
    if (!currentUser) {
      return;
    }

    let isMounted = true;
    setLoading(true);
    setPartialError('');

    const sections = [
      hasPermission(currentUser, 'READ_LEADS')
        ? { key: 'leads' as const, path: 'leads?limit=4' }
        : null,
      hasPermission(currentUser, 'READ_DEALS')
        ? { key: 'deals' as const, path: 'deals?limit=4&status=open' }
        : null,
      hasPermission(currentUser, 'READ_PROJECTS')
        ? { key: 'projects' as const, path: 'projects?limit=4&status=active' }
        : null,
      hasPermission(currentUser, 'READ_SUPPORT_TICKETS')
        ? { key: 'tickets' as const, path: 'support_tickets?limit=8' }
        : null,
      hasPermission(currentUser, 'READ_INVOICES')
        ? { key: 'invoices' as const, path: 'invoices?limit=4&status=overdue' }
        : null,
    ].filter(Boolean) as Array<{ key: keyof HubState; path: string }>;

    if (!sections.length) {
      setLoading(false);
      return;
    }

    Promise.allSettled(
      sections.map(({ key, path }) =>
        axios.get(path).then(({ data }) => ({
          key,
          data,
        })),
      ),
    ).then((results) => {
      if (!isMounted) {
        return;
      }

      const nextState: HubState = {
        leads: { ...emptySummary },
        deals: { ...emptySummary },
        projects: { ...emptySummary },
        tickets: { ...emptySummary },
        invoices: { ...emptySummary },
      };

      let hasRejected = false;

      results.forEach((result) => {
        if (result.status === 'fulfilled') {
          nextState[result.value.key] = {
            count: typeof result.value.data?.count === 'number' ? result.value.data.count : 0,
            rows: Array.isArray(result.value.data?.rows) ? result.value.data.rows : [],
          };
        } else {
          hasRejected = true;
        }
      });

      setHubData(nextState);
      setPartialError(
        hasRejected
          ? 'Certaines briques n’ont pas pu être chargées. Les widgets disponibles restent utilisables.'
          : '',
      );
      setLoading(false);
    });

    return () => {
      isMounted = false;
    };
  }, [currentUser]);

  const urgentTickets = useMemo(
    () =>
      hubData.tickets.rows
        .filter((ticket) => ['p1', 'p2'].includes(ticket.priority) || ticket.sla_breached)
        .slice(0, 4),
    [hubData.tickets.rows],
  );

  const heroQuickActions = useMemo(
    () =>
      [
        hasPermission(currentUser, 'CREATE_LEADS')
          ? { href: '/leads/leads-new', label: 'Nouveau lead' }
          : null,
        hasPermission(currentUser, 'CREATE_PROJECTS')
          ? { href: '/projects/projects-new', label: 'Nouveau projet' }
          : null,
        hasPermission(currentUser, 'CREATE_SUPPORT_TICKETS')
          ? { href: '/support_tickets/support_tickets-new', label: 'Créer ticket' }
          : null,
        hasPermission(currentUser, 'CREATE_INVOICES')
          ? { href: '/invoices/invoices-new', label: 'Créer facture' }
          : null,
      ].filter(Boolean) as Array<{ href: string; label: string }>,
    [currentUser],
  );

  const visibleWidgetCount = [
    hasPermission(currentUser, 'READ_LEADS'),
    hasPermission(currentUser, 'READ_DEALS'),
    hasPermission(currentUser, 'READ_PROJECTS'),
    hasPermission(currentUser, 'READ_SUPPORT_TICKETS'),
    hasPermission(currentUser, 'READ_INVOICES'),
  ].filter(Boolean).length;

  return (
    <>
      <Head>
        <title>{getPageTitle('Centre FleetOS')}</title>
      </Head>

      <SectionMain>
        <SectionTitleLineWithButton icon={mdiViewDashboardOutline} title="Centre FleetOS" main>
          <BaseButtons className="mt-4 lg:mt-0">
            <BaseButton href="/dashboard" label="Vue générée" color="whiteDark" />
            <BaseButton href="/leads/leads-list" label="Leads" color="info" />
          </BaseButtons>
        </SectionTitleLineWithButton>

        <div className="mb-8 grid gap-6 xl:grid-cols-[1.2fr_0.8fr]">
          <div className="overflow-hidden rounded-[32px] bg-[linear-gradient(135deg,#091224_0%,#123B7A_56%,#2563EB_100%)] p-8 text-white shadow-[0_40px_120px_-48px_rgba(15,23,42,0.9)]">
            <div className="flex flex-wrap items-center gap-2 text-xs font-semibold uppercase tracking-[0.22em] text-cyan-200">
              <span className="rounded-full border border-white/15 bg-white/10 px-3 py-1">Mission control</span>
              <span className="rounded-full border border-white/15 bg-white/10 px-3 py-1">FR / EN</span>
              <span className="rounded-full border border-white/15 bg-white/10 px-3 py-1">TSC SARL</span>
            </div>

            <h1 className="mt-6 max-w-3xl text-4xl font-semibold leading-tight lg:text-5xl">
              Bonjour {currentUser?.firstName || 'équipe'}, voici le cockpit opérationnel FleetOS.
            </h1>
            <p className="mt-4 max-w-3xl text-base leading-8 text-slate-200">
              Les leads entrants depuis la landing publique alimentent ici un workflow prêt pour les équipes commerciales, delivery, support et finance — sans réécrire les CRUD existants.
            </p>

            <div className="mt-8 grid gap-4 sm:grid-cols-3">
              <div className="rounded-[24px] border border-white/10 bg-white/10 p-5 backdrop-blur-sm">
                <p className="text-xs font-semibold uppercase tracking-[0.2em] text-cyan-200">Workflow actif</p>
                <p className="mt-3 text-2xl font-semibold">Lead → Deal</p>
                <p className="mt-2 text-sm text-slate-200">Intake public, qualification auto et préparation delivery.</p>
              </div>
              <div className="rounded-[24px] border border-white/10 bg-white/10 p-5 backdrop-blur-sm">
                <p className="text-xs font-semibold uppercase tracking-[0.2em] text-cyan-200">Modules visibles</p>
                <p className="mt-3 text-2xl font-semibold">{visibleWidgetCount}</p>
                <p className="mt-2 text-sm text-slate-200">Ventes, projets, support et billing selon vos permissions.</p>
              </div>
              <div className="rounded-[24px] border border-white/10 bg-white/10 p-5 backdrop-blur-sm">
                <p className="text-xs font-semibold uppercase tracking-[0.2em] text-cyan-200">Promesse TSC</p>
                <p className="mt-3 text-2xl font-semibold">24/7</p>
                <p className="mt-2 text-sm text-slate-200">Support priorisé avec visibilité sur SLA et facturation.</p>
              </div>
            </div>
          </div>

          <CardBox className="border-none shadow-[0_32px_80px_-48px_rgba(15,23,42,0.5)]">
            <div className="flex h-full flex-col justify-between gap-6">
              <div>
                <p className="text-xs font-semibold uppercase tracking-[0.24em] text-slate-500">Actions rapides</p>
                <h2 className="mt-3 text-2xl font-semibold text-slate-900">Une vue jeune, nette et orientée exécution.</h2>
                <p className="mt-3 text-sm leading-7 text-slate-600">
                  Accélérez le premier run commercial de FleetOS, puis prolongez vers l’allocation, le timesheet et l’invoicing automatisé.
                </p>
              </div>

              <div className="grid gap-3">
                {heroQuickActions.length > 0 ? (
                  heroQuickActions.map((action) => (
                    <Link
                      key={action.href}
                      href={action.href}
                      className="inline-flex items-center justify-between rounded-2xl border border-slate-200 px-4 py-3 text-sm font-semibold text-slate-700 transition hover:border-slate-300 hover:bg-slate-50"
                    >
                      <span>{action.label}</span>
                      <BaseIcon path={mdiPlus} size={18} />
                    </Link>
                  ))
                ) : (
                  <div className="rounded-2xl border border-dashed border-slate-200 bg-slate-50 p-4 text-sm text-slate-500">
                    Vos actions rapides apparaîtront ici selon vos permissions de création.
                  </div>
                )}
              </div>

              <div className="rounded-[28px] bg-slate-950 p-5 text-white">
                <p className="text-xs font-semibold uppercase tracking-[0.22em] text-cyan-300">TSC SARL</p>
                <p className="mt-3 text-lg font-semibold">Expertise locale combinée aux standards internationaux</p>
                <p className="mt-3 text-sm leading-7 text-slate-300">
                  Kinshasa · Lundi à Vendredi 8h00–18h00 · +243 840 765 653 · lus@nselus.org
                </p>
              </div>
            </div>
          </CardBox>
        </div>

        {partialError && (
          <div className="mb-6 rounded-2xl border border-amber-200 bg-amber-50 px-5 py-4 text-sm text-amber-700">
            {partialError}
          </div>
        )}

        <div className="grid gap-4 md:grid-cols-2 xl:grid-cols-4">
          {hasPermission(currentUser, 'READ_LEADS') && (
            <KpiCard
              title="Leads entrants"
              value={loading ? '…' : hubData.leads.count}
              subtitle="pipeline alimenté depuis la landing publique"
              icon={mdiAccountArrowRight}
              href="/leads/leads-list"
              tone={kpiTone.leads}
            />
          )}
          {hasPermission(currentUser, 'READ_DEALS') && (
            <KpiCard
              title="Deals ouverts"
              value={loading ? '…' : hubData.deals.count}
              subtitle="qualification et relances commerciales"
              icon={mdiHandshake}
              href="/deals/deals-list"
              tone={kpiTone.deals}
            />
          )}
          {hasPermission(currentUser, 'READ_PROJECTS') && (
            <KpiCard
              title="Projets actifs"
              value={loading ? '…' : hubData.projects.count}
              subtitle="delivery, risques et budget"
              icon={mdiBriefcaseVariant}
              href="/projects/projects-list"
              tone={kpiTone.projects}
            />
          )}
          {hasPermission(currentUser, 'READ_INVOICES') && (
            <KpiCard
              title="Factures en retard"
              value={loading ? '…' : hubData.invoices.count}
              subtitle="cash à sécuriser rapidement"
              icon={mdiCashMultiple}
              href="/invoices/invoices-list"
              tone={kpiTone.invoices}
            />
          )}
        </div>

        <div className="mt-8 grid gap-6 xl:grid-cols-3">
          <div className="space-y-6 xl:col-span-2">
            {hasPermission(currentUser, 'READ_LEADS') && (
              <SectionCard
                eyebrow="Acquisition"
                title="Nouveaux leads"
                icon={mdiAccountArrowRight}
                count={hubData.leads.count}
                href="/leads/leads-list"
                actionLabel="Voir tous les leads"
                emptyMessage="Aucun lead récent. Utilisez la landing publique pour injecter une première opportunité dans le pipeline."
                isEmpty={!loading && hubData.leads.rows.length === 0}
              >
                {loading ? (
                  <div className="grid gap-3 md:grid-cols-2">
                    {Array.from({ length: 2 }).map((_, index) => (
                      <div key={index} className="h-36 animate-pulse rounded-2xl bg-slate-100" />
                    ))}
                  </div>
                ) : (
                  <div className="grid gap-3 md:grid-cols-2">
                    {hubData.leads.rows.map((lead) => (
                      <Link
                        key={lead.id}
                        href={`/leads/leads-view/?id=${lead.id}`}
                        className="rounded-[24px] border border-slate-200 bg-slate-50 p-5 transition hover:border-blue-200 hover:bg-white"
                      >
                        <div className="flex items-start justify-between gap-3">
                          <div>
                            <p className="text-lg font-semibold text-slate-900">{lead.company_name || lead.full_name}</p>
                            <p className="mt-1 text-sm text-slate-500">{lead.full_name}</p>
                          </div>
                          <span className={`rounded-full px-3 py-1 text-xs font-semibold ${scoreClass(lead.score)}`}>
                            {typeof lead.score === 'number' ? `${lead.score}/100` : 'À scorer'}
                          </span>
                        </div>
                        <div className="mt-4 flex flex-wrap gap-2 text-xs">
                          <span className={`rounded-full px-3 py-1 font-semibold ${badgeClass(lead.status)}`}>
                            {statusLabel(lead.status)}
                          </span>
                          {lead.service_interest?.name_fr && (
                            <span className="rounded-full border border-slate-200 px-3 py-1 font-semibold text-slate-600">
                              {lead.service_interest.name_fr}
                            </span>
                          )}
                        </div>
                        <p className="mt-4 line-clamp-3 text-sm leading-6 text-slate-600">{lead.message}</p>
                        <div className="mt-4 flex items-center justify-between text-xs text-slate-500">
                          <span>{lead.email}</span>
                          <span>{formatDate(lead.captured_at || lead.createdAt)}</span>
                        </div>
                      </Link>
                    ))}
                  </div>
                )}
              </SectionCard>
            )}

            {hasPermission(currentUser, 'READ_DEALS') && (
              <SectionCard
                eyebrow="Pipeline"
                title="Deals à suivre"
                icon={mdiHandshake}
                count={hubData.deals.count}
                href="/deals/deals-list"
                actionLabel="Ouvrir le pipeline"
                emptyMessage="Aucune opportunité ouverte pour l’instant. Les nouvelles demandes publiques créeront automatiquement une opportunité."
                isEmpty={!loading && hubData.deals.rows.length === 0}
              >
                {loading ? (
                  <div className="grid gap-3 md:grid-cols-2">
                    {Array.from({ length: 2 }).map((_, index) => (
                      <div key={index} className="h-32 animate-pulse rounded-2xl bg-slate-100" />
                    ))}
                  </div>
                ) : (
                  <div className="grid gap-3 md:grid-cols-2">
                    {hubData.deals.rows.map((deal) => (
                      <Link
                        key={deal.id}
                        href={`/deals/deals-view/?id=${deal.id}`}
                        className="rounded-[24px] border border-slate-200 bg-white p-5 transition hover:border-cyan-200 hover:bg-slate-50"
                      >
                        <div className="flex items-start justify-between gap-3">
                          <div>
                            <p className="text-lg font-semibold text-slate-900">{deal.name}</p>
                            <p className="mt-1 text-sm text-slate-500">{deal.company?.legal_name || 'Société à confirmer'}</p>
                          </div>
                          <span className={`rounded-full px-3 py-1 text-xs font-semibold ${badgeClass(deal.status)}`}>
                            {statusLabel(deal.status)}
                          </span>
                        </div>
                        <div className="mt-4 flex flex-wrap gap-2 text-xs">
                          {deal.stage?.name && (
                            <span className="rounded-full border border-slate-200 px-3 py-1 font-semibold text-slate-600">
                              {deal.stage.name}
                            </span>
                          )}
                          {deal.service_line?.name_fr && (
                            <span className="rounded-full border border-slate-200 px-3 py-1 font-semibold text-slate-600">
                              {deal.service_line.name_fr}
                            </span>
                          )}
                        </div>
                        <div className="mt-4 flex items-end justify-between gap-3">
                          <div>
                            <p className="text-xs uppercase tracking-[0.2em] text-slate-400">Montant estimé</p>
                            <p className="mt-2 text-xl font-semibold text-slate-900">
                              {formatCurrency(deal.amount, deal.currency || 'USD')}
                            </p>
                          </div>
                          <div className="text-right text-xs text-slate-500">
                            <p>Closing cible</p>
                            <p className="mt-2 font-semibold text-slate-700">{formatDate(deal.expected_close_at)}</p>
                          </div>
                        </div>
                      </Link>
                    ))}
                  </div>
                )}
              </SectionCard>
            )}

            {hasPermission(currentUser, 'READ_PROJECTS') && (
              <SectionCard
                eyebrow="Delivery"
                title="Projets actifs"
                icon={mdiBriefcaseVariant}
                count={hubData.projects.count}
                href="/projects/projects-list"
                actionLabel="Voir les projets"
                emptyMessage="Aucun projet actif. Le prochain incrément pourra convertir un deal gagné en projet template-ready."
                isEmpty={!loading && hubData.projects.rows.length === 0}
              >
                {loading ? (
                  <div className="grid gap-3 md:grid-cols-2">
                    {Array.from({ length: 2 }).map((_, index) => (
                      <div key={index} className="h-32 animate-pulse rounded-2xl bg-slate-100" />
                    ))}
                  </div>
                ) : (
                  <div className="grid gap-3 md:grid-cols-2">
                    {hubData.projects.rows.map((project) => (
                      <Link
                        key={project.id}
                        href={`/projects/projects-view/?id=${project.id}`}
                        className="rounded-[24px] border border-slate-200 bg-slate-50 p-5 transition hover:border-violet-200 hover:bg-white"
                      >
                        <div className="flex items-start justify-between gap-3">
                          <div>
                            <p className="text-lg font-semibold text-slate-900">{project.name}</p>
                            <p className="mt-1 text-sm text-slate-500">{project.code || 'Code projet à définir'}</p>
                          </div>
                          <span className={`rounded-full px-3 py-1 text-xs font-semibold ${badgeClass(project.status)}`}>
                            {statusLabel(project.status)}
                          </span>
                        </div>
                        <p className="mt-4 line-clamp-3 text-sm leading-6 text-slate-600">{project.summary}</p>
                        <div className="mt-4 flex flex-wrap gap-2 text-xs">
                          {project.risk_level && (
                            <span className={`rounded-full px-3 py-1 font-semibold ${badgeClass(project.risk_level === 'critical' ? 'p1' : project.risk_level === 'high' ? 'p2' : 'open')}`}>
                              Risque {statusLabel(project.risk_level)}
                            </span>
                          )}
                          {project.service_line?.name_fr && (
                            <span className="rounded-full border border-slate-200 px-3 py-1 font-semibold text-slate-600">
                              {project.service_line.name_fr}
                            </span>
                          )}
                        </div>
                        <div className="mt-4 flex items-center justify-between text-xs text-slate-500">
                          <span>{formatCurrency(project.budget_amount, project.budget_currency || 'USD')}</span>
                          <span>{formatDate(project.end_at)}</span>
                        </div>
                      </Link>
                    ))}
                  </div>
                )}
              </SectionCard>
            )}
          </div>

          <div className="space-y-6">
            {hasPermission(currentUser, 'READ_SUPPORT_TICKETS') && (
              <SectionCard
                eyebrow="Support"
                title="Tickets urgents"
                icon={mdiLifebuoy}
                count={urgentTickets.length}
                href="/support_tickets/support_tickets-list"
                actionLabel="Ouvrir le Service Desk"
                emptyMessage="Aucun ticket P1/P2 dans les tickets récents."
                isEmpty={!loading && urgentTickets.length === 0}
              >
                {loading ? (
                  <div className="space-y-3">
                    {Array.from({ length: 3 }).map((_, index) => (
                      <div key={index} className="h-24 animate-pulse rounded-2xl bg-slate-100" />
                    ))}
                  </div>
                ) : (
                  <div className="space-y-3">
                    {urgentTickets.map((ticket) => (
                      <Link
                        key={ticket.id}
                        href={`/support_tickets/support_tickets-view/?id=${ticket.id}`}
                        className="block rounded-[24px] border border-slate-200 bg-white p-5 transition hover:border-rose-200 hover:bg-slate-50"
                      >
                        <div className="flex items-start justify-between gap-3">
                          <div>
                            <p className="text-base font-semibold text-slate-900">{ticket.subject}</p>
                            <p className="mt-1 text-sm text-slate-500">{ticket.ticket_number || 'Ticket'} · {ticket.company?.legal_name || 'Client non précisé'}</p>
                          </div>
                          <div className="flex flex-col items-end gap-2 text-xs">
                            <span className={`rounded-full px-3 py-1 font-semibold ${badgeClass(ticket.priority)}`}>
                              {statusLabel(ticket.priority)}
                            </span>
                            <span className={`rounded-full px-3 py-1 font-semibold ${badgeClass(ticket.status)}`}>
                              {statusLabel(ticket.status)}
                            </span>
                          </div>
                        </div>
                        <div className="mt-4 flex items-center justify-between text-xs text-slate-500">
                          <span>{ticket.sla_breached ? 'SLA à risque' : 'SLA maîtrisé'}</span>
                          <span>{formatDate(ticket.resolution_due_at || ticket.createdAt)}</span>
                        </div>
                      </Link>
                    ))}
                  </div>
                )}
              </SectionCard>
            )}

            {hasPermission(currentUser, 'READ_INVOICES') && (
              <SectionCard
                eyebrow="Cash watch"
                title="Factures à relancer"
                icon={mdiCashMultiple}
                count={hubData.invoices.count}
                href="/invoices/invoices-list"
                actionLabel="Voir la facturation"
                emptyMessage="Aucune facture overdue. Bravo — le cash est sous contrôle."
                isEmpty={!loading && hubData.invoices.rows.length === 0}
              >
                {loading ? (
                  <div className="space-y-3">
                    {Array.from({ length: 3 }).map((_, index) => (
                      <div key={index} className="h-24 animate-pulse rounded-2xl bg-slate-100" />
                    ))}
                  </div>
                ) : (
                  <div className="space-y-3">
                    {hubData.invoices.rows.map((invoice) => (
                      <Link
                        key={invoice.id}
                        href={`/invoices/invoices-view/?id=${invoice.id}`}
                        className="block rounded-[24px] border border-slate-200 bg-slate-50 p-5 transition hover:border-orange-200 hover:bg-white"
                      >
                        <div className="flex items-start justify-between gap-3">
                          <div>
                            <p className="text-base font-semibold text-slate-900">{invoice.invoice_number || 'Facture'}</p>
                            <p className="mt-1 text-sm text-slate-500">{invoice.company?.legal_name || 'Client non précisé'}</p>
                          </div>
                          <span className={`rounded-full px-3 py-1 text-xs font-semibold ${badgeClass(invoice.status)}`}>
                            {statusLabel(invoice.status)}
                          </span>
                        </div>
                        <div className="mt-4 flex items-end justify-between gap-3">
                          <div>
                            <p className="text-xs uppercase tracking-[0.2em] text-slate-400">Montant</p>
                            <p className="mt-2 text-lg font-semibold text-slate-900">
                              {formatCurrency(invoice.total, invoice.currency || 'USD')}
                            </p>
                          </div>
                          <div className="text-right text-xs text-slate-500">
                            <p>Échéance</p>
                            <p className="mt-2 font-semibold text-slate-700">{formatDate(invoice.due_at)}</p>
                          </div>
                        </div>
                      </Link>
                    ))}
                  </div>
                )}
              </SectionCard>
            )}

            {hasPermission(currentUser, 'READ_PROJECT_TEMPLATES') && (
              <CardBox className="border-none shadow-[0_32px_80px_-48px_rgba(15,23,42,0.5)]">
                <div className="mb-5 flex items-center justify-between gap-4">
                  <div>
                    <p className="text-xs font-semibold uppercase tracking-[0.24em] text-slate-500">Playbooks</p>
                    <h2 className="mt-3 text-xl font-semibold text-slate-900">Templates TSC prêts à l’emploi</h2>
                  </div>
                  <div className="rounded-2xl bg-slate-900 p-3 text-white">
                    <BaseIcon path={mdiStarFourPoints} size={20} />
                  </div>
                </div>

                <div className="space-y-3">
                  {playbooks.map((playbook) => (
                    <div key={playbook.name} className="rounded-[24px] border border-slate-200 bg-slate-50 p-4">
                      <div className="flex items-center justify-between gap-3">
                        <div>
                          <p className="font-semibold text-slate-900">{playbook.name}</p>
                          <p className="mt-1 text-sm text-slate-500">{playbook.line}</p>
                        </div>
                        <span className="rounded-full border border-slate-200 px-3 py-1 text-xs font-semibold text-slate-600">
                          {playbook.duration}
                        </span>
                      </div>
                    </div>
                  ))}
                </div>

                <div className="mt-5 rounded-[24px] bg-slate-950 p-5 text-white">
                  <p className="text-xs font-semibold uppercase tracking-[0.22em] text-cyan-300">Next-ready</p>
                  <p className="mt-3 text-sm leading-7 text-slate-300">
                    Le prochain incrément logique : transformer automatiquement un deal gagné en projet, milestones et tâches basées sur ces templates.
                  </p>
                  <Link href="/project_templates/project_templates-list" className="mt-4 inline-flex items-center text-sm font-semibold text-cyan-200 transition hover:text-white">
                    Gérer les templates
                    <BaseIcon path={mdiArrowRight} size={16} className="ml-2" />
                  </Link>
                </div>
              </CardBox>
            )}

            <CardBox className="border-none shadow-[0_32px_80px_-48px_rgba(15,23,42,0.5)]">
              <div className="flex items-start justify-between gap-4">
                <div>
                  <p className="text-xs font-semibold uppercase tracking-[0.24em] text-slate-500">Cadence</p>
                  <h2 className="mt-3 text-xl font-semibold text-slate-900">Rituel recommandé</h2>
                </div>
                <div className="rounded-2xl bg-slate-900 p-3 text-white">
                  <BaseIcon path={mdiClockOutline} size={20} />
                </div>
              </div>
              <div className="mt-5 space-y-3 text-sm leading-7 text-slate-600">
                <div className="rounded-2xl border border-slate-200 bg-slate-50 p-4">
                  08h30 — revue des leads entrants et qualification commerciale.
                </div>
                <div className="rounded-2xl border border-slate-200 bg-slate-50 p-4">
                  12h00 — check delivery : budget, risques, tickets critiques.
                </div>
                <div className="rounded-2xl border border-slate-200 bg-slate-50 p-4">
                  16h30 — suivi cash : factures en retard et actions de relance.
                </div>
              </div>
            </CardBox>
          </div>
        </div>
      </SectionMain>
    </>
  );
};

FleetOsHub.getLayout = function getLayout(page: ReactElement) {
  return <LayoutAuthenticated>{page}</LayoutAuthenticated>;
};

export default FleetOsHub;
