import React, { useCallback, useEffect, useMemo, useState } from "react";
import {
  ActivityIndicator,
  Image,
  Modal,
  Pressable,
  ScrollView,
  StyleSheet,
  Switch,
  Text,
  TextInput,
  View,
} from "react-native";
import { useFocusEffect, useNavigation, useRoute, type RouteProp } from "@react-navigation/native";
import type { NativeStackNavigationProp } from "@react-navigation/native-stack";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import {
  fetchAndStoreInterventionSteps,
  getInterventionById,
  getInterventionPrecheck,
  startIntervention,
} from "../../services/interventionsApi";
import { buildApiUrl, getApiAccessToken, isApiClientError } from "../../services/apiClient";
import { saveInterventionDetail } from "../../core/localDatabase";
import { loadStepsLocally } from "../../core/stepRepository";
import { buildPhases, isDisplayOnly, getStepMetadata } from "../../shared/workflowUtils";
import { detailValue, formatInterventionDate, getStatusStyle, getTypeLabel, isDoneStatus } from "../../shared/interventionUtils";
import type {
  MobileInterventionDetails,
  MobilePrecheckState,
  MobileStep,
  MobileStepFile,
} from "../../types/intervention";
import type { AppStackParamList } from "../../navigation/types";

type DetailRoute = RouteProp<AppStackParamList, "MissionDetail">;
type DetailNav = NativeStackNavigationProp<AppStackParamList, "MissionDetail">;

export default function MissionDetailScreen() {
  const route = useRoute<DetailRoute>();
  const navigation = useNavigation<DetailNav>();
  const insets = useSafeAreaInsets();
  const { interventionId, brandColor } = route.params;

  const [item, setItem] = useState<MobileInterventionDetails | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  // Etapes workflow chargees uniquement si la mission est terminee (lecture
  // seule cote mobile). Permet au tech de revoir ce qu'il a rempli sans
  // pouvoir editer.
  const [completedSteps, setCompletedSteps] = useState<MobileStep[]>([]);

  const fetchDetail = useCallback(async () => {
    setLoading(true);
    setError(null);
    try {
      const result = await getInterventionById(interventionId);
      setItem(result);
    } catch (err) {
      setError(err instanceof Error ? err.message : "Erreur chargement intervention");
    } finally {
      setLoading(false);
    }
  }, [interventionId]);

  useEffect(() => {
    fetchDetail();
  }, [fetchDetail]);

  // Re-fetch a chaque fois que l'ecran regagne le focus (ex: retour depuis
  // le workflow apres finalisation) pour refleter le nouveau statut
  // sans que le user ait a refresh manuellement.
  useFocusEffect(
    useCallback(() => {
      fetchDetail();
    }, [fetchDetail])
  );

  // Detection mission terminee : on s'appuie sur les statuts serveur
  // (statut='terminee' ou 'cloturee', workflow_status='completed').
  // Une mission terminee est consultee en lecture seule, on cache le
  // bouton "Debuter intervention".
  const isCompleted = Boolean(
    item &&
      (isDoneStatus(item.statut) ||
        (item as { workflow_status?: string }).workflow_status === "completed")
  );

  // Charge les etapes workflow si mission terminee pour affichage lecture
  // seule en bas du detail. Re-fetch aussi depuis le serveur pour avoir
  // les derniers comments/values (si un autre device a finalise).
  useEffect(() => {
    if (!isCompleted) {
      setCompletedSteps([]);
      return;
    }
    let cancelled = false;
    (async () => {
      try {
        await fetchAndStoreInterventionSteps(interventionId);
      } catch {
        // best-effort, fallback sur le local
      }
      const local = await loadStepsLocally(interventionId);
      if (!cancelled) {
        setCompletedSteps(local);
      }
    })();
    return () => {
      cancelled = true;
    };
  }, [isCompleted, interventionId]);

  // Depuis le contrat #168, les endpoints mobiles renvoient TOUTES les etapes
  // (y compris masquees) pour permettre le calcul de visibilite offline. Pour
  // une mission TERMINEE (etat fige), on s'appuie sur le is_visible serveur
  // pour ne montrer dans le recap que ce qui etait reellement visible a la
  // finalisation -> on exclut les extensions conditionnelles jamais declenchees.
  // is_visible undefined (ancien backend / ancienne donnee locale) = visible.
  const completedPhases = useMemo(() => {
    const visibleSteps = completedSteps.filter((s) => s.is_visible !== false);
    return visibleSteps.length > 0 ? buildPhases(visibleSteps) : [];
  }, [completedSteps]);

  // --- Pre-controle / demarrage d'intervention (clock-in) ---
  // Au lieu d'aller direct au workflow, "Debuter" passe par le start serveur
  // (statut -> en_cours, date_debut, persistance precheck CERFA/prelevement),
  // miroir de intervention_start.php cote PWA.
  const [precheckOpen, setPrecheckOpen] = useState(false);
  const [precheckLoading, setPrecheckLoading] = useState(false);
  const [precheck, setPrecheck] = useState<MobilePrecheckState | null>(null);
  const [cerfaEnabled, setCerfaEnabled] = useState(false);
  const [cerfaNumber, setCerfaNumber] = useState("");
  const [prelevementNumber, setPrelevementNumber] = useState("");
  const [starting, setStarting] = useState(false);
  const [startError, setStartError] = useState<string | null>(null);

  const goToWorkflow = () =>
    navigation.navigate("WorkflowIntervention", {
      interventionId,
      brandColor,
      machineId: Number(item?.machine_id) || 0,
    });

  const openPrecheck = async () => {
    // Deja demarree : on va directement au workflow (le start est idempotent).
    if (item?.statut === "en_cours") {
      goToWorkflow();
      return;
    }
    setPrecheckOpen(true);
    setPrecheckLoading(true);
    setStartError(null);
    try {
      const state = await getInterventionPrecheck(interventionId);
      setPrecheck(state);
      setCerfaEnabled(Boolean(state.precheck?.cerfa_enabled));
      setCerfaNumber(String(state.precheck?.cerfa_number ?? ""));
      setPrelevementNumber(String(state.precheck?.prelevement_number ?? ""));
    } catch {
      // Hors-ligne / endpoint indispo : on permet quand meme de demarrer avec
      // des valeurs vides (le start sera mis en file d'attente si offline).
      setPrecheck(null);
    } finally {
      setPrecheckLoading(false);
    }
  };

  const confirmStart = async () => {
    setStarting(true);
    setStartError(null);
    try {
      await startIntervention({
        intervention_id: interventionId,
        cerfa_enabled: cerfaEnabled,
        cerfa_number: cerfaNumber.trim(),
        prelevement_number: prelevementNumber.trim(),
      });
      setPrecheckOpen(false);
      goToWorkflow();
    } catch (e) {
      // Offline (erreur reseau, pas de status HTTP) : startIntervention a DEJA
      // mis le clock-in en file de sync. Bloquer ici laissait le tech coince sur
      // une intervention "planifiee" qu'il ne pouvait pas demarrer hors-ligne.
      // On continue en optimiste : on marque l'intervention en_cours en local
      // (idempotent au retour -> openPrecheck va direct au workflow) et on ouvre
      // le workflow. Le serveur sera reconcilie quand la file se videra.
      const isOffline = isApiClientError(e) && e.status === undefined;
      if (isOffline) {
        if (item) {
          const optimistic: MobileInterventionDetails = { ...item, statut: "en_cours" };
          setItem(optimistic);
          await saveInterventionDetail(optimistic).catch(() => {});
        }
        setPrecheckOpen(false);
        goToWorkflow();
        return;
      }
      setStartError(e instanceof Error ? e.message : "Demarrage impossible");
    } finally {
      setStarting(false);
    }
  };

  return (
    <View style={styles.root}>
      <ScrollView
        style={styles.scroll}
        contentContainerStyle={[styles.content, { paddingBottom: insets.bottom + 24 }]}
        showsVerticalScrollIndicator={false}
      >
        {loading ? (
          <View style={styles.loaderRow}>
            <ActivityIndicator size="small" />
            <Text style={styles.mutedText}>Chargement...</Text>
          </View>
        ) : null}

        {error ? (
          <View style={styles.errorBlock}>
            <Text style={styles.errorText}>{error}</Text>
            <Pressable style={styles.retryButton} onPress={fetchDetail}>
              <Text style={styles.retryText}>Reessayer</Text>
            </Pressable>
          </View>
        ) : null}

        {item ? (
          <InterventionBody
            item={item}
            isCompleted={isCompleted}
            completedPhases={completedPhases}
          />
        ) : null}
      </ScrollView>

      <View style={[styles.actionsBar, { paddingBottom: insets.bottom + 16 }]}>
        <Pressable style={styles.backButton} onPress={() => navigation.goBack()}>
          <Text style={styles.backButtonText}>Retour</Text>
        </Pressable>
        {isCompleted ? (
          // Mission deja finalisee : pas de bouton d'action, badge
          // "Lecture seule" a la place. Le detail reste affiche en entete.
          <View style={[styles.startButton, styles.completedBadge]}>
            <Text style={styles.completedBadgeText}>✓ Mission terminee (lecture seule)</Text>
          </View>
        ) : (
          <Pressable
            style={[styles.startButton, { backgroundColor: brandColor }, !item && styles.buttonDisabled]}
            disabled={!item}
            onPress={() => void openPrecheck()}
          >
            <Text style={styles.startButtonText}>Debuter intervention</Text>
          </Pressable>
        )}
      </View>

      <PrecheckModal
        visible={precheckOpen}
        loading={precheckLoading}
        precheck={precheck}
        cerfaEnabled={cerfaEnabled}
        onCerfaEnabledChange={setCerfaEnabled}
        cerfaNumber={cerfaNumber}
        onCerfaNumberChange={setCerfaNumber}
        prelevementNumber={prelevementNumber}
        onPrelevementNumberChange={setPrelevementNumber}
        starting={starting}
        startError={startError}
        brandColor={brandColor}
        bottomInset={insets.bottom}
        onClose={() => setPrecheckOpen(false)}
        onConfirm={() => void confirmStart()}
      />
    </View>
  );
}

type PrecheckModalProps = Readonly<{
  visible: boolean;
  loading: boolean;
  precheck: MobilePrecheckState | null;
  cerfaEnabled: boolean;
  onCerfaEnabledChange: (v: boolean) => void;
  cerfaNumber: string;
  onCerfaNumberChange: (v: string) => void;
  prelevementNumber: string;
  onPrelevementNumberChange: (v: string) => void;
  starting: boolean;
  startError: string | null;
  brandColor: string;
  bottomInset: number;
  onClose: () => void;
  onConfirm: () => void;
}>;

function PrecheckModal({
  visible,
  loading,
  precheck,
  cerfaEnabled,
  onCerfaEnabledChange,
  cerfaNumber,
  onCerfaNumberChange,
  prelevementNumber,
  onPrelevementNumberChange,
  starting,
  startError,
  brandColor,
  bottomInset,
  onClose,
  onConfirm,
}: PrecheckModalProps) {
  const needsCerfa = Boolean(precheck?.requirements?.needs_cerfa);
  const needsPrelevement = Boolean(precheck?.requirements?.needs_prelevement);
  const prelevementInfo = precheck?.requirements?.prelevement_info;

  return (
    <Modal
      visible={visible}
      transparent
      animationType="slide"
      onRequestClose={starting ? undefined : onClose}
    >
      <View style={styles.precheckOverlay}>
        <View style={[styles.precheckCard, { paddingBottom: bottomInset + 16 }]}>
          <Text style={styles.precheckTitle}>Pre-controle</Text>

          {loading ? (
            <View style={styles.loaderRow}>
              <ActivityIndicator size="small" />
              <Text style={styles.mutedText}>Chargement...</Text>
            </View>
          ) : (
            <>
              {needsCerfa ? (
                <View style={styles.precheckField}>
                  <View style={styles.precheckToggleRow}>
                    <Text style={styles.precheckLabel}>CERFA prepare</Text>
                    <Switch
                      value={cerfaEnabled}
                      onValueChange={onCerfaEnabledChange}
                      disabled={starting}
                    />
                  </View>
                  {cerfaEnabled ? (
                    <TextInput
                      style={styles.precheckInput}
                      value={cerfaNumber}
                      onChangeText={onCerfaNumberChange}
                      placeholder="N° CERFA"
                      editable={!starting}
                    />
                  ) : null}
                </View>
              ) : null}

              {needsPrelevement ? (
                <View style={styles.precheckField}>
                  <Text style={styles.precheckLabel}>Prelevement</Text>
                  {prelevementInfo ? (
                    <Text style={styles.precheckInfo}>{prelevementInfo}</Text>
                  ) : null}
                  <TextInput
                    style={styles.precheckInput}
                    value={prelevementNumber}
                    onChangeText={onPrelevementNumberChange}
                    placeholder="N° prelevement"
                    editable={!starting}
                  />
                </View>
              ) : null}

              {!needsCerfa && !needsPrelevement ? (
                <Text style={styles.mutedText}>
                  Aucun pre-controle requis. Vous pouvez demarrer l'intervention.
                </Text>
              ) : null}

              {startError ? <Text style={styles.errorText}>{startError}</Text> : null}

              <View style={styles.precheckButtons}>
                <Pressable
                  style={[styles.precheckBtn, styles.precheckCancel]}
                  onPress={onClose}
                  disabled={starting}
                >
                  <Text style={styles.precheckCancelText}>Annuler</Text>
                </Pressable>
                <Pressable
                  style={[styles.precheckBtn, { backgroundColor: brandColor }]}
                  onPress={onConfirm}
                  disabled={starting}
                >
                  {starting ? (
                    <ActivityIndicator size="small" color="#ffffff" />
                  ) : (
                    <Text style={styles.precheckStartText}>Demarrer</Text>
                  )}
                </Pressable>
              </View>
            </>
          )}
        </View>
      </View>
    </Modal>
  );
}

function InfoItem({ label, value }: Readonly<{ label: string; value: string }>) {
  return (
    <View style={styles.infoItem}>
      <Text style={styles.infoLabel}>{label}</Text>
      <Text style={styles.infoValue}>{value}</Text>
    </View>
  );
}

function InterventionHeader({ item }: Readonly<{ item: MobileInterventionDetails }>) {
  const status = getStatusStyle(item.statut);
  return (
    <View style={styles.header}>
      <Text style={styles.headerTitle}>{item.titre || `Intervention #${item.id}`}</Text>
      <View
        style={[
          styles.statusChip,
          { backgroundColor: status.backgroundColor, borderColor: status.borderColor },
        ]}
      >
        <Text style={[styles.statusChipText, { color: status.color }]}>{status.label}</Text>
      </View>
    </View>
  );
}

function TextSection({ title, text }: Readonly<{ title: string; text?: string }>) {
  if (!text) return null;
  return (
    <View style={styles.section}>
      <Text style={styles.sectionTitle}>{title}</Text>
      <Text style={styles.descriptionText}>{text}</Text>
    </View>
  );
}

function TechnicienSection({ item }: Readonly<{ item: MobileInterventionDetails }>) {
  if (!item.technicien_nom) return null;
  return (
    <View style={styles.section}>
      <Text style={styles.sectionTitle}>Technicien assigne</Text>
      <View style={styles.infoGrid}>
        <InfoItem
          label="Nom"
          value={`${detailValue(item.technicien_prenom)} ${detailValue(item.technicien_nom)}`}
        />
      </View>
    </View>
  );
}

function CompletedStepsSection({
  phases,
}: Readonly<{
  phases: { name: string; steps: MobileStep[] }[];
}>) {
  return (
    <View style={styles.section}>
      <Text style={styles.sectionTitle}>Détail des étapes remplies</Text>
      <Text style={styles.mutedSmall}>
        Consultez ici les valeurs et commentaires saisis lors de l'intervention. Modification impossible — la mission est terminée.
      </Text>
      {phases.map((phase, phaseIdx) => (
        <View key={phase.name} style={styles.readOnlyPhase}>
          <Text style={styles.readOnlyPhaseTitle}>
            {phaseIdx + 1}. {phase.name}
          </Text>
          {phase.steps.map((step) => (
            <ReadOnlyStepRow key={step.id} step={step} />
          ))}
        </View>
      ))}
    </View>
  );
}

function InterventionBody({
  item,
  isCompleted,
  completedPhases,
}: Readonly<{
  item: MobileInterventionDetails;
  isCompleted: boolean;
  completedPhases: { name: string; steps: MobileStep[] }[];
}>) {
  return (
    <>
      <InterventionHeader item={item} />

      <View style={styles.section}>
        <Text style={styles.sectionTitle}>Informations</Text>
        <View style={styles.infoGrid}>
          <InfoItem label="Type" value={getTypeLabel(item.type_intervention)} />
          <InfoItem label="Priorite" value={detailValue(item.priorite)} />
          <InfoItem label="Date prevue" value={formatInterventionDate(item.date_prevue)} />
          <InfoItem label="Numero R" value={detailValue(item.numero_r)} />
        </View>
      </View>

      <View style={styles.section}>
        <Text style={styles.sectionTitle}>Site</Text>
        <View style={styles.infoGrid}>
          <InfoItem label="Nom" value={detailValue(item.site_nom)} />
          <InfoItem label="Adresse" value={detailValue(item.site_adresse)} />
        </View>
      </View>

      <View style={styles.section}>
        <Text style={styles.sectionTitle}>Machine</Text>
        <View style={styles.infoGrid}>
          <InfoItem label="Nom" value={detailValue(item.machine_nom)} />
          <InfoItem label="Marque" value={detailValue(item.machine_marque)} />
          <InfoItem label="Modele" value={detailValue(item.machine_modele)} />
        </View>
      </View>

      <TechnicienSection item={item} />
      <TextSection title="Description" text={item.description} />
      <TextSection title="Recommandations" text={item.recommandations} />

      {isCompleted && completedPhases.length > 0 ? (
        <CompletedStepsSection phases={completedPhases} />
      ) : null}
    </>
  );
}

/**
 * Ligne affichant une etape workflow en lecture seule dans le detail
 * d'une mission terminee. Formate value + comment selon le type de step
 * (photo => miniatures, signature => fait/non, autre => valeur brute).
 *
 * Les fichiers (step.files) viennent de intervention_workflow_step_files
 * cote serveur (joints via mobile/intervention_steps.php). Ils sont charges
 * via le endpoint file_preview qui accepte le Bearer mobile.
 */
function formatStepDisplayValue(value: MobileStep["value"], hasFiles: boolean): string {
  if (value === null || value === undefined || value === "") {
    return hasFiles ? "" : "(non renseigne)";
  }
  if (Array.isArray(value)) {
    // Anciennes valeurs locales (StepPhotoValue[]) : on s'appuie sur step.files
    // remontes par le serveur pour l'affichage, donc pas de texte ici.
    return "";
  }
  if (typeof value === "object" && "signed" in value) {
    return value.signed ? "Signee" : "Non signee";
  }
  return String(value);
}

function ReadOnlyStepRow({ step }: Readonly<{ step: MobileStep }>) {
  const meta = getStepMetadata(step);
  if (isDisplayOnly(step)) {
    return null;
  }
  const commentText = String(meta.comment_text ?? "").trim();
  const files = Array.isArray(step.files) ? step.files : [];
  const displayValue = formatStepDisplayValue(step.value, files.length > 0);

  return (
    <View style={styles.readOnlyStepRow}>
      <Text style={styles.readOnlyStepLabel}>{step.label}</Text>
      {displayValue ? (
        <Text style={styles.readOnlyStepValue}>{displayValue}</Text>
      ) : null}
      {files.length > 0 ? (
        <View style={styles.readOnlyPhotoGrid}>
          {files.map((file) => (
            <ReadOnlyPhotoThumb key={file.id} file={file} />
          ))}
        </View>
      ) : null}
      {commentText ? (
        <Text style={styles.readOnlyStepComment}>💬 {commentText}</Text>
      ) : null}
    </View>
  );
}

/**
 * Miniature photo workflow servie par /api/intervention_workflow_file_preview.php.
 * Le endpoint exige un Bearer JWT (AuthMiddleware accepte mobile_jwt) -> on
 * passe le token via source.headers (RN supporte). Construction de l'URL
 * absolue via buildApiUrl pour respecter la baseUrl configuree (multi-tenant).
 */
function ReadOnlyPhotoThumb({ file }: Readonly<{ file: MobileStepFile }>) {
  const [uri, setUri] = useState<string | null>(null);
  const [token, setToken] = useState<string | null>(null);

  useEffect(() => {
    let cancelled = false;
    (async () => {
      const [url, accessToken] = await Promise.all([
        buildApiUrl(file.path),
        getApiAccessToken(),
      ]);
      if (cancelled) {
        return;
      }
      setUri(url);
      setToken(accessToken);
    })();
    return () => {
      cancelled = true;
    };
  }, [file.path]);

  if (!uri || !token) {
    return <View style={styles.readOnlyPhotoPlaceholder} />;
  }

  return (
    <Image
      source={{ uri, headers: { Authorization: `Bearer ${token}` } }}
      style={styles.readOnlyPhoto}
      resizeMode="cover"
    />
  );
}

const styles = StyleSheet.create({
  root: { flex: 1, backgroundColor: "#edf2f8" },
  scroll: { flex: 1 },
  content: { padding: 16, gap: 12, paddingBottom: 16 },
  loaderRow: { flexDirection: "row", alignItems: "center", gap: 8 },
  mutedText: { color: "#6a7a96" },
  errorBlock: { gap: 8 },
  errorText: { color: "#b00020" },
  retryButton: { backgroundColor: "#edf3ff", borderRadius: 8, paddingVertical: 8, alignItems: "center" },
  retryText: { color: "#1e56a8", fontWeight: "700" },
  header: { flexDirection: "row", justifyContent: "space-between", alignItems: "flex-start", gap: 8 },
  headerTitle: { flex: 1, fontSize: 18, fontWeight: "700", color: "#16325c" },
  statusChip: { borderWidth: 1, borderRadius: 999, paddingVertical: 3, paddingHorizontal: 8 },
  statusChipText: { fontSize: 11, fontWeight: "700" },
  section: { gap: 8 },
  sectionTitle: { fontSize: 13, fontWeight: "700", color: "#66748f", textTransform: "uppercase", letterSpacing: 0.5 },
  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" },
  descriptionText: { fontSize: 13, color: "#2f3e5f", lineHeight: 20, backgroundColor: "#ffffff", borderRadius: 10, padding: 12, borderWidth: 1, borderColor: "#e3ebf8" },
  actionsBar: { flexDirection: "row", gap: 10, padding: 16, backgroundColor: "#ffffff", borderTopWidth: 1, borderTopColor: "#d8e4f6" },
  backButton: { flex: 1, backgroundColor: "#e5e7eb", borderRadius: 10, alignItems: "center", paddingVertical: 12 },
  backButtonText: { color: "#334155", fontWeight: "700" },
  startButton: { flex: 1, borderRadius: 10, alignItems: "center", paddingVertical: 12 },
  startButtonText: { color: "#ffffff", fontWeight: "700" },
  buttonDisabled: { opacity: 0.4 },
  completedBadge: {
    backgroundColor: "#dcfce7",
    borderWidth: 1,
    borderColor: "#16a34a",
    justifyContent: "center",
  },
  completedBadgeText: { color: "#14532d", fontWeight: "700", fontSize: 13, textAlign: "center" },
  mutedSmall: { color: "#64748b", fontSize: 12, marginBottom: 6 },
  readOnlyPhase: {
    marginTop: 10,
    paddingTop: 8,
    borderTopWidth: 1,
    borderTopColor: "#e2e8f0",
    gap: 6,
  },
  readOnlyPhaseTitle: { fontSize: 14, fontWeight: "700", color: "#1f2f4f", marginBottom: 4 },
  readOnlyStepRow: {
    padding: 8,
    backgroundColor: "#f8fbff",
    borderRadius: 6,
    borderLeftWidth: 3,
    borderLeftColor: "#cbd5e1",
    gap: 2,
  },
  readOnlyStepLabel: { fontSize: 13, fontWeight: "600", color: "#334155" },
  readOnlyStepValue: { fontSize: 14, color: "#0f172a" },
  readOnlyStepComment: { fontSize: 12, color: "#475569", fontStyle: "italic", marginTop: 2 },
  readOnlyPhotoGrid: {
    flexDirection: "row",
    flexWrap: "wrap",
    gap: 6,
    marginTop: 4,
  },
  readOnlyPhoto: {
    width: 96,
    height: 96,
    borderRadius: 6,
    borderWidth: 1,
    borderColor: "#cbd5e1",
    backgroundColor: "#e2e8f0",
  },
  readOnlyPhotoPlaceholder: {
    width: 96,
    height: 96,
    borderRadius: 6,
    backgroundColor: "#e2e8f0",
  },
  precheckOverlay: {
    flex: 1,
    backgroundColor: "rgba(15, 23, 42, 0.45)",
    justifyContent: "flex-end",
  },
  precheckCard: {
    backgroundColor: "#ffffff",
    borderTopLeftRadius: 18,
    borderTopRightRadius: 18,
    padding: 20,
    gap: 10,
  },
  precheckTitle: { fontSize: 18, fontWeight: "800", color: "#16325c" },
  precheckField: { gap: 8 },
  precheckToggleRow: {
    flexDirection: "row",
    alignItems: "center",
    justifyContent: "space-between",
  },
  precheckLabel: { fontSize: 13, fontWeight: "700", color: "#334155" },
  precheckInfo: { fontSize: 12, color: "#6a7a96" },
  precheckInput: {
    borderWidth: 1,
    borderColor: "#d8e4f6",
    borderRadius: 10,
    paddingHorizontal: 12,
    paddingVertical: 10,
    fontSize: 15,
    color: "#1f2f4f",
    backgroundColor: "#f8fbff",
  },
  precheckButtons: { flexDirection: "row", gap: 10, marginTop: 8 },
  precheckBtn: {
    flex: 1,
    borderRadius: 10,
    paddingVertical: 12,
    alignItems: "center",
    justifyContent: "center",
  },
  precheckCancel: {
    backgroundColor: "#eef3fb",
    borderWidth: 1,
    borderColor: "#d8e4f6",
  },
  precheckCancelText: { color: "#1e56a8", fontWeight: "700" },
  precheckStartText: { color: "#ffffff", fontWeight: "800" },
});
