import React, { useEffect, useMemo, useState } 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 { NativeStackNavigationProp } from '@react-navigation/native-stack';
import { useApp } from '../context/AppContext';
import { Card } from '../components/ui/Card';
import { Button } from '../components/ui/Button';
import { currency } from '../lib/format';
import { RootStackParamList } from '../navigation/types';
import { supabase } from '../lib/supabase';
import { colors, radius, shadows } from '../lib/theme';
import { Ionicons } from '@expo/vector-icons';

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',
};

const statusIconName: Record<string, any> = {
  pendente: 'hourglass-outline',
  confirmado: 'checkmark-circle-outline',
  concluido: 'checkbox-outline',
  cancelado: 'close-circle-outline',
};

export default function Profile() {
  const navigation = useNavigation<NativeStackNavigationProp<RootStackParamList>>();
  const {
    user,
    appointments,
    orders,
    shops,
    favorites,
    logout,
    notifications,
    markNotificationRead,
    submitReview,
  } = useApp();

  const [activeTab, setActiveTab] = useState<string>(user?.role === 'barbearia' ? 'agenda_pessoal' : 'agenda');
  const [reviewedAppointments, setReviewedAppointments] = useState<Set<string>>(new Set());
  const [reviewTarget, setReviewTarget] = useState<{ appointmentId: string; shopId: string; shopName: string } | null>(null);
  const [rating, setRating] = useState(0);
  const [comment, setComment] = useState('');
  const [submittingReview, setSubmittingReview] = useState(false);
  const [shopReviews, setShopReviews] = useState<any[]>([]);

  const isBarber = user?.role === 'barbearia';
  const myShop = useMemo(() => shops.find(s => s.id === user?.shopId), [shops, user?.shopId]);

  useEffect(() => {
    let mounted = true;
    (async () => {
      if (!user) return;
      if (user.role === 'cliente') {
        const { data } = await supabase.from('reviews').select('appointment_id').eq('customer_id', user.id);
        if (!mounted || !data) return;
        setReviewedAppointments(new Set(data.map((row: any) => row.appointment_id).filter(Boolean)));
      } else if (user.role === 'barbearia' && user.shopId) {
        const { data } = await supabase.from('reviews').select('*').eq('shop_id', user.shopId).order('created_at', { ascending: false });
        if (!mounted || !data) return;
        setShopReviews(data);
      }
    })();
    return () => { mounted = false; };
  }, [user?.id]);

  const myAppointments = useMemo(
    () => (user ? (isBarber ? appointments.filter(a => a.shopId === user.shopId) : appointments.filter((a) => a.customerId === user.id)) : []),
    [appointments, user?.id, isBarber]
  );
  
  const myOrders = useMemo(
    () => (user ? orders.filter((o) => o.customerId === user.id) : []),
    [orders, user?.id]
  );
  
  const favoriteShops = useMemo(
    () => shops.filter((shop) => favorites.includes(shop.id)),
    [shops, favorites]
  );

  const myNotifications = useMemo(
    () =>
      user
        ? notifications
            .filter((n) => n.userId === user.id)
            .sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime())
        : [],
    [notifications, user?.id]
  );
  const activeAppointmentsCount = myAppointments.filter((a) => a.status !== 'cancelado').length;
  const totalOrdersValue = myOrders.reduce((sum, o) => sum + o.total, 0);
  const unreadCount = myNotifications.filter((n) => !n.read).length;

  if (!user) return null;

  const handleReviewSubmit = async () => {
    if (!reviewTarget || rating === 0) return;
    try {
      setSubmittingReview(true);
      await submitReview(reviewTarget.shopId, reviewTarget.appointmentId, rating, comment);
      setReviewedAppointments((prev) => new Set([...prev, reviewTarget.appointmentId]));
      setReviewTarget(null);
      Alert.alert('Obrigado', 'A tua avaliação foi enviada.');
    } catch (e: any) {
      Alert.alert('Erro', e?.message || 'Erro ao enviar avaliação.');
    } finally {
      setSubmittingReview(false);
    }
  };

  return (
    <SafeAreaView style={styles.container} edges={['top']}>
      <ScrollView contentContainerStyle={styles.content} showsVerticalScrollIndicator={false}>
        
        {/* Profile Card Header with Accent Bar */}
        <View style={styles.profileHeader}>
          <View style={styles.accentBar} />
          <View style={styles.profileHeaderInner}>
            <View style={styles.avatarRing}>
              <View style={styles.avatarGradient}>
                <Text style={styles.avatarText}>{user.name.charAt(0).toUpperCase()}</Text>
              </View>
            </View>
            <View style={styles.profileInfo}>
              <Text style={styles.profileName} numberOfLines={1}>{user.name}</Text>
              <Text style={styles.profileEmail} numberOfLines={1}>{user.email}</Text>
              <View style={styles.roleBadge}>
                <Ionicons 
                  name={isBarber ? "shield-checkmark-outline" : "person-outline"} 
                  size={11} 
                  color={colors.primaryDark} 
                />
                <Text style={styles.roleText}>{isBarber ? 'Gestor de Espaço' : 'Cliente'}</Text>
              </View>
            </View>
          </View>
        </View>

        {/* Stats Strip - Unified Card with Dividers */}
        <View style={styles.statsStrip}>
          <View style={styles.profileStat}>
            <Text style={styles.profileStatValue}>{activeAppointmentsCount}</Text>
            <Text style={styles.profileStatLabel}>{isBarber ? 'Marcações' : 'Agenda'}</Text>
          </View>
          <View style={styles.statsDivider} />
          <View style={styles.profileStat}>
            <Text style={styles.profileStatValue}>{isBarber ? shopReviews.length : favoriteShops.length}</Text>
            <Text style={styles.profileStatLabel}>{isBarber ? 'Reviews' : 'Favoritos'}</Text>
          </View>
          <View style={styles.statsDivider} />
          <View style={styles.profileStat}>
            <Text style={styles.profileStatValue}>
              {isBarber ? (myShop?.rating || 0).toFixed(1) : currency(totalOrdersValue)}
            </Text>
            <Text style={styles.profileStatLabel}>{isBarber ? 'Rating ★' : 'Compras'}</Text>
          </View>
        </View>

        {/* Notifications Section */}
        {myNotifications.length > 0 && (
          <View style={styles.notifSection}>
            <View style={styles.sectionHeaderRow}>
              <Ionicons name="notifications-outline" size={18} color={colors.primary} />
              <Text style={styles.sectionTitle}>Notificações Recentes</Text>
              {unreadCount > 0 && (
                <View style={styles.notifCountBadge}>
                  <Text style={styles.notifCountText}>{unreadCount}</Text>
                </View>
              )}
            </View>
            <ScrollView horizontal showsHorizontalScrollIndicator={false} style={styles.notifScroll} contentContainerStyle={{ paddingRight: 20 }}>
              {myNotifications.map((n) => (
                <View key={n.id} style={[styles.notifCard, !n.read && styles.notifUnread]}>
                  <View style={styles.notifHeader}>
                    <Ionicons name="chatbubble-ellipses-outline" size={16} color={!n.read ? colors.primaryDark : colors.textMuted} />
                    {!n.read && <View style={styles.unreadDot} />}
                  </View>
                  <Text style={styles.notifMsg} numberOfLines={2}>{n.message}</Text>
                  {!n.read && (
                    <TouchableOpacity onPress={() => markNotificationRead(n.id)} style={styles.markReadBtn} activeOpacity={0.7}>
                      <Text style={styles.markRead}>Marcar lida</Text>
                    </TouchableOpacity>
                  )}
                </View>
              ))}
            </ScrollView>
          </View>
        )}

        {/* Dynamic Tab Bar */}
        <View style={styles.tabBarContainer}>
          <ScrollView horizontal showsHorizontalScrollIndicator={false} contentContainerStyle={styles.tabBar}>
            {(isBarber
              ? [
                  ['agenda_pessoal', 'Agenda Global'],
                  ['reviews', 'Avaliações'],
                  ['estatisticas', 'Resumo'],
                ]
              : [
                  ['agenda', 'Marcações'],
                  ['favoritos', 'Favoritos'],
                  ['compras', 'Compras'],
                ]
            ).map(([id, label]) => (
              <TouchableOpacity
                key={id}
                onPress={() => setActiveTab(id)}
                style={[styles.tabItem, activeTab === id && styles.tabActive]}
                activeOpacity={0.8}
              >
                <Text style={[styles.tabText, activeTab === id && styles.tabTextActive]}>{label}</Text>
              </TouchableOpacity>
            ))}
          </ScrollView>
        </View>

        {/* Tab Content Area */}
        <View style={styles.tabContent}>
          
          {/* CLIENTE: Marcações */}
          {!isBarber && activeTab === 'agenda' && (
            <View style={styles.listContainer}>
              {myAppointments.length > 0 ? (
                myAppointments.map((appt) => {
                  const shop = shops.find((s) => s.id === appt.shopId);
                  const canReview = appt.status === 'concluido' && !reviewedAppointments.has(appt.id);
                  const dateParts = appt.date.split(' ');
                  const day = dateParts[0].split('-')[2];
                  const month = new Date(dateParts[0]).toLocaleString('pt-PT', { month: 'short' }).toUpperCase();
                  
                  return (
                    <Card key={appt.id} style={styles.agendaCardPremium}>
                      <View style={styles.agendaTop}>
                        <View style={styles.calendarBlockPremium}>
                          <Text style={styles.dateMonthPremium}>{month}</Text>
                          <Text style={styles.dateDayPremium}>{day}</Text>
                        </View>
                        
                        <View style={styles.agendaMain}>
                          <Text style={styles.agendaShopPremium} numberOfLines={1}>{shop?.name || 'Barbearia'}</Text>
                          <Text style={styles.agendaServicePremium} numberOfLines={1}>
                            {shop?.services.find((s) => s.id === appt.serviceId)?.name || 'Serviço'} · {shop?.services.find((s) => s.id === appt.serviceId)?.duration || '—'} min
                          </Text>
                          <View style={styles.agendaMetaRow}>
                            <Ionicons name="time-outline" size={14} color={colors.textMuted} />
                            <Text style={styles.agendaTimePremium}>{dateParts[1]} • {currency(appt.total)}</Text>
                          </View>
                        </View>
                        
                        <View style={[styles.statusTagPremium, { backgroundColor: statusColor[appt.status] + '1A' }]}>
                          <Text style={[styles.statusTextPremium, { color: statusColor[appt.status] }]}>{statusLabel[appt.status]}</Text>
                        </View>
                      </View>
                      
                      {canReview && (
                        <Button 
                          variant="outline" 
                          size="sm" 
                          style={styles.reviewBtn} 
                          onPress={() => setReviewTarget({ appointmentId: appt.id, shopId: appt.shopId, shopName: shop?.name || 'Barbearia' })}
                        >
                          Avaliar Serviço ⭐
                        </Button>
                      )}
                    </Card>
                  );
                })
              ) : (
                <View style={styles.emptyBlockPremium}>
                  <View style={styles.emptyIconCircle}>
                    <Ionicons name="calendar-outline" size={28} color={colors.primary} />
                  </View>
                  <Text style={styles.emptyTxtPremium}>Sem marcações agendadas.</Text>
                  <Button size="sm" variant="ghost" onPress={() => navigation.navigate('ExploreTab' as never)}>Procurar Barbearias</Button>
                </View>
              )}
            </View>
          )}

          {/* CLIENTE: Favoritos */}
          {!isBarber && activeTab === 'favoritos' && (
            <View style={styles.listContainer}>
              {favoriteShops.length > 0 ? (
                favoriteShops.map((s) => (
                  <TouchableOpacity 
                    key={s.id} 
                    onPress={() => navigation.navigate('ShopDetails', { shopId: s.id })}
                    activeOpacity={0.9}
                  >
                    <Card style={styles.shopCardPremium}>
                      <Image source={{ uri: s.imageUrl || 'https://via.placeholder.com/100' }} style={styles.shopImageMini} />
                      <View style={styles.shopCardBodyPremium}>
                        <Text style={styles.shopNamePremium} numberOfLines={1}>{s.name}</Text>
                        <View style={styles.shopLocationRow}>
                          <Ionicons name="location-outline" size={13} color={colors.textMuted} />
                          <Text style={styles.shopAddrPremium} numberOfLines={1}>
                            {s.address && s.address !== 'Endereço a definir' ? s.address : 'Morada por definir'}
                          </Text>
                        </View>
                      </View>
                      <View style={styles.shopRatingBadgePremium}>
                        <Ionicons name="star" size={14} color={colors.star} />
                        <Text style={styles.shopRatingTextPremium}>{(s.rating || 0).toFixed(1)}</Text>
                      </View>
                    </Card>
                  </TouchableOpacity>
                ))
              ) : (
                <View style={styles.emptyBlockPremium}>
                  <View style={styles.emptyIconCircle}>
                    <Ionicons name="heart-outline" size={28} color={colors.textSubtle} />
                  </View>
                  <Text style={styles.emptyTxtPremium}>Ainda não tens favoritos.</Text>
                </View>
              )}
            </View>
          )}

          {/* CLIENTE: Compras */}
          {!isBarber && activeTab === 'compras' && (
            <View style={styles.listContainer}>
              {myOrders.length > 0 ? (
                myOrders.map((order) => {
                  const shop = shops.find((s) => s.id === order.shopId);
                  return (
                    <Card key={order.id} style={styles.orderCardPremium}>
                      <View style={styles.orderTopPremium}>
                        <View style={{ flex: 1, gap: 4 }}>
                          <Text style={styles.orderShopPremium} numberOfLines={1}>{shop?.name || 'Barbearia'}</Text>
                          <View style={styles.orderMetaRow}>
                            <Ionicons name="calendar-outline" size={14} color={colors.textSubtle} />
                            <Text style={styles.orderMetaPremium}>
                              {new Date(order.createdAt).toLocaleDateString('pt-PT')} • {order.items.length} item(s)
                            </Text>
                          </View>
                        </View>
                        <View style={{ alignItems: 'flex-end', gap: 6 }}>
                          <Text style={styles.orderTotalPremium}>{currency(order.total)}</Text>
                          <View style={[styles.statusTagPremium, { backgroundColor: statusColor[order.status] + '1A' }]}>
                            <Text style={[styles.statusTextPremium, { color: statusColor[order.status] }]}>{statusLabel[order.status]}</Text>
                          </View>
                        </View>
                      </View>
                    </Card>
                  );
                })
              ) : (
                <View style={styles.emptyBlockPremium}>
                  <View style={styles.emptyIconCircle}>
                    <Ionicons name="bag-handle-outline" size={28} color={colors.textSubtle} />
                  </View>
                  <Text style={styles.emptyTxtPremium}>Ainda não tens compras efetuadas.</Text>
                </View>
              )}
            </View>
          )}

          {/* BARBER TABS */}
          {isBarber && activeTab === 'agenda_pessoal' && (
            <View style={styles.listContainer}>
              <View style={styles.subTitleRow}>
                <Ionicons name="list-outline" size={16} color={colors.primary} />
                <Text style={styles.subTitle}>Todas as marcações do espaço</Text>
              </View>
              
              {myAppointments.length > 0 ? (
                myAppointments.map((appt) => {
                  const dateParts = appt.date.split(' ');
                  const day = dateParts[0].split('-')[2];
                  const month = new Date(dateParts[0]).toLocaleString('pt-PT', { month: 'short' }).toUpperCase();
                  
                  return (
                    <Card key={appt.id} style={styles.agendaCard}>
                       <View style={styles.agendaTop}>
                        <View style={styles.calendarBlock}>
                          <View style={styles.calendarHeader} />
                          <Text style={styles.dateDay}>{day}</Text>
                          <Text style={styles.dateMonth}>{month}</Text>
                        </View>
                        <View style={styles.agendaMain}>
                          <Text style={styles.agendaShop}>{dateParts[1]}</Text>
                          <View style={styles.agendaMetaRow}>
                            <Ionicons name="people-outline" size={13} color={colors.textMuted} />
                            <Text style={styles.agendaTime}>Total: {currency(appt.total)}</Text>
                          </View>
                        </View>
                        <View style={[styles.statusTag, { backgroundColor: statusColor[appt.status] + '14' }]}>
                          <Ionicons 
                            name={statusIconName[appt.status]} 
                            size={11} 
                            color={statusColor[appt.status]} 
                          />
                          <Text style={[styles.statusText, { color: statusColor[appt.status] }]}>{statusLabel[appt.status]}</Text>
                        </View>
                      </View>
                    </Card>
                  );
                })
              ) : (
                <View style={styles.emptyBlock}>
                  <Ionicons name="calendar-outline" size={36} color={colors.textSubtle} />
                  <Text style={styles.emptyTxt}>Sem marcações registadas.</Text>
                </View>
              )}
            </View>
          )}

          {isBarber && activeTab === 'reviews' && (
            <View style={styles.listContainer}>
              {shopReviews.length > 0 ? (
                shopReviews.map((r) => (
                  <Card key={r.id} style={styles.reviewCard}>
                    <View style={styles.reviewHeader}>
                      <View style={styles.reviewStarsRow}>
                        {[1, 2, 3, 4, 5].map((star) => (
                          <Ionicons 
                            key={star} 
                            name={star <= r.rating ? "star" : "star-outline"} 
                            size={14} 
                            color={colors.star} 
                          />
                        ))}
                      </View>
                      <Text style={styles.reviewDate}>{new Date(r.created_at).toLocaleDateString()}</Text>
                    </View>
                    <Text style={styles.reviewComment}>{r.comment || 'Sem comentário escrito.'}</Text>
                  </Card>
                ))
              ) : (
                <View style={styles.emptyBlock}>
                  <Ionicons name="star-outline" size={36} color={colors.textSubtle} />
                  <Text style={styles.emptyTxt}>Ainda não há avaliações neste espaço.</Text>
                </View>
              )}
            </View>
          )}

          {isBarber && activeTab === 'estatisticas' && (
            <View style={styles.listContainer}>
              <View style={styles.statsGrid}>
                <Card style={styles.statCardHalf}>
                  <View style={[styles.statIconContainer, { backgroundColor: colors.primarySoft }]}>
                    <Ionicons name="calendar" size={22} color={colors.primary} />
                  </View>
                  <Text style={styles.statValue}>{myAppointments.length}</Text>
                  <Text style={styles.statLabel}>Total de Marcações</Text>
                </Card>
                <Card style={styles.statCardHalf}>
                  <View style={[styles.statIconContainer, { backgroundColor: colors.accentSoft }]}>
                    <Ionicons name="star" size={22} color={colors.accent} />
                  </View>
                  <Text style={styles.statValue}>{(myShop?.rating || 0).toFixed(1)} ★</Text>
                  <Text style={styles.statLabel}>Rating Médio</Text>
                </Card>
              </View>
              <Card style={styles.statCardFull}>
                <View style={[styles.statIconContainer, { backgroundColor: colors.successSoft }]}>
                  <Ionicons name="wallet" size={22} color={colors.success} />
                </View>
                <Text style={styles.statValue}>{currency(myOrders.reduce((sum, o) => sum + o.total, 0))}</Text>
                <Text style={styles.statLabel}>Vendas em Produtos</Text>
              </Card>
            </View>
          )}
        </View>

        {/* Review Modal Dialog */}
        {reviewTarget && (
          <Card style={styles.reviewModal}>
            <Text style={styles.reviewTitle}>Avaliar {reviewTarget.shopName}</Text>
            <View style={styles.stars}>
              {[1, 2, 3, 4, 5].map((s) => (
                <TouchableOpacity key={s} onPress={() => setRating(s)} activeOpacity={0.7}>
                  <Ionicons 
                    name={rating >= s ? "star" : "star-outline"} 
                    size={36} 
                    color={colors.star} 
                    style={styles.starIconSpacing} 
                  />
                </TouchableOpacity>
              ))}
            </View>
            <TextInput 
              style={styles.reviewInput} 
              placeholder="Partilha a tua opinião sobre o serviço..." 
              placeholderTextColor={colors.placeholder} 
              multiline 
              value={comment} 
              onChangeText={setComment} 
            />
            <View style={styles.reviewActions}>
              <Button variant="ghost" onPress={() => setReviewTarget(null)} style={{ flex: 1 }}>Cancelar</Button>
              <Button onPress={handleReviewSubmit} loading={submittingReview} disabled={rating === 0} style={{ flex: 2 }}>Enviar Avaliação</Button>
            </View>
          </Card>
        )}

        {/* Logout Section */}
        <View style={styles.logoutSection}>
          <TouchableOpacity style={styles.logoutButtonPremium} onPress={logout} activeOpacity={0.85}>
            <Text style={styles.logoutButtonText}>Sair da Conta</Text>
            <Ionicons name="log-out-outline" size={20} color={colors.danger} />
          </TouchableOpacity>
          <Text style={styles.versionText}>Smart Agenda v1.0.5</Text>
        </View>
      </ScrollView>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: { 
    flex: 1, 
    backgroundColor: colors.background, 
  },
  content: { 
    padding: 20, 
    paddingBottom: 40,
    gap: 20,
  },

  /* ── Profile Header ── */
  profileHeader: { 
    backgroundColor: colors.surfaceDark, 
    borderRadius: radius.lg, 
    overflow: 'hidden',
    shadowColor: colors.primaryDark,
    shadowOffset: { width: 0, height: 6 },
    shadowOpacity: 0.1,
    shadowRadius: 12,
    elevation: 4,
    borderWidth: 1,
    borderColor: 'rgba(255,255,255,0.04)',
    marginTop: 6,
  },
  accentBar: {
    height: 4,
    backgroundColor: colors.primary,
    width: '100%',
  },
  profileHeaderInner: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: 16,
    padding: 20,
  },
  avatarRing: {
    width: 72,
    height: 72,
    borderRadius: 36,
    borderWidth: 2.5,
    borderColor: 'rgba(245,158,11,0.35)',
    alignItems: 'center',
    justifyContent: 'center',
    padding: 2,
  },
  avatarGradient: { 
    width: 62, 
    height: 62, 
    borderRadius: 31, 
    backgroundColor: colors.primary, 
    alignItems: 'center', 
    justifyContent: 'center', 
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.15,
    shadowRadius: 4,
  },
  avatarText: { 
    color: colors.textInverse, 
    fontSize: 24, 
    fontWeight: '900',
  },
  profileInfo: { 
    flex: 1, 
    gap: 4, 
  },
  profileName: { 
    color: colors.textInverse, 
    fontSize: 20, 
    fontWeight: '900',
    letterSpacing: -0.4,
  },
  profileEmail: { 
    color: 'rgba(248,251,248,0.72)', 
    fontSize: 14, 
    fontWeight: '500',
  },
  roleBadge: { 
    alignSelf: 'flex-start', 
    backgroundColor: colors.primarySoft, 
    borderRadius: radius.pill, 
    paddingHorizontal: 10, 
    paddingVertical: 4, 
    marginTop: 4,
    flexDirection: 'row',
    alignItems: 'center',
    gap: 4,
  },
  roleText: { 
    color: colors.primaryDark, 
    fontSize: 10, 
    fontWeight: '800', 
    textTransform: 'uppercase',
  },

  /* ── Stats Strip (unified card) ── */
  statsStrip: { 
    flexDirection: 'row', 
    alignItems: 'center',
    backgroundColor: colors.surface,
    borderRadius: radius.lg,
    borderWidth: 1,
    borderColor: colors.border,
    ...shadows.soft,
  },
  profileStat: { 
    flex: 1, 
    paddingVertical: 14, 
    paddingHorizontal: 8,
    alignItems: 'center',
  },
  statsDivider: {
    width: 1,
    height: 32,
    backgroundColor: colors.border,
  },
  profileStatValue: { 
    color: colors.text, 
    fontSize: 18, 
    fontWeight: '900',
  },
  profileStatLabel: { 
    color: colors.textMuted, 
    fontSize: 10, 
    fontWeight: '700', 
    textTransform: 'uppercase', 
    marginTop: 2,
  },

  /* ── Notifications ── */
  sectionHeaderRow: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: 6,
    marginBottom: 10,
  },
  sectionTitle: { 
    color: colors.text, 
    fontSize: 16, 
    fontWeight: '800', 
  },
  notifCountBadge: {
    backgroundColor: colors.danger,
    borderRadius: radius.pill,
    minWidth: 20,
    height: 20,
    alignItems: 'center',
    justifyContent: 'center',
    paddingHorizontal: 6,
    marginLeft: 4,
  },
  notifCountText: {
    color: colors.textInverse,
    fontSize: 11,
    fontWeight: '800',
  },
  notifSection: { 
    marginTop: 4,
  },
  notifScroll: { 
    marginHorizontal: -20, 
    paddingHorizontal: 20,
  },
  notifCard: { 
    backgroundColor: colors.surface, 
    width: 240, 
    borderRadius: radius.lg, 
    padding: 14, 
    marginRight: 12, 
    borderWidth: 1, 
    borderColor: colors.border, 
    gap: 6, 
    ...shadows.soft,
  },
  notifUnread: { 
    borderColor: 'rgba(245,158,11,0.2)', 
    backgroundColor: colors.primarySoft, 
  },
  notifHeader: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
  },
  unreadDot: {
    width: 6,
    height: 6,
    borderRadius: 3,
    backgroundColor: colors.primary,
  },
  notifMsg: { 
    color: colors.textMuted, 
    fontSize: 13, 
    lineHeight: 18, 
    fontWeight: '500', 
  },
  markReadBtn: {
    alignSelf: 'flex-start',
    marginTop: 2,
  },
  markRead: { 
    color: colors.primaryDark, 
    fontSize: 10, 
    fontWeight: '800', 
    textTransform: 'uppercase', 
    letterSpacing: 0.3,
  },

  /* ── Tabs ── */
  tabBarContainer: {
    marginVertical: 4,
  },
  tabBar: { 
    flexDirection: 'row', 
    gap: 8, 
  },
  tabItem: { 
    paddingVertical: 10, 
    paddingHorizontal: 16, 
    borderRadius: radius.pill, 
    backgroundColor: colors.surface, 
    borderWidth: 1, 
    borderColor: colors.border, 
  },
  tabActive: { 
    backgroundColor: colors.primary, 
    borderColor: colors.primary, 
  },
  tabText: { 
    color: colors.textMuted, 
    fontSize: 14, 
    fontWeight: '700', 
  },
  tabTextActive: { 
    color: colors.textInverse, 
  },
  tabContent: { 
    minHeight: 200, 
  },

  /* ── Lists & Empty ── */
  listContainer: { 
    gap: 12, 
  },
  emptyBlock: {
    alignItems: 'center',
    justifyContent: 'center',
    paddingVertical: 40,
    gap: 10,
  },
  emptyTxt: { 
    color: colors.textMuted, 
    textAlign: 'center', 
    fontWeight: '600', 
    fontSize: 14,
  },
  subTitleRow: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: 6,
    marginBottom: 4,
  },
  subTitle: { 
    color: colors.text, 
    fontSize: 14, 
    fontWeight: '800', 
  },

  /* ── Agenda Cards ── */
  agendaCard: { 
    padding: 14, 
    backgroundColor: colors.surface, 
    borderRadius: radius.lg, 
    borderWidth: 1, 
    borderColor: colors.border,
    ...shadows.soft,
  },
  agendaTop: { 
    flexDirection: 'row', 
    alignItems: 'center', 
    gap: 14, 
  },
  calendarBlock: { 
    backgroundColor: colors.surfaceMuted, 
    borderRadius: radius.md, 
    alignItems: 'center', 
    minWidth: 52, 
    borderWidth: 1, 
    borderColor: colors.border,
    overflow: 'hidden',
  },
  calendarHeader: {
    height: 4,
    backgroundColor: colors.primary,
    width: '100%',
  },
  dateDay: { 
    color: colors.text, 
    fontSize: 18, 
    fontWeight: '900',
    marginTop: 4,
  },
  dateMonth: { 
    color: colors.primary, 
    fontSize: 9, 
    fontWeight: '800', 
    textTransform: 'uppercase',
    marginBottom: 4,
  },
  agendaMain: { 
    flex: 1, 
    gap: 3, 
  },
  agendaShop: { 
    color: colors.text, 
    fontSize: 16, 
    fontWeight: '800', 
  },
  agendaMetaRow: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: 4,
  },
  agendaTime: { 
    color: colors.textMuted, 
    fontSize: 13, 
    fontWeight: '500', 
  },
  statusTag: { 
    flexDirection: 'row',
    alignItems: 'center',
    gap: 4,
    paddingHorizontal: 8, 
    paddingVertical: 4, 
    borderRadius: radius.pill, 
  },
  statusText: { 
    fontSize: 9, 
    fontWeight: '800', 
    textTransform: 'uppercase', 
    letterSpacing: 0.2,
  },
  reviewBtn: { 
    marginTop: 10, 
    borderRadius: radius.md, 
  },

  /* ── Shop / Favorite Cards ── */
  shopCard: { 
    flexDirection: 'row', 
    alignItems: 'center', 
    gap: 12, 
    padding: 12, 
    backgroundColor: colors.surface, 
    borderRadius: radius.lg, 
    borderWidth: 1, 
    borderColor: colors.border,
    ...shadows.soft,
  },
  shopIcon: { 
    width: 44, 
    height: 44, 
    borderRadius: radius.md, 
    backgroundColor: colors.primarySoft, 
    alignItems: 'center', 
    justifyContent: 'center', 
    borderWidth: 0.5, 
    borderColor: colors.borderStrong, 
  },
  shopIconText: { 
    color: colors.primary, 
    fontSize: 18, 
    fontWeight: '900', 
  },
  shopCardBody: {
    flex: 1,
    gap: 2,
  },
  shopName: { 
    color: colors.text, 
    fontSize: 15, 
    fontWeight: '800', 
  },
  shopLocationRow: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: 4,
  },
  shopAddr: { 
    color: colors.textMuted, 
    fontSize: 12, 
    fontWeight: '500', 
    flex: 1,
  },
  shopRatingBadge: { 
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: colors.accentSoft,
    borderRadius: radius.pill,
    paddingHorizontal: 8,
    paddingVertical: 3,
    gap: 3,
  },
  shopRatingText: {
    color: colors.primaryDark,
    fontWeight: '800', 
    fontSize: 11, 
  },

  /* ── Order Cards ── */
  orderCard: { 
    padding: 14, 
    gap: 10, 
    backgroundColor: colors.surface, 
    borderRadius: radius.lg, 
    borderWidth: 1, 
    borderColor: colors.border,
    ...shadows.soft,
  },
  orderTop: { 
    flexDirection: 'row', 
    justifyContent: 'space-between', 
    alignItems: 'flex-start', 
    gap: 12, 
  },
  orderShop: { 
    color: colors.text, 
    fontSize: 16, 
    fontWeight: '800', 
  },
  orderMetaRow: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: 4,
  },
  orderMeta: { 
    color: colors.textMuted, 
    fontSize: 12, 
    fontWeight: '500', 
  },
  orderTotal: { 
    color: colors.primary, 
    fontSize: 16, 
    fontWeight: '900', 
  },

  /* ── Review Cards ── */
  reviewCard: { 
    padding: 16, 
    gap: 8, 
    backgroundColor: colors.surface, 
    borderRadius: radius.lg,
    borderWidth: 1,
    borderColor: colors.border,
    ...shadows.soft,
  },
  reviewHeader: { 
    flexDirection: 'row', 
    justifyContent: 'space-between', 
    alignItems: 'center', 
  },
  reviewStarsRow: { 
    flexDirection: 'row',
    gap: 2,
  },
  reviewDate: { 
    color: colors.textSubtle, 
    fontSize: 12, 
    fontWeight: '500', 
  },
  reviewComment: { 
    color: colors.text, 
    fontSize: 14, 
    lineHeight: 18, 
    fontWeight: '400', 
  },

  /* ── Stats Grid (Barber Estatísticas Tab) ── */
  statsGrid: {
    flexDirection: 'row',
    gap: 12,
  },
  statCardHalf: { 
    flex: 1,
    padding: 20, 
    alignItems: 'center', 
    gap: 6, 
    backgroundColor: colors.surface, 
    borderRadius: radius.lg, 
    borderWidth: 1, 
    borderColor: colors.border,
    ...shadows.soft,
  },
  statCardFull: { 
    padding: 20, 
    alignItems: 'center', 
    gap: 6, 
    backgroundColor: colors.surface, 
    borderRadius: radius.lg, 
    borderWidth: 1, 
    borderColor: colors.border,
    ...shadows.soft,
  },
  statIconContainer: {
    width: 40,
    height: 40,
    borderRadius: 20,
    backgroundColor: colors.surfaceMuted,
    alignItems: 'center',
    justifyContent: 'center',
    marginBottom: 4,
  },
  statLabel: { 
    color: colors.textMuted, 
    fontSize: 12, 
    fontWeight: '700', 
    textTransform: 'uppercase', 
  },
  statValue: { 
    color: colors.text, 
    fontSize: 24, 
    fontWeight: '900', 
  },

  /* ── Review Modal ── */
  reviewModal: { 
    marginTop: 10, 
    padding: 20, 
    gap: 14, 
    borderColor: colors.primary, 
    borderRadius: radius.lg, 
  },
  reviewTitle: { 
    color: colors.text, 
    fontSize: 16, 
    fontWeight: '800', 
    textAlign: 'center', 
  },
  stars: { 
    flexDirection: 'row', 
    justifyContent: 'center', 
    gap: 10, 
  },
  starIconSpacing: {
    paddingHorizontal: 2,
  },
  reviewInput: { 
    backgroundColor: colors.surfaceMuted, 
    borderRadius: radius.md, 
    padding: 12, 
    color: colors.text, 
    height: 90, 
    textAlignVertical: 'top', 
    borderWidth: 1, 
    borderColor: colors.borderStrong, 
  },
  reviewActions: { 
    flexDirection: 'row', 
    gap: 12, 
  },

  /* ── Logout ── */
  logoutSection: {
    marginTop: 20,
    paddingTop: 20,
    borderTopWidth: 1,
    borderTopColor: colors.borderStrong,
    alignItems: 'center',
  },
  /* ── Premium Client Layout Styles ── */
  clientSectionHeader: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: 8,
    marginBottom: 16,
    paddingHorizontal: 4,
  },
  clientSectionTitle: {
    color: colors.text,
    fontSize: 18,
    fontWeight: '900',
    letterSpacing: -0.3,
  },
  agendaCardPremium: {
    padding: 16,
    backgroundColor: colors.surface,
    borderRadius: radius.lg,
    borderWidth: 1,
    borderColor: colors.border,
    gap: 16,
    ...shadows.soft,
  },
  calendarBlockPremium: {
    width: 60,
    height: 60,
    backgroundColor: colors.primarySoft,
    borderRadius: radius.md,
    alignItems: 'center',
    justifyContent: 'center',
    borderWidth: 1,
    borderColor: colors.borderStrong,
  },
  dateMonthPremium: {
    color: colors.primaryDark,
    fontSize: 11,
    fontWeight: '800',
    textTransform: 'uppercase',
  },
  dateDayPremium: {
    color: colors.primary,
    fontSize: 22,
    fontWeight: '900',
    marginTop: -2,
  },
  agendaShopPremium: {
    color: colors.text,
    fontSize: 16,
    fontWeight: '800',
  },
  agendaServicePremium: {
    color: colors.textMuted,
    fontSize: 12,
    fontWeight: '600',
    marginTop: 2,
  },
  agendaTimePremium: {
    color: colors.textMuted,
    fontSize: 13,
    fontWeight: '600',
  },
  statusTagPremium: {
    paddingHorizontal: 10,
    paddingVertical: 4,
    borderRadius: radius.pill,
    alignSelf: 'flex-start',
  },
  statusTextPremium: {
    fontSize: 10,
    fontWeight: '800',
    textTransform: 'uppercase',
  },
  emptyBlockPremium: {
    alignItems: 'center',
    justifyContent: 'center',
    paddingVertical: 32,
    backgroundColor: colors.surface,
    borderRadius: radius.lg,
    borderWidth: 1,
    borderColor: colors.backgroundAlt,
    gap: 12,
  },
  emptyIconCircle: {
    width: 56,
    height: 56,
    borderRadius: 28,
    backgroundColor: colors.background,
    alignItems: 'center',
    justifyContent: 'center',
  },
  emptyTxtPremium: {
    color: colors.textMuted,
    fontWeight: '600',
    fontSize: 14,
    marginBottom: 4,
  },
  shopCardPremium: {
    flexDirection: 'row',
    alignItems: 'center',
    padding: 12,
    backgroundColor: colors.surface,
    borderRadius: radius.lg,
    borderWidth: 1,
    borderColor: colors.border,
    gap: 12,
  },
  shopImageMini: {
    width: 50,
    height: 50,
    borderRadius: radius.md,
    backgroundColor: colors.surfaceMuted,
  },
  shopCardBodyPremium: {
    flex: 1,
    justifyContent: 'center',
  },
  shopNamePremium: {
    color: colors.text,
    fontSize: 15,
    fontWeight: '800',
    marginBottom: 2,
  },
  shopAddrPremium: {
    color: colors.textMuted,
    fontSize: 12,
    fontWeight: '500',
    flex: 1,
  },
  shopRatingBadgePremium: {
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: colors.accentSoft,
    paddingHorizontal: 8,
    paddingVertical: 4,
    borderRadius: radius.pill,
    gap: 4,
  },
  shopRatingTextPremium: {
    color: colors.primaryDark,
    fontSize: 12,
    fontWeight: '900',
  },
  orderCardPremium: {
    padding: 16,
    backgroundColor: colors.surface,
    borderRadius: radius.lg,
    borderWidth: 1,
    borderColor: colors.border,
  },
  orderTopPremium: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'flex-start',
  },
  orderShopPremium: {
    color: colors.text,
    fontSize: 15,
    fontWeight: '800',
  },
  orderMetaPremium: {
    color: colors.textMuted,
    fontSize: 13,
    fontWeight: '500',
  },
  orderTotalPremium: {
    color: colors.primary,
    fontSize: 16,
    fontWeight: '900',
  },
  logoutButtonPremium: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: colors.dangerSoft,
    paddingVertical: 14,
    paddingHorizontal: 20,
    borderRadius: radius.lg,
    width: '100%',
    borderWidth: 1,
    borderColor: 'rgba(239,68,68,0.18)',
    gap: 10,
    shadowColor: colors.danger,
    shadowOffset: { width: 0, height: 4 },
    shadowOpacity: 0.02,
    shadowRadius: 6,
  },
  logoutButtonText: {
    color: colors.danger,
    fontSize: 15,
    fontWeight: '800',
  },
  versionText: {
    color: colors.textSubtle,
    fontSize: 11,
    marginTop: 12,
    fontWeight: '600',
  },
});
