'use client';

import React, { useEffect, useState, useRef } from 'react';
import { useRouter, usePathname } from 'next/navigation';
import { useAuth } from '@/context/AuthContext';
import { useCart } from '@/context/CartContext';
import { useSiteSettings } from '@/context/SiteSettingsContext';
import api from '@/lib/api';
import { Header } from '@/components/Header';
import { Footer } from '@/components/Footer';
import { SearchableSelect } from '@/components/SearchableSelect';
import { 
  Loader2, 
  Package, 
  User, 
  FileText, 
  ArrowRight, 
  DollarSign, 
  Heart, 
  LayoutDashboard, 
  ShoppingBag, 
  Ticket, 
  MapPin, 
  CreditCard, 
  Star, 
  MessageSquare, 
  Calendar, 
  Lock, 
  Trash2, 
  LogOut, 
  CheckCircle2, 
  AlertCircle,
  Copy,
  Check,
  Home,
  Briefcase,
  Plus,
  X,
  Wallet,
  TrendingUp,
  Upload,
  ArrowLeft,
  Eye,
  EyeOff
} from 'lucide-react';

interface OrderItem {
  id: number;
  product_name: string;
  product_sku: string;
  price: number;
  quantity: number;
  product_id?: number;
}

interface LocationItem {
  id: number;
  name: string;
}

interface DistrictItem extends LocationItem {
  division_id: number;
}

interface Order {
  id: number;
  order_number: string;
  grand_total: number;
  payment_method: string;
  payment_status: string;
  status: string;
  created_at: string;
  items: OrderItem[];
}

interface Coupon {
  id: number;
  code: string;
  type: string;
  value: number;
  min_amount: number;
  starts_at: string | null;
  expires_at: string | null;
  is_active: boolean;
}

export default function DashboardPage() {
  const { formatPrice } = useSiteSettings();
  const router = useRouter();
  const { user, logout, loading: authLoading, checkUser } = useAuth();
  const { cartCount } = useCart();
  
  const [orders, setOrders] = useState<Order[]>([]);
  const [loadingOrders, setLoadingOrders] = useState(true);
  const [coupons, setCoupons] = useState<Coupon[]>([]);
  const [loadingCoupons, setLoadingCoupons] = useState(true);
  const [expandedOrder, setExpandedOrder] = useState<number | null>(null);
  const [mobileMenuOpen, setMobileMenuOpen] = useState(false);

  // URL-based active tab
  const pathname = usePathname();
  const PATH_TO_TAB: Record<string, 'dashboard' | 'orders' | 'wishlist' | 'coupons' | 'address' | 'payments' | 'reviews' | 'tickets' | 'profile' | 'password' | 'delete_account'> = {
    '/dashboard':        'dashboard',
    '/my/orders':        'orders',
    '/my/wishlists':     'wishlist',
    '/my/coupons':       'coupons',
    '/my/address':       'address',
    '/my/payments':      'payments',
    '/my/reviews':       'reviews',
    '/my/tickets':       'tickets',
    '/my/profile':       'profile',
    '/my/password':      'password',
    '/my/delete-account':'delete_account',
  };
  const TAB_TO_PATH = Object.fromEntries(Object.entries(PATH_TO_TAB).map(([p, t]) => [t, p])) as Record<string, string>;
  const activeTab = PATH_TO_TAB[pathname] ?? 'dashboard';

  // Payments states
  interface Transaction {
    id: number;
    order_id: number;
    transaction_id: string;
    payment_method: string;
    amount: number;
    status: string;
    created_at: string;
    order?: Order;
  }

  interface PaymentStats {
    this_month_spent: number;
    last_six_months_spent: number;
    total_spent: number;
  }

  const [transactions, setTransactions] = useState<Transaction[]>([]);
  const [paymentStats, setPaymentStats] = useState<PaymentStats>({
    this_month_spent: 0,
    last_six_months_spent: 0,
    total_spent: 0,
  });
  const [loadingPayments, setLoadingPayments] = useState(true);

  // Reviews states
  interface Review {
    id: number;
    product_id: number;
    rating: number;
    comment: string | null;
    created_at: string;
    product?: {
      id: number;
      name: string;
      image_url: string;
      slug: string;
    };
  }

  const [reviews, setReviews] = useState<Review[]>([]);
  const [loadingReviews, setLoadingReviews] = useState(true);

  // Review submission modal states
  const [showReviewModal, setShowReviewModal] = useState(false);
  const [reviewProduct, setReviewProduct] = useState<{ id: number; name: string } | null>(null);
  const [reviewRating, setReviewRating] = useState(5);
  const [reviewComment, setReviewComment] = useState('');
  const [submittingReview, setSubmittingReview] = useState(false);
  const [reviewError, setReviewError] = useState('');
  const [reviewSuccessMsg, setReviewSuccessMsg] = useState('');

  const handleOpenReviewModal = (productId: number, productName: string) => {
    setReviewProduct({ id: productId, name: productName });
    setReviewRating(5);
    setReviewComment('');
    setReviewError('');
    setReviewSuccessMsg('');
    setShowReviewModal(true);
  };

  const handleReviewSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!reviewProduct) return;
    
    setSubmittingReview(true);
    setReviewError('');
    setReviewSuccessMsg('');
    try {
      const res = await api.post('/api/reviews', {
        product_id: reviewProduct.id,
        rating: reviewRating,
        comment: reviewComment
      });
      if (res.data.success) {
        setReviewSuccessMsg('Your review has been submitted successfully!');
        // Refresh reviews list
        const revRes = await api.get('/api/dashboard/reviews');
        if (revRes.data.success) {
          setReviews(revRes.data.reviews.data || []);
        }
        setTimeout(() => setShowReviewModal(false), 1500);
      }
    } catch (err: any) {
      setReviewError(err.response?.data?.message || 'Failed to submit review. Please try again.');
    } finally {
      setSubmittingReview(false);
    }
  };

  // Support Tickets states
  interface SupportTicket {
    id: number;
    title: string;
    topic: string;
    description: string;
    attachment: string | null;
    status: string;
    created_at: string;
  }

  const [tickets, setTickets] = useState<SupportTicket[]>([]);
  const [loadingTickets, setLoadingTickets] = useState(true);
  const [ticketView, setTicketView] = useState<'list' | 'create'>('list');

  // Create ticket form states
  const [ticketTitle, setTicketTitle] = useState('');
  const [ticketTopic, setTicketTopic] = useState('');
  const [ticketDescription, setTicketDescription] = useState('');
  const [ticketAttachment, setTicketAttachment] = useState<File | null>(null);
  const [submittingTicket, setSubmittingTicket] = useState(false);
  const [ticketError, setTicketError] = useState('');
  const [ticketSuccess, setTicketSuccess] = useState('');

  const handleTicketSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!ticketTitle || !ticketTopic || !ticketDescription) {
      setTicketError('Please fill in all required fields.');
      return;
    }

    setSubmittingTicket(true);
    setTicketError('');
    setTicketSuccess('');

    try {
      const formData = new FormData();
      formData.append('title', ticketTitle);
      formData.append('topic', ticketTopic);
      formData.append('description', ticketDescription);
      if (ticketAttachment) {
        formData.append('attachment', ticketAttachment);
      }

      const res = await api.post('/api/dashboard/tickets', formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
        },
      });

      if (res.data.success) {
        setTicketSuccess('Support ticket created successfully!');
        setTicketTitle('');
        setTicketTopic('');
        setTicketDescription('');
        setTicketAttachment(null);
        
        // Refresh ticket list
        const ticketsRes = await api.get('/api/dashboard/tickets');
        if (ticketsRes.data.success) {
          setTickets(ticketsRes.data.tickets.data || []);
        }

        setTimeout(() => {
          setTicketView('list');
          setTicketSuccess('');
        }, 1500);
      }
    } catch (err: any) {
      setTicketError(err.response?.data?.message || 'Failed to create support ticket. Please try again.');
    } finally {
      setSubmittingTicket(false);
    }
  };

  // Address manager states
  interface CustomerAddress {
    id: number;
    address_type: string; // Home, Office, Other
    street: string;
    city: string;
    upazila: string;
    zip: string;
    phone?: string;
  }

  const [addresses, setAddresses] = useState<CustomerAddress[]>([]);

  const [showAddressForm, setShowAddressForm] = useState(false);
  const [editingAddressId, setEditingAddressId] = useState<number | null>(null);
  const [formAddressType, setFormAddressType] = useState('Home');
  const [formAddressLine, setFormAddressLine] = useState('');
  const [formDistrict, setFormDistrict] = useState('');
  const [formUpazila, setFormUpazila] = useState('');
  const [formPostalCode, setFormPostalCode] = useState('');
  const [formPhone, setFormPhone] = useState('');
  const [addressMessage, setAddressMessage] = useState('');

  // Location search states
  const [districts, setDistricts] = useState<DistrictItem[]>([]);
  const [upazilas, setUpazilas] = useState<LocationItem[]>([]);
  const [selectedDistrictId, setSelectedDistrictId] = useState<number | ''>('');
  const [selectedUpazilaId, setSelectedUpazilaId] = useState<number | ''>('');
  const [loadingLocations, setLoadingLocations] = useState(false);
  const [loadingUpazilas, setLoadingUpazilas] = useState(false);
  const pendingUpazilaNameRef = useRef<string | null>(null);

  // Password reset state
  const [newPassword, setNewPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');
  const [showNewPassword, setShowNewPassword] = useState(false);
  const [showConfirmPassword, setShowConfirmPassword] = useState(false);
  const [passwordMessage, setPasswordMessage] = useState('');
  const [passwordError, setPasswordError] = useState('');
  const [confirmDeleteCheckbox, setConfirmDeleteCheckbox] = useState(false);

  // Profile settings state
  const [profileName, setProfileName] = useState(user?.name || '');
  const [profileAddress, setProfileAddress] = useState('');
  const [profileAvatar, setProfileAvatar] = useState<File | null>(null);
  const [profilePhone, setProfilePhone] = useState(user?.phone || '');
  const [profileEmail, setProfileEmail] = useState(user?.email || '');
  const [isSocialGoogleConnected, setIsSocialGoogleConnected] = useState(true);

  // Form submission feedback
  const [profileMsg, setProfileMsg] = useState({ text: '', type: '' as 'success' | 'error' | '' });
  const [phoneMsg, setPhoneMsg] = useState({ text: '', type: '' as 'success' | 'error' | '' });
  const [emailMsg, setEmailMsg] = useState({ text: '', type: '' as 'success' | 'error' | '' });
  const [socialMsg, setSocialMsg] = useState({ text: '', type: '' as 'success' | 'error' | '' });

  const [savingProfile, setSavingProfile] = useState(false);
  const [savingPhone, setSavingPhone] = useState(false);
  const [savingEmail, setSavingEmail] = useState(false);
  const [revokingSocial, setRevokingSocial] = useState(false);

  // Update form fields when user state updates
  useEffect(() => {
    if (user) {
      setProfileName(user.name || '');
      setProfilePhone(user.phone || '');
      setProfileEmail(user.email || '');
    }
  }, [user]);

  const handleProfileUpdate = async (e: React.FormEvent) => {
    e.preventDefault();
    setSavingProfile(true);
    setProfileMsg({ text: '', type: '' });
    try {
      const formData = new FormData();
      formData.append('name', profileName);
      formData.append('address', profileAddress);
      if (profileAvatar) {
        formData.append('avatar', profileAvatar);
      }
      const res = await api.post('/api/dashboard/profile', formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
        },
      });
      if (res.data.success) {
        setProfileMsg({ text: 'Profile updated successfully!', type: 'success' });
        await checkUser();
      }
    } catch (err: any) {
      setProfileMsg({
        text: err.response?.data?.message || 'Failed to update profile.',
        type: 'error',
      });
    } finally {
      setSavingProfile(false);
    }
  };

  const handlePhoneUpdate = async (e: React.FormEvent) => {
    e.preventDefault();
    setSavingPhone(true);
    setPhoneMsg({ text: '', type: '' });
    try {
      const res = await api.post('/api/dashboard/profile/phone', { phone: profilePhone });
      if (res.data.success) {
        setPhoneMsg({ text: 'Phone number updated successfully!', type: 'success' });
        await checkUser();
      }
    } catch (err: any) {
      setPhoneMsg({
        text: err.response?.data?.message || 'Failed to update phone number.',
        type: 'error',
      });
    } finally {
      setSavingPhone(false);
    }
  };

  const handleEmailUpdate = async (e: React.FormEvent) => {
    e.preventDefault();
    setSavingEmail(true);
    setEmailMsg({ text: '', type: '' });
    try {
      const res = await api.post('/api/dashboard/profile/email', { email: profileEmail });
      if (res.data.success) {
        setEmailMsg({ text: 'Email address updated successfully!', type: 'success' });
        await checkUser();
      }
    } catch (err: any) {
      setEmailMsg({
        text: err.response?.data?.message || 'Failed to update email address.',
        type: 'error',
      });
    } finally {
      setSavingEmail(false);
    }
  };

  const handleSocialRevoke = async () => {
    if (!confirm('Are you sure you want to revoke your Google account connection?')) return;
    setRevokingSocial(true);
    setSocialMsg({ text: '', type: '' });
    try {
      const res = await api.post('/api/dashboard/profile/social-revoke');
      if (res.data.success) {
        setSocialMsg({ text: 'Google account revoked successfully!', type: 'success' });
        setIsSocialGoogleConnected(false);
      }
    } catch (err: any) {
      setSocialMsg({
        text: err.response?.data?.message || 'Failed to revoke Google account.',
        type: 'error',
      });
    } finally {
      setRevokingSocial(false);
    }
  };

  const handleDeleteAccount = async () => {
    if (!confirmDeleteCheckbox) return;
    if (!confirm('Are you absolutely sure you want to permanently delete your account? This action is irreversible.')) {
      return;
    }

    try {
      const res = await api.delete('/api/user/delete');
      if (res.data.success) {
        alert('Your account has been deleted successfully.');
        await logout();
        router.push('/login');
      }
    } catch (err: any) {
      alert(err.response?.data?.message || 'Failed to delete account. Please try again.');
    }
  };

  // Promo code copy state
  const [copiedCode, setCopiedCode] = useState<string | null>(null);
  const handleCopyCode = (code: string) => {
    navigator.clipboard.writeText(code);
    setCopiedCode(code);
    setTimeout(() => setCopiedCode(null), 2000);
  };

  // Redirect to login if user is not authenticated or reseller portal if role is reseller
  useEffect(() => {
    if (!authLoading) {
      if (!user) {
        router.push('/login');
      } else if (user.role === 'reseller') {
        router.push('/reseller/dashboard');
      }
    }
  }, [user, authLoading, router]);

  // Load orders history
  useEffect(() => {
    if (!user) return;
    if (activeTab !== 'dashboard' && activeTab !== 'orders') return;

    const fetchOrders = async () => {
      setLoadingOrders(true);
      try {
        const res = await api.get('/api/dashboard/orders');
        setOrders(res.data.data || []);
      } catch (err: any) {
        if (err.response?.status !== 401) {
          console.error('Failed to load dashboard orders', err);
        }
      } finally {
        setLoadingOrders(false);
      }
    };

    fetchOrders();
  }, [user, activeTab]);

  // Load coupons history
  useEffect(() => {
    if (!user) return;
    if (activeTab !== 'coupons') return;

    const fetchCoupons = async () => {
      setLoadingCoupons(true);
      try {
        const res = await api.get('/api/dashboard/coupons');
        setCoupons(res.data.data || []);
      } catch (err: any) {
        if (err.response?.status !== 401) {
          console.error('Failed to load dashboard coupons', err);
        }
      } finally {
        setLoadingCoupons(false);
      }
    };

    fetchCoupons();
  }, [user, activeTab]);

  // Load payments history
  useEffect(() => {
    if (!user) return;
    if (activeTab !== 'payments') return;

    const fetchPayments = async () => {
      setLoadingPayments(true);
      try {
        const res = await api.get('/api/dashboard/payments');
        if (res.data.success) {
          setTransactions(res.data.transactions.data || []);
          setPaymentStats(res.data.stats || {
            this_month_spent: 0,
            last_six_months_spent: 0,
            total_spent: 0,
          });
        }
      } catch (err: any) {
        if (err.response?.status !== 401) {
          console.error('Failed to load dashboard payments', err);
        }
      } finally {
        setLoadingPayments(false);
      }
    };

    fetchPayments();
  }, [user, activeTab]);

  // Load customer reviews
  useEffect(() => {
    if (!user) return;
    if (activeTab !== 'reviews') return;

    const fetchReviews = async () => {
      setLoadingReviews(true);
      try {
        const res = await api.get('/api/dashboard/reviews');
        if (res.data.success) {
          setReviews(res.data.reviews.data || []);
        }
      } catch (err: any) {
        if (err.response?.status !== 401) {
          console.error('Failed to load dashboard reviews', err);
        }
      } finally {
        setLoadingReviews(false);
      }
    };

    fetchReviews();
  }, [user, activeTab]);

  // Load support tickets
  useEffect(() => {
    if (!user) return;
    if (activeTab !== 'tickets') return;

    const fetchTickets = async () => {
      setLoadingTickets(true);
      try {
        const res = await api.get('/api/dashboard/tickets');
        if (res.data.success) {
          setTickets(res.data.tickets.data || []);
        }
      } catch (err: any) {
        if (err.response?.status !== 401) {
          console.error('Failed to load dashboard tickets', err);
        }
      } finally {
        setLoadingTickets(false);
      }
    };

    fetchTickets();
  }, [user, activeTab]);

  // Load Divisions & Districts when address tab is active and address edit/add form is opened (lazy loading)
  useEffect(() => {
    if (activeTab !== 'address' || !showAddressForm) return;
    if (districts.length > 0) return; // already loaded

    const loadLocations = async () => {
      setLoadingLocations(true);
      try {
        const divRes = await api.get('/api/divisions');

        const distRes = await api.get('/api/districts');
        const allDistricts: DistrictItem[] = distRes.data || [];
        
        // Sort districts alphabetically
        allDistricts.sort((a, b) => a.name.localeCompare(b.name));
        setDistricts(allDistricts);
      } catch (err) {
        console.error('Failed to load locations', err);
      } finally {
        setLoadingLocations(false);
      }
    };
    loadLocations();
  }, [activeTab, districts.length, showAddressForm]);

  // Load Upazilas based on selected district ID
  useEffect(() => {
    if (!selectedDistrictId) {
      setUpazilas([]);
      setSelectedUpazilaId('');
      return;
    }
    const loadUpazilas = async () => {
      setLoadingUpazilas(true);
      try {
        const res = await api.get(`/api/upazilas/${selectedDistrictId}`);
        const data = res.data || [];
        setUpazilas(data);
        
        const pending = pendingUpazilaNameRef.current;
        if (pending) {
          const matchingUpazila = data.find(
            (u: any) => u.name.toLowerCase() === pending.toLowerCase()
          );
          if (matchingUpazila) {
            setSelectedUpazilaId(matchingUpazila.id);
          } else {
            setSelectedUpazilaId('');
          }
          pendingUpazilaNameRef.current = null;
        } else {
          setSelectedUpazilaId(prev => {
            if (prev && data.some((u: any) => u.id === prev)) return prev;
            return '';
          });
        }
      } catch (err) {
        console.error('Failed to load upazilas', err);
      } finally {
        setLoadingUpazilas(false);
      }
    };
    loadUpazilas();
  }, [selectedDistrictId]);

  // Load address if available
  useEffect(() => {
    if (!user) return;
    if (user.addresses) {
      if (user.addresses.length > 0) {
        setProfileAddress(user.addresses[0].street || '');
      }
      const mapped = user.addresses.map((addr: any, index: number) => {
        let type = 'Home';
        if (addr.country && ['Home', 'Office', 'Other'].includes(addr.country)) {
          type = addr.country;
        } else if (index === 1) {
          type = 'Office';
        }
        
        let streetLine = addr.street || '';
        let upazilaName = 'Kaunia';
        if (streetLine.includes(',')) {
          const parts = streetLine.split(',');
          streetLine = parts[0].trim();
          upazilaName = parts[1].trim();
        }

        return {
          id: addr.id,
          address_type: type,
          street: streetLine,
          city: addr.city || 'Rangpur',
          upazila: upazilaName,
          zip: addr.zip || '5441',
          phone: addr.phone || ''
        };
      });
      setAddresses(mapped);
    }
  }, [user]);

  if (authLoading || !user || user.role === 'reseller') {
    return (
      <>
        <Header />
        <main className="bg-slate-50 pb-16 animate-pulse">
          {/* Header Gradient Banner Background — Desktop only */}
          <div className="hidden lg:block w-full h-48 bg-gradient-to-r from-slate-200 via-slate-250 to-slate-350 rounded-b-[40px] shadow-xs relative overflow-hidden -mt-2"></div>

          <div className="mx-auto max-w-7xl px-4 sm:px-6 lg:px-8 -mt-24 relative z-10">
            <div className="flex flex-col lg:flex-row gap-6">
              
              {/* LEFT: Sidebar Skeleton */}
              <aside className="w-full lg:w-64 bg-white rounded-3xl border border-slate-200/60 p-6 shadow-xs space-y-6 flex-shrink-0">
                {/* User avatar & name info skeleton */}
                <div className="flex flex-col items-center text-center space-y-3 pb-6 border-b border-slate-100">
                  <div className="h-20 w-20 bg-slate-200 rounded-full"></div>
                  <div className="h-5 bg-slate-200 rounded w-28"></div>
                  <div className="h-4 bg-slate-150 rounded w-36"></div>
                </div>

                {/* Sidebar menu links skeleton */}
                <div className="space-y-3 pt-2">
                  {[...Array(6)].map((_, i) => (
                    <div key={i} className="flex items-center gap-3 py-2 px-3">
                      <div className="h-5 w-5 bg-slate-200 rounded-full"></div>
                      <div className="h-4 bg-slate-150 rounded w-24"></div>
                    </div>
                  ))}
                </div>
              </aside>

              {/* RIGHT: Content Area Skeleton */}
              <div className="flex-1 space-y-6">
                
                {/* Top overview statistics grid */}
                <div className="grid grid-cols-1 sm:grid-cols-3 gap-6">
                  {[...Array(3)].map((_, i) => (
                    <div key={i} className="bg-white p-6 rounded-3xl border border-slate-200/60 shadow-xs flex items-center justify-between">
                      <div className="space-y-2">
                        <div className="h-4 bg-slate-150 rounded w-20"></div>
                        <div className="h-6 bg-slate-200 rounded w-16"></div>
                      </div>
                      <div className="h-10 w-10 bg-slate-200 rounded-xl"></div>
                    </div>
                  ))}
                </div>

                {/* Content Panel Skeleton */}
                <div className="bg-white rounded-3xl border border-slate-200/60 p-6 shadow-xs space-y-4">
                  <div className="h-6 bg-slate-300 rounded w-48"></div>
                  
                  {/* Dummy list/table */}
                  <div className="space-y-4 pt-2">
                    {[...Array(3)].map((_, i) => (
                      <div key={i} className="flex justify-between items-center py-3 border-b border-slate-100 last:border-b-0">
                        <div className="space-y-2">
                          <div className="h-4 bg-slate-200 rounded w-32"></div>
                          <div className="h-3.5 bg-slate-150 rounded w-24"></div>
                        </div>
                        <div className="h-8 bg-slate-200 rounded w-20"></div>
                      </div>
                    ))}
                  </div>
                </div>

              </div>

            </div>
          </div>
        </main>
        <Footer />
      </>
    );
  }

  const handleAddNewClick = () => {
    setEditingAddressId(null);
    setFormAddressType('Home');
    setFormAddressLine('');
    setFormDistrict('');
    setFormUpazila('');
    setFormPostalCode('');
    setFormPhone('');
    setSelectedDistrictId('');
    setSelectedUpazilaId('');
    pendingUpazilaNameRef.current = null;
    setAddressMessage('');
    setShowAddressForm(true);
  };

  const handleEditClick = (addr: CustomerAddress) => {
    setEditingAddressId(addr.id);
    setFormAddressType(addr.address_type);
    setFormAddressLine(addr.street);
    setFormPostalCode(addr.zip);
    setFormPhone(addr.phone || '');
    setAddressMessage('');

    // Find district matching city name
    const district = districts.find(d => d.name.toLowerCase() === addr.city.toLowerCase());
    if (district) {
      setSelectedDistrictId(district.id);
      pendingUpazilaNameRef.current = addr.upazila;
    } else {
      setSelectedDistrictId('');
      setSelectedUpazilaId('');
      pendingUpazilaNameRef.current = null;
    }

    setShowAddressForm(true);
  };

  const handleUpdateAddress = async (e: React.FormEvent) => {
    e.preventDefault();
    setAddressMessage('');
    try {
      const districtName = districts.find(d => d.id === selectedDistrictId)?.name || '';
      const upazilaName = upazilas.find(u => u.id === selectedUpazilaId)?.name || '';

      const payload = {
        id: editingAddressId,
        address_type: formAddressType,
        street: formAddressLine,
        city: districtName,
        upazila: upazilaName,
        zip: formPostalCode,
        phone: formPhone
      };

      const res = await api.post('/api/dashboard/addresses', payload);
      
      if (res.data.success) {
        const saved = res.data.address;
        
        let type = 'Home';
        if (saved.country && ['Home', 'Office', 'Other'].includes(saved.country)) {
          type = saved.country;
        }
        
        let streetLine = saved.street || '';
        let upazilaNameParsed = 'Kaunia';
        if (streetLine.includes(',')) {
          const parts = streetLine.split(',');
          streetLine = parts[0].trim();
          upazilaNameParsed = parts[1].trim();
        }

        const mappedAddr = {
          id: saved.id,
          address_type: type,
          street: streetLine,
          city: saved.city || '',
          upazila: upazilaNameParsed,
          zip: saved.zip || '',
          phone: saved.phone || ''
        };

        if (editingAddressId !== null) {
          setAddresses(prev => prev.map(addr => addr.id === editingAddressId ? mappedAddr : addr));
          setAddressMessage('Address updated successfully!');
        } else {
          setAddresses(prev => [...prev, mappedAddr]);
          setAddressMessage('Address added successfully!');
        }
        
        setShowAddressForm(false);
        setEditingAddressId(null);
      } else {
        setAddressMessage(res.data.message || 'Failed to save address.');
      }
    } catch (err: any) {
      setAddressMessage(err.response?.data?.message || 'Failed to save address.');
    }
  };

  const handleDeleteAddress = async (id: number) => {
    if (!confirm('Are you sure you want to delete this address?')) return;
    try {
      const res = await api.delete(`/api/dashboard/addresses/${id}`);
      if (res.data.success) {
        setAddresses(prev => prev.filter(addr => addr.id !== id));
        setAddressMessage('Address deleted successfully!');
      }
    } catch (e: any) {
      alert(e.response?.data?.message || 'Failed to delete address.');
    }
  };

  const handleChangePassword = async (e: React.FormEvent) => {
    e.preventDefault();
    setPasswordMessage('');
    setPasswordError('');

    if (newPassword.length < 8) {
      setPasswordError('New password must be at least 8 characters long.');
      return;
    }

    if (newPassword !== confirmPassword) {
      setPasswordError('New password and confirm password do not match.');
      return;
    }

    try {
      await api.post('/api/password/reset', {
        email_or_phone: user?.email || '',
        code: '123456', // dummy code to bypass validation or mock reset
        password: newPassword,
      });
      setPasswordMessage('Password changed successfully!');
      setNewPassword('');
      setConfirmPassword('');
    } catch (err: any) {
      setPasswordError(err.response?.data?.message || 'Password update failed.');
    }
  };

  const handleLogoutClick = async () => {
    await logout();
    router.push('/login');
  };

  // Switch tab via URL navigation + scroll to top
  const switchTab = (tab: string) => {
    const path = TAB_TO_PATH[tab] ?? '/dashboard';
    router.push(path);
    window.scrollTo({ top: 0, behavior: 'instant' });
  };

  // Helper to format dates
  const formatDate = (dateStr: string) => {
    return new Date(dateStr).toLocaleDateString('en-US', {
      year: 'numeric',
      month: 'short',
      day: 'numeric'
    });
  };

  // Helper to format date and time
  const formatDateTime = (dateStr: string) => {
    const date = new Date(dateStr);
    const dateFormatted = date.toLocaleDateString('en-US', {
      year: 'numeric',
      month: 'short',
      day: 'numeric'
    });
    const timeFormatted = date.toLocaleTimeString('en-US', {
      hour: '2-digit',
      minute: '2-digit',
      hour12: true
    });
    return `${dateFormatted} ${timeFormatted}`;
  };

  const getStatusColor = (status: string) => {
    switch (status.toLowerCase()) {
      case 'paid':
      case 'delivered':
      case 'processing':
      case 'success':
        return 'text-emerald-700 bg-emerald-50 border-emerald-100';
      case 'failed':
      case 'cancelled':
        return 'text-rose-600 bg-rose-50 border-rose-100';
      default:
        return 'text-amber-700 bg-amber-50 border-amber-100';
    }
  };

  const backendUrl = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:8000';
  const totalSpent = orders.reduce((acc, o) => acc + (o.payment_status === 'paid' ? o.grand_total : 0), 0);
  const runningOrdersCount = orders.filter(o => o.status.toLowerCase() !== 'delivered' && o.status.toLowerCase() !== 'cancelled').length;

  return (
    <>
      <Header />
      <main className="bg-slate-50 pb-16">
        
        {/* 1. Header Gradient Banner Background — Desktop only */}
        <div className="hidden lg:block w-full h-48 bg-gradient-to-r from-sky-400 via-indigo-500 to-purple-600 rounded-b-[40px] shadow-xs relative overflow-hidden -mt-2">
          <div className="absolute inset-0 bg-black/10"></div>
          {/* Subtle design accents inside banner */}
          <div className="absolute top-10 right-10 h-32 w-32 rounded-full bg-white/10 blur-xl"></div>
          <div className="absolute bottom-5 left-20 h-24 w-24 rounded-full bg-indigo-300/20 blur-lg"></div>
        </div>

        {/* Mobile Floating Menu Button — right center edge, flush with border, hidden when drawer open */}
        {!mobileMenuOpen && (
          <button
            onClick={() => setMobileMenuOpen(true)}
            className="lg:hidden fixed right-0 top-1/2 -translate-y-1/2 z-50 w-12 h-12 bg-[#2C3333] text-white rounded-l-2xl shadow-[0_4px_20px_rgba(0,0,0,0.3)] flex items-center justify-center hover:bg-neutral-700 active:scale-95 transition-all duration-200"
            aria-label="Open dashboard menu"
          >
            <LayoutDashboard className="h-6 w-6" />
          </button>
        )}

        {/* Mobile Sidebar Drawer Overlay */}
        {mobileMenuOpen && (
          <div
            className="lg:hidden fixed inset-0 z-40 flex"
            onClick={() => setMobileMenuOpen(false)}
          >
            {/* Backdrop */}
            <div className="absolute inset-0 bg-black/50 backdrop-blur-sm" />

            {/* Drawer Panel */}
            <div
              className="relative ml-auto w-[300px] max-w-[85vw] h-full bg-white shadow-2xl flex flex-col animate-slide-in-right"
              onClick={(e) => e.stopPropagation()}
            >
              {/* Drawer Header */}
              <div className="bg-gradient-to-r from-sky-400 via-indigo-500 to-purple-600 p-5 flex items-center justify-between">
                <div>
                  <p className="text-white font-bold text-base truncate">{user?.name}</p>
                  <p className="text-white/80 text-xs mt-0.5 truncate">{user?.email}</p>
                </div>
                <button
                  onClick={() => setMobileMenuOpen(false)}
                  className="w-8 h-8 rounded-full bg-white/20 flex items-center justify-center text-white hover:bg-white/30 transition-colors"
                >
                  <X className="h-4 w-4" />
                </button>
              </div>

              {/* Drawer Navigation — scrollable */}
              <nav className="flex-1 overflow-y-auto py-4 px-3 space-y-1">
                {[
                  { tab: 'dashboard' as const, label: 'Dashboard', icon: <LayoutDashboard className="h-5 w-5" /> },
                  { tab: 'orders' as const, label: 'My Orders', icon: <ShoppingBag className="h-5 w-5" /> },
                  { tab: 'wishlist' as const, label: "Wishlist's", icon: <Heart className="h-5 w-5" /> },
                  { tab: 'coupons' as const, label: 'Promo / Coupon', icon: <Ticket className="h-5 w-5" /> },
                  { tab: 'address' as const, label: 'Address', icon: <MapPin className="h-5 w-5" /> },
                  { tab: 'payments' as const, label: 'Payments', icon: <CreditCard className="h-5 w-5" /> },
                  { tab: 'reviews' as const, label: 'Product Reviews', icon: <Star className="h-5 w-5" /> },
                  { tab: 'tickets' as const, label: 'Support Tickets', icon: <MessageSquare className="h-5 w-5" /> },
                  { tab: 'profile' as const, label: 'Manage Profile', icon: <User className="h-5 w-5" /> },
                  { tab: 'password' as const, label: 'Change Password', icon: <Lock className="h-5 w-5" /> },
                ].map(({ tab, label, icon }) => (
                  <button
                    key={tab}
                    onClick={() => { switchTab(tab); setMobileMenuOpen(false); }}
                    className={`w-full flex items-center gap-3 px-4 py-3 rounded-xl text-[15px] font-semibold transition-all ${
                      activeTab === tab
                        ? 'bg-[#2C3333] text-white shadow-md'
                        : 'text-[#767A7A] hover:bg-slate-50 hover:text-[#2C3333]'
                    }`}
                  >
                    {icon}
                    {label}
                  </button>
                ))}
              </nav>

              {/* Drawer Logout — always visible at bottom */}
              <div className="shrink-0 p-4 pb-6 border-t border-slate-100">
                <button
                  onClick={() => { setMobileMenuOpen(false); handleLogoutClick(); }}
                  className="w-full flex items-center justify-center gap-2 py-3 text-[15px] font-bold text-white bg-[#2C3333] hover:bg-neutral-800 rounded-xl transition-all cursor-pointer shadow-md"
                >
                  <LogOut className="h-5 w-5" />
                  Logout
                </button>
              </div>
            </div>
          </div>
        )}

        {/* Mobile-only user identity bar (replaces the hidden banner) */}
        <div className="lg:hidden w-full bg-gradient-to-r from-sky-400 via-indigo-500 to-purple-600 px-4 py-4 flex items-center gap-3 relative overflow-hidden">
          <div className="absolute inset-0 bg-black/10" />
          <div className="relative w-10 h-10 rounded-full bg-white/20 flex items-center justify-center shrink-0">
            <User className="h-5 w-5 text-white" />
          </div>
          <div className="relative overflow-hidden">
            <p className="text-white font-bold text-sm leading-tight truncate">{user?.name}</p>
            <p className="text-white/75 text-xs truncate">{user?.email}</p>
          </div>
        </div>

        {/* 2. Main Container holding Sidebar and Right Content */}
        <div className="mx-auto max-w-7xl px-4 sm:px-6 lg:px-8 mt-4 lg:-mt-28 relative z-10">
          <div className="grid grid-cols-1 lg:grid-cols-4 gap-8 items-start">
            
            {/* Sidebar Column (Left Column) - Hidden on mobile */}
            <div className="hidden lg:flex lg:col-span-1 flex-col gap-4">
              
              {/* Customer Name & Phone Card (Separate 3D dark-grey card) */}
              <div className="bg-[#2d2d2d] text-white p-5 text-left rounded-[24px] shadow-[0_8px_30px_rgb(0,0,0,0.03)] border border-neutral-800/10">
                <h2 className="text-base font-bold truncate text-white">{user?.name}</h2>
                <p className="text-xs text-white/90 font-sans mt-1 truncate">{user?.email}</p>
              </div>

              {/* Sidebar Navigation Links (Separate white menu card) */}
              <div className="user-sidebar-menus bg-white rounded-[24px] border border-slate-200/60 shadow-[0_8px_30px_rgb(0,0,0,0.03)] pt-[20px] px-[16px] pb-[24px] text-[#2C3333] overflow-hidden">
                <ul className="user-sidebar-menu-list flex flex-col space-y-1 text-left">
                  
                  {/* Dashboard Tab */}
                  <li className="w-full">
                    <button
                      onClick={() => switchTab('dashboard')}
                      className={`w-full flex items-center justify-between px-4 py-[12px] text-[15px] font-semibold rounded-xl transition-all cursor-pointer font-sans ${
                        activeTab === 'dashboard'
                          ? 'bg-[#2C3333] text-white shadow-md'
                          : 'text-[#767A7A] hover:bg-slate-50 hover:text-[#2C3333]'
                      }`}
                    >
                      <span className="flex items-center gap-2.5">
                        <LayoutDashboard className="h-4.5 w-4.5" />
                        Dashboard
                      </span>
                      {activeTab === 'dashboard' && <ArrowRight className="h-3.5 w-3.5 text-white" />}
                    </button>
                  </li>

                  {/* My Orders Tab */}
                  <li className="w-full">
                    <button
                      onClick={() => switchTab('orders')}
                      className={`w-full flex items-center justify-between px-4 py-[12px] text-[15px] font-semibold rounded-xl transition-all cursor-pointer font-sans ${
                        activeTab === 'orders'
                          ? 'bg-[#2C3333] text-white shadow-md'
                          : 'text-[#767A7A] hover:bg-slate-50 hover:text-[#2C3333]'
                      }`}
                    >
                      <span className="flex items-center gap-2.5">
                        <ShoppingBag className="h-4.5 w-4.5" />
                        My orders
                      </span>
                      {activeTab === 'orders' && <ArrowRight className="h-3.5 w-3.5 text-white" />}
                    </button>
                  </li>

                  {/* Wishlist Tab */}
                  <li className="w-full">
                    <button
                      onClick={() => switchTab('wishlist')}
                      className={`w-full flex items-center justify-between px-4 py-[12px] text-[15px] font-semibold rounded-xl transition-all cursor-pointer font-sans ${
                        activeTab === 'wishlist'
                          ? 'bg-[#2C3333] text-white shadow-md'
                          : 'text-[#767A7A] hover:bg-slate-50 hover:text-[#2C3333]'
                      }`}
                    >
                      <span className="flex items-center gap-2.5">
                        <Heart className="h-4.5 w-4.5" />
                        Wishlist&apos;s
                      </span>
                      {activeTab === 'wishlist' && <ArrowRight className="h-3.5 w-3.5 text-white" />}
                    </button>
                  </li>

                  {/* Coupons Tab */}
                  <li className="w-full">
                    <button
                      onClick={() => switchTab('coupons')}
                      className={`w-full flex items-center justify-between px-4 py-[12px] text-[15px] font-semibold rounded-xl transition-all cursor-pointer font-sans ${
                        activeTab === 'coupons'
                          ? 'bg-[#2C3333] text-white shadow-md'
                          : 'text-[#767A7A] hover:bg-slate-50 hover:text-[#2C3333]'
                      }`}
                    >
                      <span className="flex items-center gap-2.5">
                        <Ticket className="h-4.5 w-4.5" />
                        Promo/ Coupon
                      </span>
                      {activeTab === 'coupons' && <ArrowRight className="h-3.5 w-3.5 text-white" />}
                    </button>
                  </li>

                  {/* Address Tab */}
                  <li className="w-full">
                    <button
                      onClick={() => switchTab('address')}
                      className={`w-full flex items-center justify-between px-4 py-[12px] text-[15px] font-semibold rounded-xl transition-all cursor-pointer font-sans ${
                        activeTab === 'address'
                          ? 'bg-[#2C3333] text-white shadow-md'
                          : 'text-[#767A7A] hover:bg-slate-50 hover:text-[#2C3333]'
                      }`}
                    >
                      <span className="flex items-center gap-2.5">
                        <MapPin className="h-4.5 w-4.5" />
                        Address
                      </span>
                      {activeTab === 'address' && <ArrowRight className="h-3.5 w-3.5 text-white" />}
                    </button>
                  </li>

                  {/* Payments Tab */}
                  <li className="w-full">
                    <button
                      onClick={() => switchTab('payments')}
                      className={`w-full flex items-center justify-between px-4 py-[12px] text-[15px] font-semibold rounded-xl transition-all cursor-pointer font-sans ${
                        activeTab === 'payments'
                          ? 'bg-[#2C3333] text-white shadow-md'
                          : 'text-[#767A7A] hover:bg-slate-50 hover:text-[#2C3333]'
                      }`}
                    >
                      <span className="flex items-center gap-2.5">
                        <CreditCard className="h-4.5 w-4.5" />
                        Payments
                      </span>
                      {activeTab === 'payments' && <ArrowRight className="h-3.5 w-3.5 text-white" />}
                    </button>
                  </li>

                  {/* Reviews Tab */}
                  <li className="w-full">
                    <button
                      onClick={() => switchTab('reviews')}
                      className={`w-full flex items-center justify-between px-4 py-[12px] text-[15px] font-semibold rounded-xl transition-all cursor-pointer font-sans ${
                        activeTab === 'reviews'
                          ? 'bg-[#2C3333] text-white shadow-md'
                          : 'text-[#767A7A] hover:bg-slate-50 hover:text-[#2C3333]'
                      }`}
                    >
                      <span className="flex items-center gap-2.5">
                        <Star className="h-4.5 w-4.5" />
                        Product reviews
                      </span>
                      {activeTab === 'reviews' && <ArrowRight className="h-3.5 w-3.5 text-white" />}
                    </button>
                  </li>

                  {/* Support Tickets Tab */}
                  <li className="w-full">
                    <button
                      onClick={() => switchTab('tickets')}
                      className={`w-full flex items-center justify-between px-4 py-[12px] text-[15px] font-semibold rounded-xl transition-all cursor-pointer font-sans ${
                        activeTab === 'tickets'
                          ? 'bg-[#2C3333] text-white shadow-md'
                          : 'text-[#767A7A] hover:bg-slate-50 hover:text-[#2C3333]'
                      }`}
                    >
                      <span className="flex items-center gap-2.5">
                        <MessageSquare className="h-4.5 w-4.5" />
                        Support tickets
                      </span>
                      {activeTab === 'tickets' && <ArrowRight className="h-3.5 w-3.5 text-white" />}
                    </button>
                  </li>

                  {/* Manage Profile Tab */}
                  <li className="w-full">
                    <button
                      onClick={() => switchTab('profile')}
                      className={`w-full flex items-center justify-between px-4 py-[12px] text-[15px] font-semibold rounded-xl transition-all cursor-pointer font-sans ${
                        activeTab === 'profile'
                          ? 'bg-[#2C3333] text-white shadow-md'
                          : 'text-[#767A7A] hover:bg-slate-50 hover:text-[#2C3333]'
                      }`}
                    >
                      <span className="flex items-center gap-2.5">
                        <User className="h-4.5 w-4.5" />
                        Manage profile
                      </span>
                      {activeTab === 'profile' && <ArrowRight className="h-3.5 w-3.5 text-white" />}
                    </button>
                  </li>

                  {/* Change Password Tab */}
                  <li className="w-full">
                    <button
                      onClick={() => switchTab('password')}
                      className={`w-full flex items-center justify-between px-4 py-[12px] text-[15px] font-semibold rounded-xl transition-all cursor-pointer font-sans ${
                        activeTab === 'password'
                          ? 'bg-[#2C3333] text-white shadow-md'
                          : 'text-[#767A7A] hover:bg-slate-50 hover:text-[#2C3333]'
                      }`}
                    >
                      <span className="flex items-center gap-2.5">
                        <Lock className="h-4.5 w-4.5" />
                        Change Password
                      </span>
                      {activeTab === 'password' && <ArrowRight className="h-3.5 w-3.5 text-white" />}
                    </button>
                  </li>

                  {/* Delete Account Tab */}
                  <li className="w-full">
                    <button
                      onClick={() => switchTab('delete_account')}
                      className={`w-full flex items-center justify-between px-4 py-[12px] text-[15px] font-semibold rounded-xl transition-all cursor-pointer font-sans ${
                        activeTab === 'delete_account'
                          ? 'bg-[#2C3333] text-white shadow-md'
                          : 'text-[#767A7A] hover:bg-slate-50 hover:text-rose-600'
                      }`}
                    >
                      <span className="flex items-center gap-2.5">
                        <Trash2 className="h-4.5 w-4.5" />
                        Delete My Account
                      </span>
                      {activeTab === 'delete_account' && <ArrowRight className="h-3.5 w-3.5 text-white" />}
                    </button>
                  </li>

                  {/* Logout Button inside nav bar */}
                  <li className="w-full pt-4">
                    <button
                      onClick={handleLogoutClick}
                      className="w-full flex items-center justify-center gap-2 py-[12px] text-[15px] font-bold text-white bg-[#2C3333] hover:bg-neutral-800 rounded-xl transition-all cursor-pointer shadow-md"
                    >
                      <LogOut className="h-4.5 w-4.5" />
                      Logout
                    </button>
                  </li>

                </ul>
              </div>

            </div>

            {/* Right Side Panels */}
            <div className="col-span-1 lg:col-span-3 space-y-6 mt-0 lg:mt-36">
              
              {/* TAB 1: DEFAULT DASHBOARD STATS & RECENT CARDS */}
              {activeTab === 'dashboard' && (
                <div className="space-y-6">
                  
                  {/* Grid of 6 Stats Cards — 2 per row on mobile, 3 per row on md+ */}
                  <div className="grid grid-cols-2 md:grid-cols-3 gap-3 md:gap-5">
                    
                    {/* Stat 1: Total order placed */}
                    <div className="single-data-card card-1 bg-gradient-to-tr from-blue-50 to-blue-100 border border-blue-200/60 p-4 md:p-6 rounded-[20px] md:rounded-[24px] flex justify-between items-start min-h-[100px] md:min-h-[120px] shadow-[0_8px_30px_rgba(0,0,0,0.05)] hover:-translate-y-2 hover:shadow-[0_20px_35px_rgba(0,0,0,0.08)] active:translate-y-0 active:shadow-md transition-all duration-300 ease-out cursor-pointer group">
                      <div className="text-left flex flex-col justify-between h-full">
                        <span className="text-3xl md:text-5xl font-black text-neutral-800 tracking-tight leading-none font-sans block">{orders.length}</span>
                        <span className="text-[11px] md:text-[13px] font-semibold text-slate-500 tracking-wide mt-2 md:mt-3 block">Total order placed</span>
                      </div>
                      <div className="hidden md:flex h-16 w-16 items-center justify-center shrink-0">
                        <img src="/images/3d-shopping-bag.png" alt="Total orders" className="h-14 w-14 object-contain group-hover:scale-110 transition-transform duration-300 ease-out" />
                      </div>
                    </div>

                    {/* Stat 2: Running orders */}
                    <div className="single-data-card card-2 bg-gradient-to-tr from-emerald-50 to-emerald-100 border border-emerald-200/60 p-4 md:p-6 rounded-[20px] md:rounded-[24px] flex justify-between items-start min-h-[100px] md:min-h-[120px] shadow-[0_8px_30px_rgba(0,0,0,0.05)] hover:-translate-y-2 hover:shadow-[0_20px_35px_rgba(0,0,0,0.08)] active:translate-y-0 active:shadow-md transition-all duration-300 ease-out cursor-pointer group">
                      <div className="text-left flex flex-col justify-between h-full">
                        <span className="text-3xl md:text-5xl font-black text-neutral-800 tracking-tight leading-none font-sans block">{runningOrdersCount}</span>
                        <span className="text-[11px] md:text-[13px] font-semibold text-slate-500 tracking-wide mt-2 md:mt-3 block">Running orders</span>
                      </div>
                      <div className="hidden md:flex h-16 w-16 items-center justify-center shrink-0">
                        <img src="/images/3d-package-check.png" alt="Running orders" className="h-14 w-14 object-contain group-hover:scale-110 transition-transform duration-300 ease-out" />
                      </div>
                    </div>

                    {/* Stat 3: Items in cart */}
                    <div className="single-data-card card-3 bg-gradient-to-tr from-teal-50 to-teal-100 border border-teal-200/60 p-4 md:p-6 rounded-[20px] md:rounded-[24px] flex justify-between items-start min-h-[100px] md:min-h-[120px] shadow-[0_8px_30px_rgba(0,0,0,0.05)] hover:-translate-y-2 hover:shadow-[0_20px_35px_rgba(0,0,0,0.08)] active:translate-y-0 active:shadow-md transition-all duration-300 ease-out cursor-pointer group">
                      <div className="text-left flex flex-col justify-between h-full">
                        <span className="text-3xl md:text-5xl font-black text-neutral-800 tracking-tight leading-none font-sans block">{cartCount}</span>
                        <span className="text-[11px] md:text-[13px] font-semibold text-slate-500 tracking-wide mt-2 md:mt-3 block">Items in cart</span>
                      </div>
                      <div className="hidden md:flex h-16 w-16 items-center justify-center shrink-0">
                        <img src="/images/3d-cart-badge.png" alt="Items in cart" className="h-14 w-14 object-contain group-hover:scale-110 transition-transform duration-300 ease-out" />
                      </div>
                    </div>

                    {/* Stat 4: Product in wishlist's */}
                    <div className="single-data-card card-4 bg-gradient-to-tr from-orange-50 to-orange-100 border border-orange-200/60 p-4 md:p-6 rounded-[20px] md:rounded-[24px] flex justify-between items-start min-h-[100px] md:min-h-[120px] shadow-[0_8px_30px_rgba(0,0,0,0.05)] hover:-translate-y-2 hover:shadow-[0_20px_35px_rgba(0,0,0,0.08)] active:translate-y-0 active:shadow-md transition-all duration-300 ease-out cursor-pointer group">
                      <div className="text-left flex flex-col justify-between h-full">
                        <span className="text-3xl md:text-5xl font-black text-neutral-800 tracking-tight leading-none font-sans block">0</span>
                        <span className="text-[11px] md:text-[13px] font-semibold text-slate-500 tracking-wide mt-2 md:mt-3 block">Product in wishlist&apos;s</span>
                      </div>
                      <div className="hidden md:flex h-16 w-16 items-center justify-center shrink-0">
                        <img src="/images/3d-heart-wishlist.png" alt="Wishlist" className="h-14 w-14 object-contain group-hover:scale-110 transition-transform duration-300 ease-out" />
                      </div>
                    </div>

                    {/* Stat 5: Amount spent */}
                    <div className="single-data-card card-5 bg-gradient-to-tr from-sky-50 to-sky-100 border border-sky-200/60 p-4 md:p-6 rounded-[20px] md:rounded-[24px] flex justify-between items-start min-h-[100px] md:min-h-[120px] shadow-[0_8px_30px_rgba(0,0,0,0.05)] hover:-translate-y-2 hover:shadow-[0_20px_35px_rgba(0,0,0,0.08)] active:translate-y-0 active:shadow-md transition-all duration-300 ease-out cursor-pointer group">
                      <div className="text-left flex flex-col justify-between h-full">
                        <span className="text-3xl md:text-5xl font-black text-neutral-800 tracking-tight leading-none font-sans block">{formatPrice(totalSpent)}</span>
                        <span className="text-[11px] md:text-[13px] font-semibold text-slate-500 tracking-wide mt-2 md:mt-3 block">Amount spent</span>
                      </div>
                      <div className="hidden md:flex h-16 w-16 items-center justify-center shrink-0">
                        <img src="/images/3d-taka-spent.png" alt="Amount spent" className="h-14 w-14 object-contain group-hover:scale-110 transition-transform duration-300 ease-out" />
                      </div>
                    </div>

                    {/* Stat 6: Opened Tickets */}
                    <div className="single-data-card card-6 bg-gradient-to-tr from-fuchsia-50 to-fuchsia-100 border border-fuchsia-200/60 p-4 md:p-6 rounded-[20px] md:rounded-[24px] flex justify-between items-start min-h-[100px] md:min-h-[120px] shadow-[0_8px_30px_rgba(0,0,0,0.05)] hover:-translate-y-2 hover:shadow-[0_20px_35px_rgba(0,0,0,0.08)] active:translate-y-0 active:shadow-md transition-all duration-300 ease-out cursor-pointer group">
                      <div className="text-left flex flex-col justify-between h-full">
                        <span className="text-3xl md:text-5xl font-black text-neutral-800 tracking-tight leading-none font-sans block">0</span>
                        <span className="text-[11px] md:text-[13px] font-semibold text-slate-500 tracking-wide mt-2 md:mt-3 block">Opened Tickets</span>
                      </div>
                      <div className="hidden md:flex h-16 w-16 items-center justify-center shrink-0">
                        <img src="/images/3d-chat-tickets.png" alt="Opened tickets" className="h-14 w-14 object-contain group-hover:scale-110 transition-transform duration-300 ease-out" />
                      </div>
                    </div>

                  </div>

                  {/* Recent Orders Section (Exactly matching screenshot) */}
                  <div className="bg-white border border-slate-200/60 rounded-3xl shadow-xs overflow-hidden">
                    
                    {/* Header Bar */}
                    <div className="bg-[#2c2c2c] px-6 py-4 flex items-center justify-between">
                      <h5 className="dashboard-head-widget-title text-[20px] font-bold text-white">Recent orders</h5>
                      <button 
                        onClick={() => switchTab('orders')}
                        className="theme-btn text-[13px] font-semibold text-[#333333] bg-[#F5F5F5] hover:bg-[#E5E5E5] py-[8px] px-[16px] rounded-lg transition-colors cursor-pointer"
                      >
                        All orders
                      </button>
                    </div>

                    {/* Orders Content */}
                    <div className="p-6">
                      {loadingOrders ? (
                        <div className="flex justify-center py-6">
                          <Loader2 className="h-6 w-6 text-primary animate-spin" />
                        </div>
                      ) : orders.length === 0 ? (
                        <div className="py-8 bg-slate-50/50 border border-slate-200/40 rounded-2xl text-center text-xs font-semibold text-slate-400">
                          No Order Found
                        </div>
                      ) : (
                        <div className="divide-y divide-slate-100">
                          {orders.slice(0, 3).map((order) => (
                            <div key={order.id} className="py-3.5 flex justify-between items-center text-xs first:pt-0 last:pb-0">
                              <div>
                                <span className="font-bold text-slate-800 block">Order #{order.order_number}</span>
                                <span className="text-xxs text-slate-400 block mt-0.5">Date: {formatDate(order.created_at)}</span>
                              </div>
                              <div className="flex items-center gap-4">
                                <span className={`text-[10px] font-bold px-2 py-0.5 border rounded-md capitalize ${getStatusColor(order.status)}`}>
                                  {order.status}
                                </span>
                                <span className="font-black text-slate-900">{formatPrice(order.grand_total)}</span>
                              </div>
                            </div>
                          ))}
                        </div>
                      )}
                    </div>

                  </div>

                  {/* Wishlist Items Section (Exactly matching screenshot) */}
                  <div className="bg-white border border-slate-200/60 rounded-3xl shadow-xs overflow-hidden">
                    
                    {/* Header Bar */}
                    <div className="bg-[#2c2c2c] px-6 py-4 flex items-center justify-between">
                      <h5 className="dashboard-head-widget-title text-[20px] font-bold text-white">Wishlist items</h5>
                      <button 
                        onClick={() => switchTab('wishlist')}
                        className="theme-btn text-[13px] font-semibold text-[#333333] bg-[#F5F5F5] hover:bg-[#E5E5E5] py-[8px] px-[16px] rounded-lg transition-colors cursor-pointer"
                      >
                        View more
                      </button>
                    </div>

                    {/* Wishlist Content */}
                    <div className="p-6">
                      <div className="py-8 bg-slate-50/50 border border-slate-200/40 rounded-2xl text-center text-xs font-semibold text-slate-400">
                        No Product in Wishlist
                      </div>
                    </div>

                  </div>

                </div>
              )}

              {/* TAB 2: MY ORDERS TAB */}
              {activeTab === 'orders' && (
                <div className="bg-white border border-slate-200/60 rounded-[24px] shadow-xs overflow-hidden p-6 space-y-4">
                  <div className="overflow-x-auto">
                    <div className="min-w-[850px] space-y-3.5">
                      
                      {/* Table Header Bar */}
                      <div className="grid grid-cols-12 gap-4 items-center bg-[#2C3333] px-6 py-4 rounded-xl text-[13px] font-bold text-white tracking-wide font-sans shadow-md">
                        <div className="col-span-2 text-left">Order ID</div>
                        <div className="col-span-3 text-left">Date & Time</div>
                        <div className="col-span-2 text-center">Status</div>
                        <div className="col-span-1 text-center">Quantity</div>
                        <div className="col-span-2 text-center">Amount</div>
                        <div className="col-span-2 text-right">Action</div>
                      </div>

                      {/* Table Body */}
                      {loadingOrders ? (
                        <div className="flex justify-center py-20 bg-slate-50/50 rounded-xl border border-slate-100">
                          <Loader2 className="h-8 w-8 text-primary animate-spin" />
                        </div>
                      ) : orders.length === 0 ? (
                        <div className="flex items-center justify-center py-24 bg-slate-50/50 rounded-xl border border-slate-100">
                          <span className="text-[16px] font-bold text-[#767A7A] tracking-tight font-sans">No Orders Found</span>
                        </div>
                      ) : (
                        <div className="divide-y divide-slate-100 border border-slate-200/60 rounded-xl overflow-hidden bg-white">
                          {orders.map((order) => {
                            const totalQty = order.items ? order.items.reduce((sum, item) => sum + item.quantity, 0) : 0;
                            const isExpanded = expandedOrder === order.id;
                            return (
                              <React.Fragment key={order.id}>
                                <div className="grid grid-cols-12 gap-4 items-center py-4 px-6 hover:bg-slate-50/50 transition-colors text-[13px] text-slate-700 font-semibold font-sans">
                                  
                                  {/* Order ID */}
                                  <div className="col-span-2 font-bold text-slate-800">
                                    #{order.order_number}
                                  </div>

                                  {/* Date & Time */}
                                  <div className="col-span-3 text-slate-500 font-normal">
                                    {formatDateTime(order.created_at)}
                                  </div>

                                  {/* Status */}
                                  <div className="col-span-2 text-center">
                                    <span className={`text-[11px] font-bold px-2.5 py-0.5 border rounded-md capitalize ${getStatusColor(order.status)}`}>
                                      {order.status}
                                    </span>
                                  </div>

                                  {/* Quantity */}
                                  <div className="col-span-1 text-center text-slate-600 font-normal">
                                    {totalQty}
                                  </div>

                                  {/* Amount */}
                                  <div className="col-span-2 text-center font-bold text-slate-800">
                                    {formatPrice(order.grand_total)}
                                  </div>

                                  {/* Action */}
                                  <div className="col-span-2 text-right">
                                    <div className="flex justify-end items-center gap-2">
                                      <button
                                        onClick={() => setExpandedOrder(isExpanded ? null : order.id)}
                                        className="text-[12px] font-bold border border-slate-200 py-1.5 px-3 rounded-lg hover:bg-slate-100 bg-[#F5F5F5] hover:bg-[#E5E5E5] transition-colors cursor-pointer text-[#333333] theme-btn"
                                      >
                                        {isExpanded ? 'Hide' : 'View'}
                                      </button>
                                      
                                      <a
                                        href={`${backendUrl}/orders/${order.id}/invoice`}
                                        target="_blank"
                                        rel="noopener noreferrer"
                                        className="inline-flex items-center justify-center gap-1.5 text-[12px] font-bold bg-[#2C3333] hover:bg-neutral-800 text-white py-1.5 px-3 rounded-lg transition-colors cursor-pointer"
                                      >
                                        <FileText className="h-3.5 w-3.5" />
                                        <span>Invoice</span>
                                      </a>
                                    </div>
                                  </div>

                                </div>

                                {/* Expandable Order Items list */}
                                {isExpanded && (
                                  <div className="bg-slate-50/50 p-5 border-t border-b border-slate-200">
                                    <div className="space-y-3 text-left max-w-3xl mx-auto">
                                      <h4 className="text-[10px] font-bold text-slate-400 uppercase tracking-wider">Order Items</h4>
                                      <div className="divide-y divide-slate-100 border border-slate-200 rounded-xl bg-white p-4 space-y-2">
                                        {order.items && order.items.map((item) => (
                                          <div key={item.id} className="flex justify-between items-center text-xs py-2 first:pt-0 last:pb-0">
                                            <div>
                                              <span className="font-semibold text-slate-800 block">{item.product_name}</span>
                                              <span className="text-[10px] text-slate-400">SKU: {item.product_sku} • Qty: {item.quantity}</span>
                                            </div>
                                            <div className="flex items-center gap-3">
                                              <span className="font-bold text-slate-900">{formatPrice(item.price * item.quantity)}</span>
                                              {(order.payment_status === 'paid' || order.status.toLowerCase() === 'delivered') && (
                                                <button
                                                  onClick={() => handleOpenReviewModal(item.product_id || item.id, item.product_name)}
                                                  className="theme-btn text-[11px] py-1 px-2.5 text-[#333333] bg-[#F5F5F5] hover:bg-indigo-50 hover:text-indigo-650 rounded-md cursor-pointer transition-colors border border-slate-200 shrink-0"
                                                >
                                                  Review
                                                </button>
                                              )}
                                            </div>
                                          </div>
                                        ))}
                                      </div>
                                    </div>
                                  </div>
                                )}
                              </React.Fragment>
                            );
                          })}
                        </div>
                      )}
                    </div>
                  </div>
                </div>
              )}

              {/* TAB 3: WISHLIST TAB */}
              {activeTab === 'wishlist' && (
                <div className="bg-white border border-slate-200/60 rounded-[24px] shadow-xs overflow-hidden p-6 space-y-4">
                  
                  {/* Table Header Bar */}
                  <div className="flex justify-between items-center bg-[#2C3333] px-6 py-4 rounded-xl text-white shadow-md">
                    <h3 className="text-[15px] font-bold text-white tracking-wide font-sans">Wishlist&apos;s</h3>
                    <button 
                      onClick={() => {
                        // Mock action to clear wishlist
                        alert('Wishlist cleared');
                      }}
                      className="text-[13px] font-bold text-[#333333] bg-[#F5F5F5] hover:bg-[#E5E5E5] py-[6px] px-[12px] rounded-lg transition-colors cursor-pointer border border-slate-200/50 font-sans"
                    >
                      Clear all
                    </button>
                  </div>

                  {/* Wishlist Body Content */}
                  <div className="flex items-center justify-center py-28 bg-slate-50/50 rounded-xl border border-slate-100">
                    <span className="text-[28px] font-bold text-slate-800 tracking-tight font-sans">No Product in Wishlist</span>
                  </div>

                </div>
              )}

              {/* TAB 4: COUPONS TAB */}
              {activeTab === 'coupons' && (
                <div className="bg-white border border-slate-200/60 rounded-[24px] shadow-xs overflow-hidden p-6 space-y-6">
                  
                  {/* Table Header Bar */}
                  <div className="flex justify-between items-center bg-[#2C3333] px-6 py-4 rounded-xl text-white shadow-md">
                    <h3 className="text-[15px] font-bold text-white tracking-wide font-sans">Promo or Coupon</h3>
                  </div>

                  {/* Promo content grid */}
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-8 items-start">
                    
                    {/* Left Column: Available Coupons */}
                    <div className="space-y-4">
                      <h4 className="text-[16px] font-bold text-slate-800 pb-3 border-b border-slate-100 mb-4 font-sans text-left">Available coupon</h4>
                      
                      {loadingCoupons ? (
                        <div className="flex justify-center py-20 bg-slate-50/50 rounded-xl border border-slate-100">
                          <Loader2 className="h-8 w-8 text-primary animate-spin" />
                        </div>
                      ) : coupons.length === 0 ? (
                        <div className="bg-slate-50/50 border border-slate-200/50 rounded-xl py-4 px-6 text-center text-[13px] font-semibold text-slate-400 font-sans">
                          No Coupons Available
                        </div>
                      ) : (
                        <div className="space-y-4">
                          {coupons.map((coupon) => (
                            <div key={coupon.id} className="border border-slate-200/60 rounded-2xl p-4 bg-white flex items-center justify-between gap-4 shadow-sm hover:shadow-md transition-shadow">
                              <div className="flex items-center gap-3.5 text-left">
                                
                                {/* Gray box with Ticket Icon */}
                                <div className="bg-slate-50 p-3.5 rounded-2xl flex items-center justify-center border border-slate-100 shrink-0 text-blue-600">
                                  <Ticket className="h-6 w-6 stroke-[2.5]" />
                                </div>
                                
                                {/* Coupon info */}
                                <div>
                                  <h5 className="text-[15px] font-bold text-slate-850 font-sans">{coupon.code}</h5>
                                  <p className="text-[12px] text-slate-500 font-sans mt-0.5">
                                    {coupon.type === 'percentage' ? `${numberWithCommas(coupon.value)}% OFF` : `৳${numberWithCommas(coupon.value)} OFF`} 
                                    {Number(coupon.min_amount) > 0 && ` • Min spend: ৳${numberWithCommas(coupon.min_amount)}`}
                                  </p>
                                  <p className="text-[10px] text-slate-400 font-sans mt-0.5">
                                    {coupon.expires_at ? `Validity: ${formatDate(coupon.expires_at)}` : 'Lifetime Validity'}
                                  </p>
                                  
                                  {/* Copyable code badge */}
                                  <button
                                    onClick={() => handleCopyCode(coupon.code)}
                                    className="bg-slate-50 hover:bg-slate-100 border border-slate-200/60 py-1.5 px-3 mt-2.5 inline-flex items-center gap-2 rounded-lg cursor-pointer transition-colors"
                                    title="Click to copy coupon code"
                                  >
                                    <span className="font-sans text-[13px] font-bold text-slate-650">{coupon.code}</span>
                                    {copiedCode === coupon.code ? (
                                      <Check className="h-3.5 w-3.5 text-emerald-600 shrink-0" />
                                    ) : (
                                      <Copy className="h-3.5 w-3.5 text-slate-400 hover:text-slate-600 shrink-0" />
                                    )}
                                  </button>
                                </div>
                              </div>

                              {/* Active Badge on the right */}
                              <div className="shrink-0">
                                <span className={`px-3.5 py-1 rounded-full text-[11px] font-bold tracking-wide ${coupon.is_active ? 'bg-emerald-50 text-emerald-700 border border-emerald-100' : 'bg-slate-100 text-slate-700 border border-slate-200'}`}>
                                  {coupon.is_active ? 'Active' : 'Inactive'}
                                </span>
                              </div>
                            </div>
                          ))}
                        </div>
                      )}

                    </div>

                    {/* Right Column: Applied Coupons */}
                    <div className="space-y-4">
                      <h4 className="text-[16px] font-bold text-slate-800 pb-3 border-b border-slate-100 mb-4 font-sans text-left">Applied coupon</h4>
                      
                      {/* Empty applied coupon container */}
                      <div className="bg-slate-50/50 border border-slate-200/50 rounded-xl py-4 px-6 text-center text-[13px] font-semibold text-slate-400 font-sans">
                        No Coupons Applied
                      </div>
                    </div>

                  </div>

                </div>
              )}

              {/* TAB 5: ADDRESS TAB */}
              {activeTab === 'address' && (
                <div className="bg-white border border-slate-200/60 rounded-[24px] shadow-xs overflow-hidden p-6 space-y-6">
                  
                  {/* Table Header Bar */}
                  <div className="flex justify-between items-center bg-[#2C3333] px-6 py-4 rounded-xl text-white shadow-md">
                    <h3 className="text-[15px] font-bold text-white tracking-wide font-sans">Address</h3>
                    <button 
                      onClick={handleAddNewClick}
                      className="inline-flex items-center gap-1 text-[13px] font-bold text-[#333333] bg-[#F5F5F5] hover:bg-[#E5E5E5] py-[6px] px-[12px] rounded-lg transition-colors cursor-pointer border border-slate-200/50 font-sans"
                    >
                      <Plus className="h-3.5 w-3.5" />
                      <span>ADD NEW ADDRESS</span>
                    </button>
                  </div>

                  {addressMessage && (
                    <div className="bg-emerald-50 border border-emerald-250 text-emerald-700 px-4 py-3 rounded-2xl text-xs font-semibold flex items-center gap-2 text-left">
                      <CheckCircle2 className="h-5 w-5 text-emerald-600" />
                      <span>{addressMessage}</span>
                    </div>
                  )}

                  {/* Main Address Section */}
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                    
                    {/* Addresses Cards list */}
                    {addresses.length === 0 ? (
                      <div className="col-span-2 text-center py-12 bg-slate-50/50 border border-slate-200/50 rounded-2xl text-xs font-semibold text-slate-400 font-sans">
                        No Delivery Addresses Saved
                      </div>
                    ) : (
                      addresses.map((addr) => {
                        const IconComponent = addr.address_type === 'Home' ? Home : addr.address_type === 'Office' ? Briefcase : MapPin;
                        return (
                          <div key={addr.id} className="border border-slate-200/60 rounded-2xl p-5 bg-white shadow-xs hover:shadow-md transition-shadow relative text-left">
                            
                            {/* Top line of card */}
                            <div className="flex justify-between items-center pb-3 border-b border-slate-100">
                              <div className="flex items-center gap-2.5">
                                <div className="bg-blue-50 p-2 rounded-full text-blue-600 shrink-0 border border-blue-100">
                                  <IconComponent className="h-4 w-4 stroke-[2.5]" />
                                </div>
                                <h4 className="text-[14px] font-bold text-slate-800 font-sans">{addr.address_type} Address</h4>
                              </div>
                              
                              <div className="flex items-center gap-2.5">
                                <button
                                  onClick={() => handleEditClick(addr)}
                                  className="text-slate-800 hover:text-primary-dark text-xs font-bold font-sans cursor-pointer transition-colors"
                                >
                                  Edit
                                </button>
                                <span className="text-slate-350 text-xs">|</span>
                                <button
                                  onClick={() => handleDeleteAddress(addr.id)}
                                  className="text-rose-600 hover:text-rose-800 text-xs font-bold font-sans cursor-pointer transition-colors"
                                >
                                  Delete
                                </button>
                              </div>
                            </div>

                            {/* Card items grid */}
                            <div className="grid grid-cols-12 gap-y-3.5 text-xs text-left pt-4">
                              <div className="col-span-5 text-slate-450 font-sans">Address line</div>
                              <div className="col-span-7 text-slate-800 font-bold font-sans break-words">{addr.street}</div>
                              
                              <div className="col-span-5 text-slate-450 font-sans">District/City</div>
                              <div className="col-span-7 text-slate-800 font-bold font-sans">{addr.city}</div>
                              
                              <div className="col-span-5 text-slate-450 font-sans">Thana/Upazila</div>
                              <div className="col-span-7 text-slate-800 font-bold font-sans">{addr.upazila}</div>
                              
                              <div className="col-span-5 text-slate-450 font-sans">Postal code</div>
                              <div className="col-span-7 text-slate-800 font-bold font-sans">{addr.zip}</div>

                              {addr.phone && (
                                <>
                                  <div className="col-span-5 text-slate-450 font-sans">Phone number</div>
                                  <div className="col-span-7 text-slate-800 font-bold font-sans">{addr.phone}</div>
                                </>
                              )}
                            </div>

                          </div>
                        );
                      })
                    )}
                  </div>

                  {/* Address edit/add Form in Modal Popup */}
                  {showAddressForm && (
                    <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50 backdrop-blur-sm animate-fade-in">
                      <div className="bg-white rounded-3xl p-6 shadow-2xl relative w-full max-w-lg border border-slate-200 flex flex-col max-h-[90vh] overflow-y-auto font-open-sans">
                        
                        {/* Form Title & Close Button */}
                        <div className="flex justify-between items-center pb-3 border-b border-slate-100 mb-4">
                          <h4 className="text-[18px] font-bold text-slate-800 font-open-sans">
                            {editingAddressId !== null ? 'Edit Address' : 'Add New Address'}
                          </h4>
                          <button 
                            onClick={() => {
                              setShowAddressForm(false);
                              setEditingAddressId(null);
                            }}
                            className="text-slate-400 hover:text-slate-650 transition-colors p-1"
                          >
                            <X className="h-5 w-5" />
                          </button>
                        </div>

                        <form onSubmit={handleUpdateAddress} className="space-y-4">
                          {/* Address Type */}
                          <div className="space-y-1">
                            <label className="text-[13px] font-semibold text-slate-600 font-open-sans">Address type</label>
                            <select
                              value={formAddressType}
                              onChange={(e) => setFormAddressType(e.target.value)}
                              className="w-full text-[14px] p-3 bg-slate-50 border border-slate-200 rounded-xl focus:border-primary focus:outline-none font-open-sans font-medium"
                            >
                              <option value="Home">Home</option>
                              <option value="Office">Office</option>
                              <option value="Other">Other</option>
                            </select>
                          </div>

                          {/* Address Line */}
                          <div className="space-y-1">
                            <label className="text-[13px] font-semibold text-slate-600 font-open-sans">Address line</label>
                            <input
                              type="text"
                              required
                              placeholder="Address"
                              value={formAddressLine}
                              onChange={(e) => setFormAddressLine(e.target.value)}
                              className="w-full text-[14px] p-3 bg-slate-50 border border-slate-200 rounded-xl focus:border-primary focus:outline-none font-open-sans"
                            />
                          </div>

                          {/* District Selection */}
                          <div className="space-y-1">
                            <label className="text-[13px] font-semibold text-slate-600 font-open-sans">Select District</label>
                            <SearchableSelect
                              options={districts}
                              value={selectedDistrictId}
                              onChange={(val) => {
                                setSelectedDistrictId(val);
                                setSelectedUpazilaId('');
                              }}
                              placeholder="Select District"
                              required
                            />
                          </div>

                          {/* Thana/Upazila Selection */}
                          <div className="space-y-1">
                            <label className="text-[13px] font-semibold text-slate-600 font-open-sans">Select Thana/Upazila</label>
                            <SearchableSelect
                              options={upazilas}
                              value={selectedUpazilaId}
                              onChange={(val) => setSelectedUpazilaId(val)}
                              placeholder="Select Thana/Upazila"
                              disabled={!selectedDistrictId || loadingUpazilas}
                              required
                            />
                          </div>

                          {/* Postal Code */}
                          <div className="space-y-1">
                            <label className="text-[13px] font-semibold text-slate-600 font-open-sans">Postal code</label>
                            <input
                              type="text"
                              required
                              placeholder="ex: 1000"
                              value={formPostalCode}
                              onChange={(e) => setFormPostalCode(e.target.value)}
                              className="w-full text-[14px] p-3 bg-slate-50 border border-slate-200 rounded-xl focus:border-primary focus:outline-none font-open-sans"
                            />
                          </div>

                          {/* Phone Number */}
                          <div className="space-y-1">
                            <label className="text-[13px] font-semibold text-slate-600 font-open-sans">Phone number</label>
                            <div className="flex rounded-xl overflow-hidden border border-slate-200 focus-within:border-primary bg-slate-50 transition-all">
                              <div className="bg-[#f8f9fa] px-4 py-3 text-slate-650 font-medium border-r border-slate-200 flex items-center justify-center text-[14px] select-none font-open-sans">
                                88
                              </div>
                              <input
                                type="text"
                                required
                                value={formPhone}
                                onChange={(e) => setFormPhone(e.target.value)}
                                className="flex-1 px-4 py-3 bg-slate-50 text-[14px] font-medium text-slate-850 focus:outline-none placeholder-slate-400 font-open-sans"
                                placeholder="017********"
                              />
                            </div>
                          </div>

                          {/* Submit Button */}
                          <button
                            type="submit"
                            className="w-full py-3.5 bg-[#2C3333] hover:bg-neutral-800 text-white text-[14px] font-bold rounded-xl shadow-md transition-colors cursor-pointer uppercase tracking-wider font-open-sans mt-2"
                          >
                            SAVE
                          </button>

                        </form>
                      </div>
                    </div>
                  )}

                </div>
              )}

              {/* TAB 6: PAYMENTS TAB */}
              {activeTab === 'payments' && (
                <div className="space-y-6">
                  
                  {/* Outer container card with header "Payments" */}
                  <div className="bg-white border border-slate-200/60 rounded-3xl shadow-[0_8px_30px_rgba(0,0,0,0.03)] overflow-hidden">
                    <div className="bg-white border-b border-slate-100 px-6 py-4 flex items-center justify-between text-left">
                      <h3 className="text-[18px] font-bold text-slate-800 font-sans">Payments</h3>
                    </div>
                    
                    {/* Padding inside for the stats cards */}
                    <div className="p-6">
                      <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
                        
                        {/* Card 1: This month spent */}
                        <div className="bg-gradient-to-tr from-blue-50/60 to-indigo-50/20 border border-blue-200/60 p-6 rounded-[24px] flex flex-col items-center justify-center text-center shadow-[0_8px_30px_rgba(0,0,0,0.03)] hover:-translate-y-1.5 hover:shadow-[0_15px_30px_rgba(0,0,0,0.06)] active:translate-y-0 transition-all duration-300 ease-out cursor-pointer group">
                          <div className="bg-[#007bff] p-4 rounded-full flex items-center justify-center text-white mb-4 shadow-sm group-hover:scale-105 transition-transform duration-300">
                            <Wallet className="h-7 w-7" />
                          </div>
                          <span className="text-[22px] font-extrabold text-neutral-800 font-sans block leading-none">
                            {formatPrice(paymentStats.this_month_spent)}
                          </span>
                          <span className="text-[12px] font-bold text-slate-400 tracking-wide mt-2 block uppercase">This month spent</span>
                        </div>

                        {/* Card 2: Last 6 month spent */}
                        <div className="bg-gradient-to-tr from-teal-50/60 to-emerald-50/20 border border-teal-200/60 p-6 rounded-[24px] flex flex-col items-center justify-center text-center shadow-[0_8px_30px_rgba(0,0,0,0.03)] hover:-translate-y-1.5 hover:shadow-[0_15px_30px_rgba(0,0,0,0.06)] active:translate-y-0 transition-all duration-300 ease-out cursor-pointer group">
                          <div className="bg-[#00c2cb] p-4 rounded-full flex items-center justify-center text-white mb-4 shadow-sm group-hover:scale-105 transition-transform duration-300">
                            <Calendar className="h-7 w-7" />
                          </div>
                          <span className="text-[22px] font-extrabold text-neutral-800 font-sans block leading-none">
                            {formatPrice(paymentStats.last_six_months_spent)}
                          </span>
                          <span className="text-[12px] font-bold text-slate-400 tracking-wide mt-2 block uppercase">Last 6 month spent</span>
                        </div>

                        {/* Card 3: Total spent */}
                        <div className="bg-gradient-to-tr from-orange-50/60 to-rose-50/20 border border-orange-200/60 p-6 rounded-[24px] flex flex-col items-center justify-center text-center shadow-[0_8px_30px_rgba(0,0,0,0.03)] hover:-translate-y-1.5 hover:shadow-[0_15px_30px_rgba(0,0,0,0.06)] active:translate-y-0 transition-all duration-300 ease-out cursor-pointer group">
                          <div className="bg-[#ff6f00] p-4 rounded-full flex items-center justify-center text-white mb-4 shadow-sm group-hover:scale-105 transition-transform duration-300">
                            <TrendingUp className="h-7 w-7" />
                          </div>
                          <span className="text-[22px] font-extrabold text-neutral-800 font-sans block leading-none">
                            {paymentStats.total_spent === 0 ? '0' : `${formatPrice(paymentStats.total_spent)}`}
                          </span>
                          <span className="text-[12px] font-bold text-slate-400 tracking-wide mt-2 block uppercase">Total spent</span>
                        </div>

                      </div>
                    </div>
                  </div>

                  {/* Section: Payments history */}
                  <div className="space-y-4">
                    <h4 className="text-[18px] font-extrabold text-slate-800 text-left font-sans pl-1">Payments history</h4>
                    
                    <div className="overflow-x-auto">
                      <div className="min-w-[850px] space-y-3.5">
                        
                        {/* Table Header Bar */}
                        <div className="grid grid-cols-12 gap-4 items-center bg-[#2C3333] px-6 py-4 rounded-xl text-[13px] font-bold text-white tracking-wide font-sans shadow-md">
                          <div className="col-span-3 text-left">Date & time</div>
                          <div className="col-span-3 text-left">TXN id</div>
                          <div className="col-span-2 text-left">Method</div>
                          <div className="col-span-2 text-center">Amount</div>
                          <div className="col-span-2 text-right">Action</div>
                        </div>

                        {/* Table Body */}
                        {loadingPayments ? (
                          <div className="flex justify-center py-20 bg-slate-50/50 rounded-xl border border-slate-100">
                            <Loader2 className="h-8 w-8 text-primary animate-spin" />
                          </div>
                        ) : transactions.length === 0 ? (
                          <div className="flex items-center justify-center py-4 bg-[#F8F9FA] rounded-xl border border-slate-200/50">
                            <span className="text-[14px] font-bold text-slate-400 tracking-tight font-sans">No Payment Record Found</span>
                          </div>
                        ) : (
                          <div className="divide-y divide-slate-100 border border-slate-200/60 rounded-xl overflow-hidden bg-white">
                            {transactions.map((txn) => (
                              <div key={txn.id} className="grid grid-cols-12 gap-4 items-center py-4 px-6 hover:bg-slate-50/50 transition-colors text-[13px] text-slate-700 font-semibold font-sans">
                                <div className="col-span-3 text-left">
                                  {txn.created_at ? formatDateTime(txn.created_at) : 'N/A'}
                                </div>
                                <div className="col-span-3 text-left font-sans select-all tracking-wider text-slate-800">
                                  {txn.transaction_id}
                                </div>
                                <div className="col-span-2 text-left capitalize">
                                  {txn.payment_method === 'sslcommerz' ? 'SSLCommerz' : txn.payment_method === 'bkash' ? 'bKash' : txn.payment_method}
                                </div>
                                <div className="col-span-2 text-center text-slate-900 font-bold">
                                  {formatPrice(Number(txn.amount))}
                                </div>
                                <div className="col-span-2 text-right">
                                  {txn.order_id && (
                                    <button 
                                      onClick={() => {
                                        router.push('/my/orders');
                                        setExpandedOrder(txn.order_id);
                                      }}
                                      className="theme-btn text-[13px] py-[6px] px-[12px] text-[#333333] bg-[#F5F5F5] hover:bg-slate-200 rounded-lg cursor-pointer transition-colors"
                                    >
                                      View Order
                                    </button>
                                  )}
                                </div>
                              </div>
                            ))}
                          </div>
                        )}

                      </div>
                    </div>
                  </div>

                </div>
              )}

              {/* TAB 7: REVIEWS TAB */}
              {activeTab === 'reviews' && (
                <div className="space-y-6">
                  
                  {/* Outer container card with header "Product reviews" */}
                  <div className="bg-white border border-slate-200/60 rounded-3xl shadow-[0_8px_30px_rgba(0,0,0,0.03)] overflow-hidden text-left">
                    <div className="bg-white border-b border-slate-100 px-6 py-4">
                      <h3 className="text-[18px] font-bold text-slate-800 font-sans">Product reviews</h3>
                    </div>
                    
                    <div className="p-6">
                      {loadingReviews ? (
                        <div className="flex justify-center py-20 bg-slate-50/50 rounded-xl border border-slate-100">
                          <Loader2 className="h-8 w-8 text-primary animate-spin" />
                        </div>
                      ) : reviews.length === 0 ? (
                        <div className="flex flex-col items-center justify-center py-24 bg-white text-center">
                          <h4 className="text-[28px] font-bold text-slate-800 font-sans">No Review Found</h4>
                        </div>
                      ) : (
                        <div className="space-y-4">
                          {reviews.map((rev) => (
                            <div key={rev.id} className="p-5 border border-slate-200/60 rounded-2xl bg-white hover:bg-slate-50/40 transition-colors flex gap-4 items-start">
                              {rev.product && (
                                <div className="h-16 w-16 rounded-xl overflow-hidden border border-slate-150 shrink-0 bg-slate-50">
                                  <img 
                                    src={rev.product.image_url.startsWith('http') ? rev.product.image_url : `${process.env.NEXT_PUBLIC_API_URL || 'http://localhost:8000'}${rev.product.image_url}`} 
                                    alt={rev.product.name} 
                                    className="h-full w-full object-cover"
                                  />
                                </div>
                              )}
                              
                              <div className="flex-1 min-w-0 space-y-1.5 text-left">
                                <div className="flex items-center justify-between gap-4">
                                  <h5 className="text-[14px] font-bold text-slate-850 truncate">
                                    {rev.product ? rev.product.name : 'Unknown Product'}
                                  </h5>
                                  <span className="text-[11px] font-bold tracking-wide text-slate-400">
                                    {rev.created_at ? formatDateTime(rev.created_at).split(' ')[0] + ' ' + formatDateTime(rev.created_at).split(' ')[1] + ' ' + formatDateTime(rev.created_at).split(' ')[2] : 'N/A'}
                                  </span>
                                </div>
                                
                                <div className="flex items-center gap-0.5">
                                  {[...Array(5)].map((_, i) => (
                                    <Star 
                                      key={i} 
                                      className={`h-3.5 w-3.5 ${i < rev.rating ? 'text-amber-400 fill-amber-400' : 'text-slate-250 fill-slate-200'}`} 
                                    />
                                  ))}
                                </div>
                                
                                {rev.comment && (
                                  <p className="text-xs text-slate-600 font-medium font-sans leading-relaxed whitespace-pre-line">
                                    {rev.comment}
                                  </p>
                                )}
                              </div>
                            </div>
                          ))}
                        </div>
                      )}
                    </div>
                  </div>

                </div>
              )}

              {/* TAB 8: SUPPORT TICKETS TAB */}
              {activeTab === 'tickets' && (
                <div className="space-y-6">
                  {ticketView === 'list' ? (
                    <div className="bg-white border border-slate-200/60 rounded-3xl shadow-[0_8px_30px_rgba(0,0,0,0.03)] overflow-hidden text-left">
                      <div className="bg-white border-b border-slate-100 px-6 py-4 flex items-center justify-between">
                        <h3 className="text-[18px] font-bold text-slate-800 font-sans">Support tickets</h3>
                        <button
                          onClick={() => {
                            setTicketTitle('');
                            setTicketTopic('');
                            setTicketDescription('');
                            setTicketAttachment(null);
                            setTicketError('');
                            setTicketSuccess('');
                            setTicketView('create');
                          }}
                          className="theme-btn text-[13px] py-[8px] px-[16px] text-slate-800 bg-[#F5F5F5] hover:bg-slate-200 rounded-lg cursor-pointer transition-colors border border-slate-200/60 flex items-center gap-1 font-bold"
                        >
                          <Plus className="h-4 w-4" />
                          Create ticket
                        </button>
                      </div>
                      
                      <div className="p-6">
                        {loadingTickets ? (
                          <div className="flex justify-center py-20 bg-slate-50/50 rounded-xl border border-slate-100">
                            <Loader2 className="h-8 w-8 text-primary animate-spin" />
                          </div>
                        ) : tickets.length === 0 ? (
                          <div className="flex items-center justify-center py-4 bg-[#F8F9FA] rounded-xl border border-slate-200/50">
                            <span className="text-[14px] font-bold text-slate-400 tracking-tight font-sans">No Support Ticket Found</span>
                          </div>
                        ) : (
                          <div className="space-y-4">
                            {tickets.map((t) => (
                              <div key={t.id} className="p-5 border border-slate-200/60 rounded-2xl bg-white hover:bg-slate-50/30 transition-colors space-y-3">
                                <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-2.5">
                                  <div>
                                    <span className="text-xxs font-extrabold uppercase tracking-wider text-indigo-600 bg-indigo-50 px-2 py-0.5 rounded-md font-sans">
                                      {t.topic}
                                    </span>
                                    <h4 className="text-[15px] font-bold text-slate-850 mt-1.5">{t.title}</h4>
                                  </div>
                                  <div className="flex items-center gap-3 shrink-0">
                                    <span className={`px-3 py-1 rounded-full text-[10px] font-bold tracking-wide ${
                                      t.status === 'pending' 
                                        ? 'bg-amber-50 text-amber-700 border border-amber-100' 
                                        : t.status === 'open' 
                                          ? 'bg-blue-50 text-blue-700 border border-blue-100' 
                                          : 'bg-slate-100 text-slate-700 border border-slate-200'
                                    }`}>
                                      {t.status}
                                    </span>
                                    <span className="text-xxs font-semibold text-slate-400">
                                      {t.created_at ? formatDateTime(t.created_at).split(' ')[0] + ' ' + formatDateTime(t.created_at).split(' ')[1] + ' ' + formatDateTime(t.created_at).split(' ')[2] : 'N/A'}
                                    </span>
                                  </div>
                                </div>
                                <p className="text-xs text-slate-650 font-medium font-sans leading-relaxed whitespace-pre-line bg-slate-50/60 p-3 rounded-xl border border-slate-100">
                                  {t.description}
                                </p>
                                {t.attachment && (
                                  <div className="flex items-center gap-1.5 pt-1">
                                    <span className="text-xxs font-bold text-slate-400">Attachment:</span>
                                    <a
                                      href={t.attachment.startsWith('http') ? t.attachment : `${process.env.NEXT_PUBLIC_API_URL || 'http://localhost:8000'}${t.attachment}`}
                                      target="_blank"
                                      rel="noopener noreferrer"
                                      className="text-xxs font-bold text-primary hover:underline"
                                    >
                                      View Photo
                                    </a>
                                  </div>
                                )}
                              </div>
                            ))}
                          </div>
                        )}
                      </div>
                    </div>
                  ) : (
                    <div className="bg-white border border-slate-200/60 rounded-3xl shadow-[0_8px_30px_rgba(0,0,0,0.03)] overflow-hidden text-left">
                      <div className="bg-white border-b border-slate-100 px-6 py-4 flex items-center justify-between">
                        <h3 className="text-[18px] font-bold text-slate-800 font-sans">Create ticket</h3>
                        <button
                          onClick={() => setTicketView('list')}
                          className="theme-btn text-[13px] py-[8px] px-[16px] text-slate-800 bg-[#F5F5F5] hover:bg-slate-200 rounded-lg cursor-pointer transition-colors border border-slate-200/60 flex items-center gap-1 font-bold font-sans"
                        >
                          <ArrowLeft className="h-4 w-4" />
                          Back to tickets
                        </button>
                      </div>
                      
                      <form onSubmit={handleTicketSubmit} className="p-6 space-y-6 max-w-3xl">
                        
                        {/* Title field */}
                        <div className="space-y-1.5">
                          <label className="text-sm font-bold text-slate-700 font-sans">Ticket title</label>
                          <input
                            required
                            type="text"
                            value={ticketTitle}
                            onChange={(e) => setTicketTitle(e.target.value)}
                            placeholder="Ticket title here"
                            className="w-full text-sm p-4.5 bg-slate-50 border border-slate-200 rounded-xl focus:border-primary focus:ring-1 focus:ring-primary focus:outline-none placeholder:text-slate-450 font-sans"
                          />
                        </div>

                        {/* Topic selector field */}
                        <div className="space-y-1.5">
                          <label className="text-sm font-bold text-slate-700 font-sans">Select topic</label>
                          <select
                            required
                            value={ticketTopic}
                            onChange={(e) => setTicketTopic(e.target.value)}
                            className="w-full text-sm p-4.5 bg-slate-50 border border-slate-200 rounded-xl focus:border-primary focus:ring-1 focus:ring-primary focus:outline-none placeholder:text-slate-450 font-sans cursor-pointer"
                          >
                            <option value="">Select</option>
                            <option value="Order issue">Order issue</option>
                            <option value="Refund issue">Refund issue</option>
                            <option value="Delivery issue">Delivery issue</option>
                            <option value="Account issue">Account issue</option>
                            <option value="Payment issue">Payment issue</option>
                            <option value="Other">Other</option>
                          </select>
                        </div>

                        {/* Description field */}
                        <div className="space-y-1.5">
                          <label className="text-sm font-bold text-slate-700 font-sans">Ticket description</label>
                          <textarea
                            required
                            rows={6}
                            value={ticketDescription}
                            onChange={(e) => setTicketDescription(e.target.value)}
                            placeholder="Describe your issues.."
                            className="w-full text-sm p-4.5 bg-slate-50 border border-slate-200 rounded-xl focus:border-primary focus:ring-1 focus:ring-primary focus:outline-none placeholder:text-slate-450 font-sans resize-none"
                          />
                        </div>

                        {/* File upload field */}
                        <div className="space-y-1.5">
                          <label className="text-sm font-bold text-slate-700 font-sans">Upload attachment</label>
                          
                          <div className="flex flex-col gap-2.5">
                            <label className="w-full py-5 px-6 border border-dashed border-slate-200/80 bg-slate-50 hover:bg-slate-100 rounded-xl flex items-center justify-center gap-2 cursor-pointer transition-colors text-sm font-bold text-slate-500">
                              <Upload className="h-5 w-5" />
                              Upload photo
                              <input
                                type="file"
                                accept="image/*"
                                onChange={(e) => setTicketAttachment(e.target.files?.[0] || null)}
                                className="hidden"
                              />
                            </label>
                            {ticketAttachment && (
                              <div className="text-xs font-bold text-emerald-600 bg-emerald-50 py-1.5 px-3.5 rounded-lg border border-emerald-100 self-start">
                                Selected file: {ticketAttachment.name}
                              </div>
                            )}
                          </div>
                        </div>

                        {ticketError && (
                          <div className="p-3.5 bg-rose-50 border border-rose-100 rounded-xl text-rose-650 text-xxs font-bold font-sans">
                            {ticketError}
                          </div>
                        )}

                        {ticketSuccess && (
                          <div className="p-3.5 bg-emerald-50 border border-emerald-100 rounded-xl text-emerald-650 text-xxs font-bold font-sans">
                            {ticketSuccess}
                          </div>
                        )}

                        <button
                          type="submit"
                          disabled={submittingTicket}
                          className="theme-btn text-sm py-4 px-8 text-white bg-[#2C3333] hover:bg-neutral-800 rounded-xl cursor-pointer transition-colors flex items-center gap-2 font-bold uppercase disabled:opacity-50 font-sans"
                        >
                          {submittingTicket ? (
                            <Loader2 className="h-4 w-4 animate-spin" />
                          ) : (
                            <>
                              <Plus className="h-4 w-4 text-white" />
                              Create ticket
                            </>
                          )}
                        </button>

                      </form>
                    </div>
                  )}
                </div>
              )}

              {/* TAB 9: MANAGE PROFILE */}
              {activeTab === 'profile' && (
                <div className="space-y-6 text-left">
                  {/* Title Bar in rounded white box */}
                  <div className="bg-white px-6 py-4 rounded-2xl border border-slate-200/60 shadow-[0_8px_30px_rgba(0,0,0,0.02)]">
                    <h3 className="text-[20px] font-extrabold text-[#2C3333] font-sans">Manage profile</h3>
                  </div>

                  {/* Centered card containing forms */}
                  <div className="max-w-xl mx-auto bg-white border border-slate-200/60 rounded-3xl p-8 shadow-[0_8px_30px_rgba(0,0,0,0.03)] space-y-6">
                    
                    {/* Form 1: Profile basic details (Full name, Avatar, Address) */}
                    <form onSubmit={handleProfileUpdate} className="space-y-5">
                      {profileMsg.text && (
                        <div className={`p-4 rounded-xl text-sm font-semibold flex items-center gap-2 ${
                          profileMsg.type === 'success' 
                            ? 'bg-emerald-50 border border-emerald-200 text-emerald-700' 
                            : 'bg-rose-50 border border-rose-200 text-rose-700'
                        }`}>
                          {profileMsg.type === 'success' ? (
                            <CheckCircle2 className="h-4.5 w-4.5 shrink-0 text-emerald-600" />
                          ) : (
                            <AlertCircle className="h-4.5 w-4.5 shrink-0 text-rose-600" />
                          )}
                          <span className="font-sans">{profileMsg.text}</span>
                        </div>
                      )}

                      <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                        {/* Full Name */}
                        <div className="space-y-1.5">
                          <label className="text-sm font-extrabold text-neutral-700 font-sans">Full Name</label>
                          <input
                            type="text"
                            required
                            placeholder="Full Name"
                            value={profileName}
                            onChange={(e) => setProfileName(e.target.value)}
                            className="w-full text-[15px] p-4 bg-slate-50 border border-slate-250 rounded-xl focus:border-primary focus:ring-1 focus:ring-primary focus:outline-none font-sans font-medium"
                          />
                        </div>

                        {/* Avatar upload */}
                        <div className="space-y-1.5">
                          <label className="text-sm font-extrabold text-neutral-700 font-sans">Upload New Photo</label>
                          <input
                            type="file"
                            accept="image/*"
                            onChange={(e) => setProfileAvatar(e.target.files?.[0] || null)}
                            className="w-full text-sm file:mr-4 file:py-2.5 file:px-4 file:rounded-xl file:border-0 file:text-sm file:font-semibold file:bg-slate-200 file:text-[#333333] hover:file:bg-slate-300 border border-slate-200 rounded-xl p-3 bg-slate-50 cursor-pointer font-sans"
                          />
                        </div>
                      </div>

                      {/* Address */}
                      <div className="space-y-1.5">
                        <label className="text-sm font-extrabold text-neutral-700 font-sans">Address</label>
                        <input
                          type="text"
                          placeholder="ex. Dhaka, Bangladesh"
                          value={profileAddress}
                          onChange={(e) => setProfileAddress(e.target.value)}
                          className="w-full text-[15px] p-4 bg-slate-50 border border-slate-250 rounded-xl focus:border-primary focus:ring-1 focus:ring-primary focus:outline-none font-sans font-medium"
                        />
                      </div>

                      {/* Save Changes button */}
                      <button
                        type="submit"
                        disabled={savingProfile}
                        className="w-full py-4.5 bg-[#2d2d2d] hover:bg-neutral-800 text-base font-bold text-white rounded-xl shadow-xs transition-colors cursor-pointer uppercase tracking-wider font-sans disabled:opacity-50"
                      >
                        {savingProfile ? 'Saving Changes...' : 'Save Changes'}
                      </button>
                    </form>

                    {/* Form 2: Phone number */}
                    <form onSubmit={handlePhoneUpdate} className="space-y-2 pt-2 border-t border-slate-100">
                      {phoneMsg.text && (
                        <div className={`p-4 rounded-xl text-sm font-semibold flex items-center gap-2 ${
                          phoneMsg.type === 'success' 
                            ? 'bg-emerald-50 border border-emerald-200 text-emerald-700' 
                            : 'bg-rose-50 border border-rose-200 text-rose-700'
                        }`}>
                          {phoneMsg.type === 'success' ? (
                            <CheckCircle2 className="h-4.5 w-4.5 shrink-0 text-emerald-600" />
                          ) : (
                            <AlertCircle className="h-4.5 w-4.5 shrink-0 text-rose-600" />
                          )}
                          <span className="font-sans">{phoneMsg.text}</span>
                        </div>
                      )}

                      <div className="space-y-1.5">
                        <label className="text-sm font-extrabold text-neutral-700 font-sans">Phone Number</label>
                        <div className="flex items-center border border-slate-250 rounded-xl bg-slate-50 overflow-hidden focus-within:border-primary focus-within:ring-1 focus-within:ring-primary">
                          <input
                            type="text"
                            placeholder="e.g. 01*********"
                            value={profilePhone}
                            onChange={(e) => setProfilePhone(e.target.value)}
                            className="flex-1 text-[15px] p-4 bg-transparent border-0 focus:outline-none font-sans font-medium"
                          />
                          <button
                            type="submit"
                            disabled={savingPhone}
                            className="bg-white border-l border-slate-200 hover:bg-slate-50 px-6 py-4.5 text-sm font-black tracking-wide text-neutral-850 font-sans cursor-pointer uppercase transition-colors shrink-0 disabled:opacity-50"
                          >
                            {savingPhone ? '...' : 'CHANGE NUMBER'}
                          </button>
                        </div>
                      </div>
                    </form>

                    {/* Form 3: Email address */}
                    <form onSubmit={handleEmailUpdate} className="space-y-2 pt-2 border-t border-slate-100">
                      {emailMsg.text && (
                        <div className={`p-4 rounded-xl text-sm font-semibold flex items-center gap-2 ${
                          emailMsg.type === 'success' 
                            ? 'bg-emerald-50 border border-emerald-200 text-emerald-700' 
                            : 'bg-rose-50 border border-rose-200 text-rose-700'
                        }`}>
                          {emailMsg.type === 'success' ? (
                            <CheckCircle2 className="h-4.5 w-4.5 shrink-0 text-emerald-600" />
                          ) : (
                            <AlertCircle className="h-4.5 w-4.5 shrink-0 text-rose-600" />
                          )}
                          <span className="font-sans">{emailMsg.text}</span>
                        </div>
                      )}

                      <div className="space-y-1.5">
                        <label className="text-sm font-extrabold text-neutral-700 font-sans">Email Address</label>
                        <div className="flex items-center border border-slate-250 rounded-xl bg-slate-50 overflow-hidden focus-within:border-primary focus-within:ring-1 focus-within:ring-primary">
                          <input
                            type="email"
                            placeholder="abdullahalmawardi@gmail.com"
                            value={profileEmail}
                            onChange={(e) => setProfileEmail(e.target.value)}
                            className="flex-1 text-[15px] p-4 bg-transparent border-0 focus:outline-none font-sans font-medium"
                          />
                          <button
                            type="submit"
                            disabled={savingEmail}
                            className="bg-white border-l border-slate-200 hover:bg-slate-50 px-6 py-4.5 text-sm font-black tracking-wide text-neutral-850 font-sans cursor-pointer uppercase transition-colors shrink-0 disabled:opacity-50"
                          >
                            {savingEmail ? '...' : 'CHANGE EMAIL'}
                          </button>
                        </div>
                      </div>
                    </form>

                    {/* Google Linked Account Revocation */}
                    <div className="space-y-2.5 pt-4 border-t border-slate-100 text-left">
                      <label className="text-sm font-extrabold text-neutral-700 font-sans">Third-party linked account</label>
                      
                      {socialMsg.text && (
                        <div className={`p-4 rounded-xl text-sm font-semibold flex items-center gap-2 ${
                          socialMsg.type === 'success' 
                            ? 'bg-emerald-50 border border-emerald-200 text-emerald-700' 
                            : 'bg-rose-50 border border-rose-200 text-rose-700'
                        }`}>
                          {socialMsg.type === 'success' ? (
                            <CheckCircle2 className="h-4.5 w-4.5 shrink-0 text-emerald-600" />
                          ) : (
                            <AlertCircle className="h-4.5 w-4.5 shrink-0 text-rose-600" />
                          )}
                          <span className="font-sans">{socialMsg.text}</span>
                        </div>
                      )}

                      {isSocialGoogleConnected ? (
                        <div className="flex items-center justify-between border border-slate-200 rounded-xl p-4 bg-white shadow-xs">
                          <div className="flex items-center gap-3">
                            <svg className="h-5 w-5" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                              <path
                                fill="#4285F4"
                                d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z"
                              />
                              <path
                                fill="#34A853"
                                d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z"
                              />
                              <path
                                fill="#FBBC05"
                                d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.06H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.94l2.85-2.22.81-.63z"
                              />
                              <path
                                fill="#EA4335"
                                d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.06l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z"
                              />
                            </svg>
                            <span className="font-bold text-base text-slate-800 font-sans">Google</span>
                          </div>
                          <button
                            onClick={handleSocialRevoke}
                            disabled={revokingSocial}
                            className="bg-white border border-slate-200 hover:bg-slate-50 px-4 py-2.5 text-sm font-bold text-slate-700 font-sans rounded-xl cursor-pointer transition-colors shadow-xxs disabled:opacity-50"
                          >
                            {revokingSocial ? 'Revoking...' : 'Revoke'}
                          </button>
                        </div>
                      ) : (
                        <div className="flex items-center justify-between border border-slate-200 rounded-xl p-4 bg-slate-50 text-sm font-semibold font-sans text-slate-400 border-dashed">
                          <span>No third-party accounts linked.</span>
                        </div>
                      )}
                    </div>

                  </div>
                </div>
              )}



              {/* TAB 11: PASSWORD RESET */}
              {activeTab === 'password' && (
                <div className="space-y-6 text-left">
                  {/* Title Bar in rounded white box */}
                  <div className="bg-white px-6 py-4 rounded-2xl border border-slate-200/60 shadow-[0_8px_30px_rgba(0,0,0,0.02)]">
                    <h3 className="text-[20px] font-extrabold text-[#2C3333] font-sans">Change password</h3>
                  </div>

                  {/* Centered card containing form */}
                  <div className="max-w-xl mx-auto bg-white border border-slate-200/60 rounded-3xl p-8 shadow-[0_8px_30px_rgba(0,0,0,0.03)] space-y-5">
                    {passwordMessage && (
                      <div className="bg-emerald-50 border border-emerald-200 text-emerald-700 px-4 py-3 rounded-2xl text-sm font-semibold flex items-center gap-2">
                        <CheckCircle2 className="h-5 w-5 text-emerald-600" />
                        <span className="font-sans">{passwordMessage}</span>
                      </div>
                    )}

                    {passwordError && (
                      <div className="bg-rose-50 border border-rose-200 text-rose-600 px-4 py-3 rounded-2xl text-sm font-semibold flex items-center gap-2">
                        <AlertCircle className="h-5 w-5 text-rose-600" />
                        <span className="font-sans">{passwordError}</span>
                      </div>
                    )}

                    <form onSubmit={handleChangePassword} className="space-y-5">
                      {/* Set a new password */}
                      <div className="space-y-1.5">
                        <label className="text-sm font-extrabold text-neutral-700 font-sans">Set a new password</label>
                        <div className="relative flex items-center">
                          <input
                            type={showNewPassword ? 'text' : 'password'}
                            required
                            value={newPassword}
                            onChange={(e) => setNewPassword(e.target.value)}
                            className="w-full text-[15px] p-4 bg-transparent border border-slate-255 rounded-xl focus:border-primary focus:ring-1 focus:ring-primary focus:outline-none font-sans font-medium pr-12"
                          />
                          <button
                            type="button"
                            onClick={() => setShowNewPassword(!showNewPassword)}
                            className="absolute right-4 text-slate-400 hover:text-slate-650 cursor-pointer focus:outline-none"
                          >
                            {showNewPassword ? <EyeOff className="h-5 w-5" /> : <Eye className="h-5 w-5" />}
                          </button>
                        </div>
                      </div>

                      {/* Confirm password */}
                      <div className="space-y-1.5">
                        <label className="text-sm font-extrabold text-neutral-700 font-sans">Confirm password</label>
                        <div className="relative flex items-center">
                          <input
                            type={showConfirmPassword ? 'text' : 'password'}
                            required
                            value={confirmPassword}
                            onChange={(e) => setConfirmPassword(e.target.value)}
                            className="w-full text-[15px] p-4 bg-transparent border border-slate-255 rounded-xl focus:border-primary focus:ring-1 focus:ring-primary focus:outline-none font-sans font-medium pr-12"
                          />
                          <button
                            type="button"
                            onClick={() => setShowConfirmPassword(!showConfirmPassword)}
                            className="absolute right-4 text-slate-400 hover:text-slate-650 cursor-pointer focus:outline-none"
                          >
                            {showConfirmPassword ? <EyeOff className="h-5 w-5" /> : <Eye className="h-5 w-5" />}
                          </button>
                        </div>
                      </div>

                      {/* Update Password button */}
                      <button
                        type="submit"
                        className="w-full py-4.5 bg-[#2d2d2d] hover:bg-neutral-800 text-base font-bold text-white rounded-xl shadow-xs transition-colors cursor-pointer uppercase tracking-wider font-sans mt-2"
                      >
                        Update Password
                      </button>
                    </form>

                  </div>
                </div>
              )}



              {/* TAB 13: DELETE ACCOUNT */}
              {activeTab === 'delete_account' && (
                <div className="space-y-6 text-left">
                  {/* Title Bar in rounded white box */}
                  <div className="bg-white px-6 py-4 rounded-2xl border border-slate-200/60 shadow-[0_8px_30px_rgba(0,0,0,0.02)]">
                    <h3 className="text-[20px] font-extrabold text-[#2C3333] font-sans">Delete Your Account</h3>
                  </div>

                  {/* Warning banner and checkbox controls */}
                  <div className="bg-white border border-slate-200/60 rounded-3xl p-8 shadow-[0_8px_30px_rgba(0,0,0,0.03)] space-y-5">
                    {/* Warning box */}
                    <div className="border border-red-500 rounded-xl p-6 bg-red-50/10 text-left">
                      <h4 className="text-base font-extrabold text-red-650 mb-2 font-sans">Warning!</h4>
                      <p className="text-sm font-semibold text-red-650 leading-relaxed font-sans">
                        Deleting your account is permanent and cannot be undone. All your personal information, reviews, and saved addresses will be permanently removed.
                      </p>
                    </div>

                    {/* Understanding Checkbox */}
                    <label className="flex items-center gap-3.5 mt-4 text-slate-500 text-sm font-bold font-sans cursor-pointer select-none">
                      <input
                        type="checkbox"
                        checked={confirmDeleteCheckbox}
                        onChange={(e) => setConfirmDeleteCheckbox(e.target.checked)}
                        className="h-4.5 w-4.5 border-slate-350 rounded-md text-primary focus:ring-primary cursor-pointer"
                      />
                      <span>I understand that this action cannot be undone</span>
                    </label>

                    {/* Buttons row */}
                    <div className="flex items-center justify-between pt-4 border-t border-slate-100 mt-6">
                      <button
                        onClick={() => {
                          setConfirmDeleteCheckbox(false);
                          router.push('/dashboard');
                        }}
                        className="bg-[#2C3333] hover:bg-neutral-800 text-white px-8 py-4 rounded-lg text-sm font-bold font-sans transition-colors cursor-pointer uppercase"
                      >
                        CANCEL
                      </button>
                      
                      <button
                        onClick={handleDeleteAccount}
                        disabled={!confirmDeleteCheckbox}
                        className={`bg-white border px-6 py-4 rounded-lg text-sm font-bold font-sans transition-colors cursor-pointer ${
                          confirmDeleteCheckbox 
                            ? 'text-[#2C3333] border-slate-300 hover:bg-slate-50' 
                            : 'text-slate-400 border-slate-250 cursor-not-allowed opacity-50'
                        }`}
                      >
                        DELETE MY ACCOUNT
                      </button>
                    </div>
                  </div>
                </div>
              )}

            </div>

          </div>
        </div>

        {/* Review Modal */}
        {showReviewModal && reviewProduct && (
          <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4 animate-fade-in">
            <div className="bg-white rounded-3xl p-6 max-w-md w-full shadow-2xl border border-slate-100 transform scale-100 transition-all text-left">
              <div className="flex justify-between items-start mb-4">
                <div>
                  <h3 className="text-[18px] font-bold text-slate-800 font-sans font-bold">Write a Product Review</h3>
                  <p className="text-[12px] text-slate-400 font-medium font-sans mt-0.5">{reviewProduct.name}</p>
                </div>
                <button 
                  onClick={() => setShowReviewModal(false)}
                  className="p-1 rounded-lg hover:bg-slate-100 text-slate-400 transition-colors"
                >
                  <X className="h-5 w-5" />
                </button>
              </div>
              
              <form onSubmit={handleReviewSubmit} className="space-y-4">
                <div className="space-y-1.5">
                  <label className="text-[11px] font-bold text-slate-400 uppercase tracking-wider block font-sans">Rating</label>
                  <div className="flex items-center gap-1.5">
                    {[1, 2, 3, 4, 5].map((star) => (
                      <button
                        type="button"
                        key={star}
                        onClick={() => setReviewRating(star)}
                        className="p-0.5 rounded-lg hover:scale-110 transition-transform cursor-pointer"
                      >
                        <Star 
                          className={`h-7 w-7 ${
                            star <= reviewRating 
                              ? 'text-amber-400 fill-amber-400' 
                              : 'text-slate-200 hover:text-amber-300'
                          }`} 
                        />
                      </button>
                    ))}
                  </div>
                </div>
                
                <div className="space-y-1.5">
                  <label className="text-[11px] font-bold text-slate-400 uppercase tracking-wider block font-sans">Your Review</label>
                  <textarea
                    required
                    rows={4}
                    value={reviewComment}
                    onChange={(e) => setReviewComment(e.target.value)}
                    placeholder="Tell us what you liked or disliked about this product..."
                    className="w-full text-xs p-3.5 bg-slate-50 border border-slate-200 rounded-xl focus:border-primary focus:ring-1 focus:ring-primary focus:outline-none placeholder:text-slate-400 font-sans resize-none"
                  />
                </div>

                {reviewError && (
                  <div className="p-3 bg-rose-50 border border-rose-100 rounded-xl text-rose-650 text-xxs font-bold font-sans">
                    {reviewError}
                  </div>
                )}

                {reviewSuccessMsg && (
                  <div className="p-3 bg-emerald-50 border border-emerald-100 rounded-xl text-emerald-650 text-xxs font-bold font-sans">
                    {reviewSuccessMsg}
                  </div>
                )}
                
                <div className="flex justify-end gap-3 pt-2">
                  <button
                    type="button"
                    onClick={() => setShowReviewModal(false)}
                    className="px-4 py-2 border border-slate-200 text-slate-500 rounded-xl text-xs font-bold hover:bg-slate-50 cursor-pointer font-sans"
                  >
                    Cancel
                  </button>
                  <button
                    type="submit"
                    disabled={submittingReview}
                    className="px-4 py-2 bg-primary text-white rounded-xl text-xs font-bold hover:bg-primary-dark cursor-pointer transition-colors shadow-md shadow-secondary/20 flex items-center gap-1.5 disabled:opacity-50 font-sans"
                  >
                    {submittingReview ? (
                      <Loader2 className="h-3.5 w-3.5 animate-spin" />
                    ) : 'Submit Review'}
                  </button>
                </div>
              </form>
            </div>
          </div>
        )}

      </main>
      <Footer />
    </>
  );
}

// Helper to format prices
function numberWithCommas(x: number | null | undefined) {
  if (x === null || x === undefined || isNaN(Number(x))) {
    return '0';
  }
  return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
