"use client";

import { useEffect, useState } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import Spinner from "@/components/ui/Spinner";
import { useAuthStore, getAuthHeaders } from "@/lib/auth-store";
import { fetchJsonWithAuth } from "@/lib/api-client";
import type { SavedAddress } from "@/lib/auth-store";
import { useEnsureStoreCustomer } from "@/lib/use-ensure-store-customer";
import { useLanguage } from "@/lib/language-context";
import { formatPrice } from "@/lib/utils";
import { useCartStore } from "@/lib/cart-store";
import type { OnlineOrder, ItemReservation, CartItem } from "@/types";

const ORDER_STATUS_LABELS: Record<string, string> = {
  confirmed: "Order Confirmed",
  processing: "Processing",
  shipped: "Out for Delivery",
  delivered: "Delivered",
  cancelled: "Cancelled",
  expired: "Expired",
};

const ORDER_STATUS_STYLES: Record<
  string,
  { bg: string; text: string; border: string }
> = {
  confirmed: {
    bg: "bg-blue-50",
    text: "text-blue-700",
    border: "border-blue-100",
  },
  processing: {
    bg: "bg-amber-50",
    text: "text-amber-700",
    border: "border-amber-100",
  },
  shipped: {
    bg: "bg-indigo-50",
    text: "text-indigo-700",
    border: "border-indigo-100",
  },
  delivered: {
    bg: "bg-green-50",
    text: "text-green-700",
    border: "border-green-100",
  },
  cancelled: {
    bg: "bg-gray-100",
    text: "text-gray-600",
    border: "border-gray-200",
  },
  expired: {
    bg: "bg-gray-100",
    text: "text-gray-500",
    border: "border-gray-200",
  },
};

const inputCls =
  "w-full border border-gray-200 rounded-xl px-3 py-2 text-sm focus:border-[var(--color-primary)] focus:ring-2 focus:ring-[var(--color-primary)]/20 outline-none";

const emptyForm = {
  label: "",
  line1: "",
  line2: "",
  city: "",
  state: "",
  postal_code: "",
  country: "EG",
};

function SavedAddressesSection({
  addresses,
  onRefetch,
  t,
}: {
  addresses: SavedAddress[];
  onRefetch: () => Promise<void>;
  t: ReturnType<typeof useLanguage>["t"];
}) {
  const [showAdd, setShowAdd] = useState(false);
  const [editingId, setEditingId] = useState<string | null>(null);
  const [saving, setSaving] = useState(false);
  const [deletingId, setDeletingId] = useState<string | null>(null);
  const [addError, setAddError] = useState<string | null>(null);
  const [form, setForm] = useState(emptyForm);

  const showForm = showAdd || !!editingId;
  const isEdit = !!editingId;

  const openEdit = (addr: SavedAddress) => {
    setEditingId(addr.id);
    setAddError(null);
    setForm({
      label: addr.label,
      line1: addr.line1,
      line2: addr.line2 ?? "",
      city: addr.city,
      state: addr.state ?? "",
      postal_code: addr.postal_code ?? "",
      country: addr.country ?? "EG",
    });
  };

  const closeForm = () => {
    setShowAdd(false);
    setEditingId(null);
    setForm(emptyForm);
    setAddError(null);
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setSaving(true);
    setAddError(null);
    try {
      if (isEdit) {
        const res = await fetch(`/api/storefront-proxy/auth/addresses/${editingId}`, {
          method: "PUT",
          headers: { "Content-Type": "application/json", ...getAuthHeaders() },
          body: JSON.stringify(form),
        });
        const data = await res.json().catch(() => ({}));
        if (!res.ok) {
          setAddError((data.message as string) || "Failed to update address.");
          return;
        }
        closeForm();
      } else {
        const res = await fetch("/api/storefront-proxy/auth/addresses", {
          method: "POST",
          headers: { "Content-Type": "application/json", ...getAuthHeaders() },
          body: JSON.stringify(form),
        });
        const data = await res.json().catch(() => ({}));
        if (!res.ok) {
          setAddError((data.message as string) || "Failed to add address.");
          return;
        }
        setForm(emptyForm);
        setShowAdd(false);
      }
      await onRefetch();
    } catch {
      setAddError(isEdit ? "Failed to update address." : "Failed to add address.");
    } finally {
      setSaving(false);
    }
  };

  const handleDelete = async (id: string) => {
    setDeletingId(id);
    try {
      const res = await fetch(`/api/storefront-proxy/auth/addresses/${id}`, {
        method: "DELETE",
        headers: getAuthHeaders(),
      });
      if (!res.ok) throw new Error("Failed to delete");
      await onRefetch();
    } catch {
      // ignore
    } finally {
      setDeletingId(null);
    }
  };

  return (
    <section className="bg-white rounded-2xl border border-gray-100 shadow-sm overflow-hidden mb-8">
      <div className="px-6 py-5 border-b border-gray-100 flex items-center justify-between gap-3">
        <h2 className="text-sm font-bold text-gray-500 uppercase tracking-wide">
          {t.account.savedAddresses}
        </h2>
        <button
          type="button"
          onClick={() => {
            setEditingId(null);
            setForm(emptyForm);
            setAddError(null);
            setShowAdd((v) => !v);
          }}
          className="text-sm font-medium"
          style={{ color: "var(--color-primary)" }}
        >
          {t.account.addAddress}
        </button>
      </div>
      <div className="p-6">
        {addresses.length === 0 && !showForm && (
          <p className="text-sm text-gray-500 mb-4">{t.account.noSavedAddresses}</p>
        )}
        {showForm && (
          <form onSubmit={handleSubmit} className="mb-6 p-4 bg-gray-50 rounded-xl space-y-3">
            {addError && (
              <p className="text-sm text-red-600 bg-red-50 p-2 rounded-lg">{addError}</p>
            )}
            <input
              type="text"
              required
              placeholder={t.account.addressLabelPlaceholder}
              value={form.label}
              onChange={(e) => setForm((f) => ({ ...f, label: e.target.value }))}
              className={inputCls}
            />
            <input
              type="text"
              required
              placeholder={t.checkout.addressLine1}
              value={form.line1}
              onChange={(e) => setForm((f) => ({ ...f, line1: e.target.value }))}
              className={inputCls}
            />
            <input
              type="text"
              placeholder={t.checkout.addressLine2}
              value={form.line2}
              onChange={(e) => setForm((f) => ({ ...f, line2: e.target.value }))}
              className={inputCls}
            />
            <div className="grid grid-cols-2 gap-3">
              <input
                type="text"
                required
                placeholder={t.checkout.city}
                value={form.city}
                onChange={(e) => setForm((f) => ({ ...f, city: e.target.value }))}
                className={inputCls}
              />
              <select
                value={form.country}
                onChange={(e) => setForm((f) => ({ ...f, country: e.target.value }))}
                className={inputCls}
              >
                <option value="EG">Egypt</option>
                <option value="SA">Saudi Arabia</option>
                <option value="AE">UAE</option>
                <option value="OTHER">Other</option>
              </select>
            </div>
            <div className="flex gap-2">
              <button type="submit" disabled={saving} className="btn-primary px-4 py-2 rounded-xl text-sm">
                {saving ? "…" : isEdit ? t.account.saveAddress : t.account.addAddress}
              </button>
              <button type="button" onClick={closeForm} className="text-sm text-gray-500">
                Cancel
              </button>
            </div>
          </form>
        )}
        <ul className="space-y-3">
          {addresses.map((addr) => (
            <li
              key={addr.id}
              className="flex items-center justify-between gap-4 p-4 border border-gray-100 rounded-xl"
            >
              <div>
                <span className="font-semibold text-gray-900">{addr.label}</span>
                <p className="text-sm text-gray-500 mt-0.5">
                  {addr.line1}
                  {addr.city ? `, ${addr.city}` : ""}
                  {addr.country ? `, ${addr.country}` : ""}
                </p>
              </div>
              <div className="flex items-center gap-3">
                <button
                  type="button"
                  onClick={() => openEdit(addr)}
                  className="text-sm font-medium hover:underline"
                  style={{ color: "var(--color-primary)" }}
                >
                  {t.account.editAddress}
                </button>
                <button
                  type="button"
                  onClick={() => handleDelete(addr.id)}
                  disabled={deletingId === addr.id}
                  className="text-sm text-red-600 hover:underline disabled:opacity-50"
                >
                  {t.account.deleteAddress}
                </button>
              </div>
            </li>
          ))}
        </ul>
      </div>
    </section>
  );
}

export default function AccountPage() {
  const { t } = useLanguage();
  const router = useRouter();
  useEnsureStoreCustomer();
  const customer = useAuthStore((s) => s.customer);
  const hydrated = useAuthStore((s) => s.hydrated);
  const token = useAuthStore((s) => s.token);
  const logout = useAuthStore((s) => s.logout);

  const [orders, setOrders] = useState<OnlineOrder[]>([]);
  const [reservations, setReservations] = useState<ItemReservation[]>([]);
  const [loadingOrders, setLoadingOrders] = useState(true);
  const [loadingReservations, setLoadingReservations] = useState(true);
  const [ordersError, setOrdersError] = useState(false);
  const [reservationsError, setReservationsError] = useState(false);
  const [resendSent, setResendSent] = useState(false);
  const [resendLoading, setResendLoading] = useState(false);
  const [showProfileEdit, setShowProfileEdit] = useState(false);
  const [profileForm, setProfileForm] = useState({ name: "", phone: "", email: "" });
  const [profileSaving, setProfileSaving] = useState(false);
  const [profileError, setProfileError] = useState<string | null>(null);
  const setCustomer = useAuthStore((s) => s.setCustomer);
  const addItem = useCartStore((s) => s.addItem);

  useEffect(() => {
    if (!hydrated) return;
    if (!token) {
      router.replace("/login?redirect=/account");
      return;
    }

    // Fetch fresh customer (e.g. email_verified) on load
    fetchJsonWithAuth<{ customer: typeof customer }>("/api/storefront-proxy/auth/me").then(
      (data) => data?.customer && setCustomer(data.customer),
    );

    // Helper function to fetch with retry logic
    const fetchWithRetry = async <T,>(
      url: string,
      retryDelay = 500,
    ): Promise<T | null> => {
      const data = await fetchJsonWithAuth<T>(url);
      if (data === null) {
        // Wait for auth state to settle, then retry once
        await new Promise((r) => setTimeout(r, retryDelay));
        return fetchJsonWithAuth<T>(url);
      }
      return data;
    };

    // Fetch orders with retry
    fetchWithRetry<{ orders: OnlineOrder[] }>("/api/storefront-proxy/orders")
      .then((data) => {
        if (data?.orders) {
          setOrders(data.orders);
          setOrdersError(false);
        } else {
          setOrdersError(true);
        }
      })
      .catch(() => {
        setOrdersError(true);
      })
      .finally(() => setLoadingOrders(false));

    // Fetch reservations with retry
    fetchWithRetry<{ reservations: ItemReservation[] }>(
      "/api/storefront-proxy/reservations",
    )
      .then((data) => {
        if (data?.reservations) {
          setReservations(data.reservations);
          setReservationsError(false);
        } else {
          setReservationsError(true);
        }
      })
      .catch(() => {
        setReservationsError(true);
      })
      .finally(() => setLoadingReservations(false));
  }, [hydrated, token, router]);

  if (!hydrated || !token) {
    return (
      <div className="flex justify-center min-h-[40vh] items-center bg-gray-50/80">
        <Spinner size="lg" />
      </div>
    );
  }

  const formatDate = (iso: string | null) => {
    if (!iso) return "—";
    return new Date(iso).toLocaleDateString(undefined, {
      year: "numeric",
      month: "short",
      day: "numeric",
    });
  };

  const formatDateTime = (iso: string | null) => {
    if (!iso) return "—";
    return new Date(iso).toLocaleString(undefined, {
      year: "numeric",
      month: "short",
      day: "numeric",
      hour: "2-digit",
      minute: "2-digit",
    });
  };

  const reservationStatusConfig: Record<
    string,
    { label: string; color: string; bg: string; border: string }
  > = {
    active: {
      label: t.reservation.statusActive,
      color: "text-amber-700",
      bg: "bg-amber-50",
      border: "border-amber-200",
    },
    collected: {
      label: t.reservation.statusCollected,
      color: "text-green-700",
      bg: "bg-green-50",
      border: "border-green-200",
    },
    cancelled: {
      label: t.reservation.statusCancelled,
      color: "text-gray-600",
      bg: "bg-gray-100",
      border: "border-gray-200",
    },
    expired: {
      label: t.reservation.statusExpired,
      color: "text-red-700",
      bg: "bg-red-50",
      border: "border-red-100",
    },
  };

  const emailUnverified = customer && customer.email_verified === false;

  const handleReorder = (order: OnlineOrder) => {
    if (!order.items?.length) return;
    order.items.forEach((i) => {
      const cartItem: CartItem = {
        item_id: i.item_id,
        barcode: i.item_barcode,
        name: i.item_name,
        variant_label: i.variant_label ?? null,
        image_url: i.image_url ?? null,
        price: i.unit_price,
        quantity: i.quantity,
        available_qty: i.quantity,
        color: i.color ?? null,
        size: i.size ?? null,
      };
      addItem(cartItem);
    });
    router.push("/cart");
  };

  const handleSaveProfile = async (e: React.FormEvent) => {
    e.preventDefault();
    setProfileSaving(true);
    setProfileError(null);
    try {
      const res = await fetch("/api/storefront-proxy/auth/profile", {
        method: "PUT",
        headers: { "Content-Type": "application/json", ...getAuthHeaders() },
        body: JSON.stringify(profileForm),
      });
      const data = await res.json().catch(() => ({}));
      if (!res.ok) {
        setProfileError((data.message as string) || "Failed to update profile.");
        return;
      }
      if (data.customer) setCustomer(data.customer);
      setShowProfileEdit(false);
    } catch {
      setProfileError("Failed to update profile.");
    } finally {
      setProfileSaving(false);
    }
  };

  const handleResendVerification = async () => {
    if (!customer?.email) return;
    setResendLoading(true);
    setResendSent(false);
    try {
      const res = await fetch("/api/storefront-proxy/auth/resend-verification", {
        method: "POST",
        headers: { "Content-Type": "application/json", ...getAuthHeaders() },
        body: JSON.stringify({ email: customer.email }),
      });
      if (res.ok) setResendSent(true);
    } finally {
      setResendLoading(false);
    }
  };

  return (
    <div className="min-h-[60vh] bg-gray-50/80">
      <div className="max-w-3xl mx-auto px-4 sm:px-6 lg:px-8 py-6 sm:py-8 md:py-12">
        {emailUnverified && (
          <div className="mb-6 p-4 bg-amber-50 border border-amber-200 rounded-2xl">
            <p className="text-sm font-medium text-amber-800 mb-2">
              {t.auth.accountEmailNotVerified}
            </p>
            <div className="flex flex-wrap items-center gap-2">
              <Link
                href={`/verify-email?email=${encodeURIComponent(customer.email)}`}
                className="text-sm font-semibold py-2 px-4 rounded-xl border border-amber-300 bg-amber-100 text-amber-900 hover:bg-amber-200"
              >
                {t.auth.verifyTitle}
              </Link>
              <button
                type="button"
                onClick={handleResendVerification}
                disabled={resendLoading}
                className="text-sm text-amber-800 hover:underline disabled:opacity-50"
              >
                {resendLoading ? t.common.loading : t.auth.resendVerification}
              </button>
              {resendSent && (
                <span className="text-sm text-green-700">{t.auth.resendSent}</span>
              )}
            </div>
          </div>
        )}
        <h1
          className="text-2xl sm:text-3xl font-bold text-gray-900 mb-8"
          suppressHydrationWarning
        >
          {t.account.title}
        </h1>

        {/* Profile card */}
        <section className="bg-white rounded-2xl border border-gray-100 shadow-sm overflow-hidden mb-8">
          <div className="px-6 py-5 border-b border-gray-100 flex items-center justify-between gap-3">
            <div className="flex items-center gap-3">
              <div
                className="w-10 h-10 rounded-full flex items-center justify-center flex-shrink-0"
                style={{ backgroundColor: "var(--color-primary)", opacity: 0.15 }}
              >
                <svg
                  className="w-5 h-5"
                  style={{ color: "var(--color-primary)" }}
                  fill="none"
                  viewBox="0 0 24 24"
                  stroke="currentColor"
                  strokeWidth={2}
                >
                  <path
                    strokeLinecap="round"
                    strokeLinejoin="round"
                    d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z"
                  />
                </svg>
              </div>
              <h2
                className="text-sm font-bold text-gray-500 uppercase tracking-wide"
                suppressHydrationWarning
              >
                {t.account.profile}
              </h2>
            </div>
            {!showProfileEdit && (
              <button
                type="button"
                onClick={() => {
                  setProfileForm({
                    name: customer?.name ?? "",
                    phone: customer?.phone ?? "",
                    email: customer?.email ?? "",
                  });
                  setProfileError(null);
                  setShowProfileEdit(true);
                }}
                className="text-sm font-medium"
                style={{ color: "var(--color-primary)" }}
              >
                {t.account.editProfile}
              </button>
            )}
          </div>
          <div className="p-6">
            {showProfileEdit ? (
              <form onSubmit={handleSaveProfile} className="space-y-4">
                {profileError && (
                  <p className="text-sm text-red-600 bg-red-50 p-2 rounded-lg">{profileError}</p>
                )}
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">{t.auth.name}</label>
                  <input
                    type="text"
                    value={profileForm.name}
                    onChange={(e) => setProfileForm((f) => ({ ...f, name: e.target.value }))}
                    className={inputCls}
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">{t.auth.phone}</label>
                  <input
                    type="text"
                    value={profileForm.phone}
                    onChange={(e) => setProfileForm((f) => ({ ...f, phone: e.target.value }))}
                    className={inputCls}
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">{t.auth.email}</label>
                  <input
                    type="email"
                    value={profileForm.email}
                    onChange={(e) => setProfileForm((f) => ({ ...f, email: e.target.value }))}
                    className={inputCls}
                  />
                  <p className="text-xs text-gray-500 mt-1">
                    Changing email will require verification again.
                  </p>
                </div>
                <div className="flex gap-2">
                  <button type="submit" disabled={profileSaving} className="btn-primary px-4 py-2 rounded-xl text-sm">
                    {profileSaving ? "…" : t.account.saveProfile}
                  </button>
                  <button
                    type="button"
                    onClick={() => setShowProfileEdit(false)}
                    className="text-sm text-gray-500 hover:underline"
                  >
                    {t.account.cancelEdit}
                  </button>
                </div>
              </form>
            ) : (
              <dl className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-4 sm:gap-6 text-sm">
                <div suppressHydrationWarning>
                  <dt className="text-gray-500 font-medium mb-0.5">
                    {t.auth.name}
                  </dt>
                  <dd className="font-semibold text-gray-900">
                    {customer?.name ?? "—"}
                  </dd>
                </div>
                <div suppressHydrationWarning>
                  <dt className="text-gray-500 font-medium mb-0.5">
                    {t.auth.email}
                  </dt>
                  <dd className="font-semibold text-gray-900 break-all">
                    {customer?.email ?? "—"}
                  </dd>
                </div>
                <div suppressHydrationWarning>
                  <dt className="text-gray-500 font-medium mb-0.5">
                    {t.auth.phone}
                  </dt>
                  <dd className="font-semibold text-gray-900" dir="ltr">
                    {customer?.phone ?? "—"}
                  </dd>
                </div>
              </dl>
            )}
          </div>
        </section>

        {/* Saved Addresses */}
        <SavedAddressesSection
          addresses={customer?.saved_addresses ?? []}
          onRefetch={async () => {
            const data = await fetchJsonWithAuth<{ customer: typeof customer }>("/api/storefront-proxy/auth/me");
            if (data?.customer) setCustomer(data.customer);
          }}
          t={t}
        />

        {/* Orders */}
        <section className="bg-white rounded-2xl border border-gray-100 shadow-sm overflow-hidden mb-8">
          <div className="px-6 py-5 border-b border-gray-100 flex items-center gap-3">
            <div
              className="w-10 h-10 rounded-full flex items-center justify-center flex-shrink-0"
              style={{ backgroundColor: "var(--color-primary)", opacity: 0.15 }}
            >
              <svg
                className="w-5 h-5"
                style={{ color: "var(--color-primary)" }}
                fill="none"
                viewBox="0 0 24 24"
                stroke="currentColor"
                strokeWidth={2}
              >
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  d="M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4"
                />
              </svg>
            </div>
            <h2
              className="text-sm font-bold text-gray-500 uppercase tracking-wide"
              suppressHydrationWarning
            >
              {t.account.myOrders}
            </h2>
          </div>
          <div className="p-6">
            {loadingOrders ? (
              <div className="flex justify-center py-12">
                <Spinner size="md" />
              </div>
            ) : ordersError ? (
              <p className="text-red-600 text-sm py-8 text-center">
                {t.common.error}
              </p>
            ) : orders.length === 0 ? (
              <p
                className="text-gray-500 text-sm py-8 text-center"
                suppressHydrationWarning
              >
                {t.account.noOrders}
              </p>
            ) : (
              <ul className="space-y-4">
                {orders.map((order) => {
                  const statusStyle =
                    ORDER_STATUS_STYLES[order.status] ??
                    ORDER_STATUS_STYLES.expired;
                  return (
                    <li
                      key={order.order_number}
                      className="border border-gray-100 rounded-xl p-5 hover:border-gray-200 hover:bg-gray-50/50 transition-all"
                    >
                      <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
                        <div className="flex-1 min-w-0">
                          <div className="flex flex-wrap items-center gap-2 mb-2">
                            <span className="font-bold text-gray-900">
                              #{order.order_number}
                            </span>
                            <span
                              className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-semibold border ${statusStyle.bg} ${statusStyle.text} ${statusStyle.border}`}
                              suppressHydrationWarning
                            >
                              {ORDER_STATUS_LABELS[order.status] ??
                                order.status}
                            </span>
                          </div>
                          <p
                            className="text-sm text-gray-500"
                            suppressHydrationWarning
                          >
                            {t.account.date}:{" "}
                            {formatDate(order.created_at ?? null)}
                          </p>
                          {order.hold_expires_at &&
                            order.status === "confirmed" && (
                              <p
                                className="text-xs text-amber-600 mt-1 font-medium"
                                suppressHydrationWarning
                              >
                                {t.account.reservedUntil}{" "}
                                {formatDateTime(order.hold_expires_at)}
                              </p>
                            )}
                          {(order.shipped_at || order.delivered_at) && (
                            <div className="mt-3 pt-3 border-t border-gray-100">
                              <p className="text-xs font-semibold text-gray-500 uppercase tracking-wide mb-1">
                                {t.account.trackingDetails}
                              </p>
                              <p
                                className="text-sm text-indigo-600 font-medium"
                                suppressHydrationWarning
                              >
                                {order.delivered_at
                                  ? `Delivered ${formatDateTime(
                                      order.delivered_at,
                                    )}`
                                  : order.shipped_at
                                  ? `Shipped ${formatDateTime(
                                      order.shipped_at,
                                    )}`
                                  : ""}
                              </p>
                            </div>
                          )}
                        </div>
                        <div className="flex items-center gap-4 flex-shrink-0">
                          <span
                            className="font-bold text-lg text-gray-900"
                            style={{ color: "var(--color-primary)" }}
                            suppressHydrationWarning
                          >
                            {formatPrice(order.grand_total, order.currency)}
                          </span>
                          <button
                            type="button"
                            onClick={() => handleReorder(order)}
                            className="text-sm font-semibold px-4 py-2.5 rounded-xl border-2 border-gray-200 text-gray-700 hover:bg-gray-50 transition-colors"
                          >
                            {t.account.reorder}
                          </button>
                          <Link
                            href={`/orders/${order.order_number}`}
                            className="text-sm font-semibold px-4 py-2.5 rounded-xl border-2 transition-colors hover:opacity-90"
                            style={{
                              borderColor: "var(--color-primary)",
                              color: "var(--color-primary)",
                            }}
                          >
                            {t.account.viewOrder} →
                          </Link>
                        </div>
                      </div>
                    </li>
                  );
                })}
              </ul>
            )}
          </div>
        </section>

        {/* Reservations */}
        <section className="bg-white rounded-2xl border border-gray-100 shadow-sm overflow-hidden">
          <div className="px-6 py-5 border-b border-gray-100 flex items-center gap-3">
            <div
              className="w-10 h-10 rounded-full flex items-center justify-center flex-shrink-0"
              style={{ backgroundColor: "var(--color-primary)", opacity: 0.15 }}
            >
              <svg
                className="w-5 h-5"
                style={{ color: "var(--color-primary)" }}
                fill="none"
                viewBox="0 0 24 24"
                stroke="currentColor"
                strokeWidth={2}
              >
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z"
                />
              </svg>
            </div>
            <h2
              className="text-sm font-bold text-gray-500 uppercase tracking-wide"
              suppressHydrationWarning
            >
              {t.account.myReservations}
            </h2>
          </div>
          <div className="p-6">
            {loadingReservations ? (
              <div className="flex justify-center py-12">
                <Spinner size="md" />
              </div>
            ) : reservationsError ? (
              <p className="text-red-600 text-sm py-8 text-center">
                {t.common.error}
              </p>
            ) : reservations.length === 0 ? (
              <p
                className="text-gray-500 text-sm py-8 text-center"
                suppressHydrationWarning
              >
                {t.account.noReservations}
              </p>
            ) : (
              <ul className="space-y-4">
                {reservations.map((res) => {
                  const statusInfo =
                    reservationStatusConfig[res.status] ??
                    reservationStatusConfig.expired;
                  return (
                    <li
                      key={res.reservation_code}
                      className="border border-gray-100 rounded-xl p-5 hover:border-gray-200 hover:bg-gray-50/50 transition-all"
                    >
                      <div className="flex flex-col gap-4">
                        <div className="flex-1 min-w-0">
                          <div className="flex flex-wrap items-center gap-2 mb-1">
                            <span className="font-mono font-bold text-gray-900">
                              {res.reservation_code}
                            </span>
                            <span
                              className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-semibold border ${statusInfo.bg} ${statusInfo.color} ${statusInfo.border}`}
                              suppressHydrationWarning
                            >
                              {statusInfo.label}
                            </span>
                          </div>
                          <p className="text-sm font-medium text-gray-800 mt-1">
                            {res.item?.name ?? "—"}
                            {(res.item?.color || res.item?.size) && (
                              <span className="text-gray-500 font-normal ml-1">
                                (
                                {[res.item.color?.name, res.item.size?.name]
                                  .filter(Boolean)
                                  .join(" / ")}
                                )
                              </span>
                            )}
                          </p>
                          {res.branch && (
                            <p className="text-xs text-gray-500 mt-0.5">
                              {res.branch.name}
                            </p>
                          )}
                          {res.expires_at && res.status === "active" && (
                            <p
                              className="text-xs text-amber-600 mt-2 font-medium"
                              suppressHydrationWarning
                            >
                              {t.account.expiresAt}{" "}
                              {formatDateTime(res.expires_at)}
                            </p>
                          )}
                        </div>
                      </div>
                    </li>
                  );
                })}
              </ul>
            )}
          </div>
        </section>
      </div>
    </div>
  );
}
