'use client';

/**
 * UserDashboardView Component
 * 
 * Active "trip tracker" (Uber/Airbnb style) User Dashboard for ShineCode.
 * 
 * Features:
 * 1. Live Active Booking Hero Card with pulsing status indicator, ETA/schedule,
 *    therapist credentials & WhatsApp contact trigger, manage booking & cancel/reschedule actions.
 * 2. Past Bookings Tab with Search + Shadcn <Select> Status Filter (All, Completed, Cancelled, Refunded),
 *    adaptive status badges, Rebook flow, and itemized Tax Invoice Dialog.
 * 3. Settings Tab:
 *    - Personal Details with Large Interactive Avatar (Hover-State Camera Overlay),
 *      Verified Badges on Email & UAE Phone, and inline email editing with instant save.
 *    - Wellness & Preferences Profile with Shadcn <Select> for Gender and Skin/Hair type.
 *    - Upgraded Saved UAE Addresses with permanent Gate Code / Intercom, Delivery Notes, and Shadcn <Select> for Emirate.
 *    - "Danger Zone" Account Deletion Card with typed 'DELETE' confirmation modal guardrail.
 */

import React, { useState, useRef, useMemo, useEffect } from 'react';
import Link from 'next/link';
import { useRouter, useSearchParams } from 'next/navigation';
import {
  Calendar,
  Clock,
  MapPin,
  Star,
  ShieldCheck,
  MessageCircle,
  RotateCw,
  FileText,
  User as UserIcon,
  Sparkles,
  CheckCircle2,
  X,
  AlertCircle,
  Sliders,
  Camera,
  Heart,
  KeyRound,
  Plus,
  Trash2,
  Edit2,
  Edit3,
  Building,
  Check,
  Search,
  BadgeCheck,
  AlertTriangle,
  ShieldAlert,
} from 'lucide-react';
import { useAuthStore } from '@/lib/stores/useAuthStore';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { Tabs, TabsList, TabsTrigger, TabsContent } from '@/components/ui/tabs';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogDescription,
} from '@/components/ui/dialog';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
} from '@/components/ui/select';
import { DatePicker } from '@/components/ui/date-picker';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
import { TabbyBadge, TamaraBadge } from '@/components/BNPLPriceDisplay';
import { ImageWithFallback } from '@/components/ui/ImageWithFallback';
import { cn } from '@/lib/utils';
import type { ApiBooking } from '@/lib/api/client';

export interface BookingRecord {
  id: string;
  reference: string;
  serviceId: number;
  serviceSlug: string;
  serviceNameEn: string;
  serviceNameAr: string;
  categoryEn: string;
  categoryAr: string;
  image: string;
  status: 'confirmed' | 'in_progress' | 'completed' | 'cancelled' | 'refunded';
  statusTextEn: string;
  statusTextAr: string;
  dateEn: string;
  dateAr: string;
  timeSlot: string;
  address: string;
  buildingNotes?: string;
  therapist: {
    name: string;
    roleEn: string;
    roleAr: string;
    avatar: string;
    rating: number;
    reviewCount: number;
    phone: string;
    whatsapp: string;
  };
  pricing: {
    basePrice: number;
    addons: { nameEn: string; nameAr: string; price: number; qty: number }[];
    vat: number;
    discount?: number;
    couponCode?: string;
    total: number;
    paymentMethod: 'card' | 'tabby' | 'tamara' | 'apple_pay';
    paymentSummary: string;
  };
}

export interface SavedAddress {
  id: string;
  label: string;
  isDefault: boolean;
  emirate: string;
  addressLine: string;
  gateCode?: string;
  permanentNotes?: string;
}

export interface WellnessProfile {
  dateOfBirth: string;
  gender: 'female' | 'male' | 'prefer_not_to_say' | '';
  skinHairType: 'normal' | 'dry' | 'oily' | 'combination' | 'sensitive' | '';
  allergies: string;
}



const INITIAL_SAVED_ADDRESSES: SavedAddress[] = [
  {
    id: 'addr_01',
    label: 'Home (Dubai Marina)',
    isDefault: true,
    emirate: 'Dubai',
    addressLine: 'Marina Gate Tower 2, Apt 1404, Dubai Marina, Dubai',
    gateCode: '#1404',
    permanentNotes: 'Ring bell 1404 at security reception. Guest parking available in basement B1.',
  },
  {
    id: 'addr_02',
    label: 'Palm Villa',
    isDefault: false,
    emirate: 'Dubai',
    addressLine: 'Frond M, Villa 24, Palm Jumeirah, Dubai',
    gateCode: 'Keypad: 8821*',
    permanentNotes: 'Direct access through garden side entrance. Beware of friendly golden retriever.',
  },
];

interface UserDashboardViewProps {
  locale?: string;
}

export function UserDashboardView({ locale = 'en' }: UserDashboardViewProps) {
  const router = useRouter();
  const searchParams = useSearchParams();
  const initialTab = searchParams.get('tab') || 'active';
  const isAr = locale === 'ar';

  const { user, token, setUser, logout } = useAuthStore();
  const fileInputRef = useRef<HTMLInputElement>(null);

  // ── API Bookings State ──
  const [apiBookings, setApiBookings] = useState<BookingRecord[]>([]);
  const [bookingsLoading, setBookingsLoading] = useState<boolean>(() => Boolean(token));
  const [bookingsError, setBookingsError] = useState<string | null>(null);

  /**
   * Adapter: ApiBooking (confirmed from BookingResource.php) → BookingRecord (UI model).
   * Field names are exact matches from the Laravel resource output.
   * Gracefully handles null/missing fields.
   */
  function adaptApiBooking(b: ApiBooking): BookingRecord {
    const firstHandyman = b.handyman?.[0]?.handyman ?? null;
    const serviceImage =
      b.service_attchments?.[0]?.url ||
      'https://images.unsplash.com/photo-1632345031435-8727f6897d53?w=600&auto=format&fit=crop&q=85';
    const statusMap: Record<string, BookingRecord['status']> = {
      accept: 'confirmed',
      confirmed: 'confirmed',
      in_progress: 'in_progress',
      completed: 'completed',
      cancelled: 'cancelled',
      hold: 'cancelled',
    };
    return {
      id: String(b.id),
      reference: `SHN-${b.id}`,
      serviceId: b.service_id,
      serviceSlug: String(b.service_id), // slug not returned by booking endpoint
      serviceNameEn: b.service_name || 'Service',
      serviceNameAr: b.service_name || 'خدمة',
      categoryEn: '',
      categoryAr: '',
      image: serviceImage,
      status: statusMap[b.status] ?? 'confirmed',
      statusTextEn: b.status_label || b.status,
      statusTextAr: b.status_label || b.status,
      // booking_date is formatted by site settings (e.g. "29/08/2026 04:30 PM")
      dateEn: b.booking_date || b.date || '',
      dateAr: b.booking_date || b.date || '',
      timeSlot: b.booking_slot || b.booking_date || '',
      address: b.address || '',
      buildingNotes: undefined,
      therapist: {
        name: firstHandyman?.display_name ?? b.provider_name ?? 'Professional',
        roleEn: 'Beauty Specialist',
        roleAr: 'أخصائية تجميل',
        avatar: firstHandyman?.handyman_image ?? b.provider_image ?? '',
        rating: firstHandyman?.rating ?? b.total_rating ?? 0,
        reviewCount: 0,
        phone: firstHandyman?.phone ?? '',
        whatsapp: firstHandyman?.phone
          ? `https://wa.me/${firstHandyman.phone.replace(/\D/g, '')}`
          : '',
      },
      pricing: {
        basePrice: b.price ?? b.amount ?? 0,
        addons: (b.extra_charges ?? []).map((ec) => ({
          nameEn: ec.name,
          nameAr: ec.name,
          price: ec.price,
          qty: ec.qty,
        })),
        vat: 0,
        discount: b.coupon_data?.discount,
        couponCode: b.coupon_data?.coupon_code,
        total: b.total_amount,
        paymentMethod: (b.payment_method?.toLowerCase() as BookingRecord['pricing']['paymentMethod']) ?? 'card',
        paymentSummary: b.payment_method || '',
      },
    };
  }

  /**
   * Fetch bookings from API on mount.
   * Uses NEXT_PUBLIC_API_URL (client-side) — never the internal VPS URL.
   * Requires auth token from useAuthStore (set on login).
   * Gracefully degrades: if no token or API fails, shows empty state (no crash).
   */
  useEffect(() => {
    if (!token) {
      return;
    }

    let isMounted = true;
    fetch('/api/bookings', {
      headers: {
        Accept: 'application/json',
        Authorization: `Bearer ${token}`,
      },
    })
      .then(async (res) => {
        if (!res.ok) {
          if (res.status === 401) {
            // Token expired — log out silently
            logout();
          }
          throw new Error(`API ${res.status}`);
        }
        return res.json();
      })
      .then((json) => {
        if (!isMounted) return;
        const raw: ApiBooking[] = json?.data ?? [];
        setApiBookings(raw.map(adaptApiBooking));
        setBookingsLoading(false);
      })
      .catch((err) => {
        if (!isMounted) return;
        setBookingsError(isAr ? 'تعذّر تحميل الحجوزات' : 'Could not load bookings');
        setBookingsLoading(false);
        console.error('[Dashboard] booking-list error:', err);
      });

    return () => {
      isMounted = false;
    };
  }, [token, isAr, logout]);

  // Active booking = first booking that is NOT completed/cancelled/refunded
  const apiActiveBooking: BookingRecord | null = apiBookings.find(
    (b) => b.status !== 'completed' && b.status !== 'cancelled'
  ) ?? null;

  // Past bookings = completed or cancelled
  const apiPastBookings: BookingRecord[] = apiBookings.filter(
    (b) => b.status === 'completed' || b.status === 'cancelled'
  );

  // Active booking used in JSX (API data or null when API unavailable)
  const activeBooking = apiActiveBooking;

  const activeUser = user || {
    id: 0,
    first_name: '',
    last_name: '',
    email: '',
    avatar: '',
  };

  const [avatarPreview, setAvatarPreview] = useState<string | null>(activeUser.avatar || null);
  const [activeTab, setActiveTab] = useState(initialTab);
  const [selectedInvoice, setSelectedInvoice] = useState<BookingRecord | null>(null);
  const [isInvoiceOpen, setIsInvoiceOpen] = useState(false);
  const [isCancelModalOpen, setIsCancelModalOpen] = useState(false);
  const [isManageModalOpen, setIsManageModalOpen] = useState(false);
  const [uploadSuccess, setUploadSuccess] = useState(false);

  // ── Inline Email Editing State ──
  const [isEditingEmail, setIsEditingEmail] = useState(false);
  const [editableEmail, setEditableEmail] = useState(activeUser.email || 'sarah.c@dubai.ae');
  const [emailSuccessMessage, setEmailSuccessMessage] = useState(false);

  // ── Danger Zone Account Deletion State ──
  const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false);
  const [deleteConfirmationText, setDeleteConfirmationText] = useState('');
  const isDeleteConfirmed = deleteConfirmationText.trim().toUpperCase() === 'DELETE' || deleteConfirmationText.trim() === 'حذف';

  // ── Past Bookings Search & Status Filter State ──
  const [pastSearchQuery, setPastSearchQuery] = useState('');
  const [pastStatusFilter, setPastStatusFilter] = useState<'all' | 'completed' | 'cancelled' | 'refunded'>('all');

  // Filtered Past Bookings computation — uses API data, falls back to empty if loading
  const filteredPastBookings = useMemo(() => {
    const source = apiPastBookings;
    return source.filter((booking) => {
      if (pastStatusFilter !== 'all' && booking.status !== pastStatusFilter) return false;
      if (pastSearchQuery.trim()) {
        const q = pastSearchQuery.toLowerCase();
        const matchName =
          booking.serviceNameEn.toLowerCase().includes(q) ||
          booking.serviceNameAr.toLowerCase().includes(q);
        const matchRef = booking.reference.toLowerCase().includes(q);
        const matchTherapist = booking.therapist.name.toLowerCase().includes(q);
        const matchAddress = booking.address.toLowerCase().includes(q);
        if (!matchName && !matchRef && !matchTherapist && !matchAddress) return false;
      }
      return true;
    });
  }, [apiPastBookings, pastSearchQuery, pastStatusFilter]);


  // ── CRM & Wellness Preferences State ──
  const [wellness, setWellness] = useState<WellnessProfile>({
    dateOfBirth: '1995-04-18',
    gender: 'female',
    skinHairType: 'combination',
    allergies: 'Sensitive to synthetic fragrances. Prefer organic botanical oils and pregnancy-safe formulas.',
  });
  const [wellnessSaved, setWellnessSaved] = useState(false);

  // ── Upgraded Saved Addresses State & Modal ──
  const [savedAddresses, setSavedAddresses] = useState<SavedAddress[]>(INITIAL_SAVED_ADDRESSES);
  const [isAddressModalOpen, setIsAddressModalOpen] = useState(false);
  const [editingAddressId, setEditingAddressId] = useState<string | null>(null);
  const [addressForm, setAddressForm] = useState({
    label: '',
    emirate: 'Dubai',
    addressLine: '',
    gateCode: '',
    permanentNotes: '',
    isDefault: false,
  });

  const handleOpenInvoice = (booking: BookingRecord) => {
    setSelectedInvoice(booking);
    setIsInvoiceOpen(true);
  };

  const handleRebook = (slug: string) => {
    router.push(`/${locale}/services/${slug}`);
  };

  const handleAvatarFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (file) {
      const reader = new FileReader();
      reader.onloadend = () => {
        const result = reader.result as string;
        setAvatarPreview(result);
        setUser({
          ...activeUser,
          avatar: result,
        });
        setUploadSuccess(true);
        setTimeout(() => setUploadSuccess(false), 3000);
      };
      reader.readAsDataURL(file);
    }
  };

  const handleSaveEmail = () => {
    const clean = editableEmail.trim();
    if (!clean || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(clean)) return;
    setUser({
      ...activeUser,
      email: clean,
    });
    setIsEditingEmail(false);
    setEmailSuccessMessage(true);
    setTimeout(() => setEmailSuccessMessage(false), 3000);
  };

  const handleSaveWellness = (e: React.FormEvent) => {
    e.preventDefault();
    setWellnessSaved(true);
    setTimeout(() => setWellnessSaved(false), 3000);
  };

  const handleOpenNewAddressModal = () => {
    setEditingAddressId(null);
    setAddressForm({
      label: '',
      emirate: 'Dubai',
      addressLine: '',
      gateCode: '',
      permanentNotes: '',
      isDefault: savedAddresses.length === 0,
    });
    setIsAddressModalOpen(true);
  };

  const handleOpenEditAddressModal = (addr: SavedAddress) => {
    setEditingAddressId(addr.id);
    setAddressForm({
      label: addr.label,
      emirate: addr.emirate,
      addressLine: addr.addressLine,
      gateCode: addr.gateCode || '',
      permanentNotes: addr.permanentNotes || '',
      isDefault: addr.isDefault,
    });
    setIsAddressModalOpen(true);
  };

  const handleDeleteAddress = (id: string) => {
    setSavedAddresses((prev) => prev.filter((a) => a.id !== id));
  };

  const handleSaveAddress = (e: React.FormEvent) => {
    e.preventDefault();
    if (!addressForm.addressLine.trim()) return;

    if (editingAddressId) {
      setSavedAddresses((prev) =>
        prev.map((a) => {
          if (a.id === editingAddressId) {
            return {
              ...a,
              label: addressForm.label.trim() || 'Address',
              emirate: addressForm.emirate,
              addressLine: addressForm.addressLine.trim(),
              gateCode: addressForm.gateCode.trim(),
              permanentNotes: addressForm.permanentNotes.trim(),
              isDefault: addressForm.isDefault,
            };
          }
          return addressForm.isDefault ? { ...a, isDefault: false } : a;
        })
      );
    } else {
      const newAddr: SavedAddress = {
        id: `addr_${Date.now()}`,
        label: addressForm.label.trim() || 'Address',
        emirate: addressForm.emirate,
        addressLine: addressForm.addressLine.trim(),
        gateCode: addressForm.gateCode.trim(),
        permanentNotes: addressForm.permanentNotes.trim(),
        isDefault: addressForm.isDefault,
      };
      setSavedAddresses((prev) =>
        addressForm.isDefault
          ? [...prev.map((a) => ({ ...a, isDefault: false })), newAddr]
          : [...prev, newAddr]
      );
    }
    setIsAddressModalOpen(false);
  };

  const handleConfirmAccountDeletion = () => {
    if (!isDeleteConfirmed) return;
    logout();
    setIsDeleteModalOpen(false);
    alert(isAr ? 'تم تقديم طلب حذف الحساب بنجاح وتم تسجيل الخروج.' : 'Account deletion requested successfully. You have been logged out.');
    router.push(`/${locale}`);
  };

  const initials = ((activeUser.first_name?.charAt(0) || '') + (activeUser.last_name?.charAt(0) || '')).toUpperCase() || 'U';

  return (
    <div className="min-h-screen bg-zinc-50/60 dark:bg-zinc-950 pb-28 pt-8 sm:pt-12 transition-colors duration-200">
      <div className="max-w-5xl mx-auto px-4 sm:px-6 lg:px-8">

        {/* ── 1. Welcome Header ── */}
        <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4 mb-8">
          <div>
            <h1 className="text-3xl sm:text-4xl font-extrabold text-zinc-900 dark:text-white tracking-tight">
              {isAr
                ? `مرحباً بك مجدداً، ${activeUser.first_name || 'عزيزتي'}`
                : `Welcome back, ${activeUser.first_name || 'Sarah'}`}
            </h1>
            <p className="text-sm text-zinc-500 dark:text-zinc-400 mt-1">
              {isAr
                ? 'تتبعي موعدكِ النشط، اطلعي على فواتيركِ السابقة وأديري ملفكِ الشخصي وتفضيلاتك'
                : 'Track your upcoming treatments, view past invoices, and customize your wellness preferences'}
            </p>
          </div>

          {/* Quick Book CTA */}
          <Link
            href={`/${locale}/services`}
            className="inline-flex items-center justify-center gap-2 px-5 py-2.5 bg-zinc-900 hover:bg-brand-500 active:bg-brand-600 dark:bg-white dark:text-zinc-950 dark:hover:bg-brand-500 dark:hover:text-white text-white rounded-xl text-sm font-bold transition-colors shadow-2xs self-start sm:self-auto shrink-0"
          >
            <Sparkles className="w-4 h-4" />
            <span>{isAr ? 'حجز خدمة جديدة' : 'Book New Service'}</span>
          </Link>
        </div>

        {/* Error banner if API request failed */}
        {bookingsError && (
          <div className="mb-6 p-4 bg-rose-50 dark:bg-rose-950/40 border border-rose-200 dark:border-rose-800 rounded-2xl flex items-center gap-3 text-rose-700 dark:text-rose-300 text-xs font-semibold">
            <AlertTriangle className="w-4 h-4 shrink-0" />
            <span>{bookingsError}</span>
          </div>
        )}

        {/* Loading indicator */}
        {bookingsLoading && token && (
          <div className="mb-6 p-3 bg-zinc-50 dark:bg-zinc-900 border border-zinc-200 dark:border-zinc-800 rounded-2xl flex items-center gap-2.5 text-zinc-500 dark:text-zinc-400 text-xs font-medium">
            <RotateCw className="w-3.5 h-3.5 animate-spin text-brand-500" />
            <span>{isAr ? 'جاري تحميل الحجوزات...' : 'Loading bookings...'}</span>
          </div>
        )}

        {/* ── 2. Navigation Tabs (Active, Past, Settings) ── */}
        <Tabs value={activeTab} onValueChange={setActiveTab}>
          <TabsList className="mb-8">
            <TabsTrigger value="active" className="gap-2">
              <span className="relative flex h-2 w-2">
                <span className="animate-ping absolute inline-flex h-full w-full rounded-full bg-emerald-400 opacity-75" />
                <span className="relative inline-flex rounded-full h-2 w-2 bg-emerald-500" />
              </span>
              <span>{isAr ? 'الموعد النشط (1)' : 'Active (1)'}</span>
            </TabsTrigger>
            <TabsTrigger value="past">
              <span>{isAr ? 'الفواتير السابقة' : 'Past'}</span>
            </TabsTrigger>
            <TabsTrigger value="settings">
              <span>{isAr ? 'الإعدادات والتفضيلات' : 'Settings'}</span>
            </TabsTrigger>
          </TabsList>

          {/* ────────────────── TAB 1: ACTIVE BOOKING (Hero Trip Tracker) ────────────────── */}
          <TabsContent value="active">
            <div className="space-y-6">

              {/* Active Booking Card */}
              <div className="bg-white dark:bg-zinc-900 border border-zinc-200 dark:border-zinc-800 rounded-3xl p-6 sm:p-8 shadow-xs mb-8 space-y-6">

                {/* Top Row: Pulsing Status Indicator & Booking Ref */}
                <div className="flex items-center justify-between flex-wrap gap-3 pb-4 border-b border-zinc-100 dark:border-zinc-800">
                  <div className="flex items-center gap-2.5">
                    <span className="relative flex h-3 w-3">
                      <span className="animate-ping absolute inline-flex h-full w-full rounded-full bg-emerald-400 opacity-75" />
                      <span className="relative inline-flex rounded-full h-3 w-3 bg-emerald-500" />
                    </span>
                    <span className="font-bold text-sm sm:text-base text-emerald-700 dark:text-emerald-400">
                      {isAr ? (activeBooking?.statusTextAr ?? '') : (activeBooking?.statusTextEn ?? '')}
                    </span>
                  </div>

                  <div className="flex items-center gap-2">
                    <span className="font-mono text-xs font-bold text-zinc-500 dark:text-zinc-400 bg-zinc-100 dark:bg-zinc-800 px-2.5 py-1 rounded-lg">
                      #{activeBooking?.reference ?? '—'}
                    </span>
                    <span className="text-xs font-bold text-emerald-700 dark:text-emerald-400 bg-emerald-50 dark:bg-emerald-950/60 border border-emerald-200/80 dark:border-emerald-800/80 px-2.5 py-1 rounded-lg">
                      {isAr ? 'الوصول بعد 45 دقيقة' : 'Arriving in 45 mins'}
                    </span>
                  </div>
                </div>

                {/* Service Visual & Main Title */}
                <div className="flex items-start gap-4 sm:gap-6">
                  <div className="w-20 h-20 sm:w-24 sm:h-24 rounded-2xl overflow-hidden relative bg-zinc-100 dark:bg-zinc-800 border border-zinc-200/80 dark:border-zinc-700 shrink-0">
                    <ImageWithFallback
                      src={activeBooking?.image ?? ''}
                      fallbackSrc="/images/fallback-placeholder.svg"
                      alt={isAr ? (activeBooking?.serviceNameAr ?? '') : (activeBooking?.serviceNameEn ?? '')}
                      fill
                      className="object-cover"
                      sizes="96px"
                    />
                  </div>

                  <div className="min-w-0 flex-1 space-y-1">
                    <span className="text-xs font-bold text-brand-600 dark:text-brand-400 uppercase tracking-wider">
                      {isAr ? (activeBooking?.categoryAr || '') : (activeBooking?.categoryEn || '')}
                    </span>
                    <h2 className="text-lg sm:text-xl font-extrabold text-zinc-900 dark:text-white leading-snug">
                      {isAr ? (activeBooking?.serviceNameAr ?? '') : (activeBooking?.serviceNameEn ?? '')}
                    </h2>
                    <p className="text-xs sm:text-sm text-zinc-500 dark:text-zinc-400">
                      {isAr ? 'تشمل: مساج فروة الرأس + قناع الكولاجين للعينين' : 'Includes: 15-Min Scalp Massage + Collagen Eye Mask'}
                    </p>
                  </div>
                </div>

                {/* Middle Row: Logistics (Date/Time & Location) */}
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4 p-5 bg-zinc-50 dark:bg-zinc-800/50 rounded-2xl border border-zinc-200/80 dark:border-zinc-700/80">
                  {/* Date & Time */}
                  <div className="space-y-1.5">
                    <div className="flex items-center gap-2 text-xs font-bold uppercase tracking-wider text-zinc-400 dark:text-zinc-500">
                      <Calendar className="w-3.5 h-3.5" />
                      <span>{isAr ? 'الموعد والوقت' : 'Date & Time'}</span>
                    </div>
                    <div className="font-extrabold text-base sm:text-lg text-zinc-900 dark:text-white">
                      {isAr ? (activeBooking?.dateAr ?? '') : (activeBooking?.dateEn ?? '')}
                    </div>
                    <div className="flex items-center gap-1.5 text-xs text-zinc-600 dark:text-zinc-300 font-medium">
                      <Clock className="w-3.5 h-3.5 text-zinc-400 shrink-0" />
                      <span>{activeBooking?.timeSlot ?? ''}</span>
                    </div>
                  </div>

                  {/* Location */}
                  <div className="space-y-1.5">
                    <div className="flex items-center gap-2 text-xs font-bold uppercase tracking-wider text-zinc-400 dark:text-zinc-500">
                      <MapPin className="w-3.5 h-3.5 text-zinc-400" />
                      <span>{isAr ? 'موقع تقديم الخدمة' : 'Service Location'}</span>
                    </div>
                    <div className="font-extrabold text-base sm:text-lg text-zinc-900 dark:text-white truncate">
                      {activeBooking?.address ?? ''}
                    </div>
                    <div className="text-xs text-zinc-500 dark:text-zinc-400 line-clamp-1">
                      {activeBooking?.buildingNotes}
                    </div>
                  </div>
                </div>

                {/* The Professional UI: Therapist Credentials & Contact */}
                <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4 p-5 bg-white dark:bg-zinc-900 border border-zinc-200 dark:border-zinc-800 rounded-2xl">
                  <div className="flex items-center gap-3.5">
                    <Avatar size="lg" className="ring-2 ring-emerald-500/20 shrink-0">
                      <AvatarImage
                        src={activeBooking?.therapist.avatar ?? ''}
                        alt={activeBooking?.therapist.name ?? ''}
                      />
                      <AvatarFallback className="bg-zinc-100 dark:bg-zinc-800 font-bold">
                        {(activeBooking?.therapist.name ?? 'P').charAt(0)}
                      </AvatarFallback>
                    </Avatar>

                    <div>
                      <div className="flex items-center gap-2">
                        <span className="font-extrabold text-sm sm:text-base text-zinc-900 dark:text-white">
                          {activeBooking?.therapist.name ?? ''}
                        </span>
                        <span className="inline-flex items-center gap-1 text-[10px] font-bold text-emerald-700 dark:text-emerald-400 bg-emerald-50 dark:bg-emerald-950/60 border border-emerald-200/80 dark:border-emerald-800/80 px-2 py-0.5 rounded-full">
                          <ShieldCheck className="w-3 h-3" />
                          <span>{isAr ? 'معتمدة' : 'Verified Pro'}</span>
                        </span>
                      </div>
                      <div className="text-xs text-zinc-500 dark:text-zinc-400">
                        {isAr ? (activeBooking?.therapist.roleAr ?? '') : (activeBooking?.therapist.roleEn ?? '')}
                      </div>
                      <div className="flex items-center gap-1 text-xs font-bold text-zinc-900 dark:text-zinc-100 mt-1">
                        <Star className="w-3.5 h-3.5 fill-amber-500 text-amber-500" />
                        <span>{activeBooking?.therapist.rating ?? 0}</span>
                        <span className="text-zinc-400 font-normal">
                          ({activeBooking?.therapist.reviewCount ?? 0} {isAr ? 'تقييم' : 'reviews'})
                        </span>
                      </div>
                    </div>
                  </div>

                  {/* WhatsApp Contact Action (variant="outline") */}
                  <div className="flex items-center gap-2 self-start sm:self-auto">
                    <a
                      href={activeBooking?.therapist.whatsapp ?? '#'}
                      target="_blank"
                      rel="noopener noreferrer"
                      className="inline-flex items-center justify-center gap-2 px-4 py-2.5 border border-zinc-300 dark:border-zinc-700 hover:border-emerald-500 dark:hover:border-emerald-500 bg-white dark:bg-zinc-800/60 hover:bg-emerald-50/50 dark:hover:bg-emerald-950/30 text-zinc-900 dark:text-white rounded-xl text-xs font-bold transition-all cursor-pointer shadow-2xs"
                    >
                      <MessageCircle className="w-4 h-4 text-emerald-600 dark:text-emerald-400" />
                      <span>{isAr ? 'مراسلة عبر واتساب' : 'Contact on WhatsApp'}</span>
                    </a>
                  </div>
                </div>

                {/* Action Row: Primary "Manage Booking" and secondary "View Invoice" & "Reschedule or Cancel" */}
                <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3 pt-2">
                  <button
                    type="button"
                    onClick={() => setIsManageModalOpen(true)}
                    className="h-12 px-6 bg-zinc-900 hover:bg-brand-500 active:bg-brand-600 dark:bg-white dark:text-zinc-950 dark:hover:bg-brand-500 dark:hover:text-white text-white rounded-xl font-bold text-sm transition-colors shadow-2xs flex items-center justify-center gap-2 cursor-pointer"
                  >
                    <Sliders className="w-4 h-4" />
                    <span>{isAr ? 'إدارة تفاصيل الحجز' : 'Manage Booking'}</span>
                  </button>

                  <div className="flex items-center gap-4 self-center sm:self-auto">
                    <button
                      type="button"
                      onClick={() => activeBooking && handleOpenInvoice(activeBooking)}
                      className="text-xs font-bold text-zinc-600 dark:text-zinc-300 hover:text-zinc-900 dark:hover:text-white underline cursor-pointer flex items-center gap-1"
                    >
                      <FileText className="w-3.5 h-3.5 text-zinc-500" />
                      <span>{isAr ? 'عرض الفاتورة' : 'View Invoice'}</span>
                    </button>

                    <span className="text-zinc-300 dark:text-zinc-700">•</span>

                    <button
                      type="button"
                      onClick={() => setIsCancelModalOpen(true)}
                      className="text-xs font-bold text-rose-600 dark:text-rose-400 hover:text-rose-700 dark:hover:text-rose-300 hover:underline cursor-pointer"
                    >
                      {isAr ? 'إعادة الجدولة أو الإلغاء' : 'Reschedule or Cancel'}
                    </button>
                  </div>
                </div>

              </div>

            </div>
          </TabsContent>

          {/* ────────────────── TAB 2: PAST INVOICES (With Filter & Search Bar) ────────────────── */}
          <TabsContent value="past">
            <div className="space-y-4">

              {/* ── Control Bar: Search & Shadcn Status Filter Dropdown ── */}
              <div className="flex flex-col sm:flex-row justify-between items-center gap-4 mb-6">
                {/* Left Side: Search Input */}
                <div className="relative w-full sm:max-w-xs">
                  <Search className="w-4 h-4 absolute start-3.5 top-1/2 -translate-y-1/2 text-zinc-400 dark:text-zinc-500 pointer-events-none" />
                  <Input
                    type="text"
                    placeholder={isAr ? 'البحث في الحجوزات السابقة...' : 'Search past treatments...'}
                    value={pastSearchQuery}
                    onChange={(e) => setPastSearchQuery(e.target.value)}
                    className="ps-10 h-11 bg-white dark:bg-zinc-900 border-zinc-200 dark:border-zinc-700 text-xs w-full"
                  />
                  {pastSearchQuery && (
                    <button
                      type="button"
                      onClick={() => setPastSearchQuery('')}
                      className="absolute end-3 top-1/2 -translate-y-1/2 text-zinc-400 hover:text-zinc-700 dark:hover:text-zinc-200"
                    >
                      <X className="w-3.5 h-3.5" />
                    </button>
                  )}
                </div>

                {/* Right Side: Shadcn Select Filter Dropdown */}
                <div className="w-full sm:w-auto">
                  <Select
                    value={pastStatusFilter}
                    onValueChange={(val) => setPastStatusFilter(val as 'all' | 'completed' | 'cancelled' | 'refunded')}
                  >
                    <SelectTrigger className="w-full sm:w-[180px]">
                      <span>
                        {pastStatusFilter === 'all' && (isAr ? 'جميع الحجوزات' : 'All Bookings')}
                        {pastStatusFilter === 'completed' && (isAr ? 'المكتملة' : 'Completed')}
                        {pastStatusFilter === 'cancelled' && (isAr ? 'الملغاة' : 'Cancelled')}
                        {pastStatusFilter === 'refunded' && (isAr ? 'المستردة' : 'Refunded')}
                      </span>
                    </SelectTrigger>
                    <SelectContent align="end">
                      <SelectItem value="all">{isAr ? 'جميع الحجوزات' : 'All Bookings'}</SelectItem>
                      <SelectItem value="completed">{isAr ? 'المكتملة' : 'Completed'}</SelectItem>
                      <SelectItem value="cancelled">{isAr ? 'الملغاة' : 'Cancelled'}</SelectItem>
                      <SelectItem value="refunded">{isAr ? 'المستردة' : 'Refunded'}</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
              </div>

              {/* Past Bookings Rows */}
              {filteredPastBookings.length > 0 ? (
                filteredPastBookings.map((booking) => {
                  const isCompleted = booking.status === 'completed';
                  const isCancelled = booking.status === 'cancelled';
                  const isRefunded = booking.status === 'refunded';

                  return (
                    <div
                      key={booking.id}
                      className="bg-white dark:bg-zinc-900 border border-zinc-200 dark:border-zinc-800 rounded-3xl p-6 shadow-xs flex flex-col md:flex-row md:items-center justify-between gap-6 hover:border-zinc-300 dark:hover:border-zinc-700 transition-all"
                    >
                      {/* Left: Service Image & Metadata */}
                      <div className="flex items-start gap-4 sm:gap-5 flex-1 min-w-0">
                        <div className="w-16 h-16 sm:w-20 sm:h-20 rounded-2xl overflow-hidden relative bg-zinc-100 dark:bg-zinc-800 border border-zinc-200/80 dark:border-zinc-700 shrink-0">
                          <ImageWithFallback
                            src={booking.image}
                            fallbackSrc="/images/fallback-placeholder.svg"
                            alt={isAr ? booking.serviceNameAr : booking.serviceNameEn}
                            fill
                            className="object-cover"
                            sizes="80px"
                          />
                        </div>

                        <div className="space-y-1 min-w-0 flex-1">
                          <div className="flex items-center gap-2 flex-wrap">
                            <span className="text-[11px] font-bold text-zinc-400 dark:text-zinc-500 uppercase tracking-wider">
                              {isAr ? booking.categoryAr : booking.categoryEn}
                            </span>

                            {/* Strict Status Badges */}
                            <span
                              className={cn(
                                'inline-flex items-center gap-1 text-[10px] font-bold px-2 py-0.5 rounded-md border',
                                isCompleted && 'bg-emerald-50 dark:bg-emerald-950/50 text-emerald-700 dark:text-emerald-400 border-emerald-200/70 dark:border-emerald-800/70',
                                isCancelled && 'bg-zinc-100 dark:bg-zinc-800 text-zinc-600 dark:text-zinc-400 border-zinc-200/70 dark:border-zinc-700/70',
                                isRefunded && 'bg-amber-50 dark:bg-amber-950/50 text-amber-700 dark:text-amber-400 border-amber-200/70 dark:border-amber-800/70'
                              )}
                            >
                              {isCompleted && <CheckCircle2 className="w-3 h-3 text-emerald-600" />}
                              {isCancelled && <X className="w-3 h-3 text-zinc-500" />}
                              {isRefunded && <RotateCw className="w-3 h-3 text-amber-600" />}
                              <span>{isAr ? booking.statusTextAr : booking.statusTextEn}</span>
                            </span>
                          </div>

                          <h3 className="font-extrabold text-base sm:text-lg text-zinc-900 dark:text-white leading-snug truncate">
                            {isAr ? booking.serviceNameAr : booking.serviceNameEn}
                          </h3>

                          <div className="flex items-center gap-3 text-xs text-zinc-500 dark:text-zinc-400 flex-wrap pt-0.5">
                            <span className="flex items-center gap-1">
                              <Calendar className="w-3.5 h-3.5 text-zinc-400" />
                              <span>{isAr ? booking.dateAr : booking.dateEn}</span>
                            </span>
                            <span>•</span>
                            <span>{isAr ? `مع ${booking.therapist.name}` : `with ${booking.therapist.name}`}</span>
                          </div>
                        </div>
                      </div>

                      {/* Right: Total Price Paid & Actions */}
                      <div className="flex items-center justify-between md:justify-end gap-5 shrink-0 pt-3 md:pt-0 border-t md:border-t-0 border-zinc-100 dark:border-zinc-800">
                        <div className="text-start md:text-end">
                          <div className="text-xs text-zinc-400 dark:text-zinc-500">
                            {isAr ? 'المبلغ' : 'Amount'}
                          </div>
                          <div className="text-lg font-extrabold text-zinc-900 dark:text-white">
                            AED {booking.pricing.total}
                          </div>
                          {/* BNPL Badge if used */}
                          {booking.pricing.paymentMethod === 'tabby' && (
                            <div className="mt-0.5 flex items-center md:justify-end">
                              <TabbyBadge />
                            </div>
                          )}
                          {booking.pricing.paymentMethod === 'tamara' && (
                            <div className="mt-0.5 flex items-center md:justify-end">
                              <TamaraBadge />
                            </div>
                          )}
                        </div>

                        <div className="flex items-center gap-2">
                          {/* View Invoice Button (Shadcn Dialog Trigger) */}
                          <button
                            type="button"
                            onClick={() => handleOpenInvoice(booking)}
                            className="px-3.5 py-2 border border-zinc-200 dark:border-zinc-700 hover:bg-zinc-100 dark:hover:bg-zinc-800 rounded-xl text-xs font-bold text-zinc-700 dark:text-zinc-300 transition-colors flex items-center gap-1.5 cursor-pointer shadow-2xs"
                          >
                            <FileText className="w-3.5 h-3.5 text-zinc-500" />
                            <span>{isAr ? 'الفاتورة' : 'Invoice'}</span>
                          </button>

                          {/* Rebook Button */}
                          <button
                            type="button"
                            onClick={() => handleRebook(booking.serviceSlug)}
                            className="px-4 py-2 bg-zinc-100 hover:bg-zinc-200 dark:bg-zinc-800 dark:hover:bg-zinc-700 text-zinc-900 dark:text-white rounded-xl text-xs font-bold transition-colors flex items-center gap-1.5 cursor-pointer shadow-2xs"
                          >
                            <RotateCw className="w-3.5 h-3.5 text-brand-500" />
                            <span>{isAr ? 'إعادة الحجز' : 'Rebook'}</span>
                          </button>
                        </div>
                      </div>
                    </div>
                  );
                })
              ) : (
                /* Empty state when filters return no match */
                <div className="p-12 text-center bg-white dark:bg-zinc-900 border border-zinc-200 dark:border-zinc-800 rounded-3xl space-y-3">
                  <div className="w-12 h-12 rounded-full bg-zinc-100 dark:bg-zinc-800 flex items-center justify-center mx-auto text-zinc-400">
                    <Search className="w-5 h-5" />
                  </div>
                  <h4 className="font-extrabold text-base text-zinc-900 dark:text-white">
                    {isAr ? 'لا توجد حجوزات مطابقة للبحث' : 'No past bookings found'}
                  </h4>
                  <p className="text-xs text-zinc-500 dark:text-zinc-400 max-w-sm mx-auto">
                    {isAr
                      ? 'جربي تعديل كلمات البحث أو تصفية الحالات للعثور على فواتيرك.'
                      : 'Try adjusting your search terms or filter selection to find your past invoices.'}
                  </p>
                  <button
                    type="button"
                    onClick={() => {
                      setPastSearchQuery('');
                      setPastStatusFilter('all');
                    }}
                    className="px-4 py-2 bg-zinc-900 dark:bg-white text-white dark:text-zinc-950 rounded-xl text-xs font-bold transition-colors cursor-pointer"
                  >
                    {isAr ? 'مسح التصفية' : 'Clear Filters'}
                  </button>
                </div>
              )}
            </div>
          </TabsContent>

          {/* ────────────────── TAB 3: SETTINGS (Profile + Wellness Profile + Upgraded Addresses + Danger Zone) ────────────────── */}
          <TabsContent value="settings">
            <div className="space-y-6">

              {/* 1. Profile Card with Large Interactive Avatar, Verification Badges & Inline Email Edit */}
              <div className="bg-white dark:bg-zinc-900 border border-zinc-200 dark:border-zinc-800 rounded-3xl p-6 sm:p-8 shadow-xs space-y-6">
                <div className="flex items-center justify-between">
                  <h3 className="text-lg font-bold text-zinc-900 dark:text-white flex items-center gap-2">
                    <UserIcon className="w-5 h-5 text-brand-500" />
                    <span>{isAr ? 'الملف الشخصي والتحقق' : 'Personal Details & Verification'}</span>
                  </h3>
                </div>

                {/* Profile Avatar Hover-State UI & Clean Centered Info */}
                <div className="flex flex-col items-center justify-center p-8 bg-zinc-50 dark:bg-zinc-800/50 rounded-3xl border border-zinc-200/80 dark:border-zinc-700/80 text-center space-y-3">
                  {/* Large interactive Avatar component */}
                  <div
                    onClick={() => fileInputRef.current?.click()}
                    className="relative h-24 w-24 rounded-full overflow-hidden group cursor-pointer border-2 border-zinc-200 dark:border-zinc-700 select-none shadow-sm mx-auto"
                    title={isAr ? 'انقري لتغيير الصورة' : 'Click to change photo'}
                  >
                    {avatarPreview ? (
                      <AvatarImage src={avatarPreview} alt={activeUser.first_name} className="h-full w-full object-cover" />
                    ) : null}
                    <AvatarFallback className="h-full w-full bg-zinc-200 dark:bg-zinc-700 text-zinc-900 dark:text-white font-extrabold text-2xl flex items-center justify-center">
                      {initials}
                    </AvatarFallback>

                    {/* Hover State Overlay */}
                    <div className="absolute inset-0 bg-black/40 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity duration-200">
                      <Camera className="w-6 h-6 text-white drop-shadow-md" />
                    </div>
                  </div>

                  {/* Hidden File Input */}
                  <input
                    ref={fileInputRef}
                    type="file"
                    accept="image/*"
                    onChange={handleAvatarFileChange}
                    className="hidden"
                  />

                  {/* User's Name and Verified Badge under the avatar */}
                  <div className="space-y-1.5 flex flex-col items-center">
                    <div className="flex items-center justify-center gap-2 flex-wrap">
                      <span className="font-extrabold text-xl sm:text-2xl text-zinc-900 dark:text-white leading-tight">
                        {activeUser.first_name} {activeUser.last_name}
                      </span>
                      <span className="text-[10px] font-bold text-emerald-700 dark:text-emerald-400 bg-emerald-100 dark:bg-emerald-950 px-2.5 py-0.5 rounded-full shrink-0 flex items-center gap-1">
                        <ShieldCheck className="w-3 h-3" />
                        <span>{isAr ? 'عضوية موثقة' : 'Verified Member'}</span>
                      </span>
                    </div>

                    {uploadSuccess && (
                      <p className="text-xs text-emerald-600 dark:text-emerald-400 font-bold pt-0.5 flex items-center justify-center gap-1 animate-in fade-in">
                        <Check className="w-3.5 h-3.5" />
                        <span>{isAr ? 'تم تحديث الصورة بنجاح!' : 'Profile photo updated successfully!'}</span>
                      </p>
                    )}
                  </div>
                </div>

                {/* Personal Information Fields with Granular Verification Badges & Inline Email Edit */}
                <div className="grid grid-cols-1 sm:grid-cols-3 gap-4 pt-1">

                  {/* Full Name */}
                  <div className="p-4 bg-zinc-50 dark:bg-zinc-800/50 rounded-2xl border border-zinc-100 dark:border-zinc-800 space-y-1.5">
                    <div className="text-xs text-zinc-400 dark:text-zinc-500 font-medium">
                      {isAr ? 'الاسم بالكامل' : 'Full Name'}
                    </div>
                    <div className="font-bold text-sm text-zinc-900 dark:text-white">
                      {activeUser.first_name} {activeUser.last_name}
                    </div>
                  </div>

                  {/* Email with Verification Badge & Inline Edit */}
                  <div className="p-4 bg-zinc-50 dark:bg-zinc-800/50 rounded-2xl border border-zinc-100 dark:border-zinc-800 space-y-1.5">
                    <div className="flex items-center justify-between gap-1">
                      <span className="text-xs text-zinc-400 dark:text-zinc-500 font-medium">
                        {isAr ? 'البريد الإلكتروني' : 'Email Address'}
                      </span>
                      {/* Granular Verification Badge */}
                      <span className="inline-flex items-center gap-1 px-2 py-0.5 bg-emerald-50 dark:bg-emerald-950/60 text-emerald-700 dark:text-emerald-400 rounded-md text-[10px] font-bold uppercase tracking-wider border border-emerald-200/60 dark:border-emerald-800/60">
                        <BadgeCheck className="w-3 h-3 text-emerald-600 dark:text-emerald-400" />
                        <span>{isAr ? 'موثق' : 'Verified'}</span>
                      </span>
                    </div>

                    {isEditingEmail ? (
                      <div className="flex items-center gap-1.5 pt-0.5">
                        <Input
                          type="email"
                          value={editableEmail}
                          onChange={(e) => setEditableEmail(e.target.value)}
                          className="h-8 text-xs bg-white dark:bg-zinc-900 border-zinc-300 dark:border-zinc-700 font-medium"
                          autoFocus
                        />
                        <button
                          type="button"
                          onClick={handleSaveEmail}
                          className="px-2.5 py-1.5 bg-zinc-900 hover:bg-brand-500 dark:bg-white dark:text-zinc-950 text-white rounded-md text-xs font-bold transition-colors cursor-pointer shrink-0"
                        >
                          {isAr ? 'حفظ' : 'Save'}
                        </button>
                        <button
                          type="button"
                          onClick={() => {
                            setEditableEmail(activeUser.email || '');
                            setIsEditingEmail(false);
                          }}
                          className="p-1 text-zinc-400 hover:text-zinc-700 dark:hover:text-zinc-200 cursor-pointer shrink-0"
                        >
                          <X className="w-3.5 h-3.5" />
                        </button>
                      </div>
                    ) : (
                      <div className="flex items-center justify-between gap-2 pt-0.5">
                        <span className="font-bold text-sm text-zinc-900 dark:text-white truncate">
                          {activeUser.email}
                        </span>
                        <button
                          type="button"
                          onClick={() => {
                            setEditableEmail(activeUser.email || '');
                            setIsEditingEmail(true);
                          }}
                          className="p-1 text-zinc-400 hover:text-zinc-900 dark:hover:text-white transition-colors cursor-pointer shrink-0"
                          title={isAr ? 'تعديل البريد الإلكتروني' : 'Edit Email'}
                        >
                          <Edit2 className="w-3.5 h-3.5" />
                        </button>
                      </div>
                    )}

                    {emailSuccessMessage && (
                      <p className="text-[11px] text-emerald-600 dark:text-emerald-400 font-bold pt-0.5 animate-in fade-in">
                        {isAr ? 'تم حفظ البريد الجديد بنجاح' : 'Email updated successfully'}
                      </p>
                    )}
                  </div>

                  {/* UAE Phone with Verification Badge */}
                  <div className="p-4 bg-zinc-50 dark:bg-zinc-800/50 rounded-2xl border border-zinc-100 dark:border-zinc-800 space-y-1.5">
                    <div className="flex items-center justify-between gap-1">
                      <span className="text-xs text-zinc-400 dark:text-zinc-500 font-medium">
                        {isAr ? 'رقم الهاتف (الإمارات)' : 'UAE Phone'}
                      </span>
                      {/* Granular Verification Badge */}
                      <span className="inline-flex items-center gap-1 px-2 py-0.5 bg-emerald-50 dark:bg-emerald-950/60 text-emerald-700 dark:text-emerald-400 rounded-md text-[10px] font-bold uppercase tracking-wider border border-emerald-200/60 dark:border-emerald-800/60">
                        <BadgeCheck className="w-3 h-3 text-emerald-600 dark:text-emerald-400" />
                        <span>{isAr ? 'موثق' : 'Verified'}</span>
                      </span>
                    </div>
                    <div className="font-bold text-sm text-zinc-900 dark:text-white pt-0.5 font-mono">
                      {activeUser.phone || '+971 50 123 4567'}
                    </div>
                  </div>

                </div>
              </div>

              {/* 2. SECTION: "Wellness Profile (Optional)" with Shadcn Select Dropdowns */}
              <div className="bg-white dark:bg-zinc-900 border border-zinc-200 dark:border-zinc-800 rounded-3xl p-6 sm:p-8 shadow-xs space-y-6">
                <div>
                  <h3 className="text-lg font-bold text-zinc-900 dark:text-white flex items-center gap-2">
                    <Heart className="w-5 h-5 text-rose-500" />
                    <span>{isAr ? 'الملف الصحي والتفضيلات (اختياري)' : 'Wellness Profile (Optional)'}</span>
                  </h3>
                  <p className="text-xs sm:text-sm text-zinc-500 dark:text-zinc-400 mt-1">
                    {isAr
                      ? 'ساعدينا في تخصيص أفضل تجربة عناية مناسبة لكِ ومشاركتكِ هدايا أعياد الميلاد.'
                      : 'Help us personalize your treatments and unlock birthday rewards.'}
                  </p>
                </div>

                <form onSubmit={handleSaveWellness} className="space-y-6">
                  {/* Grid Layout: DOB, Gender, Skin/Hair Type */}
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                    {/* Date of Birth (Shadcn DatePicker Dropdown) */}
                    <div className="space-y-2">
                      <label className="text-xs font-bold uppercase tracking-wider text-zinc-500 dark:text-zinc-400 block">
                        {isAr ? 'تاريخ الميلاد (لعروض عيد الميلاد)' : 'Date of Birth (Birthday Promos)'}
                      </label>
                      <DatePicker
                        value={wellness.dateOfBirth}
                        onChange={(dateStr) => setWellness({ ...wellness, dateOfBirth: dateStr })}
                        placeholder={isAr ? 'اختاري تاريخ الميلاد' : 'Select Date of Birth'}
                        locale={locale}
                        minYear={1940}
                        maxYear={2015}
                      />
                    </div>

                    {/* Gender (Shadcn Select) */}
                    <div className="space-y-2">
                      <label className="text-xs font-bold uppercase tracking-wider text-zinc-500 dark:text-zinc-400 block">
                        {isAr ? 'الجنس' : 'Gender'}
                      </label>
                      <Select
                        value={wellness.gender}
                        onValueChange={(val) => setWellness({ ...wellness, gender: val as WellnessProfile['gender'] })}
                      >
                        <SelectTrigger className="bg-zinc-50/50 dark:bg-zinc-800/50">
                          <span>
                            {wellness.gender === 'female' && (isAr ? 'أنثى' : 'Female')}
                            {wellness.gender === 'male' && (isAr ? 'ذكر' : 'Male')}
                            {wellness.gender === 'prefer_not_to_say' && (isAr ? 'أفضل عدم التحديد' : 'Prefer not to say')}
                            {!wellness.gender && (isAr ? 'اختر الجنس' : 'Select Gender')}
                          </span>
                        </SelectTrigger>
                        <SelectContent>
                          <SelectItem value="female">{isAr ? 'أنثى' : 'Female'}</SelectItem>
                          <SelectItem value="male">{isAr ? 'ذكر' : 'Male'}</SelectItem>
                          <SelectItem value="prefer_not_to_say">{isAr ? 'أفضل عدم التحديد' : 'Prefer not to say'}</SelectItem>
                        </SelectContent>
                      </Select>
                    </div>

                    {/* Skin/Hair Type (Shadcn Select) */}
                    <div className="space-y-2 md:col-span-2">
                      <label className="text-xs font-bold uppercase tracking-wider text-zinc-500 dark:text-zinc-400 block">
                        {isAr ? 'نوع البشرة أو الشعر' : 'Skin / Hair Type'}
                      </label>
                      <Select
                        value={wellness.skinHairType}
                        onValueChange={(val) => setWellness({ ...wellness, skinHairType: val as WellnessProfile['skinHairType'] })}
                      >
                        <SelectTrigger className="bg-zinc-50/50 dark:bg-zinc-800/50">
                          <span>
                            {wellness.skinHairType === 'normal' && (isAr ? 'عادية (Normal)' : 'Normal')}
                            {wellness.skinHairType === 'dry' && (isAr ? 'جافة (Dry)' : 'Dry')}
                            {wellness.skinHairType === 'oily' && (isAr ? 'دهنية (Oily)' : 'Oily')}
                            {wellness.skinHairType === 'combination' && (isAr ? 'مختلطة (Combination)' : 'Combination')}
                            {wellness.skinHairType === 'sensitive' && (isAr ? 'حساسة (Sensitive)' : 'Sensitive')}
                            {!wellness.skinHairType && (isAr ? 'اختر نوع البشرة / الشعر' : 'Select Skin / Hair Type')}
                          </span>
                        </SelectTrigger>
                        <SelectContent>
                          <SelectItem value="normal">{isAr ? 'عادية (Normal)' : 'Normal'}</SelectItem>
                          <SelectItem value="dry">{isAr ? 'جافة (Dry)' : 'Dry'}</SelectItem>
                          <SelectItem value="oily">{isAr ? 'دهنية (Oily)' : 'Oily'}</SelectItem>
                          <SelectItem value="combination">{isAr ? 'مختلطة (Combination)' : 'Combination'}</SelectItem>
                          <SelectItem value="sensitive">{isAr ? 'حساسة (Sensitive)' : 'Sensitive'}</SelectItem>
                        </SelectContent>
                      </Select>
                    </div>

                    {/* Allergies & Sensitivities (Full Width) */}
                    <div className="space-y-2 md:col-span-2">
                      <label className="text-xs font-bold uppercase tracking-wider text-zinc-500 dark:text-zinc-400 block">
                        {isAr ? 'الحساسية والملاحظات الخاصة' : 'Allergies & Sensitivities'}
                      </label>
                      <Textarea
                        value={wellness.allergies}
                        onChange={(e) => setWellness({ ...wellness, allergies: e.target.value })}
                        placeholder={isAr
                          ? 'مثال: حساسية من العطور الاصطناعية، أظافر حساسة، تفضيل منتجات آمنة للحمل أو زيوت عطرية محددة...'
                          : 'e.g., skin sensitivities, ingredient allergies, pregnancy-safe formulas, or products to avoid...'}
                        className="min-h-[100px] bg-zinc-50/50 dark:bg-zinc-800/50 border-zinc-200 dark:border-zinc-700 text-xs leading-relaxed"
                      />
                    </div>
                  </div>

                  {/* Save Preferences Button (Bottom Right) */}
                  <div className="flex items-center justify-between pt-2 border-t border-zinc-100 dark:border-zinc-800">
                    <div>
                      {wellnessSaved && (
                        <span className="text-xs font-bold text-emerald-600 dark:text-emerald-400 inline-flex items-center gap-1.5">
                          <Check className="w-4 h-4" />
                          <span>{isAr ? 'تم حفظ التفضيلات بنجاح!' : 'Preferences saved successfully!'}</span>
                        </span>
                      )}
                    </div>

                    <button
                      type="submit"
                      className="px-6 py-2.5 bg-zinc-900 hover:bg-brand-500 active:bg-brand-600 dark:bg-white dark:text-zinc-950 dark:hover:bg-brand-500 dark:hover:text-white text-white rounded-xl text-xs font-bold transition-colors shadow-2xs cursor-pointer select-none"
                    >
                      {isAr ? 'حفظ التفضيلات' : 'Save Preferences'}
                    </button>
                  </div>
                </form>
              </div>

              {/* 3. UPGRADED "Saved UAE Addresses" Card with Gate Code & Permanent Notes */}
              <div className="bg-white dark:bg-zinc-900 border border-zinc-200 dark:border-zinc-800 rounded-3xl p-6 sm:p-8 shadow-xs space-y-5">
                <div className="flex items-center justify-between flex-wrap gap-2">
                  <div>
                    <h3 className="text-lg font-bold text-zinc-900 dark:text-white flex items-center gap-2">
                      <MapPin className="w-5 h-5 text-brand-500" />
                      <span>{isAr ? 'العناوين المحفوظة في الإمارات' : 'Saved UAE Addresses'}</span>
                    </h3>
                    <p className="text-xs text-zinc-500 dark:text-zinc-400 mt-0.5">
                      {isAr
                        ? 'احفظي تعليمات الدخول ورمز البوابة لتطبيقها تلقائياً عند كل حجز'
                        : 'Store permanent gate codes and access notes for 1-click checkout'}
                    </p>
                  </div>

                  <button
                    type="button"
                    onClick={handleOpenNewAddressModal}
                    className="inline-flex items-center gap-1.5 px-3.5 py-1.5 bg-zinc-100 hover:bg-zinc-200 dark:bg-zinc-800 dark:hover:bg-zinc-700 text-zinc-900 dark:text-white rounded-xl text-xs font-bold transition-colors cursor-pointer shadow-2xs"
                  >
                    <Plus className="w-3.5 h-3.5" />
                    <span>{isAr ? 'إضافة عنوان جديد' : 'Add New Address'}</span>
                  </button>
                </div>

                <div className="space-y-3.5 pt-1">
                  {savedAddresses.map((addr) => (
                    <div
                      key={addr.id}
                      className="p-5 bg-zinc-50/70 dark:bg-zinc-800/50 rounded-2xl border border-zinc-200/80 dark:border-zinc-700/80 space-y-3"
                    >
                      <div className="flex items-start justify-between gap-4">
                        <div className="space-y-1">
                          <div className="flex items-center gap-2">
                            <span className="font-extrabold text-sm text-zinc-900 dark:text-white">
                              {addr.label}
                            </span>
                            {addr.isDefault && (
                              <span className="text-[10px] font-bold text-emerald-700 dark:text-emerald-400 bg-emerald-100 dark:bg-emerald-950 px-2 py-0.5 rounded-full">
                                {isAr ? 'العنوان الافتراضي' : 'Default'}
                              </span>
                            )}
                          </div>
                          <p className="text-xs text-zinc-600 dark:text-zinc-300 font-medium">
                            {addr.addressLine}
                          </p>
                        </div>

                        {/* Actions: Edit & Delete */}
                        <div className="flex items-center gap-2 shrink-0">
                          <button
                            type="button"
                            onClick={() => handleOpenEditAddressModal(addr)}
                            className="p-1.5 text-zinc-500 hover:text-zinc-900 dark:hover:text-white hover:bg-zinc-200/60 dark:hover:bg-zinc-700 rounded-lg transition-colors cursor-pointer"
                            title={isAr ? 'تعديل' : 'Edit'}
                          >
                            <Edit3 className="w-4 h-4" />
                          </button>
                          {savedAddresses.length > 1 && (
                            <button
                              type="button"
                              onClick={() => handleDeleteAddress(addr.id)}
                              className="p-1.5 text-zinc-400 hover:text-rose-600 hover:bg-rose-50 dark:hover:bg-rose-950/40 rounded-lg transition-colors cursor-pointer"
                              title={isAr ? 'حذف' : 'Delete'}
                            >
                              <Trash2 className="w-4 h-4" />
                            </button>
                          )}
                        </div>
                      </div>

                      {/* Operational Badges: Gate Code & Permanent Notes */}
                      <div className="pt-2 border-t border-zinc-200/60 dark:border-zinc-700/60 grid grid-cols-1 sm:grid-cols-2 gap-2 text-xs">
                        {addr.gateCode && (
                          <div className="flex items-center gap-2 text-zinc-700 dark:text-zinc-300 bg-white dark:bg-zinc-800/80 px-3 py-1.5 rounded-xl border border-zinc-200/60 dark:border-zinc-700">
                            <KeyRound className="w-3.5 h-3.5 text-amber-500 shrink-0" />
                            <span className="font-semibold">{isAr ? 'رمز البوابة:' : 'Gate/Intercom:'}</span>
                            <span className="font-mono text-zinc-900 dark:text-white">{addr.gateCode}</span>
                          </div>
                        )}

                        {addr.permanentNotes && (
                          <div className="flex items-start gap-2 text-zinc-600 dark:text-zinc-400 bg-white dark:bg-zinc-800/80 px-3 py-1.5 rounded-xl border border-zinc-200/60 dark:border-zinc-700 sm:col-span-2">
                            <Building className="w-3.5 h-3.5 text-zinc-400 shrink-0 mt-0.5" />
                            <span className="line-clamp-1">{addr.permanentNotes}</span>
                          </div>
                        )}
                      </div>
                    </div>
                  ))}
                </div>
              </div>

              {/* 4. DANGER ZONE (Refined Luxury Safety Card) */}
              <div className="bg-white dark:bg-zinc-900 border border-zinc-200 dark:border-zinc-800 rounded-3xl p-6 sm:p-8 shadow-xs mt-12 space-y-4">
                <div className="space-y-1">
                  <div className="flex items-center gap-2 flex-wrap">
                    <ShieldAlert className="w-4 h-4 text-rose-500 shrink-0" />
                    <h4 className="text-sm sm:text-base font-bold text-zinc-900 dark:text-white">
                      {isAr ? 'منطقة الخطر وحذف الحساب' : 'Account Deletion & Data Privacy'}
                    </h4>
                    <span className="text-[10px] font-bold text-zinc-600 dark:text-zinc-400 bg-zinc-100 dark:bg-zinc-800 border border-zinc-200 dark:border-zinc-700 px-2 py-0.5 rounded-md">
                      {isAr ? 'حذف نهائي بعد 6 أشهر' : 'Deleted after 6 months'}
                    </span>
                  </div>
                  <p className="text-xs text-zinc-500 dark:text-zinc-400 leading-relaxed max-w-2xl">
                    {isAr
                      ? 'طلب تعطيل الحساب. عند تقديم الطلب، يدخل حسابك في مهلة مدتها 6 أشهر ويتم حذفه نهائياً بعدها. يرجى ملاحظة أنه يجب سداد وتسوية أي مبالغ مستحقة أو فواتير معلقة أو أقساط متبقية (تابي / تمارا) بالكامل قبل سريان الحذف.'
                      : 'Request account deactivation. Upon request, your account will enter a 6-month grace period and be permanently deleted after 6 months. All remaining balances, pending invoices, or active installments (Tabby / Tamara) must be fully cleared before deletion.'}
                  </p>
                </div>

                <div className="pt-1 flex justify-end">
                  <button
                    type="button"
                    onClick={() => {
                      setDeleteConfirmationText('');
                      setIsDeleteModalOpen(true);
                    }}
                    className="inline-flex items-center justify-center gap-1.5 h-8 px-3.5 border border-rose-200 dark:border-rose-900/60 bg-rose-50/60 dark:bg-rose-950/30 text-rose-600 dark:text-rose-400 hover:bg-rose-600 hover:text-white hover:border-rose-600 dark:hover:bg-rose-600 dark:hover:text-white dark:hover:border-rose-600 rounded-lg text-xs font-bold transition-all duration-150 cursor-pointer shadow-2xs group"
                  >
                    <Trash2 className="w-3.5 h-3.5 text-rose-500 group-hover:text-white transition-colors" />
                    <span>{isAr ? 'طلب حذف الحساب' : 'Request Account Deletion'}</span>
                  </button>
                </div>
              </div>

            </div>
          </TabsContent>
        </Tabs>

      </div>

      {/* ────────────────── DELETE ACCOUNT CONFIRMATION MODAL (Strict Guardrail & Rich UX) ────────────────── */}
      <Dialog open={isDeleteModalOpen} onOpenChange={setIsDeleteModalOpen}>
        <DialogContent className="sm:max-w-md space-y-6">
          <DialogHeader className="text-start space-y-2">
            <div className="w-12 h-12 rounded-2xl bg-rose-50 dark:bg-rose-950/60 border border-rose-200 dark:border-rose-800 text-rose-600 flex items-center justify-center mb-1">
              <AlertTriangle className="w-6 h-6" />
            </div>
            <DialogTitle className="text-xl font-extrabold text-zinc-900 dark:text-white">
              {isAr ? 'طلب حذف الحساب (نهائياً بعد 6 أشهر)' : 'Request Account Deletion'}
            </DialogTitle>
            <DialogDescription className="text-xs text-zinc-500 dark:text-zinc-400 leading-relaxed">
              {isAr
                ? 'سيتم تعطيل حسابك فوراً وجدولته للحذف النهائي بعد 6 أشهر. يرجى مراجعة الشروط التالية:'
                : 'Your account will be deactivated immediately and permanently deleted after 6 months. Please review the conditions below:'}
            </DialogDescription>
          </DialogHeader>

          {/* Impact Breakdown Callout Box */}
          <div className="p-4 bg-rose-50/60 dark:bg-rose-950/30 border border-rose-100 dark:border-rose-900/60 rounded-2xl space-y-2.5 text-xs text-zinc-700 dark:text-zinc-300">
            <div className="flex items-start gap-2">
              <span className="text-rose-600 font-bold">•</span>
              <span>
                <strong className="text-zinc-900 dark:text-white">{isAr ? 'الحذف النهائي بعد 6 أشهر:' : 'Permanent Deletion after 6 Months:'} </strong>
                {isAr
                  ? 'يتم تعطيل الحساب فوراً ويُحذف نهائياً بعد 6 أشهر. يمكنكِ إلغاء الطلب واستعادة الحساب في أي وقت خلال هذه الفترة بتسجيل الدخول.'
                  : 'Account will be deactivated immediately and permanently deleted after 6 months. You can cancel this request anytime within 6 months by logging in.'}
              </span>
            </div>
            <div className="flex items-start gap-2">
              <span className="text-rose-600 font-bold">•</span>
              <span>
                <strong className="text-zinc-900 dark:text-white">{isAr ? 'تسوية المستحقات المالية:' : 'Clear Pending Balances:'} </strong>
                {isAr
                  ? 'يجب سداد وتسوية أي مبالغ مستحقة أو فواتير معلقة أو أقساط متبقية (تابي / تمارا) بالكامل قبل اكتمال الحذف.'
                  : 'Any remaining balances, pending invoices, or active installment schedules (Tabby / Tamara) must be fully settled before deletion.'}
              </span>
            </div>
            <div className="flex items-start gap-2">
              <span className="text-rose-600 font-bold">•</span>
              <span>{isAr ? 'سيتم مسح العناوين المحفوظة وتفضيلات العناية وعروض أعياد الميلاد بعد انتهاء المهلة.' : 'Saved addresses, wellness preferences, and membership records will be permanently wiped.'}</span>
            </div>
          </div>

          {/* Guardrail Typing Box */}
          <div className="space-y-2">
            <label className="text-xs font-semibold text-zinc-700 dark:text-zinc-300 block">
              {isAr ? (
                <span>للتأكيد، يرجى كتابة <strong className="font-mono text-rose-600 px-1 bg-rose-50 dark:bg-rose-950 rounded">DELETE</strong> في الخانة أدناه:</span>
              ) : (
                <span>To confirm, please type <strong className="font-mono text-rose-600 px-1 bg-rose-50 dark:bg-rose-950 rounded">DELETE</strong> below:</span>
              )}
            </label>
            <div className="relative">
              <Input
                type="text"
                value={deleteConfirmationText}
                onChange={(e) => setDeleteConfirmationText(e.target.value)}
                placeholder="Type DELETE to confirm"
                className="h-10 font-mono uppercase bg-zinc-50/50 dark:bg-zinc-900 border-zinc-300 dark:border-zinc-700 text-xs pe-10"
                autoFocus
              />
              {isDeleteConfirmed && (
                <div className="absolute end-3 top-1/2 -translate-y-1/2 text-emerald-600 animate-in fade-in">
                  <CheckCircle2 className="w-4 h-4" />
                </div>
              )}
            </div>
          </div>

          {/* Action Buttons */}
          <div className="flex gap-3 pt-2">
            <button
              type="button"
              onClick={() => setIsDeleteModalOpen(false)}
              className="flex-1 h-10 bg-zinc-900 hover:bg-black active:bg-zinc-800 text-white dark:bg-white dark:text-zinc-950 dark:hover:bg-zinc-100 font-bold rounded-xl text-xs transition-colors cursor-pointer shadow-2xs"
            >
              {isAr ? 'الاحتفاظ بحسابي' : 'Keep My Account'}
            </button>
            <button
              type="button"
              disabled={!isDeleteConfirmed}
              onClick={handleConfirmAccountDeletion}
              className={cn(
                'flex-1 h-10 border border-rose-300 dark:border-rose-800 bg-rose-50 dark:bg-rose-950/50 text-rose-600 dark:text-rose-400 hover:bg-rose-600 hover:text-white font-bold rounded-xl text-xs transition-all shadow-xs flex items-center justify-center gap-1.5',
                !isDeleteConfirmed ? 'opacity-40 cursor-not-allowed border-zinc-200 text-zinc-400 dark:text-zinc-600 bg-transparent' : 'cursor-pointer active:scale-[0.99]'
              )}
            >
              <Trash2 className="w-3.5 h-3.5" />
              <span>{isAr ? 'تأكيد الطلب' : 'Confirm Request'}</span>
            </button>
          </div>
        </DialogContent>
      </Dialog>

      {/* ────────────────── ADD / EDIT ADDRESS DIALOG (Shadcn Dialog) ────────────────── */}
      <Dialog open={isAddressModalOpen} onOpenChange={setIsAddressModalOpen}>
        <DialogContent className="sm:max-w-lg space-y-5">
          <DialogHeader className="text-start space-y-1">
            <div className="flex items-center gap-2 text-xs font-bold uppercase tracking-wider text-brand-600 dark:text-brand-400">
              <MapPin className="w-4 h-4" />
              <span>{isAr ? 'تفاصيل الموقع' : 'Location Details'}</span>
            </div>
            <DialogTitle className="text-xl font-extrabold text-zinc-900 dark:text-white">
              {editingAddressId ? (isAr ? 'تعديل العنوان' : 'Edit Address') : (isAr ? 'إضافة عنوان جديد' : 'Add New Address')}
            </DialogTitle>
            <DialogDescription className="text-xs text-zinc-500 dark:text-zinc-400">
              {isAr
                ? 'أدخلي تفاصيل موقعكِ وتعليمات الدخول الدائمة لتسريع عمليات الحجز القادمة.'
                : 'Save permanent access codes and instructions for effortless 1-click booking.'}
            </DialogDescription>
          </DialogHeader>

          <form onSubmit={handleSaveAddress} className="space-y-4 text-xs sm:text-sm">
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
              {/* Address Label */}
              <div className="space-y-1.5">
                <label className="text-xs font-bold text-zinc-700 dark:text-zinc-300 block">
                  {isAr ? 'اسم العنوان (مثال: المنزل، الفيلا)' : 'Address Label (e.g. Home, Villa)'} *
                </label>
                <Input
                  required
                  placeholder={isAr ? 'المنزل' : 'Home'}
                  value={addressForm.label}
                  onChange={(e) => setAddressForm({ ...addressForm, label: e.target.value })}
                  className="h-11 bg-zinc-50/50 dark:bg-zinc-800/50"
                />
              </div>

              {/* Emirate (Shadcn Select) */}
              <div className="space-y-1.5">
                <label className="text-xs font-bold text-zinc-700 dark:text-zinc-300 block">
                  {isAr ? 'الإمارة' : 'Emirate'} *
                </label>
                <Select
                  value={addressForm.emirate}
                  onValueChange={(val) => setAddressForm({ ...addressForm, emirate: val })}
                >
                  <SelectTrigger className="bg-zinc-50/50 dark:bg-zinc-800/50">
                    <span>{addressForm.emirate}</span>
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="Dubai">Dubai</SelectItem>
                    <SelectItem value="Sharjah">Sharjah</SelectItem>
                    <SelectItem value="Ajman">Ajman</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </div>

            {/* Street / Building Address Line */}
            <div className="space-y-1.5">
              <label className="text-xs font-bold text-zinc-700 dark:text-zinc-300 block">
                {isAr ? 'العنوان التفصيلي (البرج، رقم الشقة، الشارع)' : 'Full Address (Building, Apt/Villa, Street)'} *
              </label>
              <Input
                required
                placeholder={isAr ? 'مثال: برج مارينا جيت 2، شقة 1404، دبي مارينا' : 'e.g., Marina Gate Tower 2, Apt 1404, Dubai Marina'}
                value={addressForm.addressLine}
                onChange={(e) => setAddressForm({ ...addressForm, addressLine: e.target.value })}
                className="h-11 bg-zinc-50/50 dark:bg-zinc-800/50"
              />
            </div>

            {/* NEW OPERATIONAL FIELD: Gate Code / Intercom Number */}
            <div className="space-y-1.5">
              <label className="text-xs font-bold text-zinc-700 dark:text-zinc-300 flex items-center gap-1.5">
                <KeyRound className="w-3.5 h-3.5 text-amber-500" />
                <span>{isAr ? 'رمز البوابة / رقم الاتصال الداخلي' : 'Gate Code / Intercom Number'}</span>
              </label>
              <Input
                placeholder={isAr ? 'مثال: #1404 أو رمز البوابة: 9876*' : 'e.g., #1404 or Keypad: 9876*'}
                value={addressForm.gateCode}
                onChange={(e) => setAddressForm({ ...addressForm, gateCode: e.target.value })}
                className="h-11 font-mono bg-zinc-50/50 dark:bg-zinc-800/50"
              />
            </div>

            {/* NEW OPERATIONAL FIELD: Permanent Delivery & Access Notes */}
            <div className="space-y-1.5">
              <label className="text-xs font-bold text-zinc-700 dark:text-zinc-300 block">
                {isAr ? 'تعليمات الوصول الدائمة للأخصائية' : 'Permanent Delivery & Access Notes'}
              </label>
              <Textarea
                placeholder={isAr
                  ? 'مثال: الرنين على شقة 1404 عند الاستقبال. مواقف الزوار متاحة في طابق B1...'
                  : 'e.g., Ring bell 1404 at security reception. Guest parking in basement B1. Beware of friendly dog.'}
                value={addressForm.permanentNotes}
                onChange={(e) => setAddressForm({ ...addressForm, permanentNotes: e.target.value })}
                className="min-h-[80px] bg-zinc-50/50 dark:bg-zinc-800/50 text-xs"
              />
            </div>

            {/* Default Address Checkbox */}
            <div className="flex items-center gap-2 pt-1">
              <input
                type="checkbox"
                id="isDefaultAddr"
                checked={addressForm.isDefault}
                onChange={(e) => setAddressForm({ ...addressForm, isDefault: e.target.checked })}
                className="w-4 h-4 rounded text-zinc-900 focus:ring-zinc-900 cursor-pointer"
              />
              <label htmlFor="isDefaultAddr" className="text-xs font-semibold text-zinc-700 dark:text-zinc-300 cursor-pointer">
                {isAr ? 'تعيين كعنوان افتراضي لجميع الحجوزات' : 'Set as default address for future bookings'}
              </label>
            </div>

            {/* Modal Actions */}
            <div className="pt-3 flex gap-3">
              <button
                type="button"
                onClick={() => setIsAddressModalOpen(false)}
                className="flex-1 h-11 border border-zinc-300 dark:border-zinc-700 hover:bg-zinc-100 dark:hover:bg-zinc-800 text-zinc-900 dark:text-white font-bold rounded-xl text-xs transition-colors cursor-pointer"
              >
                {isAr ? 'إلغاء' : 'Cancel'}
              </button>
              <button
                type="submit"
                className="flex-1 h-11 bg-zinc-900 hover:bg-brand-500 active:bg-brand-600 dark:bg-white dark:text-zinc-950 dark:hover:bg-brand-500 dark:hover:text-white text-white font-bold rounded-xl text-xs transition-colors cursor-pointer shadow-xs"
              >
                {isAr ? 'حفظ العنوان' : 'Save Address'}
              </button>
            </div>
          </form>
        </DialogContent>
      </Dialog>

      {/* ────────────────── ITEMIZED TAX INVOICE DIALOG (Shadcn Dialog) ────────────────── */}
      <Dialog open={isInvoiceOpen} onOpenChange={setIsInvoiceOpen}>
        <DialogContent className="sm:max-w-lg space-y-6">
          <DialogHeader className="text-start space-y-1">
            <div className="flex items-center gap-2 text-xs font-bold uppercase tracking-wider text-emerald-600 dark:text-emerald-400">
              <FileText className="w-4 h-4" />
              <span>{isAr ? 'فاتورة ضريبية رسمية' : 'Official Tax Invoice'}</span>
            </div>
            <DialogTitle className="text-xl font-extrabold text-zinc-900 dark:text-white">
              {selectedInvoice ? (isAr ? selectedInvoice.serviceNameAr : selectedInvoice.serviceNameEn) : 'Tax Invoice'}
            </DialogTitle>
            <DialogDescription className="text-xs text-zinc-500 dark:text-zinc-400">
              {isAr ? 'رقم الفاتورة الضريبية:' : 'Invoice Reference:'} #{selectedInvoice?.reference} • {selectedInvoice ? (isAr ? selectedInvoice.dateAr : selectedInvoice.dateEn) : ''}
            </DialogDescription>
          </DialogHeader>

          {selectedInvoice && (
            <div className="space-y-4 text-xs sm:text-sm">

              {/* Service & Specialist info */}
              <div className="p-4 bg-zinc-50 dark:bg-zinc-800/60 rounded-2xl space-y-2 border border-zinc-200/80 dark:border-zinc-700">
                <div className="flex justify-between font-bold text-zinc-900 dark:text-white">
                  <span>{isAr ? 'الأخصائية المعتمدة:' : 'Certified Specialist:'}</span>
                  <span>{selectedInvoice.therapist.name}</span>
                </div>
                <div className="flex justify-between text-zinc-600 dark:text-zinc-400 text-xs">
                  <span>{isAr ? 'الموقع:' : 'Location:'}</span>
                  <span className="truncate max-w-[240px]">{selectedInvoice.address}</span>
                </div>
                <div className="flex justify-between text-zinc-600 dark:text-zinc-400 text-xs">
                  <span>{isAr ? 'طريقة الدفع:' : 'Payment Method:'}</span>
                  <span className="font-semibold text-zinc-900 dark:text-white">{selectedInvoice.pricing.paymentSummary}</span>
                </div>
              </div>

              {/* Itemized charges */}
              <div className="space-y-2.5 pt-1">
                <div className="flex justify-between text-zinc-700 dark:text-zinc-300">
                  <span>{isAr ? selectedInvoice.serviceNameAr : selectedInvoice.serviceNameEn}</span>
                  <span className="font-bold">AED {selectedInvoice.pricing.basePrice}</span>
                </div>

                {selectedInvoice.pricing.addons.map((addon, idx) => (
                  <div key={idx} className="flex justify-between text-zinc-500 dark:text-zinc-400 text-xs">
                    <span>+ {isAr ? addon.nameAr : addon.nameEn}</span>
                    <span>+ AED {addon.price * addon.qty}</span>
                  </div>
                ))}

                {selectedInvoice.pricing.discount && (
                  <div className="flex justify-between text-emerald-600 dark:text-emerald-400 font-bold text-xs">
                    <span>{isAr ? `كود الخصم (${selectedInvoice.pricing.couponCode})` : `Promo Discount (${selectedInvoice.pricing.couponCode})`}</span>
                    <span>- AED {selectedInvoice.pricing.discount}</span>
                  </div>
                )}

                <div className="flex justify-between text-zinc-500 dark:text-zinc-400 text-xs">
                  <span>{isAr ? 'ضريبة القيمة المضافة (5% VAT)' : 'VAT (5%)'}</span>
                  <span>AED {selectedInvoice.pricing.vat}</span>
                </div>

                <div className="flex justify-between text-zinc-500 dark:text-zinc-400 text-xs">
                  <span>{isAr ? 'رسوم التنقل والخدمة المنزلية' : 'Home Service Travel Surcharge'}</span>
                  <span className="font-bold text-emerald-600 uppercase text-[11px]">
                    {isAr ? 'مجاني' : 'FREE'}
                  </span>
                </div>

                {/* Grand Total */}
                <div className="pt-3 border-t border-zinc-200 dark:border-zinc-700 flex justify-between items-baseline font-extrabold text-base text-zinc-900 dark:text-white">
                  <span>{isAr ? 'المجموع النهائي المدفوع' : 'Total Paid'}</span>
                  <span className="text-xl">AED {selectedInvoice.pricing.total}</span>
                </div>
              </div>

              {/* Action Buttons inside Invoice */}
              <div className="pt-2 flex gap-3">
                <button
                  type="button"
                  onClick={() => window.print()}
                  className="flex-1 h-11 border border-zinc-300 dark:border-zinc-700 hover:bg-zinc-100 dark:hover:bg-zinc-800 text-zinc-900 dark:text-white font-bold rounded-xl text-xs transition-colors cursor-pointer"
                >
                  {isAr ? 'طباعة الفاتورة' : 'Print Invoice'}
                </button>
                <button
                  type="button"
                  onClick={() => setIsInvoiceOpen(false)}
                  className="flex-1 h-11 bg-zinc-900 hover:bg-brand-500 text-white font-bold rounded-xl text-xs transition-colors cursor-pointer"
                >
                  {isAr ? 'إغلاق' : 'Close'}
                </button>
              </div>

            </div>
          )}
        </DialogContent>
      </Dialog>

      {/* ────────────────── MANAGE BOOKING DIALOG ────────────────── */}
      <Dialog open={isManageModalOpen} onOpenChange={setIsManageModalOpen}>
        <DialogContent className="sm:max-w-md space-y-5">
          <DialogHeader className="text-start space-y-1">
            <DialogTitle className="text-xl font-extrabold text-zinc-900 dark:text-white">
              {isAr ? 'إدارة تفاصيل الحجز' : 'Manage Booking'}
            </DialogTitle>
            <DialogDescription className="text-xs text-zinc-500 dark:text-zinc-400">
              {isAr
                ? 'يمكنك تعديل تعليمات الوصول أو الاتصال بخدمة العملاء مباشرة'
                : 'Update arrival notes, gate codes, or reach concierge support'}
            </DialogDescription>
          </DialogHeader>

          <div className="space-y-4 text-xs sm:text-sm">
            <div className="p-4 bg-zinc-50 dark:bg-zinc-800/60 rounded-2xl border border-zinc-200/80 dark:border-zinc-700 space-y-2">
              <div className="font-bold text-zinc-900 dark:text-white">
                {isAr ? 'تعليمات الوصول الحالية:' : 'Current Access Notes:'}
              </div>
              <p className="text-xs text-zinc-600 dark:text-zinc-400">
                {activeBooking?.buildingNotes || (isAr ? 'لا توجد تعليمات وصول إضافية مسجلة' : 'No custom building access notes provided.')}
              </p>
            </div>

            <div className="space-y-2">
              <a
                href={activeBooking?.therapist?.whatsapp || 'https://wa.me/971500000000'}
                target="_blank"
                rel="noopener noreferrer"
                className="w-full h-12 bg-emerald-600 hover:bg-emerald-700 text-white font-bold rounded-xl text-xs transition-colors flex items-center justify-center gap-2 shadow-xs cursor-pointer"
              >
                <MessageCircle className="w-4 h-4" />
                <span>{isAr ? 'التحدث مع الأخصائية مباشرة' : 'Chat with Specialist'}</span>
              </a>

              <button
                type="button"
                onClick={() => {
                  setIsManageModalOpen(false);
                  setIsCancelModalOpen(true);
                }}
                className="w-full h-11 border border-zinc-200 dark:border-zinc-700 hover:bg-zinc-100 dark:hover:bg-zinc-800 text-zinc-700 dark:text-zinc-300 font-bold rounded-xl text-xs transition-colors cursor-pointer"
              >
                {isAr ? 'إعادة الجدولة أو الإلغاء' : 'Reschedule or Cancel Session'}
              </button>
            </div>
          </div>
        </DialogContent>
      </Dialog>

      {/* ────────────────── RESCHEDULE / CANCEL DIALOG ────────────────── */}
      <Dialog open={isCancelModalOpen} onOpenChange={setIsCancelModalOpen}>
        <DialogContent className="sm:max-w-md space-y-5">
          <DialogHeader className="text-start space-y-1">
            <div className="w-10 h-10 rounded-full bg-amber-100 dark:bg-amber-950/60 text-amber-600 flex items-center justify-center mb-1">
              <AlertCircle className="w-5 h-5" />
            </div>
            <DialogTitle className="text-xl font-extrabold text-zinc-900 dark:text-white">
              {isAr ? 'إعادة الجدولة أو إلغاء الموعد' : 'Reschedule or Cancel Booking'}
            </DialogTitle>
            <DialogDescription className="text-xs text-zinc-500 dark:text-zinc-400">
              {isAr
                ? 'إلغاء وإعادة جدولة مجانية بالكامل قبل 4 ساعات من الموعد المحدد.'
                : 'Free cancellation and instant rescheduling up to 4 hours before your booking time.'}
            </DialogDescription>
          </DialogHeader>

          <div className="space-y-3 pt-2">
            <button
              type="button"
              onClick={() => {
                alert(isAr ? 'تم فتح نافذة إعادة الجدولة' : 'Rescheduling window activated');
                setIsCancelModalOpen(false);
              }}
              className="w-full h-12 bg-zinc-900 hover:bg-brand-500 text-white font-bold rounded-xl text-xs transition-colors flex items-center justify-center gap-2 cursor-pointer"
            >
              <Calendar className="w-4 h-4" />
              <span>{isAr ? 'اختيار موعد وتاريخ جديد (مجاناً)' : 'Select New Date & Time (Free)'}</span>
            </button>

            <button
              type="button"
              onClick={() => {
                alert(isAr ? 'تم إلغاء الحجز بنجاح وإرجاع المبلغ' : 'Booking successfully cancelled. Refund processed.');
                setIsCancelModalOpen(false);
              }}
              className="w-full h-12 border border-rose-200 dark:border-rose-900/60 text-rose-600 hover:bg-rose-50 dark:hover:bg-rose-950/40 font-bold rounded-xl text-xs transition-colors flex items-center justify-center gap-2 cursor-pointer"
            >
              <X className="w-4 h-4" />
              <span>{isAr ? 'تأكيد إلغاء الحجز واسترداد المبلغ' : 'Cancel Booking & Full Refund'}</span>
            </button>
          </div>
        </DialogContent>
      </Dialog>

    </div>
  );
}

export default UserDashboardView;
