import React, { useEffect, useMemo, useState } from "react";
import axios from "axios";
import {
  ActivityIndicator,
  Alert,
  Pressable,
  SafeAreaView,
  ScrollView,
  StyleSheet,
  Text,
  TextInput,
  View,
} from "react-native";
import { StatusBar } from "expo-status-bar";
import type { MobileUser } from "./src/types/auth";
import type {
  MobileIntervention,
  MobileInterventionDetails,
  MobilePrecheckPayload,
  MobilePrecheckRequirements,
} from "./src/types/intervention";
import {
  clearSession,
  readSession,
  saveSession,
} from "./src/services/tokenStorage";
import * as authApi from "./src/services/authApi";
import * as interventionsApi from "./src/services/interventionsApi";
import {
  clearPrecheckDraft,
  getPrecheckDraft,
  savePrecheckDraft,
} from "./src/services/precheckDraftStorage";
import {
  clearApiAuthTokens,
  initializeApiClientAuth,
  setApiAuthTokens,
} from "./src/services/apiClient";

type ViewMode = "list" | "detail" | "precheck";
type NavSection =
  | "home"
  | "missions"
  | "planifiees"
  | "profil"
  | "stats"
  | "support";

const NAV_ITEMS: Array<{ key: NavSection; label: string }> = [
  { key: "home", label: "Accueil" },
  { key: "missions", label: "Mes missions" },
  { key: "planifiees", label: "Interventions planifiees" },
  { key: "profil", label: "Mon profil" },
  { key: "stats", label: "Statistiques" },
  { key: "support", label: "Support" },
];

function getSectionTitle(section: NavSection): string {
  const item = NAV_ITEMS.find((entry) => entry.key === section);
  return item ? item.label : "CoolCare Mobile";
}

type DevisLike = {
  id?: number | string;
  numero_devis?: string;
  statut?: string;
  date_devis?: string;
  montant?: number | string;
  fichier_pdf_path?: string;
  fichiers_pdf_list?: string[];
  fichiers_pdf?: string[] | string;
};

const TYPE_LABELS: Record<string, string> = {
  maintenance_preventive: "Maintenance preventive",
  maintenance_corrective: "Maintenance corrective",
  installation: "Installation",
  mise_en_service: "Mise en service",
  controle_reglementaire: "Controle reglementaire",
  arret_definitif: "Arret definitif",
  fuite: "Reparation fuite",
  recharge: "Recharge fluide",
};

const STATUS_STYLES: Record<
  string,
  { label: string; color: string; backgroundColor: string; borderColor: string }
> = {
  en_cours: {
    label: "En cours",
    color: "#0f766e",
    backgroundColor: "#ccfbf1",
    borderColor: "#5eead4",
  },
  terminee: {
    label: "Terminee",
    color: "#166534",
    backgroundColor: "#dcfce7",
    borderColor: "#86efac",
  },
  planifiee: {
    label: "Planifiee",
    color: "#1d4ed8",
    backgroundColor: "#dbeafe",
    borderColor: "#93c5fd",
  },
  reportee: {
    label: "Reportee",
    color: "#92400e",
    backgroundColor: "#ffedd5",
    borderColor: "#fdba74",
  },
  en_attente: {
    label: "En attente",
    color: "#374151",
    backgroundColor: "#f3f4f6",
    borderColor: "#d1d5db",
  },
  annulee: {
    label: "Annulee",
    color: "#991b1b",
    backgroundColor: "#fee2e2",
    borderColor: "#fca5a5",
  },
};

function formatInterventionDate(value: string | undefined): string {
  if (!value) {
    return "-";
  }

  const parsed = new Date(value.replace(" ", "T"));
  if (Number.isNaN(parsed.getTime())) {
    return value;
  }

  return parsed.toLocaleString();
}

function formatDateFr(value: string | undefined): string {
  if (!value) {
    return "-";
  }

  const parsed = new Date(value.replace(" ", "T"));
  if (Number.isNaN(parsed.getTime())) {
    return value;
  }

  return parsed.toLocaleDateString();
}

function detailValue(value: unknown): string {
  if (value === null || value === undefined) {
    return "-";
  }

  const text = String(value).trim();
  return text === "" ? "-" : text;
}

function asObject(value: unknown): Record<string, unknown> {
  if (value && typeof value === "object" && !Array.isArray(value)) {
    return value as Record<string, unknown>;
  }

  return {};
}

function getTypeLabel(type: string | undefined): string {
  if (!type) {
    return "-";
  }

  return TYPE_LABELS[type] || type;
}

function getStatusStyle(statut: string | undefined): {
  label: string;
  color: string;
  backgroundColor: string;
  borderColor: string;
} {
  if (!statut) {
    return {
      label: "Inconnu",
      color: "#374151",
      backgroundColor: "#f3f4f6",
      borderColor: "#d1d5db",
    };
  }

  return (
    STATUS_STYLES[statut] || {
      label: statut,
      color: "#374151",
      backgroundColor: "#f3f4f6",
      borderColor: "#d1d5db",
    }
  );
}

function getFluideLabel(intervention: MobileIntervention): string {
  if (intervention.machine_marque && intervention.machine_modele) {
    return `${intervention.machine_marque} ${intervention.machine_modele}`;
  }

  if (intervention.machine_marque) {
    return intervention.machine_marque;
  }

  const machineName = (intervention.machine_nom || "").toLowerCase();
  if (machineName.includes("r410a") || machineName.includes("r-410a")) {
    return "R410A";
  }
  if (machineName.includes("r407c") || machineName.includes("r-407c")) {
    return "R407C";
  }
  if (machineName.includes("r134a") || machineName.includes("r-134a")) {
    return "R134A";
  }
  if (machineName.includes("r22") || machineName.includes("r-22")) {
    return "R22";
  }
  if (machineName.includes("r404a") || machineName.includes("r-404a")) {
    return "R404A";
  }
  if (machineName.includes("r507") || machineName.includes("r-507")) {
    return "R507";
  }

  return intervention.machine_nom ? "Fluide frigorifique" : "-";
}

function detectRequirements(intervention: MobileInterventionDetails | null): {
  needsCerfa: boolean;
  needsPrelevement: boolean;
  prelevementInfo: string;
} {
  if (!intervention) {
    return {
      needsCerfa: false,
      needsPrelevement: false,
      prelevementInfo: "Non requis selon la machine.",
    };
  }

  const machine = asObject(intervention.machine_details);
  const needsCerfa =
    intervention.type_intervention === "controle_reglementaire" ||
    Boolean(machine.frequence_controle_cerfa);

  const prelevementRequired = Number(machine.prelevement_huile_requis || 0) === 1;
  const freqRaw = detailValue(machine.prelevement_huile_frequence);
  const prelevementInfo = prelevementRequired
    ? `Requis selon la machine${freqRaw !== "-" ? ` (frequence: ${freqRaw} an).` : "."}`
    : "Non requis selon la machine.";

  return {
    needsCerfa,
    needsPrelevement: prelevementRequired,
    prelevementInfo,
  };
}

function formatAmount(amount: unknown): string {
  if (amount === null || amount === undefined || amount === "") {
    return "-";
  }

  const num = Number(amount);
  if (Number.isNaN(num)) {
    return String(amount);
  }

  return `${num.toLocaleString(undefined, {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2,
  })} EUR`;
}

function extractDevisFiles(item: DevisLike): string[] {
  const files: string[] = [];

  if (item.fichier_pdf_path) {
    files.push(String(item.fichier_pdf_path));
  }

  if (Array.isArray(item.fichiers_pdf_list)) {
    files.push(...item.fichiers_pdf_list.map(String));
  }

  if (Array.isArray(item.fichiers_pdf)) {
    files.push(...item.fichiers_pdf.map(String));
  } else if (typeof item.fichiers_pdf === "string" && item.fichiers_pdf.trim() !== "") {
    try {
      const parsed = JSON.parse(item.fichiers_pdf);
      if (Array.isArray(parsed)) {
        files.push(...parsed.map(String));
      }
    } catch {
      // Ignore malformed payload.
    }
  }

  return Array.from(new Set(files.map((path) => path.replace(/^\/+/, "").trim()).filter(Boolean)));
}

function toTimestamp(dateValue: string | undefined): number {
  if (!dateValue) {
    return 0;
  }

  const time = new Date(dateValue.replace(" ", "T")).getTime();
  return Number.isNaN(time) ? 0 : time;
}

function extractDevisEntries(intervention: MobileInterventionDetails | null): DevisLike[] {
  if (!intervention) {
    return [];
  }

  const entries: DevisLike[] = [];
  const rawInterventions = (intervention as Record<string, unknown>).devis_interventions;
  if (Array.isArray(rawInterventions)) {
    for (const row of rawInterventions) {
      if (row && typeof row === "object") {
        entries.push(row as DevisLike);
      }
    }
  }

  const rawDetails = (intervention as Record<string, unknown>).devis_details;
  if (rawDetails && typeof rawDetails === "object") {
    entries.push(rawDetails as DevisLike);
  }

  if (entries.length === 0) {
    return [];
  }

  const unique = new Map<string, DevisLike>();
  for (const item of entries) {
    const key = `${detailValue(item.id)}|${detailValue(item.numero_devis)}|${detailValue(item.date_devis)}`;
    if (!unique.has(key)) {
      unique.set(key, item);
    }
  }

  return Array.from(unique.values()).sort(
    (a, b) => toTimestamp(b.date_devis) - toTimestamp(a.date_devis)
  );
}

function buildDevisLine(item: DevisLike): string {
  const files = extractDevisFiles(item);
  const pdfLabel = files.length > 0 ? `${files.length} PDF` : "Aucun PDF";

  return `#${detailValue(item.id)} - ${detailValue(item.numero_devis)} | ${detailValue(
    item.statut
  )} | ${formatDateFr(item.date_devis)} | ${formatAmount(item.montant)} | ${pdfLabel}`;
}

function isLikelyOfflineError(error: unknown): boolean {
  if (axios.isAxiosError(error)) {
    if (!error.response) {
      return true;
    }

    const code = String(error.code || "").toUpperCase();
    if (
      code.includes("NETWORK") ||
      code.includes("TIMEOUT") ||
      code === "ECONNABORTED"
    ) {
      return true;
    }
  }

  const message =
    error instanceof Error ? error.message.toLowerCase() : String(error || "").toLowerCase();
  return (
    message.includes("network") ||
    message.includes("timeout") ||
    message.includes("failed to fetch")
  );
}

export default function App() {
  const [booting, setBooting] = useState(true);
  const [submitting, setSubmitting] = useState(false);
  const [checkingSession, setCheckingSession] = useState(false);
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [error, setError] = useState<string | null>(null);
  const [interventionsError, setInterventionsError] = useState<string | null>(null);
  const [user, setUser] = useState<MobileUser | null>(null);
  const [statusMessage, setStatusMessage] = useState<string | null>(null);
  const [interventions, setInterventions] = useState<MobileIntervention[]>([]);
  const [loadingInterventions, setLoadingInterventions] = useState(false);
  const [activeSection, setActiveSection] = useState<NavSection>("home");
  const [drawerOpen, setDrawerOpen] = useState(false);

  const [viewMode, setViewMode] = useState<ViewMode>("list");
  const [selectedInterventionId, setSelectedInterventionId] = useState<number | null>(null);
  const [selectedIntervention, setSelectedIntervention] =
    useState<MobileInterventionDetails | null>(null);
  const [loadingInterventionDetails, setLoadingInterventionDetails] = useState(false);
  const [interventionDetailsError, setInterventionDetailsError] = useState<string | null>(null);

  const [cerfaEnabled, setCerfaEnabled] = useState(false);
  const [cerfaValue, setCerfaValue] = useState("");
  const [prelevementValue, setPrelevementValue] = useState("");
  const [precheckError, setPrecheckError] = useState<string | null>(null);
  const [precheckLoading, setPrecheckLoading] = useState(false);
  const [precheckRequirements, setPrecheckRequirements] =
    useState<MobilePrecheckRequirements | null>(null);

  const loadInterventions = async (): Promise<number> => {
    setLoadingInterventions(true);
    setInterventionsError(null);

    try {
      const payload = await interventionsApi.getMyInterventions();
      setInterventions(payload.items);
      return payload.count;
    } catch (e) {
      const message = e instanceof Error ? e.message : "Interventions loading failed";
      setInterventionsError(message);
      return 0;
    } finally {
      setLoadingInterventions(false);
    }
  };

  const loadInterventionDetails = async (id: number): Promise<void> => {
    setLoadingInterventionDetails(true);
    setInterventionDetailsError(null);
    setPrecheckRequirements(null);

    try {
      const item = await interventionsApi.getInterventionById(id);
      setSelectedIntervention(item);
      setSelectedInterventionId(id);
      setViewMode("detail");
      setActiveSection("missions");
      setPrecheckError(null);
    } catch (e) {
      const message = e instanceof Error ? e.message : "Intervention details loading failed";
      setInterventionDetailsError(message);
      setSelectedIntervention(null);
      setSelectedInterventionId(id);
      setViewMode("detail");
      setActiveSection("missions");
    } finally {
      setLoadingInterventionDetails(false);
    }
  };

  const buildPrecheckPayload = (interventionId: number): MobilePrecheckPayload => ({
    intervention_id: interventionId,
    cerfa_enabled: cerfaEnabled,
    cerfa_number: cerfaValue.trim(),
    prelevement_number: prelevementValue.trim(),
  });

  const loadPrecheckForIntervention = async (interventionId: number): Promise<void> => {
    setPrecheckLoading(true);
    setPrecheckError(null);

    const localDraft = await getPrecheckDraft(interventionId);
    if (localDraft) {
      setCerfaEnabled(localDraft.cerfa_enabled);
      setCerfaValue(localDraft.cerfa_number);
      setPrelevementValue(localDraft.prelevement_number);
    }

    try {
      const state = await interventionsApi.getInterventionPrecheck(interventionId);
      setPrecheckRequirements(state.requirements ?? null);

      if (!localDraft && state.precheck) {
        setCerfaEnabled(state.precheck.cerfa_enabled);
        setCerfaValue(state.precheck.cerfa_number || "");
        setPrelevementValue(state.precheck.prelevement_number || "");
      }
    } catch (error) {
      if (!localDraft) {
        const message =
          error instanceof Error ? error.message : "Unable to load precheck state";
        setPrecheckError(message);
      }
    } finally {
      setPrecheckLoading(false);
    }
  };

  useEffect(() => {
    const bootstrap = async () => {
      try {
        await initializeApiClientAuth();
        const session = await readSession();
        if (!session.accessToken || !session.refreshToken) {
          setBooting(false);
          return;
        }

        setApiAuthTokens(session.accessToken, session.refreshToken);
        const currentUser = await authApi.me();

        setUser(currentUser);
        await loadInterventions();
        setStatusMessage("Session restored.");
      } catch {
        await clearSession();
        clearApiAuthTokens();
      }

      setBooting(false);
    };

    void bootstrap();
  }, []);

  useEffect(() => {
    if (viewMode !== "precheck" || selectedInterventionId === null) {
      return;
    }

    const payload: MobilePrecheckPayload = {
      intervention_id: selectedInterventionId,
      cerfa_enabled: cerfaEnabled,
      cerfa_number: cerfaValue,
      prelevement_number: prelevementValue,
    };

    const timer = setTimeout(() => {
      void savePrecheckDraft(payload);
    }, 250);

    return () => {
      clearTimeout(timer);
    };
  }, [viewMode, selectedInterventionId, cerfaEnabled, cerfaValue, prelevementValue]);

  const onLogin = async () => {
    if (!email.trim() || !password) {
      setError("Email and password are required.");
      return;
    }

    setSubmitting(true);
    setError(null);

    try {
      const result = await authApi.login(email.trim(), password);
      await saveSession(result.access_token, result.refresh_token, result.user);
      setApiAuthTokens(result.access_token, result.refresh_token);
      setUser(result.user);
      const count = await loadInterventions();
      setPassword("");
      setViewMode("list");
      setActiveSection("home");
      setDrawerOpen(false);
      setStatusMessage(
        `Connected. ${count} intervention${count > 1 ? "s" : ""} loaded.`
      );
    } catch (e) {
      const message = e instanceof Error ? e.message : "Login error";
      setError(message);
    } finally {
      setSubmitting(false);
    }
  };

  const onLogout = async () => {
    try {
      const session = await readSession();
      if (session.refreshToken) {
        await authApi.logout(session.refreshToken);
      }
    } catch {
      // Ignore logout API failure and clear local session anyway.
    }

    await clearSession();
    clearApiAuthTokens();
    setUser(null);
    setInterventions([]);
    setInterventionsError(null);
    setSelectedInterventionId(null);
    setSelectedIntervention(null);
    setInterventionDetailsError(null);
    setViewMode("list");
    setCerfaEnabled(false);
    setCerfaValue("");
    setPrelevementValue("");
    setPrecheckError(null);
    setPrecheckRequirements(null);
    setActiveSection("home");
    setDrawerOpen(false);
    setPassword("");
    setStatusMessage("Logged out.");
  };

  const onCheckSessionApi = async () => {
    setCheckingSession(true);
    setError(null);

    try {
      const currentUser = await authApi.me();
      setUser(currentUser);
      const count = await loadInterventions();
      setStatusMessage(
        `Session API valid. ${count} intervention${count > 1 ? "s" : ""} loaded.`
      );
    } catch (e) {
      const message = e instanceof Error ? e.message : "Session check failed";
      setError(message);
      setStatusMessage(null);
    } finally {
      setCheckingSession(false);
    }
  };

  const onRefreshInterventions = async () => {
    const count = await loadInterventions();
    if (selectedInterventionId !== null) {
      await loadInterventionDetails(selectedInterventionId);
    }
    setStatusMessage(
      `Interventions refreshed (${count} intervention${count > 1 ? "s" : ""}).`
    );
  };

  const onShowApiInfo = () => {
    Alert.alert(
      "API base URL",
      "Defined via EXPO_PUBLIC_API_BASE_URL or default CoolCare endpoint."
    );
  };

  const onOpenSection = (section: NavSection) => {
    setActiveSection(section);
    setDrawerOpen(false);
    if (section === "home") {
      setViewMode("list");
      return;
    }
    if (section === "missions") {
      setViewMode("list");
      setSelectedInterventionId(null);
      setSelectedIntervention(null);
      setInterventionDetailsError(null);
      setPrecheckError(null);
      setPrecheckRequirements(null);
    }
  };

  const onBackToList = () => {
    setActiveSection("missions");
    setViewMode("list");
    setSelectedInterventionId(null);
    setSelectedIntervention(null);
    setInterventionDetailsError(null);
    setPrecheckError(null);
    setPrecheckRequirements(null);
  };

  const onNoStartFromDetail = () => {
    Alert.alert("Ne pas debuter", "Confirmer que vous ne demarrez pas cette intervention ?", [
      { text: "Annuler", style: "cancel" },
      {
        text: "Confirmer",
        style: "destructive",
        onPress: () => {
          setStatusMessage("Mission laissee non demarree.");
          onBackToList();
        },
      },
    ]);
  };

  const onStartFromDetail = async () => {
    if (!selectedInterventionId) {
      return;
    }

    const requirements = detectRequirements(selectedIntervention);
    setPrecheckRequirements(null);
    setCerfaEnabled(requirements.needsCerfa);
    setCerfaValue("");
    setPrelevementValue("");
    setPrecheckError(null);
    setViewMode("precheck");
    await loadPrecheckForIntervention(selectedInterventionId);
  };

  const onNoStartFromPrecheck = async () => {
    if (selectedInterventionId) {
      const payload = buildPrecheckPayload(selectedInterventionId);
      try {
        await interventionsApi.saveInterventionPrecheck(payload);
        await clearPrecheckDraft(selectedInterventionId);
        setStatusMessage("Pre-check sauvegarde.");
      } catch (error) {
        await savePrecheckDraft(payload);
        if (isLikelyOfflineError(error)) {
          setStatusMessage("Pre-check sauvegarde localement (hors ligne).");
        } else {
          const message =
            error instanceof Error ? error.message : "Pre-check save failed";
          setStatusMessage(`Pre-check local uniquement: ${message}`);
        }
      }
    }

    setPrecheckError(null);
    setViewMode("detail");
  };

  const onStartFromPrecheck = async () => {
    if (!selectedInterventionId) {
      return;
    }

    const requirements = precheckRequirements
      ? {
          needsCerfa: precheckRequirements.needs_cerfa,
          needsPrelevement: precheckRequirements.needs_prelevement,
          prelevementInfo: precheckRequirements.prelevement_info,
        }
      : detectRequirements(selectedIntervention);
    const cerfa = cerfaValue.trim();
    const prelevement = prelevementValue.trim();

    if (cerfaEnabled && cerfa === "") {
      setPrecheckError("Le N degre CERFA est active: merci de le renseigner.");
      return;
    }

    if (requirements.needsPrelevement && prelevement === "") {
      setPrecheckError("Le N degre prelevement huile est requis pour cette mission.");
      return;
    }

    setPrecheckError(null);
    const payload = buildPrecheckPayload(selectedInterventionId);

    try {
      await interventionsApi.startIntervention(payload);
      await clearPrecheckDraft(selectedInterventionId);
      await loadInterventions();
      await loadInterventionDetails(selectedInterventionId);
      setViewMode("detail");
      setStatusMessage("Intervention demarree et synchronisee.");
    } catch (error) {
      if (isLikelyOfflineError(error)) {
        await savePrecheckDraft(payload);
        setStatusMessage("Hors ligne: debut d'intervention sauvegarde localement.");
        setViewMode("detail");
        return;
      }

      const message = error instanceof Error ? error.message : "Start failed";
      setPrecheckError(message);
    }
  };

  const requirements = useMemo(
    () =>
      precheckRequirements
        ? {
            needsCerfa: precheckRequirements.needs_cerfa,
            needsPrelevement: precheckRequirements.needs_prelevement,
            prelevementInfo: precheckRequirements.prelevement_info,
          }
        : detectRequirements(selectedIntervention),
    [selectedIntervention, precheckRequirements]
  );

  const devisEntries = useMemo(
    () => extractDevisEntries(selectedIntervention),
    [selectedIntervention]
  );

  const pendingDevis = useMemo(
    () => devisEntries.filter((item) => item.statut === "en_attente"),
    [devisEntries]
  );

  const lastDevis = useMemo(() => (devisEntries.length > 0 ? [devisEntries[0]] : []), [devisEntries]);
  const plannedInterventions = useMemo(
    () =>
      interventions.filter(
        (item) =>
          (item.statut || "").toLowerCase() === "planifiee" ||
          (item.statut || "").toLowerCase() === "reportee"
      ),
    [interventions]
  );
  const quickStats = useMemo(() => {
    const total = interventions.length;
    const enCours = interventions.filter(
      (item) => (item.statut || "").toLowerCase() === "en_cours"
    ).length;
    const planifiees = interventions.filter(
      (item) => (item.statut || "").toLowerCase() === "planifiee"
    ).length;
    const terminees = interventions.filter(
      (item) => (item.statut || "").toLowerCase() === "terminee"
    ).length;
    const completionRate =
      total > 0 ? `${Math.round((terminees / total) * 100)}%` : "0%";

    return {
      total,
      enCours,
      planifiees,
      terminees,
      completionRate,
    };
  }, [interventions]);

  if (booting) {
    return (
      <SafeAreaView style={styles.centered}>
        <StatusBar style="dark" />
        <ActivityIndicator size="large" />
        <Text style={styles.mutedText}>Loading session...</Text>
      </SafeAreaView>
    );
  }

  const siteDetails = asObject(selectedIntervention?.site_details);
  const machineDetails = asObject(selectedIntervention?.machine_details);
  const detailStatus = getStatusStyle(selectedIntervention?.statut);
  const isHomeScreen = activeSection === "home";
  const isInSection = !isHomeScreen;

  return (
    <SafeAreaView style={styles.container}>
      <StatusBar style="dark" />
      <ScrollView
        contentContainerStyle={[
          styles.scrollContent,
          user ? styles.scrollContentLogged : undefined,
        ]}
      >
        <View style={styles.card}>
          {!user ? <Text style={styles.title}>CoolCare Mobile</Text> : null}

          {user ? (
            <View style={styles.loggedBlock}>
              <View style={isHomeScreen ? styles.homeHeader : styles.navHeader}>
                {isInSection ? (
                  <Pressable
                    style={styles.menuButton}
                    onPress={() => setDrawerOpen((prev) => !prev)}
                  >
                    <Text style={styles.menuButtonText}>☰</Text>
                  </Pressable>
                ) : (
                  <Text style={styles.homeBrand}>CoolCare</Text>
                )}
                <View
                  style={[
                    styles.navHeaderTextWrap,
                    isHomeScreen ? styles.navHeaderTextWrapHome : undefined,
                  ]}
                >
                  <Text style={styles.navHeaderTitle}>
                    {isHomeScreen ? user.name : getSectionTitle(activeSection)}
                  </Text>
                  <Text style={styles.navHeaderSubtitle}>
                    {isHomeScreen ? "Technicien" : user.email}
                  </Text>
                </View>
              </View>

              {isInSection && drawerOpen ? (
                <View style={styles.drawerPanel}>
                  {NAV_ITEMS.map((item) => (
                    <Pressable
                      key={item.key}
                      style={[
                        styles.drawerItem,
                        activeSection === item.key && styles.drawerItemActive,
                      ]}
                      onPress={() => onOpenSection(item.key)}
                    >
                      <Text
                        style={[
                          styles.drawerItemText,
                          activeSection === item.key && styles.drawerItemTextActive,
                        ]}
                      >
                        {item.label}
                      </Text>
                    </Pressable>
                  ))}

                  <Pressable style={styles.drawerFooterButton} onPress={onShowApiInfo}>
                    <Text style={styles.drawerFooterText}>API Info</Text>
                  </Pressable>
                  <Pressable style={styles.drawerFooterDanger} onPress={onLogout}>
                    <Text style={styles.drawerFooterDangerText}>Deconnexion</Text>
                  </Pressable>
                </View>
              ) : null}

              {statusMessage ? <Text style={styles.success}>{statusMessage}</Text> : null}

              {isHomeScreen ? (
                <View style={styles.homeGrid}>
                  <Pressable
                    style={[styles.homeCard, styles.homeCardPrimary]}
                    onPress={() => onOpenSection("missions")}
                  >
                    <Text style={styles.homeCardTitle}>Interventions a realiser</Text>
                    <Text style={styles.homeCardText}>
                      Consulter l'historique de mes rapports
                    </Text>
                    <Text style={styles.homeCardAccent}>
                      {interventions.length} intervention(s)
                    </Text>
                  </Pressable>

                  <Pressable
                    style={styles.homeCard}
                    onPress={() => onOpenSection("planifiees")}
                  >
                    <Text style={styles.homeCardTitle}>Interventions planifiees</Text>
                    <Text style={styles.homeCardText}>
                      {plannedInterventions.length} intervention(s) planifiee(s)
                    </Text>
                    {plannedInterventions[0] ? (
                      <Text style={styles.homeCardHint}>
                        [!] {detailValue(plannedInterventions[0].site_nom)}
                      </Text>
                    ) : (
                      <Text style={styles.homeCardHint}>Aucune intervention en attente.</Text>
                    )}
                  </Pressable>

                  <Pressable
                    style={styles.homeCard}
                    onPress={() => onOpenSection("profil")}
                  >
                    <Text style={styles.homeCardTitle}>Mes informations</Text>
                    <Text style={styles.homeCardText}>Email: {detailValue(user.email)}</Text>
                    <Text style={styles.homeCardHint}>Detection fuite: A verifier</Text>
                    <Text style={styles.homeCardHint}>Capteur T: A verifier</Text>
                    <Text style={styles.homeCardHint}>Balance: A verifier</Text>
                  </Pressable>

                  <Pressable
                    style={[styles.homeCard, styles.homeCardPrimary]}
                    onPress={() => onOpenSection("stats")}
                  >
                    <Text style={styles.homeCardTitle}>Statistiques</Text>
                    <Text style={styles.homeCardText}>
                      {quickStats.total} interventions ce mois
                    </Text>
                    <Text style={styles.homeCardHint}>
                      {quickStats.completionRate} taux de completion
                    </Text>
                  </Pressable>

                  <Pressable
                    style={styles.homeCard}
                    onPress={() => onOpenSection("support")}
                  >
                    <Text style={styles.homeCardTitle}>Support</Text>
                    <Text style={styles.homeCardText}>support@coolcare.fr</Text>
                    <Text style={styles.homeCardHint}>01.XX.XX.XX.XX</Text>
                  </Pressable>

                  <View style={styles.homeActionsRow}>
                    <Pressable
                      style={[styles.secondaryButton, loadingInterventions && styles.buttonDisabled]}
                      onPress={onRefreshInterventions}
                      disabled={loadingInterventions}
                    >
                      <Text style={styles.secondaryButtonText}>
                        {loadingInterventions ? "Refreshing..." : "Rafraichir"}
                      </Text>
                    </Pressable>
                    <Pressable style={styles.primaryButton} onPress={onLogout}>
                      <Text style={styles.primaryButtonText}>Deconnexion</Text>
                    </Pressable>
                  </View>
                </View>
              ) : null}

              {activeSection === "missions" ? (
                <Pressable
                  style={[styles.secondaryButton, checkingSession && styles.buttonDisabled]}
                  onPress={onCheckSessionApi}
                  disabled={checkingSession}
                >
                  <Text style={styles.secondaryButtonText}>
                    {checkingSession ? "Checking..." : "Check API session"}
                  </Text>
                </Pressable>
              ) : null}

              {activeSection === "missions" ? (
                <Pressable
                  style={[styles.secondaryButton, loadingInterventions && styles.buttonDisabled]}
                  onPress={onRefreshInterventions}
                  disabled={loadingInterventions}
                >
                  <Text style={styles.secondaryButtonText}>
                    {loadingInterventions ? "Refreshing..." : "Refresh interventions"}
                  </Text>
                </Pressable>
              ) : null}

              {activeSection === "missions" ? (
                <>
                  {interventionsError ? <Text style={styles.error}>{interventionsError}</Text> : null}
                  <View style={styles.interventionsBlock}>
                {viewMode === "list" ? (
                  <View>
                    <Text style={styles.sectionTitle}>
                      Historique des interventions ({interventions.length})
                    </Text>

                    {loadingInterventions ? (
                      <View style={styles.inlineLoader}>
                        <ActivityIndicator size="small" />
                        <Text style={styles.mutedText}>Loading interventions...</Text>
                      </View>
                    ) : null}

                    {!loadingInterventions && interventions.length === 0 ? (
                      <Text style={styles.mutedText}>
                        No intervention available for this period.
                      </Text>
                    ) : null}

                    {!loadingInterventions &&
                      interventions.map((intervention) => {
                        const status = getStatusStyle(intervention.statut);
                        return (
                          <View key={String(intervention.id)} style={styles.historyCard}>
                            <View style={styles.historyHeader}>
                              <Text style={styles.historyTitle}>
                                {intervention.titre || `Intervention #${intervention.id}`}
                              </Text>
                              <View
                                style={[
                                  styles.statusChip,
                                  {
                                    backgroundColor: status.backgroundColor,
                                    borderColor: status.borderColor,
                                  },
                                ]}
                              >
                                <Text style={[styles.statusChipText, { color: status.color }]}>
                                  {status.label}
                                </Text>
                              </View>
                            </View>

                            <View style={styles.infoGrid}>
                              <View style={styles.infoItem}>
                                <Text style={styles.infoLabel}>Date</Text>
                                <Text style={styles.infoValue}>
                                  {formatInterventionDate(intervention.date_prevue)}
                                </Text>
                              </View>
                              <View style={styles.infoItem}>
                                <Text style={styles.infoLabel}>Site</Text>
                                <Text style={styles.infoValue}>{detailValue(intervention.site_nom)}</Text>
                              </View>
                              <View style={styles.infoItem}>
                                <Text style={styles.infoLabel}>Machine</Text>
                                <Text style={styles.infoValue}>
                                  {detailValue(intervention.machine_nom)}
                                </Text>
                              </View>
                              <View style={styles.infoItem}>
                                <Text style={styles.infoLabel}>Type mission</Text>
                                <Text style={styles.infoValue}>
                                  {getTypeLabel(intervention.type_intervention)}
                                </Text>
                              </View>
                              <View style={styles.infoItem}>
                                <Text style={styles.infoLabel}>Type fluide</Text>
                                <Text style={styles.infoValue}>{getFluideLabel(intervention)}</Text>
                              </View>
                              <View style={styles.infoItem}>
                                <Text style={styles.infoLabel}>Numero R</Text>
                                <Text style={styles.infoValue}>{detailValue(intervention.numero_r)}</Text>
                              </View>
                            </View>

                            <Pressable
                              style={styles.openDetailButton}
                              onPress={() => {
                                void loadInterventionDetails(intervention.id);
                              }}
                            >
                              <Text style={styles.openDetailText}>Open detail</Text>
                            </Pressable>
                          </View>
                        );
                      })}
                  </View>
                ) : null}

                {viewMode === "detail" ? (
                  <View style={styles.detailBlock}>
                    <Pressable style={styles.backButton} onPress={onBackToList}>
                      <Text style={styles.backButtonText}>Back to list</Text>
                    </Pressable>

                    <Text style={styles.sectionTitle}>Detail intervention #{selectedInterventionId}</Text>

                    {loadingInterventionDetails ? (
                      <View style={styles.inlineLoader}>
                        <ActivityIndicator size="small" />
                        <Text style={styles.mutedText}>Loading detail...</Text>
                      </View>
                    ) : null}

                    {interventionDetailsError ? (
                      <Text style={styles.error}>{interventionDetailsError}</Text>
                    ) : null}

                    {selectedIntervention ? (
                      <>
                        <View style={styles.summaryCard}>
                          <View style={styles.historyHeader}>
                            <Text style={styles.historyTitle}>
                              {selectedIntervention.titre ||
                                `Intervention #${selectedIntervention.id}`}
                            </Text>
                            <View
                              style={[
                                styles.statusChip,
                                {
                                  backgroundColor: detailStatus.backgroundColor,
                                  borderColor: detailStatus.borderColor,
                                },
                              ]}
                            >
                              <Text
                                style={[styles.statusChipText, { color: detailStatus.color }]}
                              >
                                {detailStatus.label}
                              </Text>
                            </View>
                          </View>

                          <View style={styles.infoGrid}>
                            <View style={styles.infoItem}>
                              <Text style={styles.infoLabel}>Type mission</Text>
                              <Text style={styles.infoValue}>
                                {getTypeLabel(selectedIntervention.type_intervention)}
                              </Text>
                            </View>
                            <View style={styles.infoItem}>
                              <Text style={styles.infoLabel}>Priorite</Text>
                              <Text style={styles.infoValue}>
                                {detailValue(selectedIntervention.priorite)}
                              </Text>
                            </View>
                            <View style={styles.infoItem}>
                              <Text style={styles.infoLabel}>Date prevue</Text>
                              <Text style={styles.infoValue}>
                                {formatInterventionDate(selectedIntervention.date_prevue)}
                              </Text>
                            </View>
                            <View style={styles.infoItem}>
                              <Text style={styles.infoLabel}>Date debut</Text>
                              <Text style={styles.infoValue}>
                                {formatInterventionDate(selectedIntervention.date_debut)}
                              </Text>
                            </View>
                            <View style={styles.infoItem}>
                              <Text style={styles.infoLabel}>Date fin</Text>
                              <Text style={styles.infoValue}>
                                {formatInterventionDate(selectedIntervention.date_fin)}
                              </Text>
                            </View>
                            <View style={styles.infoItem}>
                              <Text style={styles.infoLabel}>Numero R</Text>
                              <Text style={styles.infoValue}>
                                {detailValue(selectedIntervention.numero_r)}
                              </Text>
                            </View>
                          </View>
                        </View>

                        <View style={styles.summaryCard}>
                          <Text style={styles.subsectionTitle}>Site d'intervention</Text>
                          <View style={styles.infoGrid}>
                            <View style={styles.infoItem}>
                              <Text style={styles.infoLabel}>Nom site</Text>
                              <Text style={styles.infoValue}>
                                {detailValue(siteDetails.nom_lieu ?? selectedIntervention.site_nom)}
                              </Text>
                            </View>
                            <View style={styles.infoItem}>
                              <Text style={styles.infoLabel}>Adresse</Text>
                              <Text style={styles.infoValue}>
                                {detailValue(
                                  siteDetails.adresse_complete ??
                                    selectedIntervention.site_adresse
                                )}
                              </Text>
                            </View>
                            <View style={styles.infoItem}>
                              <Text style={styles.infoLabel}>Contact</Text>
                              <Text style={styles.infoValue}>
                                {detailValue(
                                  siteDetails.contact_principal ??
                                    siteDetails.nom_responsable
                                )}
                              </Text>
                            </View>
                            <View style={styles.infoItem}>
                              <Text style={styles.infoLabel}>Telephone</Text>
                              <Text style={styles.infoValue}>
                                {detailValue(siteDetails.telephone)}
                              </Text>
                            </View>
                          </View>
                        </View>

                        <View style={styles.summaryCard}>
                          <Text style={styles.subsectionTitle}>Equipement</Text>
                          <View style={styles.infoGrid}>
                            <View style={styles.infoItem}>
                              <Text style={styles.infoLabel}>Machine</Text>
                              <Text style={styles.infoValue}>
                                {detailValue(
                                  machineDetails.nom_machine ??
                                    selectedIntervention.machine_nom
                                )}
                              </Text>
                            </View>
                            <View style={styles.infoItem}>
                              <Text style={styles.infoLabel}>Marque</Text>
                              <Text style={styles.infoValue}>
                                {detailValue(
                                  machineDetails.marque ??
                                    selectedIntervention.machine_marque
                                )}
                              </Text>
                            </View>
                            <View style={styles.infoItem}>
                              <Text style={styles.infoLabel}>Modele</Text>
                              <Text style={styles.infoValue}>
                                {detailValue(
                                  machineDetails.modele ??
                                    selectedIntervention.machine_modele
                                )}
                              </Text>
                            </View>
                            <View style={styles.infoItem}>
                              <Text style={styles.infoLabel}>Fluide</Text>
                              <Text style={styles.infoValue}>
                                {detailValue(machineDetails.gaz)}
                              </Text>
                            </View>
                          </View>
                        </View>

                        <View style={styles.summaryCard}>
                          <Text style={styles.subsectionTitle}>Description et recommandations</Text>
                          <Text style={styles.longText}>
                            {detailValue(selectedIntervention.description)}
                          </Text>
                          <Text style={styles.longText}>
                            {detailValue(selectedIntervention.recommandations)}
                          </Text>
                        </View>

                        {selectedIntervention.statut !== "en_cours" &&
                        selectedIntervention.statut !== "terminee" ? (
                          <View style={styles.stepActions}>
                            <Pressable style={styles.noStartButton} onPress={onNoStartFromDetail}>
                              <Text style={styles.noStartButtonText}>Ne pas debuter</Text>
                            </Pressable>
                            <Pressable
                              style={styles.startButton}
                              onPress={() => {
                                void onStartFromDetail();
                              }}
                            >
                              <Text style={styles.startButtonText}>Debuter intervention</Text>
                            </Pressable>
                          </View>
                        ) : null}
                      </>
                    ) : null}
                  </View>
                ) : null}

                {viewMode === "precheck" ? (
                  <View style={styles.precheckBlock}>
                    <Pressable
                      style={styles.backButton}
                      onPress={() => {
                        setViewMode("detail");
                        setPrecheckError(null);
                      }}
                    >
                      <Text style={styles.backButtonText}>Back detail</Text>
                    </Pressable>

                    <Text style={styles.sectionTitle}>Etape 1/1 obligatoire: Avant intervention</Text>
                    <Text style={styles.mutedText}>
                      Preparer la mission avant de commencer le rapport d'intervention.
                    </Text>
                    {precheckLoading ? (
                      <View style={styles.inlineLoader}>
                        <ActivityIndicator size="small" />
                        <Text style={styles.mutedText}>Chargement pre-check...</Text>
                      </View>
                    ) : null}

                    <View style={styles.summaryCard}>
                      <View style={styles.infoGrid}>
                        <View style={styles.infoItem}>
                          <Text style={styles.infoLabel}>Mission</Text>
                          <Text style={styles.infoValue}>#{detailValue(selectedIntervention?.id)}</Text>
                        </View>
                        <View style={styles.infoItem}>
                          <Text style={styles.infoLabel}>Date prevue</Text>
                          <Text style={styles.infoValue}>
                            {formatDateFr(selectedIntervention?.date_prevue)}
                          </Text>
                        </View>
                        <View style={styles.infoItem}>
                          <Text style={styles.infoLabel}>Type</Text>
                          <Text style={styles.infoValue}>
                            {getTypeLabel(selectedIntervention?.type_intervention)}
                          </Text>
                        </View>
                        <View style={styles.infoItem}>
                          <Text style={styles.infoLabel}>Site</Text>
                          <Text style={styles.infoValue}>{detailValue(selectedIntervention?.site_nom)}</Text>
                        </View>
                        <View style={styles.infoItem}>
                          <Text style={styles.infoLabel}>Machine</Text>
                          <Text style={styles.infoValue}>{detailValue(selectedIntervention?.machine_nom)}</Text>
                        </View>
                        <View style={styles.infoItem}>
                          <Text style={styles.infoLabel}>Numero R</Text>
                          <Text style={styles.infoValue}>{detailValue(selectedIntervention?.numero_r)}</Text>
                        </View>
                      </View>
                    </View>

                    <View style={styles.tableBox}>
                      <View style={styles.tableHeaderRow}>
                        <Text style={[styles.tableHeaderCell, styles.colPhase]}>PHASE</Text>
                        <Text style={[styles.tableHeaderCell, styles.colAction]}>ACTION</Text>
                        <Text style={[styles.tableHeaderCell, styles.colItem]}>ITEM</Text>
                        <Text style={[styles.tableHeaderCell, styles.colResult]}>SAISIE / RESULTAT</Text>
                      </View>

                      <View style={styles.tableRow}>
                        <Text style={[styles.tableCell, styles.colPhase, styles.phaseCell]}>
                          Avant intervention
                        </Text>
                        <Text style={[styles.tableCell, styles.colAction]}>
                          Si necessaire demander au technicien de preparer
                        </Text>
                        <Text style={[styles.tableCell, styles.colItem]}>N degre CERFA</Text>
                        <View style={[styles.tableCell, styles.colResult]}>
                          <Pressable
                            style={styles.checkboxRow}
                            onPress={() => setCerfaEnabled((prev) => !prev)}
                          >
                            <View style={[styles.checkbox, cerfaEnabled && styles.checkboxChecked]}>
                              <Text style={styles.checkboxMark}>{cerfaEnabled ? "X" : ""}</Text>
                            </View>
                            <Text style={styles.checkboxLabel}>Oui, preparer un N degre CERFA</Text>
                          </Pressable>

                          {cerfaEnabled ? (
                            <TextInput
                              style={styles.tableInput}
                              placeholder="Ex: CERFA-2026-001"
                              value={cerfaValue}
                              onChangeText={setCerfaValue}
                            />
                          ) : null}

                          {requirements.needsCerfa ? (
                            <Text style={styles.tableHint}>
                              Recommande selon le type d'intervention / la configuration machine.
                            </Text>
                          ) : null}
                        </View>
                      </View>

                      <View style={styles.tableRow}>
                        <Text style={[styles.tableCell, styles.colPhase]}>{""}</Text>
                        <Text style={[styles.tableCell, styles.colAction]}>
                          Si necessaire demander au technicien de preparer
                        </Text>
                        <Text style={[styles.tableCell, styles.colItem]}>N degre prelevement huile</Text>
                        <View style={[styles.tableCell, styles.colResult]}>
                          <Text style={styles.tableHint}>{requirements.prelevementInfo}</Text>
                          <TextInput
                            style={styles.tableInput}
                            placeholder="Ex: PH-2026-014"
                            value={prelevementValue}
                            onChangeText={setPrelevementValue}
                          />
                        </View>
                      </View>

                      <View style={styles.tableRow}>
                        <Text style={[styles.tableCell, styles.colPhase]}>{""}</Text>
                        <Text style={[styles.tableCell, styles.colAction]}>Afficher</Text>
                        <Text style={[styles.tableCell, styles.colItem]}>Liste devis en attente</Text>
                        <View style={[styles.tableCell, styles.colResult]}>
                          {pendingDevis.length > 0 ? (
                            pendingDevis.map((item, index) => (
                              <Text key={`pending-${index}`} style={styles.listLine}>
                                {buildDevisLine(item)}
                              </Text>
                            ))
                          ) : (
                            <Text style={styles.tableHint}>Aucun devis en attente.</Text>
                          )}
                        </View>
                      </View>

                      <View style={styles.tableRow}>
                        <Text style={[styles.tableCell, styles.colPhase]}>{""}</Text>
                        <Text style={[styles.tableCell, styles.colAction]}>Afficher</Text>
                        <Text style={[styles.tableCell, styles.colItem]}>Liste dernier devis</Text>
                        <View style={[styles.tableCell, styles.colResult]}>
                          {lastDevis.length > 0 ? (
                            lastDevis.map((item, index) => (
                              <Text key={`last-${index}`} style={styles.listLine}>
                                {buildDevisLine(item)}
                              </Text>
                            ))
                          ) : (
                            <Text style={styles.tableHint}>Aucun devis disponible.</Text>
                          )}
                        </View>
                      </View>
                    </View>

                    {precheckError ? <Text style={styles.error}>{precheckError}</Text> : null}

                    <View style={styles.stepActions}>
                      <Pressable
                        style={styles.noStartButton}
                        onPress={() => {
                          void onNoStartFromPrecheck();
                        }}
                      >
                        <Text style={styles.noStartButtonText}>Ne pas debuter</Text>
                      </Pressable>
                      <Pressable
                        style={styles.startButton}
                        onPress={() => {
                          void onStartFromPrecheck();
                        }}
                      >
                        <Text style={styles.startButtonText}>Debuter intervention</Text>
                      </Pressable>
                    </View>
                  </View>
                ) : null}

                  </View>
                </>
              ) : null}

              {activeSection === "planifiees" ? (
                <View style={styles.interventionsBlock}>
                  <Text style={styles.sectionTitle}>
                    Interventions planifiees ({plannedInterventions.length})
                  </Text>
                  {plannedInterventions.length === 0 ? (
                    <Text style={styles.mutedText}>Aucune intervention planifiee.</Text>
                  ) : (
                    plannedInterventions.map((intervention) => {
                      const status = getStatusStyle(intervention.statut);
                      return (
                        <View key={`planned-${intervention.id}`} style={styles.historyCard}>
                          <View style={styles.historyHeader}>
                            <Text style={styles.historyTitle}>
                              {intervention.titre || `Intervention #${intervention.id}`}
                            </Text>
                            <View
                              style={[
                                styles.statusChip,
                                {
                                  backgroundColor: status.backgroundColor,
                                  borderColor: status.borderColor,
                                },
                              ]}
                            >
                              <Text style={[styles.statusChipText, { color: status.color }]}>
                                {status.label}
                              </Text>
                            </View>
                          </View>

                          <View style={styles.infoGrid}>
                            <View style={styles.infoItem}>
                              <Text style={styles.infoLabel}>Date</Text>
                              <Text style={styles.infoValue}>
                                {formatInterventionDate(intervention.date_prevue)}
                              </Text>
                            </View>
                            <View style={styles.infoItem}>
                              <Text style={styles.infoLabel}>Site</Text>
                              <Text style={styles.infoValue}>
                                {detailValue(intervention.site_nom)}
                              </Text>
                            </View>
                          </View>

                          <Pressable
                            style={styles.openDetailButton}
                            onPress={() => {
                              void loadInterventionDetails(intervention.id);
                            }}
                          >
                            <Text style={styles.openDetailText}>Ouvrir la mission</Text>
                          </Pressable>
                        </View>
                      );
                    })
                  )}
                </View>
              ) : null}



              {activeSection === "profil" ? (
                <View style={styles.interventionsBlock}>
                  <Text style={styles.sectionTitle}>Mon profil technicien</Text>
                  <View style={styles.summaryCard}>
                    <View style={styles.infoGrid}>
                      <View style={styles.infoItem}>
                        <Text style={styles.infoLabel}>Nom</Text>
                        <Text style={styles.infoValue}>{detailValue(user.name)}</Text>
                      </View>
                      <View style={styles.infoItem}>
                        <Text style={styles.infoLabel}>Email</Text>
                        <Text style={styles.infoValue}>{detailValue(user.email)}</Text>
                      </View>
                      <View style={styles.infoItem}>
                        <Text style={styles.infoLabel}>Role</Text>
                        <Text style={styles.infoValue}>{detailValue(user.role)}</Text>
                      </View>
                      <View style={styles.infoItem}>
                        <Text style={styles.infoLabel}>Type utilisateur</Text>
                        <Text style={styles.infoValue}>{detailValue(user.user_type)}</Text>
                      </View>
                    </View>
                  </View>
                </View>
              ) : null}

              {activeSection === "stats" ? (
                <View style={styles.interventionsBlock}>
                  <Text style={styles.sectionTitle}>Statistiques rapides</Text>
                  <View style={styles.infoGrid}>
                    <View style={styles.infoItem}>
                      <Text style={styles.infoLabel}>Total missions</Text>
                      <Text style={styles.infoValue}>{quickStats.total}</Text>
                    </View>
                    <View style={styles.infoItem}>
                      <Text style={styles.infoLabel}>En cours</Text>
                      <Text style={styles.infoValue}>{quickStats.enCours}</Text>
                    </View>
                    <View style={styles.infoItem}>
                      <Text style={styles.infoLabel}>Planifiees</Text>
                      <Text style={styles.infoValue}>{quickStats.planifiees}</Text>
                    </View>
                    <View style={styles.infoItem}>
                      <Text style={styles.infoLabel}>Terminees</Text>
                      <Text style={styles.infoValue}>{quickStats.terminees}</Text>
                    </View>
                    <View style={styles.infoItem}>
                      <Text style={styles.infoLabel}>Taux completion</Text>
                      <Text style={styles.infoValue}>{quickStats.completionRate}</Text>
                    </View>
                  </View>
                </View>
              ) : null}

              {activeSection === "support" ? (
                <View style={styles.interventionsBlock}>
                  <Text style={styles.sectionTitle}>Support</Text>
                  <View style={styles.summaryCard}>
                    <Text style={styles.longText}>
                      Pour assistance technique, contacte le support CoolCare.
                    </Text>
                    <Text style={styles.longText}>Email: support@coolcare.fr</Text>
                    <Text style={styles.longText}>Telephone: 01.XX.XX.XX.XX</Text>
                  </View>
                </View>
              ) : null}
            </View>
          ) : (
            <View style={styles.form}>
              <TextInput
                style={styles.input}
                placeholder="Email"
                value={email}
                autoCapitalize="none"
                autoCorrect={false}
                keyboardType="email-address"
                onChangeText={setEmail}
              />
              <TextInput
                style={styles.input}
                placeholder="Password"
                value={password}
                secureTextEntry
                onChangeText={setPassword}
              />

              {error ? <Text style={styles.error}>{error}</Text> : null}
              {statusMessage ? <Text style={styles.success}>{statusMessage}</Text> : null}

              <Pressable
                style={[styles.primaryButton, submitting && styles.buttonDisabled]}
                onPress={onLogin}
                disabled={submitting}
              >
                <Text style={styles.primaryButtonText}>
                  {submitting ? "Signing in..." : "Sign in"}
                </Text>
              </Pressable>
            </View>
          )}
        </View>
      </ScrollView>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "#edf2f8",
  },
  scrollContent: {
    flexGrow: 1,
    justifyContent: "center",
    padding: 16,
  },
  scrollContentLogged: {
    justifyContent: "flex-start",
  },
  centered: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
    gap: 12,
  },
  card: {
    backgroundColor: "#ffffff",
    borderRadius: 14,
    padding: 16,
    shadowColor: "#000000",
    shadowOpacity: 0.08,
    shadowOffset: { width: 0, height: 4 },
    shadowRadius: 12,
    elevation: 3,
  },
  title: {
    fontSize: 22,
    fontWeight: "700",
    marginBottom: 16,
    color: "#16325c",
  },
  form: {
    gap: 12,
  },
  input: {
    borderWidth: 1,
    borderColor: "#c5d2e5",
    borderRadius: 10,
    paddingHorizontal: 12,
    paddingVertical: 10,
    backgroundColor: "#fbfdff",
  },
  primaryButton: {
    marginTop: 8,
    backgroundColor: "#1e56a8",
    borderRadius: 10,
    alignItems: "center",
    paddingVertical: 12,
  },
  primaryButtonText: {
    color: "#ffffff",
    fontWeight: "700",
  },
  secondaryButton: {
    marginTop: 10,
    backgroundColor: "#edf3ff",
    borderRadius: 10,
    alignItems: "center",
    paddingVertical: 10,
  },
  secondaryButtonText: {
    color: "#1e56a8",
    fontWeight: "600",
  },
  buttonDisabled: {
    opacity: 0.5,
  },
  error: {
    color: "#b00020",
    marginTop: 6,
  },
  success: {
    color: "#1c7f45",
    marginTop: 4,
  },
  loggedBlock: {
    gap: 6,
  },
  homeHeader: {
    flexDirection: "row",
    alignItems: "center",
    justifyContent: "space-between",
    gap: 10,
    marginBottom: 8,
  },
  homeBrand: {
    color: "#16325c",
    fontSize: 22,
    fontWeight: "800",
  },
  navHeader: {
    flexDirection: "row",
    alignItems: "center",
    gap: 10,
    marginBottom: 4,
  },
  menuButton: {
    width: 38,
    height: 38,
    borderRadius: 10,
    backgroundColor: "#1e56a8",
    alignItems: "center",
    justifyContent: "center",
  },
  menuButtonText: {
    color: "#ffffff",
    fontSize: 18,
    fontWeight: "700",
  },
  navHeaderTextWrap: {
    flex: 1,
    alignItems: "flex-start",
  },
  navHeaderTextWrapHome: {
    alignItems: "flex-end",
  },
  navHeaderTitle: {
    fontSize: 18,
    fontWeight: "700",
    color: "#16325c",
  },
  navHeaderSubtitle: {
    color: "#6a7a96",
    fontSize: 12,
  },
  homeGrid: {
    marginTop: 8,
    gap: 10,
  },
  homeCard: {
    borderWidth: 1,
    borderColor: "#d8e4f6",
    backgroundColor: "#f8fbff",
    borderRadius: 12,
    padding: 12,
    gap: 6,
  },
  homeCardPrimary: {
    borderColor: "#8cb6ef",
    backgroundColor: "#eef5ff",
  },
  homeCardTitle: {
    color: "#1f2f4f",
    fontSize: 22,
    fontWeight: "700",
  },
  homeCardText: {
    color: "#5b6c88",
    fontSize: 13,
    lineHeight: 18,
  },
  homeCardAccent: {
    color: "#1e56a8",
    fontSize: 13,
    fontWeight: "700",
  },
  homeCardHint: {
    color: "#d97706",
    fontSize: 12,
    fontWeight: "600",
  },
  homeActionsRow: {
    flexDirection: "row",
    gap: 10,
    marginTop: 4,
  },
  drawerPanel: {
    borderWidth: 1,
    borderColor: "#d8e4f6",
    borderRadius: 12,
    backgroundColor: "#f8fbff",
    padding: 10,
    gap: 6,
    marginBottom: 6,
  },
  drawerItem: {
    borderRadius: 8,
    paddingVertical: 8,
    paddingHorizontal: 10,
    backgroundColor: "#edf3ff",
  },
  drawerItemActive: {
    backgroundColor: "#dbeafe",
    borderWidth: 1,
    borderColor: "#93c5fd",
  },
  drawerItemText: {
    color: "#1e56a8",
    fontWeight: "600",
    fontSize: 13,
  },
  drawerItemTextActive: {
    color: "#1d4ed8",
    fontWeight: "700",
  },
  drawerFooterButton: {
    marginTop: 6,
    backgroundColor: "#e2e8f0",
    borderRadius: 8,
    paddingVertical: 8,
    alignItems: "center",
  },
  drawerFooterText: {
    color: "#1f2f4f",
    fontWeight: "600",
  },
  drawerFooterDanger: {
    backgroundColor: "#fee2e2",
    borderRadius: 8,
    paddingVertical: 8,
    alignItems: "center",
  },
  drawerFooterDangerText: {
    color: "#991b1b",
    fontWeight: "700",
  },
  label: {
    color: "#6a7a96",
  },
  value: {
    fontSize: 20,
    fontWeight: "700",
    color: "#16325c",
  },
  mutedText: {
    color: "#6a7a96",
  },
  interventionsBlock: {
    marginTop: 16,
    borderTopWidth: 1,
    borderTopColor: "#dbe6f7",
    paddingTop: 12,
    gap: 10,
  },
  sectionTitle: {
    fontSize: 17,
    fontWeight: "700",
    color: "#16325c",
    marginBottom: 8,
  },
  historyCard: {
    borderWidth: 1,
    borderColor: "#d8e4f6",
    backgroundColor: "#f8fbff",
    borderRadius: 12,
    padding: 12,
    marginBottom: 10,
    gap: 10,
  },
  historyHeader: {
    flexDirection: "row",
    justifyContent: "space-between",
    alignItems: "center",
    gap: 8,
  },
  historyTitle: {
    flex: 1,
    color: "#16325c",
    fontWeight: "700",
    fontSize: 15,
  },
  statusChip: {
    borderWidth: 1,
    borderRadius: 999,
    paddingVertical: 3,
    paddingHorizontal: 8,
  },
  statusChipText: {
    fontSize: 11,
    fontWeight: "700",
  },
  infoGrid: {
    flexDirection: "row",
    flexWrap: "wrap",
    gap: 8,
  },
  infoItem: {
    minWidth: "47%",
    backgroundColor: "#ffffff",
    borderWidth: 1,
    borderColor: "#e3ebf8",
    borderRadius: 10,
    padding: 8,
  },
  infoLabel: {
    fontSize: 11,
    color: "#66748f",
    fontWeight: "600",
    marginBottom: 2,
  },
  infoValue: {
    fontSize: 13,
    color: "#1f2f4f",
    fontWeight: "600",
  },
  openDetailButton: {
    backgroundColor: "#1e56a8",
    borderRadius: 8,
    paddingVertical: 8,
    alignItems: "center",
  },
  openDetailText: {
    color: "#ffffff",
    fontWeight: "700",
  },
  inlineLoader: {
    flexDirection: "row",
    alignItems: "center",
    gap: 8,
  },
  detailBlock: {
    gap: 10,
  },
  backButton: {
    alignSelf: "flex-start",
    backgroundColor: "#edf3ff",
    borderRadius: 8,
    paddingHorizontal: 10,
    paddingVertical: 6,
  },
  backButtonText: {
    color: "#1e56a8",
    fontWeight: "600",
  },
  summaryCard: {
    borderWidth: 1,
    borderColor: "#d8e4f6",
    backgroundColor: "#f8fbff",
    borderRadius: 12,
    padding: 12,
    gap: 8,
  },
  subsectionTitle: {
    fontSize: 15,
    fontWeight: "700",
    color: "#16325c",
  },
  longText: {
    fontSize: 13,
    color: "#2f3e5f",
    lineHeight: 18,
  },
  precheckBlock: {
    gap: 10,
  },
  tableBox: {
    borderWidth: 1,
    borderColor: "#d1d5db",
    borderRadius: 8,
    overflow: "hidden",
  },
  tableHeaderRow: {
    flexDirection: "row",
    backgroundColor: "#f3f4f6",
    borderBottomWidth: 1,
    borderBottomColor: "#d1d5db",
  },
  tableHeaderCell: {
    fontSize: 11,
    fontWeight: "700",
    color: "#374151",
    paddingVertical: 8,
    paddingHorizontal: 6,
  },
  tableRow: {
    flexDirection: "row",
    borderBottomWidth: 1,
    borderBottomColor: "#e5e7eb",
  },
  tableCell: {
    fontSize: 12,
    color: "#1f2f4f",
    paddingVertical: 8,
    paddingHorizontal: 6,
    borderRightWidth: 1,
    borderRightColor: "#e5e7eb",
  },
  colPhase: {
    width: "18%",
  },
  colAction: {
    width: "26%",
  },
  colItem: {
    width: "17%",
  },
  colResult: {
    width: "39%",
    borderRightWidth: 0,
  },
  phaseCell: {
    fontWeight: "700",
  },
  checkboxRow: {
    flexDirection: "row",
    alignItems: "center",
    gap: 6,
  },
  checkbox: {
    width: 18,
    height: 18,
    borderWidth: 1,
    borderColor: "#94a3b8",
    borderRadius: 3,
    alignItems: "center",
    justifyContent: "center",
    backgroundColor: "#ffffff",
  },
  checkboxChecked: {
    backgroundColor: "#dbeafe",
    borderColor: "#3b82f6",
  },
  checkboxMark: {
    fontSize: 11,
    fontWeight: "700",
    color: "#1d4ed8",
  },
  checkboxLabel: {
    flex: 1,
    fontSize: 12,
    color: "#1f2f4f",
  },
  tableInput: {
    marginTop: 6,
    borderWidth: 1,
    borderColor: "#cbd5e1",
    borderRadius: 6,
    paddingHorizontal: 8,
    paddingVertical: 7,
    backgroundColor: "#ffffff",
    fontSize: 12,
  },
  tableHint: {
    marginTop: 4,
    fontSize: 11,
    color: "#6b7280",
    fontStyle: "italic",
  },
  listLine: {
    fontSize: 12,
    color: "#1f2f4f",
    marginBottom: 4,
  },
  stepActions: {
    flexDirection: "row",
    gap: 10,
    marginTop: 4,
  },
  noStartButton: {
    flex: 1,
    backgroundColor: "#e5e7eb",
    borderRadius: 10,
    alignItems: "center",
    paddingVertical: 10,
  },
  noStartButtonText: {
    color: "#334155",
    fontWeight: "700",
  },
  startButton: {
    flex: 1,
    backgroundColor: "#1e56a8",
    borderRadius: 10,
    alignItems: "center",
    paddingVertical: 10,
  },
  startButtonText: {
    color: "#ffffff",
    fontWeight: "700",
  },
  formLabel: {
    fontSize: 12,
    color: "#4b5d7e",
    fontWeight: "700",
    marginTop: 2,
    marginBottom: 4,
  },
});
