"use client"

import { useState, useEffect, Suspense } from "react"
import Link from "next/link"
import { useRouter, useSearchParams } from "next/navigation"
import {
  User, ShoppingBag, MapPin, Compass, ArrowRight, CheckCircle,
  ChevronDown, LogOut, Mail, Search, AlertCircle, CheckCircle2,
  Lock, Eye, EyeOff, UserPlus, Phone, RefreshCw, FileText, XCircle,
} from "lucide-react"
import Header from "@/components/Header"
import Footer from "@/components/Footer"
import { GoogleOAuthProvider, GoogleLogin } from "@react-oauth/google"
import Swal from "sweetalert2";

type OrderItem = {
  id: string; quantity: number; price: number
  productTitle: string; thumbnail: string; color: string; size: string; length: string | null
}

type Order = {
  id: string; totalAmount: number; status: string
  paymentStatus: string; shippingAddress: string; shippingPhone: string
  createdAt: string; items: OrderItem[]
}

type CustomerProfile = { id: string; name: string; email: string; phone: string }

// ─── Auth Mode ───────────────────────────────────────────────────────────────
type AuthMode = "login" | "register"

async function AccountPageContent({ clientId }: { clientId: string }) {
  const router = useRouter()
  const searchParams = useSearchParams()

  const [mounted, setMounted] = useState(false)
  const [authMode, setAuthMode] = useState<AuthMode>("login")
  const [isLoggedIn, setIsLoggedIn] = useState(false)

  // Login form
  const [loginEmail, setLoginEmail] = useState("")
  const [loginPassword, setLoginPassword] = useState("")
  const [showLoginPassword, setShowLoginPassword] = useState(false)
  const [loginLoading, setLoginLoading] = useState(false)
  const [loginError, setLoginError] = useState("")

  // Register form
  const [regName, setRegName] = useState("")
  const [regEmail, setRegEmail] = useState("")
  const [regPhone, setRegPhone] = useState("")
  const [regPassword, setRegPassword] = useState("")
  const [showRegPassword, setShowRegPassword] = useState(false)
  const [regLoading, setRegLoading] = useState(false)
  const [regError, setRegError] = useState("")
  const [regSuccess, setRegSuccess] = useState("")

  // Dashboard state
  const [profile, setProfile] = useState<CustomerProfile | null>(null)
  const [orders, setOrders] = useState<Order[]>([])
  const [dashLoading, setDashLoading] = useState(false)
  const [activeTab, setActiveTab] = useState<"orders" | "profile" | "track">("orders")
  const [expandedOrders, setExpandedOrders] = useState<Record<string, boolean>>({})
  const [editName, setEditName] = useState("")
  const [editPhone, setEditPhone] = useState("")
  const [updatingProfile, setUpdatingProfile] = useState(false)
  const [profileSuccessMsg, setProfileSuccessMsg] = useState("")

  // Order cancel & return state
  const [cancellingOrder, setCancellingOrder] = useState<string | null>(null)
  const [returnOrderId, setReturnOrderId] = useState<string | null>(null)
  const [returnReason, setReturnReason] = useState("")
  const [submittingReturn, setSubmittingReturn] = useState(false)

  // Track state
  const [trackOrderId, setTrackOrderId] = useState("")
  const [trackingOrder, setTrackingOrder] = useState<any>(null)
  const [trackingStages, setTrackingStages] = useState<any[]>([])
  const [trackingLoading, setTrackingLoading] = useState(false)
  const [trackingError, setTrackingError] = useState("")

  // ── Check login status on mount ─────────────────────────────────────────────
  useEffect(() => {
    setMounted(true)
    const savedSession = localStorage.getItem("ag_customer_session")
    if (savedSession) {
      try {
        const parsed = JSON.parse(savedSession)
        setProfile(parsed)
        setIsLoggedIn(true)
        fetchOrders(parsed.email)
      } catch {}
    }
    const urlOrderId = searchParams.get("track")
    if (urlOrderId) {
      setTrackOrderId(urlOrderId)
      setActiveTab("track")
      handleTrackOrder(urlOrderId)
    }
  }, [searchParams])

  // ── Login ───────────────────────────────────────────────────────────────────
  const handleLogin = async (e: React.FormEvent) => {
    e.preventDefault()
    setLoginError("")
    setLoginLoading(true)
    try {
      const res = await fetch("/api/auth/customer/login", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ email: loginEmail, password: loginPassword }),
      })
      const data = await res.json()
      if (!res.ok) throw new Error(data.message)

      localStorage.setItem("ag_customer_session", JSON.stringify(data.user))
      localStorage.setItem("customer-email", data.user.email)
      setProfile(data.user)
      setEditName(data.user.name)
      setEditPhone(data.user.phone || "")
      setIsLoggedIn(true)
      await fetchOrders(data.user.email)
    } catch (err: any) {
      setLoginError(err.message || "Login failed. Please try again.")
    } finally {
      setLoginLoading(false)
    }
  }

  // ── Google Login ────────────────────────────────────────────────────────────
  const handleGoogleSuccess = async (credentialResponse: any) => {
    setLoginError("")
    setRegError("")
    setLoginLoading(true)
    try {
      const res = await fetch("/api/auth/customer/google", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ credential: credentialResponse.credential }),
      })
      const data = await res.json()
      if (!res.ok) throw new Error(data.message)

      localStorage.setItem("ag_customer_session", JSON.stringify(data.user))
      localStorage.setItem("customer-email", data.user.email)
      setProfile(data.user)
      setEditName(data.user.name)
      setEditPhone(data.user.phone || "")
      setIsLoggedIn(true)
      await fetchOrders(data.user.email)
    } catch (err: any) {
      setLoginError(err.message || "Google login failed. Please try again.")
    } finally {
      setLoginLoading(false)
    }
  }

  // ── Register ────────────────────────────────────────────────────────────────
  const handleRegister = async (e: React.FormEvent) => {
    e.preventDefault()
    setRegError("")
    setRegSuccess("")
    setRegLoading(true)
    try {
      const res = await fetch("/api/auth/customer/register", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ name: regName, email: regEmail, phone: regPhone, password: regPassword }),
      })
      const data = await res.json()
      if (!res.ok) throw new Error(data.message)
      setRegSuccess("Account created! Please login now.")
      setTimeout(() => { setAuthMode("login"); setLoginEmail(regEmail); setRegSuccess("") }, 2000)
    } catch (err: any) {
      setRegError(err.message || "Registration failed.")
    } finally {
      setRegLoading(false)
    }
  }

  // ── Logout ──────────────────────────────────────────────────────────────────
  const handleLogout = async () => {
    await fetch("/api/auth/customer/logout", { method: "POST" })
    localStorage.removeItem("ag_customer_session")
    localStorage.removeItem("customer-email")
    setIsLoggedIn(false)
    setProfile(null)
    setOrders([])
  }

  // ── Fetch orders ─────────────────────────────────────────────────────────────
  const fetchOrders = async (email: string) => {
    setDashLoading(true)
    try {
      const res = await fetch(`/api/customer/account?email=${encodeURIComponent(email)}`)
      const data = await res.json()
      if (data.found) {
        setOrders(data.orders || [])
        setEditName(data.user.name)
        setEditPhone(data.user.phone || "")
      }
    } catch { }
    setDashLoading(false)
  }

  // ── Update profile ──────────────────────────────────────────────────────────
  const handleUpdateProfile = async (e: React.FormEvent) => {
    e.preventDefault()
    setUpdatingProfile(true)
    setProfileSuccessMsg("")
    try {
      const res = await fetch("/api/customer/account", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ email: profile?.email, name: editName, phone: editPhone }),
      })
      const data = await res.json()
      if (!res.ok) throw new Error(data.error)
      const updated = { ...profile!, name: editName, phone: editPhone }
      setProfile(updated)
      localStorage.setItem("ag_customer_session", JSON.stringify(updated))
      setProfileSuccessMsg("Profile updated successfully!")
      setTimeout(() => setProfileSuccessMsg(""), 3000)
    } catch (err: any) {
      Swal.fire({ text: err.message || "Failed to update profile.", confirmButtonColor: "#18181b", icon: "error" })
    } finally {
      setUpdatingProfile(false)
    }
  }

  // ── Cancel order ────────────────────────────────────────────────────────────
  const handleCancelOrder = async (orderId: string) => {
    if (!(await Swal.fire({ title: "Are you sure?", text: "Are you sure you want to cancel this order?", icon: "warning", showCancelButton: true, confirmButtonColor: "#18181b", cancelButtonColor: "#ef4444", confirmButtonText: "Yes" })).isConfirmed) return
    setCancellingOrder(orderId)
    try {
      const res = await fetch(`/api/customer/orders/${orderId}/cancel`, { method: "POST" })
      const data = await res.json()
      if (!res.ok) throw new Error(data.message)
      Swal.fire({ text: "Order cancelled successfully.", confirmButtonColor: "#18181b", icon: "success" })
      if (profile) await fetchOrders(profile.email)
    } catch (err: any) {
      Swal.fire({ text: err.message || "Failed to cancel order.", confirmButtonColor: "#18181b", icon: "error" })
    } finally {
      setCancellingOrder(null)
    }
  }

  // ── Submit return ─────────────────────────────────────────────────────────────
  const handleSubmitReturn = async () => {
    if (!returnReason.trim()) { Swal.fire({ text: "Please enter a reason for the return.", confirmButtonColor: "#18181b" }); return }
    setSubmittingReturn(true)
    try {
      const res = await fetch("/api/customer/returns", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ orderId: returnOrderId, userId: profile?.id, reason: returnReason }),
      })
      const data = await res.json()
      if (!res.ok) throw new Error(data.message)
      Swal.fire({ text: "Return request submitted successfully. We'll review it shortly.", confirmButtonColor: "#18181b", icon: "success" })
      setReturnOrderId(null)
      setReturnReason("")
    } catch (err: any) {
      Swal.fire({ text: err.message || "Failed to submit return request.", confirmButtonColor: "#18181b", icon: "error" })
    } finally {
      setSubmittingReturn(false)
    }
  }

  // ── Track order ─────────────────────────────────────────────────────────────
  const handleTrackOrder = async (id?: string) => {
    const orderId = id || trackOrderId
    if (!orderId) { setTrackingError("Please enter an Order ID."); return }
    setTrackingLoading(true)
    setTrackingError("")
    setTrackingOrder(null)
    try {
      const res = await fetch(`/api/customer/track?orderId=${encodeURIComponent(orderId)}`)
      const data = await res.json()
      if (!res.ok || !data.found) throw new Error(data.message || "Order not found.")
      setTrackingOrder(data.order)
      setTrackingStages(data.stages)
    } catch (err: any) {
      setTrackingError(err.message)
    } finally {
      setTrackingLoading(false)
    }
  }

  if (!mounted) return <div className="min-h-screen bg-zinc-50 flex items-center justify-center"><div className="w-8 h-8 border-2 border-zinc-200 border-t-zinc-950 rounded-full animate-spin" /></div>

  return (
    <div className="flex flex-col min-h-screen bg-zinc-50/50 text-zinc-950 font-sans antialiased">
      <Header />

      <main className="flex-1 max-w-5xl w-full mx-auto px-4 sm:px-6 py-12">

        {/* ── AUTH PORTAL ─────────────────────────────────────────────────────── */}
        {!isLoggedIn ? (
          <div className="max-w-md mx-auto">
            <div className="bg-white border border-zinc-100 rounded-2xl p-8 shadow-xl shadow-zinc-100/40">
              <div className="text-center mb-8">
                <div className="w-16 h-16 bg-zinc-950 rounded-2xl flex items-center justify-center mx-auto mb-5">
                  <User className="w-8 h-8 text-white" />
                </div>
                <h1 className="text-2xl font-black uppercase tracking-tight text-zinc-900">
                  {authMode === "login" ? "Sign In" : "Create Account"}
                </h1>
                <p className="text-zinc-400 text-xs mt-2">
                  {authMode === "login" ? "Access your orders and account details." : "Register to track orders and save your details."}
                </p>
              </div>

              {/* Tab Toggle */}
              <div className="flex border border-zinc-200 rounded-xl overflow-hidden mb-6">
                <button onClick={() => { setAuthMode("login"); setLoginError(""); setRegError(""); setRegSuccess("") }} className={`flex-1 py-3 text-xs font-bold uppercase tracking-widest transition-colors ${authMode === "login" ? "bg-zinc-950 text-white" : "bg-white text-zinc-500 hover:text-zinc-900"}`}>Sign In</button>
                <button onClick={() => { setAuthMode("register"); setLoginError(""); setRegError(""); setRegSuccess("") }} className={`flex-1 py-3 text-xs font-bold uppercase tracking-widest transition-colors ${authMode === "register" ? "bg-zinc-950 text-white" : "bg-white text-zinc-500 hover:text-zinc-900"}`}>Register</button>
              </div>

              {/* Login Form */}
              {authMode === "login" && (
                <form onSubmit={handleLogin} className="space-y-4">
                  {clientId && (
                    <>
                      <div className="flex justify-center mb-2">
                        <GoogleLogin
                          onSuccess={handleGoogleSuccess}
                          onError={() => setLoginError("Google login was unsuccessful.")}
                          useOneTap
                        />
                      </div>
                      <div className="relative flex items-center py-2">
                        <div className="flex-grow border-t border-zinc-200"></div>
                        <span className="flex-shrink-0 mx-4 text-zinc-400 text-[10px] uppercase font-bold tracking-widest">or sign in with email</span>
                        <div className="flex-grow border-t border-zinc-200"></div>
                      </div>
                    </>
                  )}
                  <div>
                    <label className="block text-[10px] font-bold uppercase tracking-widest text-zinc-400 mb-1.5">Email</label>
                    <div className="relative">
                      <Mail className="absolute left-3.5 top-3.5 w-4 h-4 text-zinc-400" />
                      <input type="email" required value={loginEmail} onChange={e => setLoginEmail(e.target.value)} placeholder="you@example.com" className="w-full pl-10 pr-4 py-3 text-sm border border-zinc-200 bg-zinc-50 focus:bg-white focus:outline-none focus:ring-2 focus:ring-zinc-950 transition rounded-lg" />
                    </div>
                  </div>
                  <div>
                    <label className="block text-[10px] font-bold uppercase tracking-widest text-zinc-400 mb-1.5">Password</label>
                    <div className="relative">
                      <Lock className="absolute left-3.5 top-3.5 w-4 h-4 text-zinc-400" />
                      <input type={showLoginPassword ? "text" : "password"} required value={loginPassword} onChange={e => setLoginPassword(e.target.value)} placeholder="••••••••" className="w-full pl-10 pr-10 py-3 text-sm border border-zinc-200 bg-zinc-50 focus:bg-white focus:outline-none focus:ring-2 focus:ring-zinc-950 transition rounded-lg" />
                      <button type="button" onClick={() => setShowLoginPassword(p => !p)} className="absolute right-3.5 top-3.5 text-zinc-400 hover:text-zinc-700">
                        {showLoginPassword ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
                      </button>
                    </div>
                  </div>
                  {loginError && <p className="text-red-500 text-xs flex items-center gap-1.5"><AlertCircle className="w-3.5 h-3.5" />{loginError}</p>}
                  <button type="submit" disabled={loginLoading} className="w-full bg-zinc-950 hover:bg-zinc-800 text-white font-bold py-3.5 rounded-xl transition text-xs uppercase tracking-widest disabled:opacity-50 flex items-center justify-center gap-2">
                    {loginLoading ? "Signing in..." : <><ArrowRight className="w-4 h-4" /> Sign In</>}
                  </button>
                </form>
              )}

              {/* Register Form */}
              {authMode === "register" && (
                <form onSubmit={handleRegister} className="space-y-4">
                  {clientId && (
                    <>
                      <div className="flex justify-center mb-2">
                        <GoogleLogin
                          text="signup_with"
                          onSuccess={handleGoogleSuccess}
                          onError={() => setRegError("Google signup was unsuccessful.")}
                        />
                      </div>
                      <div className="relative flex items-center py-2">
                        <div className="flex-grow border-t border-zinc-200"></div>
                        <span className="flex-shrink-0 mx-4 text-zinc-400 text-[10px] uppercase font-bold tracking-widest">or register with email</span>
                        <div className="flex-grow border-t border-zinc-200"></div>
                      </div>
                    </>
                  )}
                  <div>
                    <label className="block text-[10px] font-bold uppercase tracking-widest text-zinc-400 mb-1.5">Full Name</label>
                    <div className="relative">
                      <User className="absolute left-3.5 top-3.5 w-4 h-4 text-zinc-400" />
                      <input type="text" required value={regName} onChange={e => setRegName(e.target.value)} placeholder="Your Name" className="w-full pl-10 pr-4 py-3 text-sm border border-zinc-200 bg-zinc-50 focus:bg-white focus:outline-none focus:ring-2 focus:ring-zinc-950 transition rounded-lg" />
                    </div>
                  </div>
                  <div>
                    <label className="block text-[10px] font-bold uppercase tracking-widest text-zinc-400 mb-1.5">Email</label>
                    <div className="relative">
                      <Mail className="absolute left-3.5 top-3.5 w-4 h-4 text-zinc-400" />
                      <input type="email" required value={regEmail} onChange={e => setRegEmail(e.target.value)} placeholder="you@example.com" className="w-full pl-10 pr-4 py-3 text-sm border border-zinc-200 bg-zinc-50 focus:bg-white focus:outline-none focus:ring-2 focus:ring-zinc-950 transition rounded-lg" />
                    </div>
                  </div>
                  <div>
                    <label className="block text-[10px] font-bold uppercase tracking-widest text-zinc-400 mb-1.5">Phone (Optional)</label>
                    <div className="relative">
                      <Phone className="absolute left-3.5 top-3.5 w-4 h-4 text-zinc-400" />
                      <input type="tel" value={regPhone} onChange={e => setRegPhone(e.target.value)} placeholder="+880 17XX XXXXXX" className="w-full pl-10 pr-4 py-3 text-sm border border-zinc-200 bg-zinc-50 focus:bg-white focus:outline-none focus:ring-2 focus:ring-zinc-950 transition rounded-lg" />
                    </div>
                  </div>
                  <div>
                    <label className="block text-[10px] font-bold uppercase tracking-widest text-zinc-400 mb-1.5">Password</label>
                    <div className="relative">
                      <Lock className="absolute left-3.5 top-3.5 w-4 h-4 text-zinc-400" />
                      <input type={showRegPassword ? "text" : "password"} required minLength={6} value={regPassword} onChange={e => setRegPassword(e.target.value)} placeholder="Min 6 characters" className="w-full pl-10 pr-10 py-3 text-sm border border-zinc-200 bg-zinc-50 focus:bg-white focus:outline-none focus:ring-2 focus:ring-zinc-950 transition rounded-lg" />
                      <button type="button" onClick={() => setShowRegPassword(p => !p)} className="absolute right-3.5 top-3.5 text-zinc-400 hover:text-zinc-700">
                        {showRegPassword ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
                      </button>
                    </div>
                  </div>
                  {regError && <p className="text-red-500 text-xs flex items-center gap-1.5"><AlertCircle className="w-3.5 h-3.5" />{regError}</p>}
                  {regSuccess && <p className="text-emerald-600 text-xs flex items-center gap-1.5"><CheckCircle2 className="w-3.5 h-3.5" />{regSuccess}</p>}
                  <button type="submit" disabled={regLoading} className="w-full bg-zinc-950 hover:bg-zinc-800 text-white font-bold py-3.5 rounded-xl transition text-xs uppercase tracking-widest disabled:opacity-50 flex items-center justify-center gap-2">
                    {regLoading ? "Creating account..." : <><UserPlus className="w-4 h-4" /> Create Account</>}
                  </button>
                </form>
              )}
            </div>
          </div>
        ) : (
          /* ── DASHBOARD ──────────────────────────────────────────────────────── */
          <div className="space-y-6 animate-in fade-in duration-300">
            {/* Header */}
            <div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4 bg-white border border-zinc-100 rounded-2xl p-6 shadow-sm">
              <div className="flex items-center gap-4">
                <div className="w-12 h-12 bg-zinc-950 text-white font-black rounded-full flex items-center justify-center text-lg">
                  {profile?.name?.charAt(0).toUpperCase() || "U"}
                </div>
                <div>
                  <h1 className="text-xl font-black uppercase tracking-tight text-zinc-900">Welcome, {profile?.name}!</h1>
                  <p className="text-zinc-400 text-xs mt-0.5">{profile?.email}</p>
                </div>
              </div>
              <button onClick={handleLogout} className="inline-flex items-center gap-1.5 px-4 py-2.5 border border-zinc-200 rounded-xl text-[10px] font-bold uppercase tracking-wider text-zinc-500 hover:text-red-500 hover:bg-red-50 hover:border-red-100 transition cursor-pointer">
                <LogOut className="w-3.5 h-3.5" /> Sign Out
              </button>
            </div>

            <div className="grid grid-cols-1 lg:grid-cols-12 gap-6 items-start">
              {/* Sidebar Nav */}
              <div className="lg:col-span-3 flex flex-row lg:flex-col gap-2 overflow-x-auto lg:overflow-visible">
                {([
                  { id: "orders", label: "My Orders", icon: ShoppingBag },
                  { id: "profile", label: "Profile", icon: User },
                  { id: "track", label: "Track Order", icon: Compass },
                ] as const).map(tab => (
                  <button key={tab.id} onClick={() => setActiveTab(tab.id)}
                    className={`flex items-center gap-3 px-4 py-3 text-xs font-bold uppercase tracking-wider rounded-xl transition shrink-0 ${activeTab === tab.id ? "bg-zinc-950 text-white" : "bg-white text-zinc-500 hover:text-zinc-900 border border-zinc-200"}`}>
                    <tab.icon className="w-4 h-4" />{tab.label}
                  </button>
                ))}
              </div>

              {/* Main Content */}
              <div className="lg:col-span-9 bg-white border border-zinc-100 rounded-2xl p-6 shadow-sm">

                {/* ── ORDERS TAB ──────────────────────────────────────────────── */}
                {activeTab === "orders" && (
                  <div className="space-y-5">
                    <div className="flex items-center justify-between border-b border-zinc-100 pb-4">
                      <div>
                        <h2 className="text-base font-black uppercase tracking-wide text-zinc-900">Order History</h2>
                        <p className="text-zinc-400 text-xs mt-0.5">Manage and track all your orders.</p>
                      </div>
                      <button onClick={() => profile && fetchOrders(profile.email)} className="text-zinc-400 hover:text-zinc-950 transition"><RefreshCw className="w-4 h-4" /></button>
                    </div>

                    {dashLoading ? (
                      <div className="flex items-center justify-center py-16"><div className="w-8 h-8 border-2 border-zinc-200 border-t-zinc-950 rounded-full animate-spin" /></div>
                    ) : orders.length === 0 ? (
                      <div className="text-center py-16 border border-dashed border-zinc-200 rounded-2xl">
                        <ShoppingBag className="w-10 h-10 text-zinc-300 mx-auto mb-3" />
                        <p className="text-sm font-bold text-zinc-900 uppercase">No orders yet</p>
                        <Link href="/shop" className="mt-4 inline-block bg-zinc-950 text-white text-[10px] font-bold uppercase tracking-widest px-6 py-2.5 rounded-lg">Shop Now</Link>
                      </div>
                    ) : (
                      <div className="space-y-4">
                        {orders.map(order => {
                          const isExpanded = !!expandedOrders[order.id]
                          const date = new Date(order.createdAt).toLocaleDateString("en-US", { year: "numeric", month: "short", day: "numeric" })
                          return (
                            <div key={order.id} className="border border-zinc-100 rounded-2xl overflow-hidden">
                              <div onClick={() => setExpandedOrders(p => ({ ...p, [order.id]: !p[order.id] }))} className="flex flex-wrap items-center justify-between gap-4 p-4 bg-zinc-50/50 cursor-pointer hover:bg-zinc-50 transition">
                                <div className="space-y-1">
                                  <div className="flex items-center gap-2">
                                    <span className="text-[10px] font-mono font-bold text-zinc-500">#{order.id.slice(-8).toUpperCase()}</span>
                                    <span className="text-[9px] bg-zinc-950 text-white px-2 py-0.5 rounded font-bold">{date}</span>
                                  </div>
                                  <p className="text-sm font-black text-zinc-900">৳{order.totalAmount.toLocaleString("en-US", { minimumFractionDigits: 2 })}</p>
                                </div>
                                <div className="flex items-center gap-3">
                                  <span className={`text-[9px] font-extrabold uppercase px-2 py-0.5 rounded border ${order.status === "DELIVERED" ? "bg-emerald-50 text-emerald-600 border-emerald-100" : order.status === "SHIPPED" ? "bg-blue-50 text-blue-600 border-blue-100" : order.status === "CANCELLED" ? "bg-red-50 text-red-600 border-red-100" : "bg-amber-50 text-amber-600 border-amber-100"}`}>
                                    {order.status}
                                  </span>
                                  <ChevronDown className={`w-4 h-4 text-zinc-400 transition-transform ${isExpanded ? "rotate-180" : ""}`} />
                                </div>
                              </div>

                              {isExpanded && (
                                <div className="p-5 space-y-5 border-t border-zinc-100">
                                  {/* Items */}
                                  <div className="space-y-3">
                                    {order.items.map(item => (
                                      <div key={item.id} className="flex gap-4 items-center">
                                        <div className="w-12 h-16 rounded-lg bg-zinc-50 border border-zinc-100 overflow-hidden shrink-0">
                                          <img src={item.thumbnail} alt={item.productTitle} className="w-full h-full object-cover" />
                                        </div>
                                        <div className="flex-1 min-w-0">
                                          <h4 className="text-xs font-bold uppercase truncate text-zinc-900">{item.productTitle}</h4>
                                          <p className="text-[10px] text-zinc-400 mt-0.5">{item.color} · {item.size} {item.length ? `· ${item.length}` : ""} · Qty {item.quantity}</p>
                                        </div>
                                        <p className="text-xs font-black text-zinc-950">৳{(item.price * item.quantity).toLocaleString()}</p>
                                      </div>
                                    ))}
                                  </div>

                                  {/* Order Actions */}
                                  <div className="flex flex-wrap gap-2 pt-2 border-t border-zinc-100">
                                    <Link href={`/orders/${order.id}/invoice`} target="_blank" className="inline-flex items-center gap-1.5 px-3 py-2 text-[10px] font-bold uppercase tracking-widest border border-zinc-200 rounded-lg hover:bg-zinc-950 hover:text-white hover:border-zinc-950 transition">
                                      <FileText className="w-3 h-3" /> Invoice
                                    </Link>
                                    <button onClick={() => { setActiveTab("track"); setTrackOrderId(order.id); handleTrackOrder(order.id) }} className="inline-flex items-center gap-1.5 px-3 py-2 text-[10px] font-bold uppercase tracking-widest border border-zinc-200 rounded-lg hover:bg-zinc-950 hover:text-white hover:border-zinc-950 transition">
                                      <Compass className="w-3 h-3" /> Track
                                    </button>
                                    {order.status === "PENDING" && (
                                      <button onClick={() => handleCancelOrder(order.id)} disabled={cancellingOrder === order.id} className="inline-flex items-center gap-1.5 px-3 py-2 text-[10px] font-bold uppercase tracking-widest border border-red-200 text-red-500 rounded-lg hover:bg-red-500 hover:text-white hover:border-red-500 transition disabled:opacity-50">
                                        <XCircle className="w-3 h-3" /> {cancellingOrder === order.id ? "Cancelling..." : "Cancel"}
                                      </button>
                                    )}
                                    {order.status === "DELIVERED" && (
                                      <button onClick={() => setReturnOrderId(order.id)} className="inline-flex items-center gap-1.5 px-3 py-2 text-[10px] font-bold uppercase tracking-widest border border-blue-200 text-blue-500 rounded-lg hover:bg-blue-500 hover:text-white hover:border-blue-500 transition">
                                        <RefreshCw className="w-3 h-3" /> Return
                                      </button>
                                    )}
                                  </div>
                                </div>
                              )}
                            </div>
                          )
                        })}
                      </div>
                    )}
                  </div>
                )}

                {/* ── PROFILE TAB ─────────────────────────────────────────────── */}
                {activeTab === "profile" && (
                  <div className="space-y-6">
                    <div className="border-b border-zinc-100 pb-4">
                      <h2 className="text-base font-black uppercase tracking-wide text-zinc-900">Profile Details</h2>
                    </div>
                    <form onSubmit={handleUpdateProfile} className="space-y-5">
                      <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                        <div>
                          <label className="block text-[10px] font-bold uppercase tracking-widest text-zinc-400 mb-1.5">Full Name</label>
                          <input type="text" required value={editName} onChange={e => setEditName(e.target.value)} className="w-full px-4 py-3 text-sm border border-zinc-200 bg-zinc-50 focus:bg-white focus:outline-none focus:ring-2 focus:ring-zinc-950 transition rounded-lg" />
                        </div>
                        <div>
                          <label className="block text-[10px] font-bold uppercase tracking-widest text-zinc-400 mb-1.5">Phone</label>
                          <input type="tel" value={editPhone} onChange={e => setEditPhone(e.target.value)} className="w-full px-4 py-3 text-sm border border-zinc-200 bg-zinc-50 focus:bg-white focus:outline-none focus:ring-2 focus:ring-zinc-950 transition rounded-lg" />
                        </div>
                        <div className="sm:col-span-2">
                          <label className="block text-[10px] font-bold uppercase tracking-widest text-zinc-300 mb-1.5">Email (Cannot be changed)</label>
                          <input type="email" disabled value={profile?.email} className="w-full px-4 py-3 text-sm border border-zinc-150 bg-zinc-100 text-zinc-400 cursor-not-allowed rounded-lg" />
                        </div>
                      </div>
                      {profileSuccessMsg && (
                        <p className="text-emerald-600 text-xs flex items-center gap-1.5"><CheckCircle2 className="w-3.5 h-3.5" />{profileSuccessMsg}</p>
                      )}
                      <button type="submit" disabled={updatingProfile} className="bg-zinc-950 hover:bg-zinc-800 text-white font-bold py-3 px-6 rounded-xl transition text-xs uppercase tracking-widest disabled:opacity-50">
                        {updatingProfile ? "Saving..." : "Save Changes"}
                      </button>
                    </form>
                  </div>
                )}

                {/* ── TRACK TAB ───────────────────────────────────────────────── */}
                {activeTab === "track" && (
                  <div className="space-y-6">
                    <div className="border-b border-zinc-100 pb-4">
                      <h2 className="text-base font-black uppercase tracking-wide text-zinc-900">Track Order</h2>
                    </div>
                    <div className="flex gap-3">
                      <div className="relative flex-1">
                        <Search className="absolute left-3.5 top-3.5 w-4 h-4 text-zinc-400" />
                        <input type="text" value={trackOrderId} onChange={e => setTrackOrderId(e.target.value)} placeholder="Enter your Order ID..." className="w-full pl-10 pr-4 py-3 text-sm border border-zinc-200 bg-zinc-50 focus:bg-white focus:outline-none focus:ring-2 focus:ring-zinc-950 transition rounded-lg" />
                      </div>
                      <button onClick={() => handleTrackOrder()} disabled={trackingLoading} className="bg-zinc-950 text-white px-6 py-3 text-xs font-bold uppercase tracking-widest rounded-lg disabled:opacity-50">
                        {trackingLoading ? "..." : "Track"}
                      </button>
                    </div>
                    {trackingError && <p className="text-red-500 text-xs flex items-center gap-1.5"><AlertCircle className="w-3.5 h-3.5" />{trackingError}</p>}
                    {trackingOrder && (
                      <div className="space-y-4">
                        <div className="bg-zinc-50 p-4 rounded-xl border border-zinc-100 flex flex-wrap justify-between items-center gap-3">
                          <div><p className="text-[9px] text-zinc-400 uppercase font-bold">Order ID</p><p className="text-xs font-mono font-bold">#{trackingOrder.id}</p></div>
                          <div><p className="text-[9px] text-zinc-400 uppercase font-bold">Status</p><span className="text-[10px] font-black bg-zinc-950 text-white px-2.5 py-1 rounded">{trackingOrder.status}</span></div>
                          <div><p className="text-[9px] text-zinc-400 uppercase font-bold">Total</p><p className="text-xs font-black">৳{trackingOrder.totalAmount?.toLocaleString()}</p></div>
                        </div>
                        <div className="relative pl-8 border-l border-zinc-100 space-y-6 ml-2">
                          {trackingStages.map((stage: any, i: number) => (
                            <div key={stage.key} className="relative">
                              {i < trackingStages.length - 1 && <div className={`absolute left-[-33.5px] top-6 w-0.5 h-12 ${stage.completed ? "bg-zinc-950" : "bg-zinc-100"}`} />}
                              <div className={`absolute left-[-40px] top-1 w-5 h-5 rounded-full border-2 flex items-center justify-center ${stage.active ? "bg-zinc-950 border-zinc-950 ring-4 ring-zinc-200" : stage.completed ? "bg-zinc-950 border-zinc-950" : "bg-white border-zinc-200"}`}>
                                {stage.completed && <CheckCircle className="w-3 h-3 text-white fill-white stroke-zinc-950" />}
                              </div>
                              <h4 className={`text-xs font-black uppercase ${stage.active ? "text-zinc-950" : stage.completed ? "text-zinc-700" : "text-zinc-300"}`}>{stage.label}</h4>
                              <p className="text-[10px] text-zinc-400 mt-0.5">{stage.desc}</p>
                            </div>
                          ))}
                        </div>
                      </div>
                    )}
                  </div>
                )}
              </div>
            </div>
          </div>
        )}
      </main>

      {/* ── Return Request Modal ─────────────────────────────────────────────── */}
      {returnOrderId && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm">
          <div className="bg-white rounded-2xl p-8 max-w-md w-full mx-4 shadow-2xl">
            <h2 className="text-lg font-black uppercase tracking-wider text-zinc-950 mb-4">Request Return</h2>
            <p className="text-xs text-zinc-500 mb-4">Order #{returnOrderId.slice(-8).toUpperCase()}</p>
            <label className="text-xs font-bold uppercase tracking-widest text-zinc-700 block mb-2">Reason for Return</label>
            <textarea value={returnReason} onChange={e => setReturnReason(e.target.value)} className="w-full px-3 py-2 text-sm border border-zinc-200 rounded-lg bg-zinc-50 focus:outline-none focus:ring-2 focus:ring-zinc-950 transition mb-5 resize-none" rows={4} placeholder="Please describe why you want to return this order..." />
            <div className="flex gap-3">
              <button onClick={handleSubmitReturn} disabled={submittingReturn} className="flex-1 py-3 text-xs font-bold uppercase tracking-widest bg-zinc-950 text-white rounded-lg hover:bg-zinc-800 disabled:opacity-50 transition">
                {submittingReturn ? "Submitting..." : "Submit Request"}
              </button>
              <button onClick={() => { setReturnOrderId(null); setReturnReason("") }} className="flex-1 py-3 text-xs font-bold uppercase tracking-widest border border-zinc-200 rounded-lg hover:bg-zinc-100 transition">Cancel</button>
            </div>
          </div>
        </div>
      )}

      <Footer />
    </div>
  )
}

export default function AccountPage() {
  const clientId = process.env.NEXT_PUBLIC_GOOGLE_CLIENT_ID || ""
  return (
    <Suspense fallback={<div className="min-h-screen bg-zinc-50 flex items-center justify-center"><div className="w-8 h-8 border-2 border-zinc-200 border-t-zinc-950 rounded-full animate-spin" /></div>}>
      {clientId ? (
        <GoogleOAuthProvider clientId={clientId}>
          <AccountPageContent clientId={clientId} />
        </GoogleOAuthProvider>
      ) : (
        <AccountPageContent clientId="" />
      )}
    </Suspense>
  )
}
