import React, { useState, useMemo } from 'react';
import { Alert, ScrollView, StyleSheet, Text, TextInput, TouchableOpacity, View, Image } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { useNavigation } from '@react-navigation/native';
import * as ImagePicker from 'expo-image-picker';
import { useApp } from '../context/AppContext';
import { Card } from '../components/ui/Card';
import { Button } from '../components/ui/Button';
import { Badge } from '../components/ui/Badge';
import { currency } from '../lib/format';
import { supabase } from '../lib/supabase';
import { colors, radius, shadows } from '../lib/theme';
import { ShopSchedule } from '../types';

type Tab = 'visao' | 'estatisticas' | 'agenda' | 'historico' | 'pedidos' | 'servicos' | 'produtos' | 'equipa' | 'perfil';
type Period = 'hoje' | 'semana' | 'mes' | 'total';

const periods: Record<Period, (date: Date) => boolean> = {
  hoje: (d) => d.toDateString() === new Date().toDateString(),
  semana: (d) => {
    const now = new Date();
    return now.getTime() - d.getTime() <= 7 * 24 * 60 * 60 * 1000;
  },
  mes: (d) => {
    const now = new Date();
    return d.getMonth() === now.getMonth() && d.getFullYear() === now.getFullYear();
  },
  total: () => true,
};

const parseDate = (value: string) => new Date(value.replace(' ', 'T'));

const filterSchedule = (sched: ShopSchedule[]) => {
  const todayStr = new Date().toISOString().split('T')[0];
  return sched.filter((s) => !(s.isException && s.date && s.date < todayStr));
};

const statusColor: Record<string, string> = {
  pendente: colors.primary,
  confirmado: colors.success,
  concluido: colors.success,
  cancelado: colors.danger,
};

const statusLabel: Record<string, string> = {
  pendente: 'Pendente',
  confirmado: 'Confirmado',
  concluido: 'Concluído',
  cancelado: 'Cancelado',
};

export default function Dashboard() {
  const navigation = useNavigation();
  const {
    user,
    shops,
    appointments,
    orders,
    refreshShops,
    updateAppointmentStatus,
    updateOrderStatus,
    users,
    addService,
    deleteService,
    addProduct,
    deleteProduct,
    addBarber,
    deleteBarber,
    updateShopDetails,
    logout,
  } = useApp();

  const shop = useMemo(() => shops.find((s) => s.id === user?.shopId), [shops, user?.shopId]);
  const [activeTab, setActiveTab] = useState<Tab>('visao');
  const [period, setPeriod] = useState<Period>('semana');
  const [loading, setLoading] = useState(false);

  // Clear forms on tab change
  React.useEffect(() => {
    setFormSvc({ name: '', price: '', duration: '' });
    setFormProd({ name: '', price: '', stock: '' });
    setFormBarb({ name: '', specialties: '' });
  }, [activeTab]);

  const allShopAppointments = useMemo(() => {
    if (!shop) return [];
    return appointments
      .filter((a) => a.shopId === shop.id && periods[period](parseDate(a.date)))
      .sort((a, b) => a.date.localeCompare(b.date));
  }, [appointments, shop?.id, period]);

  const activeShopAppointments = useMemo(
    () => allShopAppointments.filter((a) => a.status !== 'concluido' && a.status !== 'cancelado'),
    [allShopAppointments]
  );

  const pendingAppts = useMemo(
    () => activeShopAppointments.filter((a) => a.status === 'pendente'),
    [activeShopAppointments]
  );

  const confirmedAppts = useMemo(
    () => activeShopAppointments.filter((a) => a.status === 'confirmado'),
    [activeShopAppointments]
  );

  const historyAppointments = useMemo(
    () => allShopAppointments.filter((a) => a.status === 'concluido' || a.status === 'cancelado'),
    [allShopAppointments]
  );

  const shopOrders = useMemo(() => {
    if (!shop) return [];
    return orders.filter(
      (o) => o.shopId === shop.id && o.status !== 'concluido' && periods[period](new Date(o.createdAt))
    );
  }, [orders, shop?.id, period]);

  const upcomingAppointments = useMemo(
    () =>
      appointments
        .filter((a) => {
          if (a.shopId !== shop?.id || a.status === 'cancelado') return false;
          return parseDate(a.date) > new Date();
        })
        .sort((a, b) => a.date.localeCompare(b.date))
        .slice(0, 5),
    [appointments, shop?.id]
  );

  // Form states
  const [formSvc, setFormSvc] = useState({ name: '', price: '', duration: '' });
  const [formProd, setFormProd] = useState({ name: '', price: '', stock: '' });
  const [formBarb, setFormBarb] = useState({ name: '', specialties: '' });

  // Settings states
  const [shopName, setShopName] = useState(shop?.name || '');
  const [shopAddr, setShopAddr] = useState(shop?.address || '');
  const [phone1, setPhone1] = useState(shop?.contacts?.phone1 || '');
  const [whatsapp, setWhatsapp] = useState(shop?.socialNetworks?.whatsapp || '');
  const [instagram, setInstagram] = useState(shop?.socialNetworks?.instagram || '');
  const [facebook, setFacebook] = useState(shop?.socialNetworks?.facebook || '');
  const [paymentMethods, setPaymentMethods] = useState(shop?.paymentMethods?.join(', ') || '');
  const [exceptionDate, setExceptionDate] = useState('');
  const [exceptionClosed, setExceptionClosed] = useState(true);
  const [schedule, setSchedule] = useState<ShopSchedule[]>(shop?.schedule || [
    { day: 'Segunda', open: '09:00', close: '19:00' },
    { day: 'Terça', open: '09:00', close: '19:00' },
    { day: 'Quarta', open: '09:00', close: '19:00' },
    { day: 'Quinta', open: '09:00', close: '19:00' },
    { day: 'Sexta', open: '09:00', close: '19:00' },
    { day: 'Sábado', open: '09:00', close: '18:00' },
    { day: 'Domingo', open: '00:00', close: '00:00', closed: true },
  ]);

  React.useEffect(() => {
    if (shop?.schedule?.length) {
      setSchedule(filterSchedule(shop.schedule));
    }
  }, [shop?.id, shop?.schedule]);

  const weeklySchedule = useMemo(() => schedule.filter((s) => !s.isException), [schedule]);
  const exceptionSlots = useMemo(() => schedule.filter((s) => s.isException), [schedule]);

  const statsData = useMemo(() => {
    if (!shop) return null;

    const shopAppts = appointments.filter((a) => a.shopId === shop.id);
    const totalConcluidas = shopAppts.filter((a) => a.status === 'concluido').length;
    const totalCanceladas = shopAppts.filter((a) => a.status === 'cancelado').length;
    const taxaConclusao = shopAppts.length > 0 ? Math.round((totalConcluidas / shopAppts.length) * 100) : 0;
    const revenueServicos = shopAppts
      .filter((a) => a.status === 'concluido')
      .reduce((sum, a) => sum + (a.total || 0), 0);
    const revenueProdutos = orders
      .filter((o) => o.shopId === shop.id && o.status === 'concluido')
      .reduce((sum, o) => sum + o.total, 0);

    const diasPT = ['Dom', 'Seg', 'Ter', 'Qua', 'Qui', 'Sex', 'Sáb'];
    const byDayOfWeek = Array.from({ length: 7 }, (_, i) => ({ name: diasPT[i], reservas: 0 }));
    shopAppts.filter((a) => a.status !== 'cancelado').forEach((a) => {
      const d = new Date(a.date.replace(' ', 'T')).getDay();
      byDayOfWeek[d].reservas += 1;
    });

    const svcMap = new Map<string, { name: string; value: number }>();
    shopAppts.filter((a) => a.status !== 'cancelado').forEach((a) => {
      const svc = shop.services.find((s) => s.id === a.serviceId);
      if (!svc) return;
      const prev = svcMap.get(a.serviceId)?.value ?? 0;
      svcMap.set(a.serviceId, { name: svc.name, value: prev + 1 });
    });
    const topServices = Array.from(svcMap.values()).sort((a, b) => b.value - a.value).slice(0, 5);

    const barberMap = new Map<string, { name: string; qty: number }>();
    shopAppts.filter((a) => a.status !== 'cancelado').forEach((a) => {
      const barber = shop.barbers.find((b) => b.id === a.barberId);
      if (!barber) return;
      const prev = barberMap.get(a.barberId)?.qty ?? 0;
      barberMap.set(a.barberId, { name: barber.name, qty: prev + 1 });
    });
    const topBarbers = Array.from(barberMap.values()).sort((a, b) => b.qty - a.qty);

    const weeklyData: { name: string; reservas: number; concluidas: number }[] = [];
    for (let i = 7; i >= 0; i -= 1) {
      const wStart = new Date();
      wStart.setDate(wStart.getDate() - i * 7 - 6);
      wStart.setHours(0, 0, 0, 0);
      const wEnd = new Date();
      wEnd.setDate(wEnd.getDate() - i * 7);
      wEnd.setHours(23, 59, 59, 999);
      const label = wStart.toLocaleDateString('pt-PT', { day: 'numeric', month: 'short' });
      const weekAppts = shopAppts.filter((a) => {
        const d = new Date(a.date.replace(' ', 'T'));
        return d >= wStart && d <= wEnd;
      });
      weeklyData.push({
        name: label,
        reservas: weekAppts.length,
        concluidas: weekAppts.filter((a) => a.status === 'concluido').length,
      });
    }

    return {
      totalAppts: shopAppts.length,
      totalConcluidas,
      totalCanceladas,
      taxaConclusao,
      revenueServicos,
      revenueProdutos,
      byDayOfWeek,
      topServices,
      topBarbers,
      weeklyData,
    };
  }, [appointments, orders, shop]);

  const updateWeeklySlot = (day: string, patch: Partial<ShopSchedule>) => {
    setSchedule((prev) =>
      prev.map((slot) => (slot.day === day && !slot.isException ? { ...slot, ...patch } : slot))
    );
  };

  const addException = () => {
    if (!exceptionDate.trim()) {
      Alert.alert('Atenção', 'Selecione uma data para a exceção.');
      return;
    }
    if (schedule.some((s) => s.isException && s.date === exceptionDate)) {
      Alert.alert('Atenção', 'Já existe uma exceção configurada para esta data.');
      return;
    }
    setSchedule((prev) => [
      ...prev,
      {
        day: 'Exceção',
        open: '09:00',
        close: '19:30',
        closed: exceptionClosed,
        date: exceptionDate.trim(),
        isException: true,
      },
    ]);
    setExceptionDate('');
  };

  const removeException = (date?: string) => {
    setSchedule((prev) => prev.filter((s) => !(s.isException && s.date === date)));
  };

  const pickImage = async (target: 'shop' | 'barber', barberId?: string) => {
    const result = await ImagePicker.launchImageLibraryAsync({
      mediaTypes: ImagePicker.MediaTypeOptions.Images,
      allowsEditing: true,
      aspect: [16, 9],
      quality: 0.5,
    });

    if (!result.canceled && result.assets[0].uri) {
      setLoading(true);
      try {
        const uri = result.assets[0].uri;
        const fileExt = uri.split('.').pop();
        const fileName = `${Date.now()}.${fileExt}`;
        const filePath = `shop-${shop?.id}/${fileName}`;

        const formData = new FormData();
        formData.append('file', {
          uri,
          name: fileName,
          type: `image/${fileExt}`,
        } as any);

        const { data: uploadData, error: uploadError } = await supabase.storage
          .from('shops')
          .upload(filePath, formData);

        if (uploadError) throw uploadError;

        const { data: { publicUrl } } = supabase.storage
          .from('shops')
          .getPublicUrl(filePath);

        if (target === 'shop') {
          await updateShopDetails(shop!.id, { imageUrl: publicUrl });
        } else if (barberId) {
          const b = shop?.barbers.find(x => x.id === barberId);
          if (b) {
            // Update barber logic in context or direct supabase
            await supabase.from('barbers').update({ image_url: publicUrl }).eq('id', barberId);
          }
        }
        await refreshShops();
      } catch (e: any) {
        Alert.alert('Erro no Upload', e.message);
      } finally {
        setLoading(false);
      }
    }
  };

  const handleSaveSettings = async () => {
    if (!shop) return;
    setLoading(true);
    try {
      await updateShopDetails(shop.id, {
        name: shopName,
        address: shopAddr,
        contacts: { phone1 },
        socialNetworks: { whatsapp, instagram, facebook },
        paymentMethods: paymentMethods.split(',').map(s => s.trim()).filter(Boolean),
        schedule,
      });
      Alert.alert('Sucesso', 'Definições guardadas com sucesso.');
      await refreshShops();
    } catch (e: any) {
      Alert.alert('Erro', e.message);
    } finally {
      setLoading(false);
    }
  };

  if (!shop) return null;

  const renderAppointmentActions = (appt: typeof appointments[number], mode: 'pending' | 'confirmed') => (
    <View style={styles.ticketActions}>
      {mode === 'pending' ? (
        <>
          <TouchableOpacity
            onPress={() => updateAppointmentStatus(appt.id, 'cancelado')}
            style={[styles.premiumActionBtn, styles.rejectBtn]}
          >
            <Text style={[styles.premiumActionBtnTxt, { color: colors.danger }]}>Recusar</Text>
          </TouchableOpacity>
          <TouchableOpacity
            onPress={() => updateAppointmentStatus(appt.id, 'confirmado')}
            style={[styles.premiumActionBtn, styles.acceptBtn]}
          >
            <Text style={[styles.premiumActionBtnTxt, { color: colors.textInverse }]}>Aceitar</Text>
          </TouchableOpacity>
        </>
      ) : (
        <>
          <TouchableOpacity
            onPress={() => updateAppointmentStatus(appt.id, 'cancelado')}
            style={[styles.premiumActionBtn, styles.rejectBtn]}
          >
            <Text style={[styles.premiumActionBtnTxt, { color: colors.danger }]}>Cancelar</Text>
          </TouchableOpacity>
          <TouchableOpacity
            onPress={() => updateAppointmentStatus(appt.id, 'concluido')}
            style={[styles.premiumActionBtn, styles.completeBtn]}
          >
            <Text style={[styles.premiumActionBtnTxt, { color: colors.textInverse }]}>Concluir</Text>
          </TouchableOpacity>
        </>
      )}
    </View>
  );

  const renderAppointmentCard = (appt: typeof appointments[number], mode: 'pending' | 'confirmed' | 'history') => {
    const svc = shop.services.find((s) => s.id === appt.serviceId);
    const barb = shop.barbers.find((b) => b.id === appt.barberId);
    const customer = users.find((u) => u.id === appt.customerId);
    const aptDate = parseDate(appt.date);

    return (
      <Card key={appt.id} style={styles.agendaTicket}>
        <View style={styles.ticketMain}>
          <View style={styles.ticketRow}>
            <Text style={styles.ticketSvc}>{svc?.name || 'Serviço'}</Text>
            <Text style={styles.ticketPrice}>{currency(appt.total)}</Text>
          </View>
          <Text style={styles.ticketMeta}>Cliente: {customer?.name || 'Cliente'} · {barb?.name || 'Profissional'}</Text>
          <Text style={styles.ticketMeta}>
            {aptDate.toLocaleDateString('pt-PT', { day: 'numeric', month: 'short' })} às{' '}
            {aptDate.toLocaleTimeString('pt-PT', { hour: '2-digit', minute: '2-digit' })}
          </Text>
          {mode === 'history' && (
            <View style={{ marginTop: 8 }}>
              <Badge color={appt.status === 'concluido' ? 'green' : 'red'} variant="soft">
                {statusLabel[appt.status]}
              </Badge>
            </View>
          )}
          {mode !== 'history' && renderAppointmentActions(appt, mode)}
        </View>
      </Card>
    );
  };

  return (
    <SafeAreaView style={styles.container}>
      {/* Header Dashboard */}
      <View style={styles.header}>
        <View style={styles.headerCopy}>
          <Text style={styles.headerKicker}>Painel</Text>
          <Text style={styles.headerTitle} numberOfLines={1}>{shop.name}</Text>
        </View>
        <TouchableOpacity style={styles.brandPill} onPress={() => navigation.navigate('BarberProfileTab' as never)}>
          <Text style={styles.brandText}>{user?.name.charAt(0)}</Text>
        </TouchableOpacity>
      </View>

      <View style={styles.periodRow}>
        {([
          ['hoje', 'Hoje'],
          ['semana', 'Semana'],
          ['mes', 'Mês'],
          ['total', 'Total'],
        ] as const).map(([id, label]) => (
          <TouchableOpacity
            key={id}
            onPress={() => setPeriod(id)}
            style={[styles.periodChip, period === id && styles.periodChipActive]}
          >
            <Text style={[styles.periodChipText, period === id && styles.periodChipTextActive]}>{label}</Text>
          </TouchableOpacity>
        ))}
      </View>

      {/* Tabs Horizontais */}
      <View style={styles.tabContainer}>
        <ScrollView horizontal showsHorizontalScrollIndicator={false} contentContainerStyle={styles.tabsScroll}>
          {[
            ['visao', 'Visão Geral'],
            ['estatisticas', 'Estatísticas'],
            ['agenda', `Agendamentos${pendingAppts.length ? ` (${pendingAppts.length})` : ''}`],
            ['historico', 'Histórico'],
            ['pedidos', `Pedidos${shopOrders.length ? ` (${shopOrders.length})` : ''}`],
            ['servicos', 'Serviços'],
            ['produtos', 'Produtos'],
            ['equipa', 'Profissionais'],
            ['perfil', 'Definições'],
          ].map(([id, label]) => (
            <TouchableOpacity
              key={id}
              onPress={() => setActiveTab(id as Tab)}
              style={[styles.tabItem, activeTab === id && styles.tabItemActive]}
            >
              <Text style={[styles.tabText, activeTab === id && styles.tabTextActive]}>{label}</Text>
            </TouchableOpacity>
          ))}
        </ScrollView>
      </View>

      <ScrollView contentContainerStyle={styles.content}>
        {activeTab === 'visao' && (
          <View style={styles.tabBox}>
            <View>
              <Text style={styles.sectionTitle}>
                {new Date().toLocaleDateString('pt-PT', { weekday: 'long', day: 'numeric', month: 'long' })}
              </Text>
              <Text style={styles.sectionSubtitle}>
                {(() => {
                  const hour = new Date().getHours();
                  if (hour < 12) return 'Bom dia';
                  if (hour < 18) return 'Boa tarde';
                  return 'Boa noite';
                })()}, {user?.name}
              </Text>
            </View>

            <View style={styles.statsKpiGrid}>
              {[
                { label: 'Total de Reservas', value: String(allShopAppointments.length) },
                { label: 'Concluídas', value: String(allShopAppointments.filter((a) => a.status === 'concluido').length) },
                { label: 'Pendentes', value: String(pendingAppts.length) },
                { label: 'Clientes Únicos', value: String(new Set(allShopAppointments.map((a) => a.customerId)).size) },
              ].map((kpi) => (
                <Card key={kpi.label} style={styles.statsKpiCard}>
                  <Text style={styles.statsKpiLabel}>{kpi.label}</Text>
                  <Text style={styles.statsKpiValue}>{kpi.value}</Text>
                </Card>
              ))}
            </View>

            <Card style={styles.statsBlockCard}>
              <View style={styles.sectionHeaderRow}>
                <Text style={styles.statsBlockTitle}>Próximos Agendamentos</Text>
                <TouchableOpacity onPress={() => setActiveTab('agenda')}>
                  <Text style={styles.linkAction}>Gerir →</Text>
                </TouchableOpacity>
              </View>
              {upcomingAppointments.length > 0 ? (
                upcomingAppointments.map((appt) => {
                  const svc = shop.services.find((s) => s.id === appt.serviceId);
                  const aptDate = parseDate(appt.date);
                  return (
                    <View key={appt.id} style={styles.statsWeekRow}>
                      <Text style={styles.statsWeekLabel}>{svc?.name || 'Serviço'}</Text>
                      <Text style={styles.statsWeekValue}>
                        {aptDate.toLocaleDateString('pt-PT', { day: 'numeric', month: 'short' })} · {aptDate.toLocaleTimeString('pt-PT', { hour: '2-digit', minute: '2-digit' })}
                      </Text>
                    </View>
                  );
                })
              ) : (
                <Text style={styles.exceptionEmpty}>Sem agendamentos futuros.</Text>
              )}
            </Card>

            <Card style={styles.statsBlockCard}>
              <Text style={styles.statsBlockTitle}>Resumo do Período</Text>
              <View style={styles.statsWeekRow}>
                <Text style={styles.statsWeekLabel}>Confirmados</Text>
                <Text style={styles.statsWeekValue}>{confirmedAppts.length}</Text>
              </View>
              <View style={styles.statsWeekRow}>
                <Text style={styles.statsWeekLabel}>Pedidos produtos</Text>
                <Text style={styles.statsWeekValue}>{shopOrders.length}</Text>
              </View>
              <View style={styles.statsWeekRow}>
                <Text style={styles.statsWeekLabel}>Serviços activos</Text>
                <Text style={styles.statsWeekValue}>{shop.services.length}</Text>
              </View>
            </Card>
          </View>
        )}

        {activeTab === 'agenda' && (
          <View style={styles.tabBox}>
            <View>
              <Text style={styles.sectionTitle}>Caixa de Pedidos</Text>
              <Text style={styles.sectionSubtitle}>
                Aprove ou recuse pedidos pendentes e conclua os serviços confirmados.
              </Text>
            </View>

            <Card style={styles.pendingSection}>
              <View style={styles.sectionHeaderRow}>
                <Text style={styles.statsBlockTitle}>Aguardam Aprovação</Text>
                <Badge color="indigo" variant="soft">{pendingAppts.length}</Badge>
              </View>
              {pendingAppts.length > 0 ? (
                pendingAppts.map((appt) => renderAppointmentCard(appt, 'pending'))
              ) : (
                <Text style={styles.exceptionEmpty}>Não há pedidos pendentes no momento.</Text>
              )}
            </Card>

            <Card style={styles.statsBlockCard}>
              <View style={styles.sectionHeaderRow}>
                <Text style={styles.statsBlockTitle}>Agendamentos Aprovados</Text>
                <Badge color="slate" variant="soft">{confirmedAppts.length}</Badge>
              </View>
              {confirmedAppts.length > 0 ? (
                confirmedAppts.map((appt) => renderAppointmentCard(appt, 'confirmed'))
              ) : (
                <Text style={styles.exceptionEmpty}>Próximos serviços irão aparecer aqui.</Text>
              )}
            </Card>
          </View>
        )}

        {activeTab === 'historico' && (
          <View style={styles.tabBox}>
            <View style={styles.sectionHeaderRow}>
              <Text style={styles.sectionTitle}>Histórico de Agendamentos</Text>
              <Badge color="slate" variant="soft">{historyAppointments.length} registos</Badge>
            </View>
            {historyAppointments.length > 0 ? (
              historyAppointments.map((appt) => renderAppointmentCard(appt, 'history'))
            ) : (
              <View style={styles.emptyBox}>
                <Text style={styles.emptyTxt}>Nenhum registo no período selecionado.</Text>
              </View>
            )}
          </View>
        )}

        {activeTab === 'pedidos' && (
          <View style={styles.tabBox}>
            <View style={styles.sectionHeaderRow}>
              <Text style={styles.sectionTitle}>Pedidos de Produtos</Text>
              <Badge color="slate" variant="soft">{shopOrders.length} no período</Badge>
            </View>
            {shopOrders.length > 0 ? (
              shopOrders.map((order) => {
                const productItems = order.items.filter((i) => i.type === 'product');
                const productTotal = productItems.reduce((sum, item) => {
                  const prod = shop.products.find((p) => p.id === item.refId);
                  return sum + (prod?.price ?? 0) * item.qty;
                }, 0);
                const customer = users.find((u) => u.id === order.customerId);
                return (
                  <Card key={order.id} style={styles.orderCard}>
                    <View style={styles.sectionHeaderRow}>
                      <Text style={styles.orderTotal}>{currency(productTotal)}</Text>
                      <Badge
                        color={order.status === 'pendente' ? 'indigo' : order.status === 'cancelado' ? 'red' : 'green'}
                        variant="soft"
                      >
                        {statusLabel[order.status] || order.status}
                      </Badge>
                    </View>
                    <Text style={styles.ticketMeta}>
                      Cliente: {customer?.name || 'Cliente'} · {new Date(order.createdAt).toLocaleString('pt-PT')}
                    </Text>
                    {productItems.map((item) => {
                      const prod = shop.products.find((p) => p.id === item.refId);
                      return (
                        <View key={item.refId} style={styles.orderItemRow}>
                          <Text style={styles.orderItemName}>{prod?.name || 'Produto'} x{item.qty}</Text>
                          <Text style={styles.orderItemPrice}>{currency((prod?.price ?? 0) * item.qty)}</Text>
                        </View>
                      );
                    })}
                    <View style={styles.ticketActions}>
                      {(['pendente', 'concluido'] as const).map((status) => (
                        <TouchableOpacity
                          key={status}
                          onPress={() => updateOrderStatus(order.id, status)}
                          style={[
                            styles.premiumActionBtn,
                            order.status === status ? styles.acceptBtn : styles.rejectBtn,
                          ]}
                        >
                          <Text
                            style={[
                              styles.premiumActionBtnTxt,
                              order.status === status ? { color: colors.textInverse } : { color: colors.textSoft },
                            ]}
                          >
                            {status === 'pendente' ? 'Pendente' : 'Concluído'}
                          </Text>
                        </TouchableOpacity>
                      ))}
                    </View>
                  </Card>
                );
              })
            ) : (
              <View style={styles.emptyBox}>
                <Text style={styles.emptyTxt}>Nenhum pedido de produtos no período.</Text>
              </View>
            )}
          </View>
        )}

        {activeTab === 'servicos' && (
          <View style={styles.tabBox}>
            <Text style={styles.sectionTitle}>Serviços Disponíveis</Text>
            {shop.services.map(s => (
              <Card key={s.id} style={styles.itemCard}>
                <View style={styles.itemInfo}>
                  <Text style={styles.itemName}>{s.name}</Text>
                  <Text style={styles.itemMeta}>{s.duration} min · {currency(s.price)}</Text>
                </View>
                <TouchableOpacity onPress={() => deleteService(shop.id, s.id)} style={styles.deleteIcon}>
                  <Text style={styles.deleteTxt}>✕</Text>
                </TouchableOpacity>
              </Card>
            ))}
            
            <Card style={styles.formCard}>
              <Text style={styles.formTitle}>Novo Serviço</Text>
              <TextInput style={styles.input} placeholder="Nome do serviço" placeholderTextColor={colors.placeholder} value={formSvc.name} onChangeText={t => setFormSvc({...formSvc, name: t})} />
              <View style={styles.row}>
                <TextInput style={[styles.input, {flex: 1}]} placeholder="Preço (€)" placeholderTextColor={colors.placeholder} keyboardType="numeric" value={formSvc.price} onChangeText={t => setFormSvc({...formSvc, price: t})} />
                <TextInput style={[styles.input, {flex: 1}]} placeholder="Duração (min)" placeholderTextColor={colors.placeholder} keyboardType="numeric" value={formSvc.duration} onChangeText={t => setFormSvc({...formSvc, duration: t})} />
              </View>
              <Button size="sm" onPress={async () => {
                try {
                  await addService(shop.id, { name: formSvc.name, price: Number(formSvc.price), duration: Number(formSvc.duration), barberIds: [] });
                  setFormSvc({ name: '', price: '', duration: '' });
                  Alert.alert('Sucesso', 'Serviço adicionado.');
                } catch (e: any) {
                  Alert.alert('Erro', e.message || 'Erro ao adicionar serviço.');
                }
              }}>Adicionar Serviço</Button>
            </Card>
          </View>
        )}

        {activeTab === 'produtos' && (
          <View style={styles.tabBox}>
            <Text style={styles.sectionTitle}>Inventário de Produtos</Text>
            {shop.products.map(p => (
              <Card key={p.id} style={styles.itemCard}>
                <View style={styles.itemInfo}>
                  <Text style={styles.itemName}>{p.name}</Text>
                  <Text style={styles.itemMeta}>{currency(p.price)}</Text>
                </View>
                <View style={styles.stockControl}>
                  <TouchableOpacity 
                    onPress={() => supabase.from('products').update({ stock: Math.max(0, p.stock - 1) }).eq('id', p.id).then(() => refreshShops())} 
                    style={styles.stockBtn}
                  >
                    <Text style={styles.stockBtnTxt}>-</Text>
                  </TouchableOpacity>
                  <Text style={styles.stockVal}>{p.stock}</Text>
                  <TouchableOpacity 
                    onPress={() => supabase.from('products').update({ stock: p.stock + 1 }).eq('id', p.id).then(() => refreshShops())} 
                    style={styles.stockBtn}
                  >
                    <Text style={styles.stockBtnTxt}>+</Text>
                  </TouchableOpacity>
                </View>
                <TouchableOpacity onPress={() => deleteProduct(shop.id, p.id)} style={styles.deleteIcon}>
                  <Text style={styles.deleteTxt}>✕</Text>
                </TouchableOpacity>
              </Card>
            ))}

            <Card style={styles.formCard}>
              <Text style={styles.formTitle}>Novo Produto</Text>
              <TextInput style={styles.input} placeholder="Nome do produto" placeholderTextColor={colors.placeholder} value={formProd.name} onChangeText={t => setFormProd({...formProd, name: t})} />
              <View style={styles.row}>
                <TextInput style={[styles.input, {flex: 1}]} placeholder="Preço (€)" placeholderTextColor={colors.placeholder} keyboardType="numeric" value={formProd.price} onChangeText={t => setFormProd({...formProd, price: t})} />
                <TextInput style={[styles.input, {flex: 1}]} placeholder="Stock" placeholderTextColor={colors.placeholder} keyboardType="numeric" value={formProd.stock} onChangeText={t => setFormProd({...formProd, stock: t})} />
              </View>
              <Button size="sm" onPress={async () => {
                try {
                  await addProduct(shop.id, { name: formProd.name, price: Number(formProd.price), stock: Number(formProd.stock) });
                  setFormProd({ name: '', price: '', stock: '' });
                  Alert.alert('Sucesso', 'Produto adicionado.');
                } catch (e: any) {
                  Alert.alert('Erro', e.message || 'Erro ao adicionar produto.');
                }
              }}>Adicionar Produto</Button>
            </Card>
          </View>
        )}

        {activeTab === 'equipa' && (
          <View style={styles.tabBox}>
            <Text style={styles.sectionTitle}>Membros da Equipa</Text>
            {shop.barbers.map(b => (
              <Card key={b.id} style={styles.itemCard}>
                <TouchableOpacity onPress={() => pickImage('barber', b.id)} style={styles.barberAvatar}>
                  {b.imageUrl ? <Image source={{uri: b.imageUrl}} style={styles.fullImg} /> : <Text style={styles.avatarTxt}>{b.name.charAt(0)}</Text>}
                </TouchableOpacity>
                <View style={styles.itemInfo}>
                  <Text style={styles.itemName}>{b.name}</Text>
                  <Text style={styles.itemMeta}>{b.specialties.join(', ')}</Text>
                </View>
                <TouchableOpacity onPress={() => deleteBarber(shop.id, b.id)} style={styles.deleteIcon}>
                  <Text style={styles.deleteTxt}>✕</Text>
                </TouchableOpacity>
              </Card>
            ))}

            <Card style={styles.formCard}>
              <Text style={styles.formTitle}>Novo Profissional</Text>
              <TextInput style={styles.input} placeholder="Nome do profissional" placeholderTextColor={colors.placeholder} value={formBarb.name} onChangeText={t => setFormBarb({...formBarb, name: t})} />
              <TextInput style={styles.input} placeholder="Especialidades (separadas por vírgula)" placeholderTextColor={colors.placeholder} value={formBarb.specialties} onChangeText={t => setFormBarb({...formBarb, specialties: t})} />
              <Button size="sm" onPress={async () => {
                try {
                  await addBarber(shop.id, { 
                    name: formBarb.name, 
                    specialties: formBarb.specialties.split(',').map(s => s.trim()).filter(Boolean),
                    schedule: []
                  });
                  setFormBarb({ name: '', specialties: '' });
                  Alert.alert('Sucesso', 'Membro adicionado.');
                } catch (e: any) {
                  Alert.alert('Erro', e.message || 'Erro ao adicionar membro.');
                }
              }}>Adicionar Membro</Button>
            </Card>
          </View>
        )}

        {activeTab === 'estatisticas' && statsData && (
          <View style={styles.tabBox}>
            <View>
              <Text style={styles.sectionTitle}>Estatísticas</Text>
              <Text style={styles.sectionSubtitle}>
                Análise completa do desempenho da barbearia (todos os dados históricos)
              </Text>
            </View>

            <View style={styles.statsKpiGrid}>
              {[
                { label: 'Total de Reservas', value: String(statsData.totalAppts) },
                { label: 'Concluídas', value: String(statsData.totalConcluidas) },
                { label: 'Canceladas', value: String(statsData.totalCanceladas) },
                { label: 'Taxa Conclusão', value: `${statsData.taxaConclusao}%` },
              ].map((kpi) => (
                <Card key={kpi.label} style={styles.statsKpiCard}>
                  <Text style={styles.statsKpiLabel}>{kpi.label}</Text>
                  <Text style={styles.statsKpiValue}>{kpi.value}</Text>
                </Card>
              ))}
            </View>

            <View style={styles.statsRevenueRow}>
              <Card style={styles.statsRevenueCard}>
                <Text style={styles.statsRevenueTitle}>Receita de Serviços</Text>
                <Text style={[styles.statsRevenueValue, { color: colors.success }]}>
                  {currency(statsData.revenueServicos)}
                </Text>
                <Text style={styles.statsRevenueHint}>Baseado nos agendamentos concluídos</Text>
              </Card>
              <Card style={styles.statsRevenueCard}>
                <Text style={styles.statsRevenueTitle}>Receita de Produtos</Text>
                <Text style={[styles.statsRevenueValue, { color: colors.primary }]}>
                  {currency(statsData.revenueProdutos)}
                </Text>
                <Text style={styles.statsRevenueHint}>Baseado nos pedidos concluídos</Text>
              </Card>
            </View>

            <Card style={styles.statsBlockCard}>
              <Text style={styles.statsBlockTitle}>Evolução de Reservas (últimas 8 semanas)</Text>
              {statsData.weeklyData.map((week) => (
                <View key={week.name} style={styles.statsWeekRow}>
                  <Text style={styles.statsWeekLabel}>{week.name}</Text>
                  <Text style={styles.statsWeekValue}>
                    {week.concluidas}/{week.reservas} concluídas
                  </Text>
                </View>
              ))}
            </Card>

            <Card style={styles.statsBlockCard}>
              <Text style={styles.statsBlockTitle}>Reservas por Dia da Semana</Text>
              {statsData.byDayOfWeek.map((day) => {
                const max = Math.max(...statsData.byDayOfWeek.map((d) => d.reservas), 1);
                const pct = Math.round((day.reservas / max) * 100);
                return (
                  <View key={day.name} style={styles.statsBarRow}>
                    <Text style={styles.statsBarLabel}>{day.name}</Text>
                    <View style={styles.statsBarTrack}>
                      <View style={[styles.statsBarFill, { width: `${pct}%` }]} />
                    </View>
                    <Text style={styles.statsBarValue}>{day.reservas}</Text>
                  </View>
                );
              })}
            </Card>

            {statsData.topServices.length > 0 && (
              <Card style={styles.statsBlockCard}>
                <Text style={styles.statsBlockTitle}>Serviços Mais Populares</Text>
                {statsData.topServices.map((svc) => (
                  <View key={svc.name} style={styles.statsListRow}>
                    <Text style={styles.statsListName}>{svc.name}</Text>
                    <Text style={styles.statsListValue}>{svc.value} reservas</Text>
                  </View>
                ))}
              </Card>
            )}

            {statsData.topBarbers.length > 0 && (
              <Card style={styles.statsBlockCard}>
                <Text style={styles.statsBlockTitle}>Ranking de Profissionais</Text>
                {statsData.topBarbers.map((barber, index) => {
                  const maxQty = statsData.topBarbers[0]?.qty || 1;
                  const pct = Math.round((barber.qty / maxQty) * 100);
                  return (
                    <View key={barber.name} style={styles.statsRankRow}>
                      <Text style={styles.statsRankPos}>#{index + 1}</Text>
                      <Text style={styles.statsRankName} numberOfLines={1}>{barber.name}</Text>
                      <View style={styles.statsBarTrack}>
                        <View style={[styles.statsBarFill, { width: `${pct}%` }]} />
                      </View>
                      <Text style={styles.statsRankQty}>{barber.qty}</Text>
                    </View>
                  );
                })}
              </Card>
            )}
          </View>
        )}

        {activeTab === 'perfil' && (
          <View style={styles.tabBox}>
            <Text style={styles.sectionTitle}>Configurações do Espaço</Text>
            <TouchableOpacity onPress={() => pickImage('shop')} style={styles.coverUpload}>
              {shop.imageUrl ? (
                <Image source={{ uri: shop.imageUrl }} style={styles.fullImg} />
              ) : (
                <Text style={styles.uploadTxt}>Alterar Foto de Capa</Text>
              )}
              <View style={styles.uploadOverlay}><Text style={styles.uploadIcon}>📷</Text></View>
            </TouchableOpacity>
            
            <Card style={styles.formCard}>
              <Text style={styles.inputLabel}>Informação Geral</Text>
              <TextInput style={styles.input} placeholder="Nome da Barbearia" placeholderTextColor={colors.placeholder} value={shopName} onChangeText={setShopName} />
              <TextInput style={styles.input} placeholder="Endereço Completo" placeholderTextColor={colors.placeholder} value={shopAddr} onChangeText={setShopAddr} />
              <TextInput style={styles.input} placeholder="Telefone de Contacto" placeholderTextColor={colors.placeholder} value={phone1} onChangeText={setPhone1} keyboardType="phone-pad" />
              
              <Text style={[styles.inputLabel, { marginTop: 12 }]}>Redes Sociais</Text>
              <TextInput style={styles.input} placeholder="WhatsApp (ex: 351912345678)" placeholderTextColor={colors.placeholder} value={whatsapp} onChangeText={setWhatsapp} />
              <TextInput style={styles.input} placeholder="Instagram (User)" placeholderTextColor={colors.placeholder} value={instagram} onChangeText={setInstagram} />
              <TextInput style={styles.input} placeholder="Facebook (Link)" placeholderTextColor={colors.placeholder} value={facebook} onChangeText={setFacebook} />

              <Text style={[styles.inputLabel, { marginTop: 12 }]}>Pagamentos</Text>
              <TextInput style={styles.input} placeholder="Métodos (ex: Dinheiro, MBWay, Cartão)" placeholderTextColor={colors.placeholder} value={paymentMethods} onChangeText={setPaymentMethods} />
              
              <Text style={[styles.inputLabel, { marginTop: 12 }]}>Horário de Funcionamento</Text>
              {weeklySchedule.map((s) => (
                <View key={s.day} style={styles.scheduleRow}>
                  <Text style={styles.dayLabel}>{s.day}</Text>
                  <TouchableOpacity 
                    onPress={() => updateWeeklySlot(s.day, { closed: !s.closed })}
                    style={[styles.closedBtn, s.closed && styles.closedBtnActive]}
                  >
                    <Text style={[styles.closedText, s.closed && styles.closedTextActive]}>
                      {s.closed ? 'Fechado' : 'Aberto'}
                    </Text>
                  </TouchableOpacity>
                  {!s.closed && (
                    <View style={styles.timeInputs}>
                      <TextInput 
                        style={styles.timeInput} 
                        value={s.open} 
                        onChangeText={(t) => updateWeeklySlot(s.day, { open: t })}
                      />
                      <Text style={{ color: colors.textSubtle }}>-</Text>
                      <TextInput 
                        style={styles.timeInput} 
                        value={s.close} 
                        onChangeText={(t) => updateWeeklySlot(s.day, { close: t })}
                      />
                    </View>
                  )}
                </View>
              ))}

              <View style={styles.exceptionSection}>
                <Text style={styles.inputLabel}>Exceções de Horário (Datas Específicas)</Text>
                <Text style={styles.exceptionHint}>
                  Defina datas especiais em que a barbearia estará fechada (ex: Natal) ou aberta num dia normalmente fechado.
                </Text>

                <View style={styles.exceptionForm}>
                  <TextInput
                    style={[styles.input, styles.exceptionDateInput]}
                    placeholder="AAAA-MM-DD"
                    placeholderTextColor={colors.placeholder}
                    value={exceptionDate}
                    onChangeText={setExceptionDate}
                  />
                  <View style={styles.exceptionToggleRow}>
                    {[
                      [true, 'Fechado'],
                      [false, 'Aberto'],
                    ].map(([closed, label]) => (
                      <TouchableOpacity
                        key={String(closed)}
                        style={[
                          styles.exceptionToggleBtn,
                          exceptionClosed === closed && styles.exceptionToggleBtnActive,
                        ]}
                        onPress={() => setExceptionClosed(Boolean(closed))}
                      >
                        <Text
                          style={[
                            styles.exceptionToggleText,
                            exceptionClosed === closed && styles.exceptionToggleTextActive,
                          ]}
                        >
                          {label}
                        </Text>
                      </TouchableOpacity>
                    ))}
                  </View>
                  <Button size="sm" onPress={addException}>Adicionar Exceção</Button>
                </View>

                {exceptionSlots.length > 0 ? (
                  exceptionSlots.map((slot) => (
                    <View key={slot.date} style={styles.exceptionItem}>
                      <View style={styles.exceptionItemInfo}>
                        <Text style={styles.exceptionItemDate}>
                          {slot.date
                            ? new Date(`${slot.date}T00:00:00`).toLocaleDateString('pt-PT', {
                                day: 'numeric',
                                month: 'long',
                                year: 'numeric',
                              })
                            : 'Data inválida'}
                        </Text>
                        <View
                          style={[
                            styles.exceptionBadge,
                            slot.closed ? styles.exceptionBadgeClosed : styles.exceptionBadgeOpen,
                          ]}
                        >
                          <Text
                            style={[
                              styles.exceptionBadgeText,
                              slot.closed ? styles.exceptionBadgeTextClosed : styles.exceptionBadgeTextOpen,
                            ]}
                          >
                            {slot.closed ? 'Fechado' : 'Aberto'}
                          </Text>
                        </View>
                      </View>
                      <TouchableOpacity onPress={() => removeException(slot.date)} style={styles.exceptionRemoveBtn}>
                        <Text style={styles.exceptionRemoveText}>Remover</Text>
                      </TouchableOpacity>
                    </View>
                  ))
                ) : (
                  <Text style={styles.exceptionEmpty}>Nenhuma exceção configurada.</Text>
                )}
              </View>

              <Button style={{ marginTop: 10 }} onPress={handleSaveSettings} loading={loading}>Guardar Todas as Alterações</Button>
              
              <View style={styles.logoutSection}>
                <TouchableOpacity style={styles.logoutButtonPremium} onPress={logout}>
                  <Text style={styles.logoutButtonText}>Sair da Conta</Text>
                  <Text style={styles.logoutButtonIcon}>⎗</Text>
                </TouchableOpacity>
                <Text style={styles.versionText}>Smart Agenda v1.0.4</Text>
              </View>
            </Card>
          </View>
        )}
      </ScrollView>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: colors.background,
  },
  header: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    paddingHorizontal: 20,
    paddingVertical: 16,
    backgroundColor: colors.surface,
    borderBottomWidth: 1,
    borderBottomColor: colors.border,
  },
  headerCopy: {
    flex: 1,
  },
  headerKicker: {
    color: colors.textMuted,
    fontSize: 12,
    fontWeight: '800',
    textTransform: 'uppercase',
  },
  headerTitle: {
    color: colors.text,
    fontSize: 22,
    fontWeight: '900',
    marginTop: 2,
  },
  brandPill: {
    width: 44,
    height: 44,
    borderRadius: radius.md,
    backgroundColor: colors.primarySoft,
    alignItems: 'center',
    justifyContent: 'center',
    borderWidth: 1,
    borderColor: colors.border,
  },
  brandText: {
    color: colors.primary,
    fontSize: 18,
    fontWeight: '900',
  },
  tabContainer: {
    backgroundColor: colors.surface,
    paddingVertical: 8,
    borderBottomWidth: 1,
    borderBottomColor: colors.border,
  },
  periodRow: {
    flexDirection: 'row',
    gap: 8,
    paddingHorizontal: 20,
    paddingVertical: 10,
    backgroundColor: colors.surface,
    borderBottomWidth: 1,
    borderBottomColor: colors.border,
  },
  periodChip: {
    paddingHorizontal: 12,
    paddingVertical: 7,
    borderRadius: radius.md,
    borderWidth: 1,
    borderColor: colors.border,
    backgroundColor: colors.surfaceMuted,
  },
  periodChipActive: {
    backgroundColor: colors.primarySoft,
    borderColor: colors.primary,
  },
  periodChipText: {
    color: colors.textMuted,
    fontSize: 11,
    fontWeight: '700',
  },
  periodChipTextActive: {
    color: colors.primaryDark,
  },
  sectionHeaderRow: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    gap: 8,
    marginBottom: 8,
  },
  linkAction: {
    color: colors.primaryDark,
    fontSize: 13,
    fontWeight: '800',
  },
  pendingSection: {
    padding: 16,
    gap: 12,
    borderColor: colors.primarySoft,
    backgroundColor: colors.primarySoft,
  },
  acceptBtn: {
    backgroundColor: colors.surfaceDark,
    borderColor: colors.surfaceDark,
  },
  rejectBtn: {
    backgroundColor: colors.dangerSoft,
    borderColor: '#fecaca',
  },
  completeBtn: {
    backgroundColor: colors.success,
    borderColor: colors.success,
  },
  orderCard: {
    padding: 16,
    gap: 10,
  },
  orderTotal: {
    color: colors.primaryDark,
    fontSize: 18,
    fontWeight: '900',
  },
  orderItemRow: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    backgroundColor: colors.backgroundAlt,
    borderRadius: radius.sm,
    paddingHorizontal: 10,
    paddingVertical: 8,
  },
  orderItemName: {
    color: colors.textSoft,
    fontSize: 13,
    fontWeight: '600',
  },
  orderItemPrice: {
    color: colors.primaryDark,
    fontSize: 13,
    fontWeight: '800',
  },
  tabsScroll: {
    paddingHorizontal: 20,
    gap: 8,
  },
  tabItem: {
    paddingVertical: 10,
    paddingHorizontal: 14,
    borderRadius: radius.pill,
    borderWidth: 1,
    borderColor: colors.border,
    backgroundColor: colors.surfaceMuted,
  },
  tabItemActive: {
    backgroundColor: colors.surfaceDark,
    borderColor: colors.surfaceDark,
  },
  tabText: {
    color: colors.textMuted,
    fontSize: 14,
    fontWeight: '700',
  },
  tabTextActive: {
    color: colors.brandAccent,
  },
  content: {
    padding: 20,
    paddingBottom: 40,
    gap: 20,
  },
  proStatsCard: {
    backgroundColor: colors.surface,
    borderRadius: radius.xl,
    overflow: 'hidden',
    marginBottom: 8,
    ...shadows.card,
  },
  proMainArea: {
    backgroundColor: colors.surfaceDark,
    padding: 24,
    alignItems: 'center',
    justifyContent: 'center',
  },
  proMainLabel: {
    color: '#87948f', // A specific tone that looks good on dark
    fontSize: 12,
    fontWeight: '800',
    textTransform: 'uppercase',
    letterSpacing: 1.5,
    marginBottom: 8,
  },
  proMainValue: {
    color: colors.textInverse,
    fontSize: 48,
    fontWeight: '900',
  },
  proSubArea: {
    flexDirection: 'row',
    paddingVertical: 18,
    backgroundColor: colors.surface,
  },
  proSubItem: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
  },
  proSubDivider: {
    width: 1,
    backgroundColor: colors.border,
    height: '60%',
    alignSelf: 'center',
  },
  proSubValue: {
    color: colors.text,
    fontSize: 18,
    fontWeight: '900',
    marginBottom: 4,
  },
  proSubLabel: {
    color: colors.textMuted,
    fontSize: 11,
    fontWeight: '700',
    textTransform: 'uppercase',
    letterSpacing: 0.5,
  },
  tabBox: {
    gap: 20,
  },
  agendaHeader: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
  },
  sectionTitle: {
    color: colors.text,
    fontSize: 18,
    fontWeight: '800',
  },
  dateInput: {
    backgroundColor: colors.surface,
    borderRadius: radius.md,
    paddingHorizontal: 12,
    paddingVertical: 6,
    color: colors.text,
    fontSize: 13,
    fontWeight: '700',
    borderWidth: 1,
    borderColor: colors.border,
  },
  agendaTicket: {
    padding: 14,
    gap: 8,
  },
  ticketSide: {
    width: 70,
    backgroundColor: colors.primarySoft,
    alignItems: 'center',
    justifyContent: 'center',
    gap: 8,
  },
  ticketTime: {
    color: colors.primaryDark,
    fontSize: 18,
    fontWeight: '900',
  },
  ticketDot: {
    width: 8,
    height: 8,
    borderRadius: 4,
  },
  ticketMain: {
    flex: 1,
    padding: 16,
    justifyContent: 'center',
  },
  ticketRow: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
  },
  ticketSvc: {
    color: colors.text,
    fontSize: 16,
    fontWeight: '800',
  },
  ticketPrice: {
    color: colors.primary,
    fontSize: 15,
    fontWeight: '800',
  },
  ticketMeta: {
    color: colors.textMuted,
    fontSize: 12,
    marginTop: 4,
  },
  ticketActions: {
    flexDirection: 'row',
    gap: 12,
    marginTop: 12,
  },
  premiumActionBtn: {
    backgroundColor: colors.successSoft,
    paddingHorizontal: 16,
    paddingVertical: 8,
    borderRadius: radius.pill,
    borderWidth: 1,
    borderColor: '#bbf7d0',
  },
  premiumActionBtnTxt: {
    color: '#166534',
    fontSize: 12,
    fontWeight: '800',
    textTransform: 'uppercase',
    letterSpacing: 0,
  },
  emptyBox: {
    alignItems: 'center',
    padding: 40,
    backgroundColor: colors.surface,
    borderRadius: radius.sm,
    borderWidth: 1,
    borderColor: colors.border,
    borderStyle: 'dashed',
  },
  emptyTxt: {
    color: colors.textMuted,
    fontSize: 14,
    fontWeight: '600',
  },
  itemCard: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: 14,
    padding: 14,
    backgroundColor: colors.surface,
    borderRadius: radius.sm,
    marginBottom: 12,
    borderWidth: 1,
    borderColor: colors.border,
  },
  itemInfo: {
    flex: 1,
  },
  itemName: {
    color: colors.text,
    fontSize: 16,
    fontWeight: '800',
  },
  itemMeta: {
    color: colors.textMuted,
    fontSize: 13,
  },
  stockControl: {
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: colors.surfaceMuted,
    borderRadius: radius.md,
    padding: 4,
    gap: 12,
    marginRight: 10,
  },
  stockBtn: {
    width: 28,
    height: 28,
    borderRadius: radius.xs,
    backgroundColor: colors.surface,
    alignItems: 'center',
    justifyContent: 'center',
    borderWidth: 1,
    borderColor: colors.border,
  },
  stockBtnTxt: {
    color: colors.text,
    fontSize: 16,
    fontWeight: 'bold',
  },
  stockVal: {
    color: colors.text,
    fontSize: 14,
    fontWeight: '800',
    minWidth: 20,
    textAlign: 'center',
  },
  deleteIcon: {
    width: 32,
    height: 32,
    borderRadius: radius.md,
    backgroundColor: colors.dangerSoft,
    alignItems: 'center',
    justifyContent: 'center',
  },
  deleteTxt: {
    color: colors.danger,
    fontSize: 12,
    fontWeight: '900',
  },
  formCard: {
    padding: 20,
    gap: 12,
    borderWidth: 1,
    borderColor: colors.borderStrong,
    borderRadius: radius.sm,
    marginTop: 10,
  },
  formTitle: {
    color: colors.text,
    fontSize: 16,
    fontWeight: '800',
    marginBottom: 4,
  },
  input: {
    backgroundColor: colors.surfaceMuted,
    borderRadius: radius.md,
    paddingHorizontal: 14,
    paddingVertical: 12,
    color: colors.text,
    fontSize: 14,
    borderWidth: 1,
    borderColor: colors.border,
    marginBottom: 8,
  },
  inputLabel: {
    color: colors.textMuted,
    fontSize: 12,
    fontWeight: '700',
    textTransform: 'uppercase',
    letterSpacing: 0,
    marginBottom: 8,
  },
  row: {
    flexDirection: 'row',
    gap: 12,
  },
  barberAvatar: {
    width: 48,
    height: 48,
    borderRadius: radius.md,
    backgroundColor: colors.primarySoft,
    alignItems: 'center',
    justifyContent: 'center',
    overflow: 'hidden',
  },
  avatarTxt: {
    color: colors.primary,
    fontSize: 20,
    fontWeight: '900',
  },
  coverUpload: {
    height: 180,
    borderRadius: radius.sm,
    backgroundColor: colors.surface,
    overflow: 'hidden',
    position: 'relative',
    alignItems: 'center',
    justifyContent: 'center',
    borderWidth: 1,
    borderColor: colors.border,
    ...shadows.card,
  },
  fullImg: {
    width: '100%',
    height: '100%',
  },
  uploadOverlay: {
    position: 'absolute',
    bottom: 12,
    right: 12,
    width: 40,
    height: 40,
    borderRadius: 20,
    backgroundColor: colors.primary,
    alignItems: 'center',
    justifyContent: 'center',
    elevation: 4,
  },
  uploadIcon: {
    fontSize: 18,
  },
  uploadTxt: {
    color: colors.textMuted,
    fontSize: 14,
    fontWeight: '700',
  },
  scheduleRow: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: 10,
    marginBottom: 10,
  },
  dayLabel: {
    color: colors.text,
    fontSize: 13,
    fontWeight: '700',
    width: 65,
  },
  closedBtn: {
    paddingHorizontal: 8,
    paddingVertical: 4,
    borderRadius: radius.xs,
    backgroundColor: colors.successSoft,
    borderWidth: 1,
    borderColor: '#bbf7d0',
  },
  closedBtnActive: {
    backgroundColor: colors.dangerSoft,
    borderColor: '#fecaca',
  },
  closedText: {
    color: '#166534',
    fontSize: 11,
    fontWeight: '800',
  },
  closedTextActive: {
    color: colors.danger,
  },
  timeInputs: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: 6,
  },
  timeInput: {
    backgroundColor: colors.surfaceMuted,
    borderRadius: radius.xs,
    paddingHorizontal: 8,
    paddingVertical: 4,
    color: colors.text,
    fontSize: 12,
    borderWidth: 1,
    borderColor: colors.border,
    width: 55,
    textAlign: 'center',
  },
  logoutSection: {
    marginTop: 40,
    paddingTop: 20,
    borderTopWidth: 1,
    borderTopColor: colors.border,
    alignItems: 'center',
  },
  logoutButtonPremium: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: colors.dangerSoft,
    paddingVertical: 16,
    paddingHorizontal: 24,
    borderRadius: radius.sm,
    width: '100%',
    borderWidth: 1,
    borderColor: '#fecaca',
    gap: 12,
  },
  logoutButtonText: {
    color: colors.danger,
    fontSize: 16,
    fontWeight: '800',
  },
  logoutButtonIcon: {
    color: colors.danger,
    fontSize: 20,
  },
  versionText: {
    color: colors.textSubtle,
    fontSize: 12,
    marginTop: 16,
    fontWeight: '600',
  },
  sectionSubtitle: {
    color: colors.textMuted,
    fontSize: 13,
    fontWeight: '500',
    marginTop: 4,
    lineHeight: 18,
  },
  statsKpiGrid: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    gap: 10,
  },
  statsKpiCard: {
    width: '48%',
    padding: 14,
    gap: 4,
  },
  statsKpiLabel: {
    color: colors.textMuted,
    fontSize: 11,
    fontWeight: '700',
  },
  statsKpiValue: {
    color: colors.text,
    fontSize: 24,
    fontWeight: '900',
  },
  statsRevenueRow: {
    gap: 12,
  },
  statsRevenueCard: {
    padding: 16,
    gap: 6,
  },
  statsRevenueTitle: {
    color: colors.text,
    fontSize: 15,
    fontWeight: '800',
  },
  statsRevenueValue: {
    fontSize: 28,
    fontWeight: '900',
  },
  statsRevenueHint: {
    color: colors.textMuted,
    fontSize: 11,
    fontWeight: '500',
  },
  statsBlockCard: {
    padding: 16,
    gap: 10,
  },
  statsBlockTitle: {
    color: colors.text,
    fontSize: 15,
    fontWeight: '800',
    marginBottom: 4,
  },
  statsWeekRow: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    paddingVertical: 6,
    borderBottomWidth: 1,
    borderBottomColor: colors.border,
  },
  statsWeekLabel: {
    color: colors.textSoft,
    fontSize: 13,
    fontWeight: '600',
  },
  statsWeekValue: {
    color: colors.text,
    fontSize: 12,
    fontWeight: '700',
  },
  statsBarRow: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: 8,
    marginBottom: 8,
  },
  statsBarLabel: {
    width: 34,
    color: colors.textMuted,
    fontSize: 12,
    fontWeight: '700',
  },
  statsBarTrack: {
    flex: 1,
    height: 8,
    backgroundColor: colors.backgroundAlt,
    borderRadius: radius.pill,
    overflow: 'hidden',
  },
  statsBarFill: {
    height: '100%',
    backgroundColor: colors.primary,
    borderRadius: radius.pill,
  },
  statsBarValue: {
    width: 24,
    textAlign: 'right',
    color: colors.text,
    fontSize: 12,
    fontWeight: '800',
  },
  statsListRow: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    paddingVertical: 8,
    borderBottomWidth: 1,
    borderBottomColor: colors.border,
  },
  statsListName: {
    flex: 1,
    color: colors.text,
    fontSize: 14,
    fontWeight: '600',
  },
  statsListValue: {
    color: colors.textMuted,
    fontSize: 12,
    fontWeight: '800',
  },
  statsRankRow: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: 8,
    marginBottom: 10,
  },
  statsRankPos: {
    width: 22,
    color: colors.textSubtle,
    fontSize: 12,
    fontWeight: '800',
  },
  statsRankName: {
    width: 72,
    color: colors.textSoft,
    fontSize: 13,
    fontWeight: '700',
  },
  statsRankQty: {
    width: 24,
    textAlign: 'right',
    color: colors.text,
    fontSize: 12,
    fontWeight: '800',
  },
  exceptionSection: {
    marginTop: 20,
    paddingTop: 16,
    borderTopWidth: 1,
    borderTopColor: colors.border,
    gap: 10,
  },
  exceptionHint: {
    color: colors.textMuted,
    fontSize: 12,
    lineHeight: 17,
    fontWeight: '500',
  },
  exceptionForm: {
    gap: 10,
    backgroundColor: colors.backgroundAlt,
    borderRadius: radius.lg,
    borderWidth: 1,
    borderColor: colors.border,
    padding: 12,
  },
  exceptionDateInput: {
    marginBottom: 0,
  },
  exceptionToggleRow: {
    flexDirection: 'row',
    gap: 8,
  },
  exceptionToggleBtn: {
    flex: 1,
    paddingVertical: 10,
    borderRadius: radius.md,
    borderWidth: 1,
    borderColor: colors.border,
    backgroundColor: colors.surface,
    alignItems: 'center',
  },
  exceptionToggleBtnActive: {
    backgroundColor: colors.surfaceDark,
    borderColor: colors.surfaceDark,
  },
  exceptionToggleText: {
    color: colors.textMuted,
    fontSize: 13,
    fontWeight: '700',
  },
  exceptionToggleTextActive: {
    color: colors.brandAccent,
  },
  exceptionItem: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    gap: 10,
    padding: 12,
    borderRadius: radius.md,
    borderWidth: 1,
    borderColor: colors.border,
    backgroundColor: colors.surface,
  },
  exceptionItemInfo: {
    flex: 1,
    gap: 6,
  },
  exceptionItemDate: {
    color: colors.textSoft,
    fontSize: 14,
    fontWeight: '700',
  },
  exceptionBadge: {
    alignSelf: 'flex-start',
    paddingHorizontal: 8,
    paddingVertical: 3,
    borderRadius: radius.pill,
  },
  exceptionBadgeClosed: {
    backgroundColor: colors.dangerSoft,
  },
  exceptionBadgeOpen: {
    backgroundColor: colors.successSoft,
  },
  exceptionBadgeText: {
    fontSize: 10,
    fontWeight: '800',
    textTransform: 'uppercase',
  },
  exceptionBadgeTextClosed: {
    color: colors.danger,
  },
  exceptionBadgeTextOpen: {
    color: colors.success,
  },
  exceptionRemoveBtn: {
    paddingHorizontal: 10,
    paddingVertical: 8,
    borderRadius: radius.sm,
    borderWidth: 1,
    borderColor: '#fecaca',
    backgroundColor: colors.dangerSoft,
  },
  exceptionRemoveText: {
    color: colors.danger,
    fontSize: 12,
    fontWeight: '800',
  },
  exceptionEmpty: {
    color: colors.textMuted,
    fontSize: 12,
    fontStyle: 'italic',
  },
});
