'use client';

import axios from 'axios';
import { Link, useRouter } from 'expo-router';
import { useEffect, useMemo, useState } from 'react';
import { Image, Linking, SafeAreaView, ScrollView, StyleSheet, Text, TextInput, TouchableOpacity, View } from 'react-native';
import { DriverFlowNav } from '../components/driver-flow-nav';
import { API_URL, DRIVER_EMAIL, DRIVER_PASSWORD } from '../src/runtime-config';
import { useDriverSession } from '../src/store/session';
import { driverShadow, driverTheme, formatCurrency, formatDistance, toNumber } from '../src/lib/driver-ui';
import { extractErrorMessage, isUnauthorizedError } from '../src/lib/driver-api';

type LoginResponse = {
  accessToken: string;
  refreshToken?: string;
  user?: {
    id: string;
    role: string;
    email?: string;
    phone?: string;
    status?: string;
  };
};

type DriverSignupPayload = {
  fullName: string;
  email: string;
  password: string;
  phone: string;
  documentNumber: string;
  vehiclePlate: string;
  vehicleModel: string;
  pixKey?: string;
};

type DriverOrder = {
  id: string;
  restaurant: {
    name: string;
    street?: string | null;
    number?: string | null;
    complement?: string | null;
    state?: string | null;
    zipCode?: string | null;
    latitude?: number | string | null;
    longitude?: number | string | null;
    neighborhood?: string | null;
    city?: string | null;
  };
  customer: { fullName: string };
  address?: {
    street?: string | null;
    number?: string | null;
    complement?: string | null;
    neighborhood?: string | null;
    city?: string | null;
    state?: string | null;
    latitude?: number | string | null;
    longitude?: number | string | null;
  } | null;
};

type DeliveryOffer = {
  id: string;
  status: string;
  etaMinutes?: number | null;
  distanceKm?: number | null;
  driverEarning?: number | null;
  order: DriverOrder;
};

type FinanceDashboard = {
  grossRevenue: number;
  netRevenue: number;
  paidOrders: number;
  averageTicket: number;
};

type DriverProfile = {
  id: string;
  fullName: string;
  vehiclePlate?: string | null;
  vehicleModel?: string | null;
  pixKey?: string | null;
  user: {
    email?: string | null;
    phone?: string | null;
    status?: string | null;
  };
};

function validationCode(orderId: string) {
  return orderId.slice(-6).toUpperCase();
}

function formatAddress(address?: DriverOrder['address']) {
  if (!address) {
    return 'Endereco do cliente pendente';
  }

  return [
    [address.street, address.number].filter(Boolean).join(', '),
    address.complement,
    address.neighborhood,
    [address.city, address.state].filter(Boolean).join(' - '),
  ]
    .filter(Boolean)
    .join(' | ');
}

function formatRestaurantAddress(restaurant?: DriverOrder['restaurant']) {
  if (!restaurant) {
    return 'Endereco da loja pendente';
  }

  return [
    [restaurant.street, restaurant.number].filter(Boolean).join(', '),
    restaurant.complement,
    restaurant.neighborhood,
    [restaurant.city, restaurant.state].filter(Boolean).join(' - '),
  ]
    .filter(Boolean)
    .join(' | ');
}

async function openPickupMap(restaurant: DriverOrder['restaurant']) {
  const lat = toNumber(restaurant.latitude);
  const lng = toNumber(restaurant.longitude);
  const label = formatRestaurantAddress(restaurant) || restaurant.name;

  if (lat !== null && lng !== null) {
    await Linking.openURL(`https://www.google.com/maps/dir/?api=1&origin=Current+Location&destination=${lat},${lng}&travelmode=driving`);
    return;
  }

  await Linking.openURL(`https://www.google.com/maps/search/?api=1&query=${encodeURIComponent(label)}`);
}

export default function DriverHomeScreen() {
  const router = useRouter();
  const { accessToken, user, online, setOnline, setSession, clearSession } = useDriverSession();
  const [showLogin, setShowLogin] = useState(false);
  const [showSignup, setShowSignup] = useState(false);
  const [email, setEmail] = useState(DRIVER_EMAIL);
  const [password, setPassword] = useState(DRIVER_PASSWORD);
  const [signup, setSignup] = useState<DriverSignupPayload>({
    fullName: '',
    email: '',
    password: '',
    phone: '',
    documentNumber: '',
    vehiclePlate: '',
    vehicleModel: '',
    pixKey: '',
  });
  const [offers, setOffers] = useState<DeliveryOffer[]>([]);
  const [activeDelivery, setActiveDelivery] = useState<DeliveryOffer | null>(null);
  const [finance, setFinance] = useState<FinanceDashboard | null>(null);
  const [profile, setProfile] = useState<DriverProfile | null>(null);
  const [loading, setLoading] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState('');

  const authHeaders = useMemo(
    () => (accessToken ? { Authorization: `Bearer ${accessToken}` } : undefined),
    [accessToken],
  );

  const expireSession = (message = 'Sua sessao expirou. Entre novamente para continuar.') => {
    setOffers([]);
    setActiveDelivery(null);
    setFinance(null);
    setProfile(null);
    setOnline(false);
    clearSession();
    setShowSignup(false);
    setShowLogin(true);
    setError(message);
  };

  const load = async (token: string) => {
    setLoading(true);
    try {
      const headers = { Authorization: `Bearer ${token}` };
      const [profileResponse, offersResponse, deliveriesResponse, financeResponse] = await Promise.all([
        axios.get<DriverProfile>(`${API_URL}/driver/profile`, { headers }),
        axios.get<DeliveryOffer[]>(`${API_URL}/driver/deliveries/offers`, { headers }),
        axios.get<DeliveryOffer[]>(`${API_URL}/driver/deliveries/active`, { headers }),
        axios.get<FinanceDashboard>(`${API_URL}/finance/dashboard`, { headers }),
      ]);

      setProfile(profileResponse.data);
      setOffers(offersResponse.data);
      setActiveDelivery(deliveriesResponse.data[0] ?? null);
      setFinance(financeResponse.data);
      setError('');
    } catch (loadError) {
      if (isUnauthorizedError(loadError)) {
        expireSession();
        return;
      }
      setError(extractErrorMessage(loadError, 'Falha ao carregar as corridas do entregador.'));
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    if (!accessToken) {
      return;
    }
    void load(accessToken);
  }, [accessToken]);

  useEffect(() => {
    if (!accessToken || !online) {
      return;
    }

    const heartbeatId = setInterval(() => {
      void axios.patch(
        `${API_URL}/driver/status`,
        { isOnline: true },
        { headers: { Authorization: `Bearer ${accessToken}` } },
      ).catch(() => undefined);
      void load(accessToken);
    }, 25000);

    return () => clearInterval(heartbeatId);
  }, [accessToken, online]);

  const handleLogin = async () => {
    setSubmitting(true);
    setError('');
    try {
      const response = await axios.post<LoginResponse>(`${API_URL}/auth/login/driver`, {
        email,
        password,
      });
      setSession({
        accessToken: response.data.accessToken,
        refreshToken: response.data.refreshToken,
        user: response.data.user ?? null,
      });
      setShowLogin(false);
      setOnline(false);
      await load(response.data.accessToken);
    } catch (loginError) {
      setError(extractErrorMessage(loginError, 'Falha ao entrar como entregador.'));
    } finally {
      setSubmitting(false);
    }
  };

  const handleSignup = async () => {
    setSubmitting(true);
    setError('');
    try {
      const response = await axios.post<{ message: string }>(`${API_URL}/auth/register/driver`, signup);
      setShowSignup(false);
      setShowLogin(true);
      setError(response.data.message);
    } catch (signupError) {
      setError(extractErrorMessage(signupError, 'Falha ao enviar o cadastro do entregador.'));
    } finally {
      setSubmitting(false);
    }
  };

  const handleLogout = async () => {
    if (accessToken) {
      await axios.patch(
        `${API_URL}/driver/status`,
        { isOnline: false },
        { headers: { Authorization: `Bearer ${accessToken}` } },
      ).catch(() => undefined);
    }

    setOffers([]);
    setActiveDelivery(null);
    setFinance(null);
    setProfile(null);
    clearSession();
    setShowLogin(true);
  };

  const toggleStatus = async () => {
    if (!accessToken || !authHeaders) {
      return;
    }

    const next = !online;
    try {
      await axios.patch(`${API_URL}/driver/status`, { isOnline: next }, { headers: authHeaders });
      setOnline(next);
      if (next) {
        await load(accessToken);
      } else {
        setOffers([]);
      }
      setError('');
    } catch (requestError) {
      if (isUnauthorizedError(requestError)) {
        expireSession();
        return;
      }
      setError(extractErrorMessage(requestError, 'Falha ao atualizar o status do entregador.'));
    }
  };

  const handleOffer = async (offerId: string, action: 'accept' | 'reject') => {
    if (!authHeaders || !accessToken) {
      return;
    }

    setLoading(true);
    try {
      await axios.patch(`${API_URL}/driver/deliveries/${offerId}/${action}`, {}, { headers: authHeaders });
      const acceptedOffer = offers.find((offer) => offer.id === offerId) ?? null;
      await load(accessToken);

      if (action === 'accept' && acceptedOffer) {
        await openPickupMap(acceptedOffer.order.restaurant);
        router.push(`/active-delivery?orderId=${acceptedOffer.order.id}&deliveryId=${acceptedOffer.id}` as never);
      }
    } catch (requestError) {
      if (isUnauthorizedError(requestError)) {
        expireSession();
        return;
      }
      setError(extractErrorMessage(requestError, 'Falha ao processar a corrida.'));
      setLoading(false);
    }
  };

  if (!accessToken && !showLogin) {
    return (
      <SafeAreaView style={styles.safeArea}>
        <View style={styles.landingWrap}>
          <Image source={require('../assets/chego-logo.png')} style={styles.landingLogo} resizeMode="contain" />
          <Text style={styles.landingEyebrow}>Chego Driver</Text>
          <Text style={styles.landingTitle}>Corridas claras, rotas rapidas e menos atrito para ganhar dinheiro.</Text>
          <Text style={styles.landingBody}>O app do entregador agora prioriza leitura rapida, acao imediata e confirmacao de entrega sem confusao.</Text>
          <TouchableOpacity onPress={() => setShowLogin(true)} style={styles.landingButton}>
            <Text style={styles.landingButtonText}>Entrar agora</Text>
          </TouchableOpacity>
        </View>
      </SafeAreaView>
    );
  }

  if (!accessToken || !user) {
    return (
      <SafeAreaView style={styles.safeArea}>
        <ScrollView contentContainerStyle={styles.authContent} showsVerticalScrollIndicator={false}>
          <View style={styles.authCard}>
            <Text style={styles.authEyebrow}>{showSignup ? 'Cadastro do entregador' : 'Acesso do entregador'}</Text>
            <Text style={styles.authTitle}>
              {showSignup ? 'Entre para a fila de validacao com seus dados, moto e chave PIX.' : 'Entre para receber corridas e ativar sua presenca.'}
            </Text>

            {showSignup ? (
              <>
                <TextInput value={signup.fullName} onChangeText={(value) => setSignup((state) => ({ ...state, fullName: value }))} placeholder="Nome completo" placeholderTextColor="#94A3B8" style={styles.input} />
                <TextInput value={signup.email} onChangeText={(value) => setSignup((state) => ({ ...state, email: value }))} placeholder="E-mail" placeholderTextColor="#94A3B8" autoCapitalize="none" keyboardType="email-address" style={styles.input} />
                <TextInput value={signup.password} onChangeText={(value) => setSignup((state) => ({ ...state, password: value }))} placeholder="Senha" placeholderTextColor="#94A3B8" secureTextEntry style={styles.input} />
                <TextInput value={signup.phone} onChangeText={(value) => setSignup((state) => ({ ...state, phone: value }))} placeholder="Telefone" placeholderTextColor="#94A3B8" keyboardType="phone-pad" style={styles.input} />
                <TextInput value={signup.documentNumber} onChangeText={(value) => setSignup((state) => ({ ...state, documentNumber: value }))} placeholder="CPF" placeholderTextColor="#94A3B8" style={styles.input} />
                <TextInput value={signup.vehiclePlate} onChangeText={(value) => setSignup((state) => ({ ...state, vehiclePlate: value.toUpperCase() }))} placeholder="Placa da moto" placeholderTextColor="#94A3B8" autoCapitalize="characters" style={styles.input} />
                <TextInput value={signup.vehicleModel} onChangeText={(value) => setSignup((state) => ({ ...state, vehicleModel: value }))} placeholder="Modelo da moto" placeholderTextColor="#94A3B8" style={styles.input} />
                <TextInput value={signup.pixKey} onChangeText={(value) => setSignup((state) => ({ ...state, pixKey: value }))} placeholder="Chave PIX para repasse" placeholderTextColor="#94A3B8" style={styles.input} />
              </>
            ) : (
              <>
                <TextInput value={email} onChangeText={setEmail} placeholder="E-mail do entregador" placeholderTextColor="#94A3B8" autoCapitalize="none" keyboardType="email-address" style={styles.input} />
                <TextInput value={password} onChangeText={setPassword} placeholder="Senha" placeholderTextColor="#94A3B8" secureTextEntry style={styles.input} />
              </>
            )}

            {error ? <View style={styles.warningCard}><Text style={styles.warningText}>{error}</Text></View> : null}

            <TouchableOpacity onPress={() => void (showSignup ? handleSignup() : handleLogin())} style={styles.authButton} disabled={submitting}>
              <Text style={styles.authButtonText}>{submitting ? 'Enviando...' : showSignup ? 'Enviar cadastro' : 'Entrar como entregador'}</Text>
            </TouchableOpacity>

            <TouchableOpacity onPress={() => setShowSignup((value) => !value)} style={styles.switchModeButton}>
              <Text style={styles.switchModeText}>{showSignup ? 'Ja tenho cadastro e quero entrar' : 'Nao tenho cadastro ainda'}</Text>
            </TouchableOpacity>
          </View>
        </ScrollView>
      </SafeAreaView>
    );
  }

  return (
    <SafeAreaView style={styles.safeArea}>
      <ScrollView contentContainerStyle={styles.content} showsVerticalScrollIndicator={false}>
        <DriverFlowNav />

        <View style={styles.topBar}>
          <View style={styles.topBarIdentity}>
            <Text style={styles.topBarKicker}>Entregador ativo</Text>
            <Text style={styles.topBarName}>{profile?.fullName ?? user.email ?? 'Painel do entregador'}</Text>
            <Text style={styles.topBarSubtext}>{profile?.vehicleModel ?? 'Moto pronta para rodar'} {profile?.vehiclePlate ? `• ${profile.vehiclePlate}` : ''}</Text>
          </View>
          <View style={[styles.topStatusBadge, online ? styles.topStatusBadgeOnline : styles.topStatusBadgeOffline]}>
            <Text style={styles.topStatusText}>{online ? 'Online' : 'Offline'}</Text>
          </View>
        </View>

        <View style={styles.heroCard}>
          <Text style={styles.heroEyebrow}>Operacao do turno</Text>
          <Text style={styles.heroTitle}>{activeDelivery ? 'Voce ja esta em corrida' : online ? 'Pronto para receber chamadas' : 'Ative sua presenca para entrar na fila'}</Text>
          <Text style={styles.heroBody}>
            {activeDelivery
              ? 'Tudo o que voce precisa agora e retirar, confirmar e entregar sem perder tempo com telas confusas.'
              : 'O painel mostra chamadas, liquido, corrida ativa e atalhos criticos sem excesso de informacao.'}
          </Text>
        </View>

        <View style={styles.metricRow}>
          <View style={styles.metricCard}>
            <Text style={styles.metricLabel}>Chamadas</Text>
            <Text style={styles.metricValue}>{offers.length}</Text>
          </View>
          <View style={styles.metricCard}>
            <Text style={styles.metricLabel}>Ativa</Text>
            <Text style={styles.metricValue}>{activeDelivery ? '1' : '0'}</Text>
          </View>
          <View style={styles.metricCardWide}>
            <Text style={styles.metricLabel}>Liquido</Text>
            <Text style={styles.metricValue}>{formatCurrency(finance?.netRevenue)}</Text>
          </View>
        </View>

        <View style={styles.actionCard}>
          <View style={styles.actionRow}>
            <TouchableOpacity onPress={() => void toggleStatus()} style={styles.primaryButtonShell}>
              <Text style={styles.primaryButtonText}>{online ? 'Ficar offline' : 'Ficar online'}</Text>
            </TouchableOpacity>
            <TouchableOpacity onPress={() => accessToken ? void load(accessToken) : undefined} style={styles.secondaryButtonShell}>
              <Text style={styles.secondaryButtonText}>Atualizar</Text>
            </TouchableOpacity>
            <TouchableOpacity onPress={() => void handleLogout()} style={styles.secondaryButtonShell}>
              <Text style={styles.secondaryButtonText}>Sair</Text>
            </TouchableOpacity>
          </View>
          <View style={styles.quickLinkRow}>
            <Link href="/earnings" style={styles.quickLink}>Ganhos</Link>
            <Link href="/documents" style={styles.quickLink}>Documentos</Link>
            <Link href="/account" style={styles.quickLink}>Conta e PIX</Link>
          </View>
        </View>

        {error ? <View style={styles.warningCard}><Text style={styles.warningText}>{error}</Text></View> : null}

        {activeDelivery ? (
          <View style={styles.card}>
            <Text style={styles.sectionTitle}>Entrega em andamento</Text>
            <Text style={styles.routeHeadline}>{activeDelivery.order.restaurant.name} {'->'} {activeDelivery.order.customer.fullName}</Text>
            <Text style={styles.copy}>Coleta: {formatRestaurantAddress(activeDelivery.order.restaurant)}</Text>
            <Text style={styles.copy}>Entrega: {formatAddress(activeDelivery.order.address)}</Text>
            <Text style={styles.codeLine}>Codigo da corrida: {validationCode(activeDelivery.order.id)}</Text>
            <Link href={`/active-delivery?orderId=${activeDelivery.order.id}&deliveryId=${activeDelivery.id}`} style={styles.routeButton}>
              Abrir entrega ativa
            </Link>
          </View>
        ) : null}

        <View style={styles.card}>
          <Text style={styles.sectionTitle}>Chamadas recebidas</Text>
          <Text style={styles.sectionSubtitle}>Aceite rapido com leitura clara de distancia, ganho e enderecos.</Text>
          {loading ? <Text style={styles.copy}>Carregando chamadas...</Text> : null}
          {!loading && !offers.length ? <Text style={styles.copy}>Nenhuma corrida disponivel para voce agora.</Text> : null}

          <View style={styles.offerList}>
            {offers.map((offer) => (
              <View key={offer.id} style={styles.offerCard}>
                <View style={styles.offerHeader}>
                  <Text style={styles.offerTitle}>{offer.order.restaurant.name}</Text>
                  <Text style={styles.offerValue}>{formatCurrency(offer.driverEarning)}</Text>
                </View>
                <Text style={styles.offerMeta}>Cliente: {offer.order.customer.fullName}</Text>
                <Text style={styles.offerMeta}>Distancia: {formatDistance(offer.distanceKm)}</Text>
                <Text style={styles.offerMeta}>ETA estimado: {offer.etaMinutes ?? '--'} min</Text>
                <Text style={styles.offerMeta}>Retirada: {formatRestaurantAddress(offer.order.restaurant)}</Text>
                <Text style={styles.offerMeta}>Entrega: {formatAddress(offer.order.address)}</Text>
                <Text style={styles.offerCode}>Codigo de retirada: {validationCode(offer.order.id)}</Text>
                <View style={styles.offerActions}>
                  <TouchableOpacity onPress={() => void handleOffer(offer.id, 'accept')} style={styles.acceptButton}>
                    <Text style={styles.acceptButtonText}>Aceitar</Text>
                  </TouchableOpacity>
                  <TouchableOpacity onPress={() => void handleOffer(offer.id, 'reject')} style={styles.rejectButton}>
                    <Text style={styles.rejectButtonText}>Recusar</Text>
                  </TouchableOpacity>
                </View>
              </View>
            ))}
          </View>
        </View>
      </ScrollView>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  safeArea: { flex: 1, backgroundColor: driverTheme.background },
  landingWrap: {
    flex: 1,
    paddingHorizontal: 28,
    paddingTop: 68,
    paddingBottom: 40,
    justifyContent: 'space-between',
  },
  landingLogo: { width: 170, height: 54 },
  landingEyebrow: { fontSize: 12, letterSpacing: 3, textTransform: 'uppercase', color: '#FDBA74', fontWeight: '800' },
  landingTitle: { marginTop: 12, fontSize: 34, lineHeight: 40, fontWeight: '900', color: '#FFFFFF', maxWidth: 320 },
  landingBody: { marginTop: 12, fontSize: 15, lineHeight: 22, color: '#CBD5E1', maxWidth: 320 },
  landingButton: { borderRadius: 999, backgroundColor: '#FFFFFF', paddingHorizontal: 18, paddingVertical: 14, alignSelf: 'flex-start' },
  landingButtonText: { color: '#0F172A', fontWeight: '900' },
  authContent: { padding: 18, justifyContent: 'center', flexGrow: 1 },
  authCard: { borderRadius: 24, padding: 18, backgroundColor: driverTheme.card, ...driverShadow },
  authEyebrow: { fontSize: 11, letterSpacing: 2.2, textTransform: 'uppercase', color: driverTheme.accentDark, fontWeight: '900' },
  authTitle: { marginTop: 8, fontSize: 20, lineHeight: 26, color: driverTheme.textDark, fontWeight: '900' },
  input: { marginTop: 10, borderRadius: 18, borderWidth: 1, borderColor: '#CBD5E1', backgroundColor: '#FFFFFF', paddingHorizontal: 16, paddingVertical: 12, fontSize: 15, color: '#0F172A' },
  authButton: { marginTop: 14, borderRadius: 999, backgroundColor: driverTheme.accent, paddingHorizontal: 18, paddingVertical: 14 },
  authButtonText: { textAlign: 'center', color: '#FFFFFF', fontWeight: '900', fontSize: 15 },
  switchModeButton: { marginTop: 10, alignSelf: 'center', paddingHorizontal: 10, paddingVertical: 6 },
  switchModeText: { color: '#0F172A', fontWeight: '800', fontSize: 12 },
  content: { padding: 16, gap: 14, paddingBottom: 24 },
  topBar: { borderRadius: 22, padding: 16, backgroundColor: driverTheme.panelStrong, borderWidth: 1, borderColor: driverTheme.border },
  topBarIdentity: { flex: 1 },
  topBarKicker: { fontSize: 10, letterSpacing: 2.3, textTransform: 'uppercase', color: '#FB923C', fontWeight: '800' },
  topBarName: { marginTop: 6, fontSize: 20, lineHeight: 24, fontWeight: '900', color: driverTheme.text },
  topBarSubtext: { marginTop: 4, fontSize: 12, color: driverTheme.textMuted, fontWeight: '700' },
  topStatusBadge: { position: 'absolute', right: 16, top: 16, borderRadius: 999, paddingHorizontal: 12, paddingVertical: 8 },
  topStatusBadgeOnline: { backgroundColor: 'rgba(16, 185, 129, 0.18)' },
  topStatusBadgeOffline: { backgroundColor: 'rgba(148, 163, 184, 0.18)' },
  topStatusText: { fontSize: 12, fontWeight: '900', color: '#FFFFFF' },
  heroCard: { borderRadius: 24, padding: 18, backgroundColor: '#131E34', borderWidth: 1, borderColor: driverTheme.border },
  heroEyebrow: { fontSize: 10, letterSpacing: 2.2, textTransform: 'uppercase', color: '#FCD34D', fontWeight: '800' },
  heroTitle: { marginTop: 10, fontSize: 24, lineHeight: 30, fontWeight: '900', color: driverTheme.text },
  heroBody: { marginTop: 8, fontSize: 14, lineHeight: 21, color: '#CBD5E1', fontWeight: '600' },
  metricRow: { flexDirection: 'row', gap: 10 },
  metricCard: { flex: 1, borderRadius: 20, padding: 14, backgroundColor: driverTheme.panel, borderWidth: 1, borderColor: driverTheme.border },
  metricCardWide: { flex: 1.25, borderRadius: 20, padding: 14, backgroundColor: driverTheme.panel, borderWidth: 1, borderColor: driverTheme.border },
  metricLabel: { fontSize: 10, letterSpacing: 1.1, textTransform: 'uppercase', color: driverTheme.textMuted, fontWeight: '900' },
  metricValue: { marginTop: 8, fontSize: 18, color: '#FFFFFF', fontWeight: '900' },
  actionCard: { borderRadius: 22, padding: 14, backgroundColor: driverTheme.card },
  actionRow: { flexDirection: 'row', gap: 8 },
  primaryButtonShell: { flex: 1.25, borderRadius: 999, backgroundColor: driverTheme.accent, paddingHorizontal: 12, paddingVertical: 13 },
  primaryButtonText: { textAlign: 'center', fontWeight: '900', color: '#FFFFFF' },
  secondaryButtonShell: { flex: 1, borderRadius: 999, backgroundColor: '#E2E8F0', paddingHorizontal: 10, paddingVertical: 13 },
  secondaryButtonText: { textAlign: 'center', fontWeight: '800', color: '#0F172A', fontSize: 12 },
  quickLinkRow: { marginTop: 10, flexDirection: 'row', gap: 8, flexWrap: 'wrap' },
  quickLink: { borderRadius: 999, overflow: 'hidden', backgroundColor: driverTheme.panelStrong, color: '#FFFFFF', paddingHorizontal: 12, paddingVertical: 11, fontWeight: '800', fontSize: 12 },
  warningCard: { borderRadius: 18, padding: 14, backgroundColor: driverTheme.warningSoft },
  warningText: { color: '#92400E', fontSize: 13, lineHeight: 19, fontWeight: '700' },
  card: { borderRadius: 24, padding: 18, backgroundColor: driverTheme.card },
  sectionTitle: { fontSize: 20, fontWeight: '900', color: driverTheme.textDark },
  sectionSubtitle: { marginTop: 6, fontSize: 12, lineHeight: 18, color: '#64748B', fontWeight: '700' },
  routeHeadline: { marginTop: 10, fontSize: 16, lineHeight: 22, fontWeight: '900', color: driverTheme.textDark },
  copy: { marginTop: 8, fontSize: 13, lineHeight: 20, color: '#475569' },
  codeLine: { marginTop: 10, fontSize: 16, fontWeight: '900', color: '#9A3412', letterSpacing: 1.5 },
  routeButton: { marginTop: 16, borderRadius: 999, backgroundColor: '#0F766E', color: '#FFFFFF', textAlign: 'center', paddingHorizontal: 18, paddingVertical: 14, fontWeight: '900', overflow: 'hidden' },
  offerList: { marginTop: 14, gap: 12 },
  offerCard: { borderRadius: 20, padding: 16, backgroundColor: driverTheme.accentSoft },
  offerHeader: { flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', gap: 8 },
  offerTitle: { flex: 1, fontSize: 16, fontWeight: '900', color: '#111827' },
  offerValue: { fontSize: 16, fontWeight: '900', color: driverTheme.accentDark },
  offerMeta: { marginTop: 6, fontSize: 13, lineHeight: 20, color: '#475569' },
  offerCode: { marginTop: 8, fontSize: 13, fontWeight: '900', color: '#9A3412' },
  offerActions: { marginTop: 14, flexDirection: 'row', gap: 10 },
  acceptButton: { flex: 1, borderRadius: 999, backgroundColor: driverTheme.accent, paddingHorizontal: 16, paddingVertical: 12 },
  acceptButtonText: { textAlign: 'center', color: '#FFFFFF', fontWeight: '900' },
  rejectButton: { flex: 1, borderRadius: 999, backgroundColor: '#0F172A', paddingHorizontal: 16, paddingVertical: 12 },
  rejectButtonText: { textAlign: 'center', color: '#FFFFFF', fontWeight: '900' },
});
