import { useState, useEffect, useCallback } from "react";
import { createFileRoute, Link, useNavigate } from "@tanstack/react-router";
import {
  User,
  Package,
  MapPin,
  Settings,
  LogOut,
  Eye,
  EyeOff,
  ChevronRight,
  Star,
  AlertCircle,
  Loader2,
  ShoppingCart,
  Link2,
} from "lucide-react";
import LoyaltyDashboard from "@/components/LoyaltyDashboard";
import PasswordStrength from "@/components/PasswordStrength";
import { useLoyalty } from "@/hooks/useLoyalty";
import { useAuthStore, type WcCustomerSession } from "@/stores/authStore";
import { wc, type WcCustomer } from "@/lib/woocommerce";
import { gqlLogin, gqlRegister } from "@/lib/graphql/auth";
import { useSessionStore } from "@/stores/sessionStore";
import { orderStatusLabel, orderStatusPill } from "@/lib/orderStatus";
import { OrderShippingStatus, ReorderButton } from "@/components/OrderTracking";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { toast } from "sonner";
import { z } from "zod";
import { Turnstile, resetTurnstile } from "@/components/Turnstile";
import { useT, useLang, headLang, locale } from "@/lib/i18n";

export const Route = createFileRoute("/my-account")({
  validateSearch: (search: Record<string, unknown>): { redirect?: string; tab?: string } => {
    const raw = typeof search.redirect === "string" ? search.redirect : "";
    // Only allow same-origin relative paths
    const redirect = raw.startsWith("/") && !raw.startsWith("//") ? raw : "";
    const tab = typeof search.tab === "string" ? search.tab : undefined;
    return { redirect: redirect || undefined, tab };
  },

  head: (ctx) => {
    const lang = headLang(ctx);
    const title = lang === "en" ? "My Account | Peptidewinkel" : "Mijn Account | Peptidewinkel";
    const description =
      lang === "en"
        ? "Manage your account, orders and addresses at Peptidewinkel."
        : "Beheer je account, bestellingen en adressen bij Peptidewinkel.";
    return {
      meta: [
        { title },
        { name: "description", content: description },
        { name: "robots", content: "noindex, nofollow" },
      ],
    };
  },
  component: AccountPage,
});

type Tab = "dashboard" | "orders" | "loyalty" | "addresses" | "details";
type AuthView = "login" | "register" | "forgot";

function AccountPage() {
  const t = useT();
  const lang = useLang();
  const { loyalty } = useLoyalty();
  const { customer, isLoggedIn, login, logout, updateCustomer } = useAuthStore();
  const { redirect } = Route.useSearch();
  const navigate = useNavigate();
  const [authView, setAuthView] = useState<AuthView>("login");
  const VALID_TABS: Tab[] = ["dashboard", "orders", "loyalty", "addresses", "details"];
  const getTabFromHash = (): Tab => {
    if (typeof window === "undefined") return "dashboard";
    const h = window.location.hash.replace("#", "") as Tab;
    return VALID_TABS.includes(h) ? h : "dashboard";
  };
  const [activeTab, setActiveTabState] = useState<Tab>(getTabFromHash);

  const loginSchema = z.object({
    email: z.string().trim().email(t("Ongeldig e-mailadres", "Invalid email address")).max(255),
    password: z.string().min(1, t("Wachtwoord is verplicht", "Password is required")),
  });

  const registerSchema = z.object({
    first_name: z
      .string()
      .trim()
      .min(1, t("Voornaam is verplicht", "First name is required"))
      .max(100),
    last_name: z
      .string()
      .trim()
      .min(1, t("Achternaam is verplicht", "Last name is required"))
      .max(100),
    email: z.string().trim().email(t("Ongeldig e-mailadres", "Invalid email address")).max(255),
    password: z.string().min(8, t("Min. 8 tekens", "Min. 8 characters")),
  });

  const setActiveTab = useCallback((tab: Tab) => {
    setActiveTabState(tab);
    const newHash = `#${tab}`;
    if (window.location.hash !== newHash) window.history.pushState(null, "", newHash);
  }, []);

  useEffect(() => {
    const onPop = () => setActiveTabState(getTabFromHash());
    window.addEventListener("popstate", onPop);
    window.addEventListener("hashchange", onPop);
    return () => {
      window.removeEventListener("popstate", onPop);
      window.removeEventListener("hashchange", onPop);
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const [showPassword, setShowPassword] = useState(false);
  const [authError, setAuthError] = useState("");
  const captchaDisabled = import.meta.env.VITE_DISABLE_TURNSTILE === "true";
  const [captchaToken, setCaptchaToken] = useState(captchaDisabled ? "disabled" : "");
  const [registerPassword, setRegisterPassword] = useState("");
  const queryClient = useQueryClient();

  const loginMutation = useMutation({
    mutationFn: async ({ email, password }: { email: string; password: string }) => {
      // Parallel: REST geeft wc_token (nodig voor de checkout serverFn) +
      // GraphQL geeft authToken/refreshToken (voor cart, viewer en queries).
      // Beide mogen falen; we vereisen dat minstens REST slaagt (Turnstile-validatie).
      const [restRes, gqlRes] = await Promise.allSettled([
        wc.loginCustomer(email, password, captchaToken),
        gqlLogin(email, password),
      ]);
      if (restRes.status === "rejected") throw restRes.reason;
      if (gqlRes.status === "rejected") {
        // eslint-disable-next-line no-console
        console.warn("[auth] GraphQL login mislukt, alleen REST sessie actief:", gqlRes.reason);
      }
      return restRes.value;
    },
    onSuccess: (data) => {
      const session: WcCustomerSession = {
        id: data.id,
        email: data.email,
        first_name: data.first_name,
        last_name: data.last_name,
        billing: data.billing,
        shipping: data.shipping,
        roles: (data as { roles?: string[] }).roles || [],
      };
      login(session, data.wc_token);
      // Nieuwe cart-sessie ophalen na login (server kan een user-bound cart teruggeven).
      queryClient.invalidateQueries({ queryKey: ["gql-cart"] });
      setAuthError("");
      toast.success(t("Succesvol ingelogd!", "Successfully logged in!"));
      if (redirect) navigate({ to: redirect });
    },
    onError: (err: Error) => {
      setAuthError(err.message);
      setCaptchaToken("");
      resetTurnstile();
    },
  });

  const registerMutation = useMutation({
    mutationFn: async (data: {
      email: string;
      first_name: string;
      last_name: string;
      password: string;
    }) => {
      return await wc.registerCustomer({ ...data, turnstile_token: captchaToken });
    },
    onSuccess: async (data, vars) => {
      // Auto-login om wc_token (checkout) én authToken (GraphQL) te krijgen.
      try {
        const [loginRes] = await Promise.all([
          wc.loginCustomer(vars.email, vars.password, captchaToken),
          gqlLogin(vars.email, vars.password).catch((e) => {
            // eslint-disable-next-line no-console
            console.warn("[auth] GraphQL login na register mislukt:", e);
          }),
        ]);
        const session: WcCustomerSession = {
          id: loginRes.id,
          email: loginRes.email,
          first_name: loginRes.first_name,
          last_name: loginRes.last_name,
          billing: loginRes.billing,
          shipping: loginRes.shipping,
          roles: (loginRes as { roles?: string[] }).roles || [],
        };
        login(session, loginRes.wc_token);
      } catch {
        // Fallback: laat user inloggen via login-tab — REST kan onbekende reden falen.
        const session: WcCustomerSession = {
          id: data.id,
          email: data.email,
          first_name: data.first_name,
          last_name: data.last_name,
          billing: data.billing,
          shipping: data.shipping,
        };
        login(session);
      }
      queryClient.invalidateQueries({ queryKey: ["gql-cart"] });
      setAuthError("");
      toast.success(
        t(
          "Account aangemaakt! Claim je welkomstbonus in de Loyalty tab.",
          "Account created! Claim your welcome bonus in the Loyalty tab.",
        ),
      );
      if (redirect) navigate({ to: redirect });
    },
    onError: (err: Error) => {
      setAuthError(err.message);
      setCaptchaToken("");
      resetTurnstile();
    },
  });

  const forgotMutation = useMutation({
    // Forgot password blijft REST: gebruikt Turnstile-captcha verificatie
    // server-side. WPGraphQL's sendPasswordResetEmail mist die check.
    mutationFn: async (email: string) => await wc.forgotPassword(email, captchaToken),
    onSuccess: () => {
      setAuthError("");
      toast.success(
        t(
          "Als het e-mailadres bekend is, ontvangt u een reset-link.",
          "If the email address is known, you will receive a reset link.",
        ),
      );
    },
    onError: (err: Error) => {
      setAuthError(err.message);
      setCaptchaToken("");
      resetTurnstile();
    },
  });

  const { data: orders, isLoading: ordersLoading } = useQuery({
    queryKey: ["wc-orders", customer?.id],
    queryFn: async () => {
      if (!customer?.id) return [];
      const result = await wc.getOrders(customer.id);
      return result.data;
    },
    enabled: isLoggedIn && !!customer?.id,
    staleTime: 2 * 60 * 1000,
  });

  const updateMutation = useMutation({
    mutationFn: async (data: Partial<WcCustomer>) => {
      if (!customer?.id) throw new Error(t("Niet ingelogd", "Not logged in"));
      const result = await wc.updateCustomer(customer.id, data);
      return result.data;
    },
    onSuccess: (data) => {
      updateCustomer({
        first_name: data.first_name,
        last_name: data.last_name,
        email: data.email,
        billing: data.billing,
        shipping: data.shipping,
      });
      toast.success(t("Gegevens opgeslagen!", "Details saved!"));
    },
    onError: (err: Error) => toast.error(err.message || t("Opslaan mislukt", "Saving failed")),
  });

  const handleLogout = () => {
    logout();
    useSessionStore.getState().clear();
    queryClient.clear();
    toast.success(t("U bent uitgelogd.", "You have been logged out."));
  };

  if (!isLoggedIn) {
    return (
      <div className="container py-12 md:py-20 max-w-md">
        <div className="text-center mb-8">
          <h1 className="text-3xl font-black mb-2">{t("Mijn Account", "My Account")}</h1>
          <p className="text-muted-foreground text-sm">
            {t("Log in of maak een account aan.", "Log in or create an account.")}
          </p>
        </div>
        <div className="bg-card border border-border/50 rounded-2xl shadow-card overflow-hidden">
          {authView !== "forgot" && (
            <div className="flex bg-surface/50 p-1.5 m-4 rounded-xl">
              {(["login", "register"] as const).map((view) => (
                <button
                  key={view}
                  onClick={() => {
                    setAuthView(view);
                    setAuthError("");
                  }}
                  className={`flex-1 py-2.5 text-sm font-semibold rounded-lg transition-all duration-200 ${authView === view ? "gradient-primary text-white shadow-sm" : "text-muted-foreground hover:text-foreground"}`}
                >
                  {view === "login" ? t("Inloggen", "Log in") : t("Registreren", "Register")}
                </button>
              ))}
            </div>
          )}
          {authView === "forgot" && (
            <div className="m-4 mb-0">
              <h2 className="text-lg font-bold">{t("Wachtwoord Vergeten", "Forgot Password")}</h2>
            </div>
          )}

          <div className="p-6 pt-2">
            {authError && (
              <div className="flex items-center gap-2 bg-destructive/10 text-destructive text-sm p-3 rounded-xl mb-4">
                <AlertCircle className="w-4 h-4 shrink-0" />
                <span>{authError}</span>
              </div>
            )}

            {authView === "login" ? (
              <form
                onSubmit={(e) => {
                  e.preventDefault();
                  const fd = new FormData(e.currentTarget);
                  const parsed = loginSchema.safeParse({
                    email: fd.get("email"),
                    password: fd.get("password"),
                  });
                  if (!parsed.success) {
                    setAuthError(parsed.error.errors[0].message);
                    return;
                  }
                  loginMutation.mutate(parsed.data);
                }}
                className="space-y-4"
              >
                <div>
                  <label className="block text-sm font-semibold mb-1.5">
                    {t("E-mailadres", "Email address")}
                  </label>
                  <input
                    name="email"
                    type="email"
                    required
                    maxLength={255}
                    className="w-full px-4 py-3 border border-border/50 rounded-xl bg-background text-sm outline-none focus:ring-2 focus:ring-primary/20"
                  />
                </div>
                <div>
                  <label className="block text-sm font-semibold mb-1.5">
                    {t("Wachtwoord", "Password")}
                  </label>
                  <div className="relative">
                    <input
                      name="password"
                      type={showPassword ? "text" : "password"}
                      required
                      className="w-full px-4 py-3 border border-border/50 rounded-xl bg-background text-sm outline-none focus:ring-2 focus:ring-primary/20 pr-12"
                    />
                    <button
                      type="button"
                      onClick={() => setShowPassword(!showPassword)}
                      className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground"
                    >
                      {showPassword ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
                    </button>
                  </div>
                </div>
                {!captchaDisabled && (
                  <Turnstile
                    action="login"
                    onVerify={setCaptchaToken}
                    onExpire={() => setCaptchaToken("")}
                  />
                )}
                <button
                  type="submit"
                  disabled={loginMutation.isPending || !captchaToken}
                  className="w-full flex items-center justify-center gap-2 gradient-primary text-white font-bold py-3.5 rounded-xl hover:shadow-glow transition-all text-sm uppercase tracking-wide disabled:opacity-50"
                >
                  {loginMutation.isPending && <Loader2 className="w-4 h-4 animate-spin" />}{" "}
                  {t("Inloggen", "Log in")}
                </button>
                <button
                  type="button"
                  onClick={() => {
                    setAuthView("forgot");
                    setAuthError("");
                  }}
                  className="w-full text-center text-sm text-primary hover:underline font-medium mt-1"
                >
                  {t("Wachtwoord vergeten?", "Forgot password?")}
                </button>
              </form>
            ) : authView === "register" ? (
              <form
                onSubmit={(e) => {
                  e.preventDefault();
                  const fd = new FormData(e.currentTarget);
                  const parsed = registerSchema.safeParse({
                    first_name: fd.get("first_name"),
                    last_name: fd.get("last_name"),
                    email: fd.get("email"),
                    password: fd.get("password"),
                  });
                  if (!parsed.success) {
                    setAuthError(parsed.error.errors[0].message);
                    return;
                  }
                  registerMutation.mutate(parsed.data);
                }}
                className="space-y-4"
              >
                <div className="grid grid-cols-2 gap-3">
                  <div>
                    <label className="block text-sm font-semibold mb-1.5">
                      {t("Voornaam", "First name")}
                    </label>
                    <input
                      name="first_name"
                      required
                      maxLength={100}
                      className="w-full px-4 py-3 border border-border/50 rounded-xl bg-background text-sm outline-none focus:ring-2 focus:ring-primary/20"
                    />
                  </div>
                  <div>
                    <label className="block text-sm font-semibold mb-1.5">
                      {t("Achternaam", "Last name")}
                    </label>
                    <input
                      name="last_name"
                      required
                      maxLength={100}
                      className="w-full px-4 py-3 border border-border/50 rounded-xl bg-background text-sm outline-none focus:ring-2 focus:ring-primary/20"
                    />
                  </div>
                </div>
                <div>
                  <label className="block text-sm font-semibold mb-1.5">
                    {t("E-mailadres", "Email address")}
                  </label>
                  <input
                    name="email"
                    type="email"
                    required
                    maxLength={255}
                    className="w-full px-4 py-3 border border-border/50 rounded-xl bg-background text-sm outline-none focus:ring-2 focus:ring-primary/20"
                  />
                </div>
                <div>
                  <label className="block text-sm font-semibold mb-1.5">
                    {t("Wachtwoord", "Password")}
                  </label>
                  <div className="relative">
                    <input
                      name="password"
                      type={showPassword ? "text" : "password"}
                      required
                      minLength={8}
                      value={registerPassword}
                      onChange={(e) => setRegisterPassword(e.target.value)}
                      className="w-full px-4 py-3 border border-border/50 rounded-xl bg-background text-sm outline-none focus:ring-2 focus:ring-primary/20 pr-12"
                    />
                    <button
                      type="button"
                      onClick={() => setShowPassword(!showPassword)}
                      className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground"
                    >
                      {showPassword ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
                    </button>
                  </div>
                  <PasswordStrength password={registerPassword} />
                </div>
                {!captchaDisabled && (
                  <Turnstile
                    action="register"
                    onVerify={setCaptchaToken}
                    onExpire={() => setCaptchaToken("")}
                  />
                )}
                <button
                  type="submit"
                  disabled={registerMutation.isPending || !captchaToken}
                  className="w-full flex items-center justify-center gap-2 gradient-primary text-white font-bold py-3.5 rounded-xl hover:shadow-glow transition-all text-sm uppercase tracking-wide disabled:opacity-50"
                >
                  {registerMutation.isPending && <Loader2 className="w-4 h-4 animate-spin" />}{" "}
                  {t("Account Aanmaken", "Create Account")}
                </button>
              </form>
            ) : (
              <div className="space-y-4">
                <p className="text-sm text-muted-foreground">
                  {t(
                    "Voer uw e-mailadres in voor een reset-link.",
                    "Enter your email address for a reset link.",
                  )}
                </p>
                <form
                  onSubmit={(e) => {
                    e.preventDefault();
                    const fd = new FormData(e.currentTarget);
                    const email = String(fd.get("email") || "").trim();
                    if (!email || !z.string().email().safeParse(email).success) {
                      setAuthError(
                        t("Voer een geldig e-mailadres in.", "Enter a valid email address."),
                      );
                      return;
                    }
                    forgotMutation.mutate(email);
                  }}
                  className="space-y-4"
                >
                  <input
                    name="email"
                    type="email"
                    required
                    maxLength={255}
                    placeholder={t("uw@email.nl", "you@email.com")}
                    className="w-full px-4 py-3 border border-border/50 rounded-xl bg-background text-sm outline-none focus:ring-2 focus:ring-primary/20"
                  />
                  {!captchaDisabled && (
                    <Turnstile
                      action="forgot_password"
                      onVerify={setCaptchaToken}
                      onExpire={() => setCaptchaToken("")}
                    />
                  )}
                  <button
                    type="submit"
                    disabled={forgotMutation.isPending || !captchaToken}
                    className="w-full flex items-center justify-center gap-2 gradient-primary text-white font-bold py-3.5 rounded-xl hover:shadow-glow transition-all text-sm uppercase tracking-wide disabled:opacity-50"
                  >
                    {forgotMutation.isPending && <Loader2 className="w-4 h-4 animate-spin" />}{" "}
                    {t("Verstuur reset-link", "Send reset link")}
                  </button>
                </form>
                <button
                  type="button"
                  onClick={() => {
                    setAuthView("login");
                    setAuthError("");
                  }}
                  className="w-full text-center text-sm text-primary hover:underline font-medium"
                >
                  {t("← Terug naar inloggen", "← Back to log in")}
                </button>
              </div>
            )}
          </div>
        </div>
      </div>
    );
  }

  const tabs = [
    { key: "dashboard" as const, label: t("Dashboard", "Dashboard"), icon: User },
    { key: "orders" as const, label: t("Bestellingen", "Orders"), icon: Package },
    { key: "loyalty" as const, label: t("Loyaliteit", "Loyalty"), icon: Star },
    { key: "addresses" as const, label: t("Adressen", "Addresses"), icon: MapPin },
    { key: "details" as const, label: t("Accountgegevens", "Account details"), icon: Settings },
  ];

  return (
    <div className="min-h-screen account-hero">
      <div className="border-b border-border/40">
        <div className="container py-6 md:py-10">
          <p className="text-xs uppercase tracking-[0.18em] text-primary font-bold mb-1.5">
            {t("Mijn Account", "My Account")}
          </p>
          <h1 className="text-3xl md:text-4xl font-black tracking-tight">
            {t("Hoi,", "Hi,")} {customer?.first_name || t("daar", "there")} 👋
          </h1>
          <p className="text-sm text-muted-foreground mt-1.5">
            {t(
              "Bekijk je bestellingen, beheer je gegevens en houd je punten in de gaten.",
              "View your orders, manage your details and keep an eye on your points.",
            )}
          </p>
        </div>
      </div>

      <div className="container py-8 md:py-12">
        <div className="md:hidden -mx-4 px-4 mb-6 overflow-x-auto">
          <div className="flex gap-2 min-w-max">
            {tabs.map((tab) => (
              <button
                key={tab.key}
                onClick={() => setActiveTab(tab.key)}
                className={`flex items-center gap-2 px-4 py-2.5 rounded-full text-xs font-bold whitespace-nowrap ${activeTab === tab.key ? "gradient-primary text-white shadow-glow" : "glass-panel text-muted-foreground"}`}
              >
                <tab.icon className="w-3.5 h-3.5" /> {tab.label}
              </button>
            ))}
            <Link
              to="/my-account/affiliate"
              className="flex items-center gap-2 px-4 py-2.5 rounded-full text-xs font-bold whitespace-nowrap glass-panel text-muted-foreground"
            >
              <Link2 className="w-3.5 h-3.5" /> {t("Affiliate", "Affiliate")}
            </Link>
          </div>
        </div>

        <div className="grid md:grid-cols-[280px_1fr] gap-8 lg:gap-10">
          <aside className="hidden md:block">
            <div className="glass-card rounded-3xl p-5 sticky top-24">
              <div className="flex items-center gap-3 mb-5 pb-5 border-b border-border/40">
                <div className="w-12 h-12 gradient-primary rounded-2xl flex items-center justify-center text-white font-black text-lg shadow-glow">
                  {customer?.first_name?.[0]?.toUpperCase() || "U"}
                </div>
                <div className="min-w-0">
                  <p className="font-bold text-sm truncate">
                    {customer?.first_name} {customer?.last_name}
                  </p>
                  <p className="text-xs text-muted-foreground truncate">{customer?.email}</p>
                </div>
              </div>
              <nav className="space-y-1">
                {tabs.map((tab) => (
                  <button
                    key={tab.key}
                    onClick={() => setActiveTab(tab.key)}
                    className={`w-full flex items-center gap-3 px-4 py-2.5 rounded-xl text-sm font-semibold ${activeTab === tab.key ? "gradient-primary text-white shadow-glow" : "text-muted-foreground hover:bg-muted/40 hover:text-foreground"}`}
                  >
                    <tab.icon className="w-4 h-4" />
                    <span className="flex-1 text-left">{tab.label}</span>
                    {activeTab === tab.key && <ChevronRight className="w-4 h-4 opacity-80" />}
                  </button>
                ))}
                <div className="my-2 border-t border-border/40" />
                <button
                  onClick={handleLogout}
                  className="w-full flex items-center gap-3 px-4 py-2.5 rounded-xl text-sm font-semibold text-destructive hover:bg-destructive/10"
                >
                  <LogOut className="w-4 h-4" /> {t("Uitloggen", "Log out")}
                </button>
              </nav>
              <Link
                to="/my-account/affiliate"
                className="w-full flex items-center gap-3 px-4 py-2.5 rounded-xl text-sm font-semibold text-muted-foreground hover:bg-muted/40 hover:text-foreground mt-1"
              >
                <Link2 className="w-4 h-4" />
                <span className="flex-1 text-left">{t("Affiliate", "Affiliate")}</span>
              </Link>
            </div>
          </aside>

          <div className="min-w-0">
            {activeTab === "dashboard" && (
              <div className="space-y-6">
                <div className="glass-card rounded-3xl p-7">
                  <h2 className="text-2xl font-black mb-2">
                    {t("Welkom terug,", "Welcome back,")} {customer?.first_name}!
                  </h2>
                  <p className="text-sm text-muted-foreground">
                    {t(
                      "Beheer je bestellingen en loyalty punten.",
                      "Manage your orders and loyalty points.",
                    )}
                  </p>
                </div>
                <div className="grid grid-cols-2 md:grid-cols-3 gap-4">
                  {[
                    {
                      label: t("Bestellingen", "Orders"),
                      value: orders?.length ?? "—",
                      icon: Package,
                    },
                    {
                      label: t("Loyalty Punten", "Loyalty Points"),
                      value: loyalty?.balance?.toLocaleString() ?? "—",
                      icon: Star,
                    },
                    { label: t("Tier", "Tier"), value: loyalty?.tier ?? "—", icon: User },
                  ].map((s) => (
                    <div key={s.label} className="glass-card rounded-2xl p-5">
                      <div className="w-10 h-10 mb-3 gradient-primary rounded-xl flex items-center justify-center shadow-glow">
                        <s.icon className="w-5 h-5 text-white" />
                      </div>
                      <p className="text-3xl font-black">{s.value}</p>
                      <p className="text-xs font-semibold mt-1">{s.label}</p>
                    </div>
                  ))}
                </div>
              </div>
            )}

            {activeTab === "orders" && (
              <div>
                {ordersLoading ? (
                  <div className="space-y-3">
                    {[1, 2, 3].map((i) => (
                      <div key={i} className="h-24 bg-muted/30 rounded-2xl animate-pulse" />
                    ))}
                  </div>
                ) : orders && orders.length > 0 ? (
                  <div className="space-y-4">
                    {orders.map((order) => (
                      <div key={order.id} className="glass-card rounded-3xl overflow-hidden">
                        <div className="flex flex-wrap items-center justify-between gap-3 p-5 border-b border-border/40">
                          <div>
                            <p className="font-black">
                              {t("Bestelling", "Order")} #{order.id}
                            </p>
                            <p className="text-xs text-muted-foreground">
                              {new Date(order.date_created).toLocaleDateString(locale(lang), {
                                day: "numeric",
                                month: "long",
                                year: "numeric",
                              })}
                            </p>
                          </div>
                          <div className="flex items-center gap-3">
                            <span
                              className={`text-[10px] font-bold uppercase tracking-wide px-2.5 py-1 rounded-full ${orderStatusPill(order.status)}`}
                            >
                              {orderStatusLabel(order.status)}
                            </span>
                            <span className="font-black text-lg text-primary">
                              €{parseFloat(order.total).toFixed(2)}
                            </span>
                          </div>
                        </div>
                        <div className="p-5 space-y-2">
                          {order.line_items.map((item, i) => (
                            <div key={i} className="flex justify-between text-sm">
                              <span className="text-muted-foreground">
                                {item.quantity}× {item.name}
                              </span>
                              <span className="font-semibold">
                                €{parseFloat(item.total).toFixed(2)}
                              </span>
                            </div>
                          ))}
                        </div>
                        <div className="px-5 pb-5 space-y-3">
                          <OrderShippingStatus order={order} />
                          <div className="flex flex-wrap items-center gap-3">
                            <ReorderButton items={order.line_items} />
                            <span className="text-xs text-muted-foreground">
                              {order.payment_method_title
                                ? `${t("Betaald met", "Paid with")} ${order.payment_method_title}`
                                : ""}
                            </span>
                          </div>
                        </div>
                      </div>
                    ))}
                  </div>
                ) : (
                  <div className="text-center py-14 px-6 glass-card rounded-3xl">
                    <Package className="w-12 h-12 mx-auto text-muted-foreground mb-4" />
                    <p className="font-black text-lg mb-1.5">
                      {t("Nog geen bestellingen", "No orders yet")}
                    </p>
                    <Link
                      to="/shop"
                      className="inline-flex items-center gap-2 gradient-primary text-white font-bold px-6 py-3 rounded-xl text-sm mt-4"
                    >
                      <ShoppingCart className="w-4 h-4" />{" "}
                      {t("Naar de webshop", "Go to the webshop")}
                    </Link>
                  </div>
                )}
              </div>
            )}

            {activeTab === "loyalty" && <LoyaltyDashboard />}

            {activeTab === "addresses" && (
              <div className="grid md:grid-cols-2 gap-5">
                <AddressCard
                  title={t("Factuuradres", "Billing address")}
                  address={customer?.billing}
                  onSave={(data) => updateMutation.mutate({ billing: data } as Partial<WcCustomer>)}
                  saving={updateMutation.isPending}
                />
                <AddressCard
                  title={t("Verzendadres", "Shipping address")}
                  address={customer?.shipping}
                  onSave={(data) =>
                    updateMutation.mutate({ shipping: data } as Partial<WcCustomer>)
                  }
                  saving={updateMutation.isPending}
                />
              </div>
            )}

            {activeTab === "details" && (
              <div className="glass-card rounded-3xl p-6 md:p-8 max-w-2xl">
                <h3 className="text-xl font-black mb-5">
                  {t("Persoonlijke gegevens", "Personal details")}
                </h3>
                <form
                  className="space-y-5"
                  onSubmit={(e) => {
                    e.preventDefault();
                    const fd = new FormData(e.currentTarget);
                    updateMutation.mutate({
                      first_name: fd.get("first_name") as string,
                      last_name: fd.get("last_name") as string,
                      email: fd.get("email") as string,
                    } as Partial<WcCustomer>);
                  }}
                >
                  <div className="grid grid-cols-2 gap-4">
                    <div>
                      <label className="block text-sm font-semibold mb-1.5">
                        {t("Voornaam", "First name")}
                      </label>
                      <input
                        name="first_name"
                        defaultValue={customer?.first_name}
                        maxLength={100}
                        className="w-full px-4 py-3 border border-border/50 rounded-xl bg-background/60 text-sm"
                      />
                    </div>
                    <div>
                      <label className="block text-sm font-semibold mb-1.5">
                        {t("Achternaam", "Last name")}
                      </label>
                      <input
                        name="last_name"
                        defaultValue={customer?.last_name}
                        maxLength={100}
                        className="w-full px-4 py-3 border border-border/50 rounded-xl bg-background/60 text-sm"
                      />
                    </div>
                  </div>
                  <div>
                    <label className="block text-sm font-semibold mb-1.5">
                      {t("E-mail", "Email")}
                    </label>
                    <input
                      name="email"
                      type="email"
                      defaultValue={customer?.email}
                      maxLength={255}
                      className="w-full px-4 py-3 border border-border/50 rounded-xl bg-background/60 text-sm"
                    />
                  </div>
                  <button
                    type="submit"
                    disabled={updateMutation.isPending}
                    className="flex items-center gap-2 gradient-primary text-white font-bold px-8 py-3 rounded-xl text-sm uppercase tracking-wide disabled:opacity-50"
                  >
                    {updateMutation.isPending && <Loader2 className="w-4 h-4 animate-spin" />}{" "}
                    {t("Opslaan", "Save")}
                  </button>
                </form>
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}

interface AddressCardProps {
  title: string;
  address?: WcCustomerSession["billing"];
  onSave: (data: Record<string, string>) => void;
  saving: boolean;
}

function AddressCard({ title, address, onSave, saving }: AddressCardProps) {
  const t = useT();
  const [editing, setEditing] = useState(false);

  if (!editing) {
    const hasAddress = address?.address_1;
    return (
      <div className="glass-card rounded-3xl p-6">
        <div className="flex items-center justify-between mb-4">
          <div className="flex items-center gap-2.5">
            <div className="w-9 h-9 rounded-xl gradient-primary flex items-center justify-center shadow-glow">
              <MapPin className="w-4 h-4 text-white" />
            </div>
            <h3 className="font-black text-sm">{title}</h3>
          </div>
          <button
            onClick={() => setEditing(true)}
            className="text-xs text-primary font-bold hover:underline"
          >
            {t("Bewerken", "Edit")}
          </button>
        </div>
        {hasAddress ? (
          <div className="text-sm text-muted-foreground space-y-0.5 leading-relaxed">
            <p className="font-semibold text-foreground">
              {address.first_name} {address.last_name}
            </p>
            {address.company && <p>{address.company}</p>}
            <p>{address.address_1}</p>
            {address.address_2 && <p>{address.address_2}</p>}
            <p>
              {address.postcode} {address.city}
            </p>
            <p className="uppercase tracking-wide text-xs font-semibold mt-1">{address.country}</p>
          </div>
        ) : (
          <div className="text-center py-7 px-4 border border-dashed border-border/60 rounded-2xl">
            <p className="text-sm font-semibold mb-3">
              {t("Nog geen", "No")} {title.toLowerCase()}
            </p>
            <button
              onClick={() => setEditing(true)}
              className="text-xs font-bold text-primary hover:underline"
            >
              {t("Adres toevoegen", "Add address")}
            </button>
          </div>
        )}
      </div>
    );
  }

  const inputCls = "w-full px-3 py-2.5 border border-border/50 rounded-xl bg-background/60 text-sm";

  return (
    <div className="glass-card rounded-3xl p-6">
      <h3 className="font-black text-sm mb-5">
        {title} {t("bewerken", "editing")}
      </h3>
      <form
        className="space-y-3"
        onSubmit={(e) => {
          e.preventDefault();
          const fd = new FormData(e.currentTarget);
          const data: Record<string, string> = {};
          fd.forEach((v, k) => {
            data[k] = v as string;
          });
          onSave(data);
          setEditing(false);
        }}
      >
        <div className="grid grid-cols-2 gap-3">
          <input
            name="first_name"
            placeholder={t("Voornaam", "First name")}
            defaultValue={address?.first_name}
            maxLength={100}
            className={inputCls}
          />
          <input
            name="last_name"
            placeholder={t("Achternaam", "Last name")}
            defaultValue={address?.last_name}
            maxLength={100}
            className={inputCls}
          />
        </div>
        <input
          name="company"
          placeholder={t("Bedrijf (optioneel)", "Company (optional)")}
          defaultValue={address?.company}
          maxLength={100}
          className={inputCls}
        />
        <input
          name="address_1"
          placeholder={t("Adresregel 1", "Address line 1")}
          defaultValue={address?.address_1}
          maxLength={200}
          className={inputCls}
        />
        <input
          name="address_2"
          placeholder={t("Adresregel 2 (optioneel)", "Address line 2 (optional)")}
          defaultValue={address?.address_2}
          maxLength={200}
          className={inputCls}
        />
        <div className="grid grid-cols-2 gap-3">
          <input
            name="postcode"
            placeholder={t("Postcode", "Postcode")}
            defaultValue={address?.postcode}
            maxLength={20}
            className={inputCls}
          />
          <input
            name="city"
            placeholder={t("Plaats", "City")}
            defaultValue={address?.city}
            maxLength={100}
            className={inputCls}
          />
        </div>
        <input
          name="country"
          placeholder={t("Land (NL/BE/…)", "Country (NL/BE/…)")}
          defaultValue={address?.country || "NL"}
          maxLength={10}
          className={inputCls}
        />
        <div className="flex gap-3 pt-2">
          <button
            type="submit"
            disabled={saving}
            className="flex items-center gap-2 gradient-primary text-white font-bold px-5 py-2.5 rounded-xl text-xs uppercase tracking-wide disabled:opacity-50"
          >
            {saving && <Loader2 className="w-3.5 h-3.5 animate-spin" />} {t("Opslaan", "Save")}
          </button>
          <button
            type="button"
            onClick={() => setEditing(false)}
            className="px-5 py-2.5 border border-border/60 rounded-xl text-xs font-semibold text-muted-foreground"
          >
            {t("Annuleren", "Cancel")}
          </button>
        </div>
      </form>
    </div>
  );
}
