"use client";

import { useState, useEffect } from "react";
import Link from "next/link";
import { useCartStore } from "@/lib/cart-store";
import { useAuthStore, getAuthHeaders } from "@/lib/auth-store";
import { useEnsureStoreCustomer } from "@/lib/use-ensure-store-customer";
import { useStorefrontConfig } from "@/lib/storefront-config-context";
import { formatPrice } from "@/lib/utils";
import { useLanguage } from "@/lib/language-context";
import { v4 as uuidv4 } from "uuid";
import PhoneInput from "@/components/ui/PhoneInput";
import type { ShippingAddress } from "@/types";
import GateModal from "@/components/auth/GateModal";

interface ShippingArea {
  value: string;
  label: string;
  label_ar?: string | null;
  zone_id: number;
  zone_name: string;
  zone_name_ar?: string | null;
}

interface FormState {
  customer_name: string;
  customer_phone: string;
  customer_email: string;
  line1: string;
  line2: string;
  city: string;
  state: string;
  postal_code: string;
  country: string;
  notes: string;
}

const defaultForm: FormState = {
  customer_name: "",
  customer_phone: "",
  customer_email: "",
  line1: "",
  line2: "",
  city: "",
  state: "",
  postal_code: "",
  country: "EG",
  notes: "",
};

export default function CheckoutPage() {
  const { t, locale } = useLanguage();
  const { website } = useStorefrontConfig();
  const allowGuestCheckout = !!website?.allow_guest_checkout;
  const { items, total } = useCartStore();
  useEnsureStoreCustomer();
  const customer = useAuthStore((s) => s.customer);
  const isLoggedIn = useAuthStore((s) => s.isLoggedIn());
  const [showCheckoutGate, setShowCheckoutGate] = useState(false);
  const registrationRequired = !allowGuestCheckout && !isLoggedIn;
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState("");
  const [form, setForm] = useState<FormState>(defaultForm);
  const [selectedAddressId, setSelectedAddressId] = useState<string | "">("");
  const [paymentMethod, setPaymentMethod] = useState<"cod" | "online">("cod");
  const paymentEnabled = !!website?.payment_enabled;
  const [shippingRates, setShippingRates] = useState<any[]>([]);
  const [selectedShippingRate, setSelectedShippingRate] = useState<any>(null);
  const [loadingRates, setLoadingRates] = useState(false);
  const [shippingAreas, setShippingAreas] = useState<ShippingArea[]>([]);
  const [loadingAreas, setLoadingAreas] = useState(true);

  const savedAddresses = customer?.saved_addresses ?? [];
  const hasShippingAreas = shippingAreas.length > 0;

  useEffect(() => {
    const fetchAreas = async () => {
      setLoadingAreas(true);
      try {
        const response = await fetch("/api/storefront-proxy/shipping-areas", {
          headers: getAuthHeaders(),
        });
        if (!response.ok) {
          throw new Error("Failed to fetch shipping areas");
        }
        const data = await response.json();
        setShippingAreas(data.areas || []);
      } catch (err) {
        console.error("Error fetching shipping areas:", err);
        setShippingAreas([]);
      } finally {
        setLoadingAreas(false);
      }
    };

    fetchAreas();
  }, []);

  useEffect(() => {
    if (!customer) return;
    setForm((prev) => ({
      ...prev,
      customer_name: customer.name || prev.customer_name,
      customer_phone: customer.phone || prev.customer_phone,
      customer_email: customer.email || prev.customer_email,
      line1: customer.address?.line1 || prev.line1,
      line2: customer.address?.line2 ?? prev.line2,
      city: customer.address?.city || prev.city,
      state: customer.address?.state ?? prev.state,
      postal_code: customer.address?.postal_code ?? prev.postal_code,
      country: customer.address?.country || prev.country,
    }));
  }, [customer?.id]);

  useEffect(() => {
    if (!form.city || items.length === 0) {
      setShippingRates([]);
      setSelectedShippingRate(null);
      return;
    }

    const fetchRates = async () => {
      setLoadingRates(true);
      try {
        const response = await fetch("/api/storefront-proxy/shipping-rates", {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
            ...getAuthHeaders(),
          },
          body: JSON.stringify({
            city: form.city,
            country: form.country,
            state: form.state,
            items: items.map((i) => ({
              item_id: i.item_id,
              quantity: i.quantity,
              price: i.price,
            })),
          }),
        });

        if (!response.ok) {
          throw new Error("Failed to fetch shipping rates");
        }

        const data = await response.json();
        setShippingRates(data.rates || []);
        if (data.rates && data.rates.length > 0) {
          setSelectedShippingRate(data.rates[0]);
        }
      } catch (err) {
        console.error("Error fetching shipping rates:", err);
        setShippingRates([]);
        setSelectedShippingRate(null);
      } finally {
        setLoadingRates(false);
      }
    };

    fetchRates();
  }, [form.city, form.country, items.length]);

  const applySavedAddress = (addr: { line1: string; line2?: string; city: string; state?: string; postal_code?: string; country: string }) => {
    setForm((prev) => ({
      ...prev,
      line1: addr.line1,
      line2: addr.line2 ?? "",
      city: addr.city,
      state: addr.state ?? "",
      postal_code: addr.postal_code ?? "",
      country: addr.country,
    }));
  };

  const formatAreaLabel = (area: ShippingArea) => {
    if (area.value.startsWith("zone:")) {
      return locale === "ar" && area.label_ar ? area.label_ar : area.label;
    }

    const zoneName =
      locale === "ar" && area.zone_name_ar ? area.zone_name_ar : area.zone_name;
    const areaLabel = locale === "ar" && area.label_ar ? area.label_ar : area.label;
    return `${areaLabel} — ${zoneName}`;
  };

  const handleShippingAreaChange = (value: string) => {
    setForm((prev) => ({ ...prev, city: value }));
    setSelectedShippingRate(null);
  };

  if (registrationRequired) {
    return (
      <>
        <div className="max-w-2xl mx-auto px-4 sm:px-6 py-12 sm:py-24 text-center">
          <h1 className="text-2xl font-bold text-gray-900 mb-2">
            {t.gate.checkoutTitle}
          </h1>
          <p className="text-gray-500 mb-6">{t.gate.checkoutMessage}</p>
          <button
            type="button"
            onClick={() => setShowCheckoutGate(true)}
            className="btn-primary px-8 py-3.5 rounded-2xl font-semibold text-sm"
          >
            {t.auth.login}
          </button>
          <Link
            href="/cart"
            className="block text-center text-sm text-gray-400 hover:text-gray-600 mt-4"
          >
            ← {t.checkout.backToCart}
          </Link>
        </div>
        <GateModal
          open={showCheckoutGate}
          type="checkout"
          returnTo="/checkout"
          onClose={() => setShowCheckoutGate(false)}
        />
      </>
    );
  }

  if (items.length === 0) {
    return (
      <div className="max-w-2xl mx-auto px-4 sm:px-6 py-12 sm:py-24 text-center">
        <div className="w-20 h-20 rounded-full bg-gray-100 flex items-center justify-center mx-auto mb-6">
          <svg
            className="w-10 h-10 text-gray-400"
            fill="none"
            viewBox="0 0 24 24"
            stroke="currentColor"
            strokeWidth={1.25}
          >
            <path
              strokeLinecap="round"
              strokeLinejoin="round"
              d="M3 3h2l.4 2M7 13h10l4-8H5.4M7 13L5.4 5M7 13l-2.293 2.293c-.63.63-.184 1.707.707 1.707H17m0 0a2 2 0 100 4 2 2 0 000-4zm-8 2a2 2 0 11-4 0 2 2 0 014 0z"
            />
          </svg>
        </div>
        <p className="text-gray-500 mb-6">{t.cart.empty}</p>
        <Link
          href="/products"
          className="btn-primary px-8 py-3.5 rounded-2xl inline-block font-semibold text-sm"
        >
          {t.common.browseProducts}
        </Link>
      </div>
    );
  }

  const set =
    (field: keyof FormState) =>
    (
      e: React.ChangeEvent<
        HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement
      >,
    ) =>
      setForm((f) => ({ ...f, [field]: e.target.value }));

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setSubmitting(true);
    setError("");

    const idempotencyKey = uuidv4();
    const selectedArea = shippingAreas.find((area) => area.value === form.city);
    const shippingCity =
      selectedArea != null
        ? locale === "ar" && selectedArea.label_ar
          ? selectedArea.label_ar
          : selectedArea.label
        : form.city;
    const shipping: ShippingAddress = {
      line1: form.line1,
      ...(form.line2 ? { line2: form.line2 } : {}),
      city: shippingCity,
      ...(form.state ? { state: form.state } : {}),
      ...(form.postal_code ? { postal_code: form.postal_code } : {}),
      country: form.country,
    };

    const payload = {
      idempotency_key: idempotencyKey,
      customer_name: form.customer_name,
      customer_phone: form.customer_phone,
      ...(form.customer_email ? { customer_email: form.customer_email } : {}),
      shipping_address: shipping,
      payment_method: paymentMethod,
      ...(form.notes ? { notes: form.notes } : {}),
      ...(selectedShippingRate
        ? {
            shipping_fee: selectedShippingRate.rate || 0,
            shipping_zone_name: selectedShippingRate.zone_name || "",
            shipping_rate_name: selectedShippingRate.name || "",
          }
        : {}),
      items: items.map((i) => ({
        item_id: i.item_id,
        quantity: i.quantity,
        unit_price: i.price,
      })),
    };

    try {
      const res = await fetch("/api/storefront-proxy/orders", {
        method: "POST",
        headers: { "Content-Type": "application/json", ...getAuthHeaders() },
        body: JSON.stringify(payload),
      });
      const data = await res.json();
      if (!res.ok) {
        if (data.error === "registration_required") {
          setShowCheckoutGate(true);
        }
        setError(data.message || t.checkout.placeOrderError);
        return;
      }
      sessionStorage.setItem(
        `order_phone_${data.order.order_number}`,
        form.customer_phone,
      );
      // Also store by idempotency key so the order page can find the phone
      // even when the payment gateway echoes back the UUID instead of order_number
      sessionStorage.setItem(
        `order_phone_${idempotencyKey}`,
        form.customer_phone,
      );
      if (data.payment_url) {
        window.location.href = data.payment_url;
        return;
      }
      // Hard redirect — cart is cleared by the order confirmation page on arrival
      window.location.href = `/orders/${data.order.order_number}?placed=1`;
    } catch (err: any) {
      setError(err.message || t.common.error);
    } finally {
      setSubmitting(false);
    }
  };

  const inputCls = "input-base";

  const steps = [
    {
      label: t.checkout.contactInfo,
      icon: "M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z",
    },
    {
      label: t.checkout.deliveryAddress,
      icon: "M17.657 16.657L13.414 20.9a1.998 1.998 0 01-2.827 0l-4.244-4.243a8 8 0 1111.314 0z",
    },
    {
      label: t.checkout.paymentMethod,
      icon: "M3 10h18M7 15h1m4 0h1m-7 4h12a3 3 0 003-3V8a3 3 0 00-3-3H6a3 3 0 00-3 3v8a3 3 0 003 3z",
    },
  ];

  return (
    <div className="max-w-5xl mx-auto px-4 sm:px-6 lg:px-8 py-6 sm:py-8">
      {/* Page header */}
      <div className="mb-8">
        <Link
          href="/cart"
          className="text-sm text-gray-400 hover:text-gray-600 transition-colors flex items-center gap-1 mb-4"
        >
          <svg
            className="w-4 h-4"
            fill="none"
            viewBox="0 0 24 24"
            stroke="currentColor"
            strokeWidth={2}
          >
            <path
              strokeLinecap="round"
              strokeLinejoin="round"
              d="M15 19l-7-7 7-7"
            />
          </svg>
          {t.checkout.backToCart}
        </Link>
        <h1 className="text-2xl font-bold text-gray-900">{t.checkout.title}</h1>
        {(website as { theme_settings?: { delivery_message?: string } })?.theme_settings?.delivery_message && (
          <p className="mt-2 text-sm text-gray-600">
            {(website as { theme_settings?: { delivery_message?: string } }).theme_settings!.delivery_message}
          </p>
        )}
      </div>

      {/* Step indicator */}
      <div className="flex items-center gap-0 mb-10 overflow-x-auto scrollbar-hide">
        {steps.map((step, i) => (
          <div key={i} className="flex items-center flex-shrink-0">
            <div className="flex items-center gap-2">
              <div
                className="w-7 h-7 rounded-full flex items-center justify-center flex-shrink-0"
                style={{ backgroundColor: "var(--color-primary)" }}
              >
                <svg
                  className="w-3.5 h-3.5 text-white"
                  fill="none"
                  viewBox="0 0 24 24"
                  stroke="currentColor"
                  strokeWidth={2}
                >
                  <path
                    strokeLinecap="round"
                    strokeLinejoin="round"
                    d={step.icon}
                  />
                </svg>
              </div>
              <span className="text-xs font-semibold text-gray-700 whitespace-nowrap">
                {step.label}
              </span>
            </div>
            {i < steps.length - 1 && (
              <div className="w-8 sm:w-12 h-px bg-gray-200 mx-2 flex-shrink-0" />
            )}
          </div>
        ))}
      </div>

      <form onSubmit={handleSubmit}>
        <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
          {/* ── Form ── */}
          <div className="lg:col-span-2 space-y-5">
            {/* Contact */}
            <section className="bg-white rounded-2xl border border-gray-100 p-6 shadow-sm">
              <div className="flex items-center gap-2 mb-5">
                <div
                  className="w-6 h-6 rounded-full flex items-center justify-center text-white text-xs font-bold"
                  style={{ backgroundColor: "var(--color-primary)" }}
                >
                  1
                </div>
                <h2 className="text-sm font-bold text-gray-900">
                  {t.checkout.contactInfo}
                </h2>
              </div>
              <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                <div>
                  <label className="block text-xs font-semibold text-gray-500 mb-1.5">
                    {t.checkout.fullName}{" "}
                    <span className="text-red-400">*</span>
                  </label>
                  <input
                    type="text"
                    value={form.customer_name}
                    onChange={set("customer_name")}
                    required
                    placeholder="Ahmed Mohamed"
                    className={inputCls}
                  />
                </div>
                <div>
                  <label className="block text-xs font-semibold text-gray-500 mb-1.5">
                    {t.checkout.phone} <span className="text-red-400">*</span>
                  </label>
                  <PhoneInput
                    value={form.customer_phone}
                    onChange={(v) =>
                      setForm((f) => ({ ...f, customer_phone: v }))
                    }
                    placeholder="1234567890"
                    required
                  />
                </div>
                <div className="sm:col-span-2">
                  <label className="block text-xs font-semibold text-gray-500 mb-1.5">
                    {t.checkout.email}{" "}
                    <span className="text-gray-400 font-normal">
                      (optional)
                    </span>
                  </label>
                  <input
                    type="email"
                    value={form.customer_email}
                    onChange={set("customer_email")}
                    placeholder="ahmed@example.com"
                    className={inputCls}
                  />
                </div>
              </div>
            </section>

            {/* Shipping */}
            <section className="bg-white rounded-2xl border border-gray-100 p-6 shadow-sm">
              <div className="flex items-center gap-2 mb-5">
                <div
                  className="w-6 h-6 rounded-full flex items-center justify-center text-white text-xs font-bold"
                  style={{ backgroundColor: "var(--color-primary)" }}
                >
                  2
                </div>
                <h2 className="text-sm font-bold text-gray-900">
                  {t.checkout.deliveryAddress}
                </h2>
              </div>
              {savedAddresses.length > 0 && (
                <div className="mb-4">
                  <label className="block text-xs font-semibold text-gray-500 mb-1.5">
                    {t.checkout.deliverTo}
                  </label>
                  <select
                    value={selectedAddressId}
                    onChange={(e) => {
                      const id = e.target.value;
                      setSelectedAddressId(id);
                      if (id) {
                        const addr = savedAddresses.find((a) => a.id === id);
                        if (addr) applySavedAddress(addr);
                      }
                    }}
                    className={inputCls}
                  >
                    <option value="">{t.checkout.addNewAddress}</option>
                    {savedAddresses.map((addr) => (
                      <option key={addr.id} value={addr.id}>
                        {addr.label} — {addr.line1}, {addr.city}
                      </option>
                    ))}
                  </select>
                </div>
              )}
              <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                <div className="sm:col-span-2">
                  <label className="block text-xs font-semibold text-gray-500 mb-1.5">
                    {t.checkout.addressLine1}{" "}
                    <span className="text-red-400">*</span>
                  </label>
                  <input
                    type="text"
                    value={form.line1}
                    onChange={set("line1")}
                    required
                    placeholder="123 Tahrir St, Apt 4"
                    className={inputCls}
                  />
                </div>
                <div className="sm:col-span-2">
                  <label className="block text-xs font-semibold text-gray-500 mb-1.5">
                    {t.checkout.addressLine2}{" "}
                    <span className="text-gray-400 font-normal">
                      (optional)
                    </span>
                  </label>
                  <input
                    type="text"
                    value={form.line2}
                    onChange={set("line2")}
                    placeholder="Floor, building, landmark…"
                    className={inputCls}
                  />
                </div>
                <div className="sm:col-span-2">
                  <label className="block text-xs font-semibold text-gray-500 mb-1.5">
                    {hasShippingAreas ? t.checkout.shippingArea : t.checkout.city}{" "}
                    <span className="text-red-400">*</span>
                  </label>
                  {loadingAreas ? (
                    <div className="input-base flex items-center text-sm text-gray-400">
                      {t.common.loading || "Loading…"}
                    </div>
                  ) : hasShippingAreas ? (
                    <select
                      value={form.city}
                      onChange={(e) => handleShippingAreaChange(e.target.value)}
                      required
                      className={inputCls}
                    >
                      <option value="">{t.checkout.selectShippingArea}</option>
                      {shippingAreas.map((area) => (
                        <option key={`${area.zone_id}-${area.value}`} value={area.value}>
                          {formatAreaLabel(area)}
                        </option>
                      ))}
                    </select>
                  ) : (
                    <input
                      type="text"
                      value={form.city}
                      onChange={set("city")}
                      required
                      placeholder="Cairo"
                      className={inputCls}
                    />
                  )}
                  {!loadingAreas && !hasShippingAreas && (
                    <p className="text-xs text-amber-600 mt-1.5">
                      {t.checkout.noShippingAreas}
                    </p>
                  )}
                </div>
                <div>
                  <label className="block text-xs font-semibold text-gray-500 mb-1.5">
                    {t.checkout.state}
                  </label>
                  <input
                    type="text"
                    value={form.state}
                    onChange={set("state")}
                    placeholder="Cairo"
                    className={inputCls}
                  />
                </div>
                <div>
                  <label className="block text-xs font-semibold text-gray-500 mb-1.5">
                    {t.checkout.postalCode}
                  </label>
                  <input
                    type="text"
                    value={form.postal_code}
                    onChange={set("postal_code")}
                    placeholder="11511"
                    className={inputCls}
                  />
                </div>
                <div>
                  <label className="block text-xs font-semibold text-gray-500 mb-1.5">
                    {t.checkout.country} <span className="text-red-400">*</span>
                  </label>
                  <select
                    value={form.country}
                    onChange={set("country")}
                    required
                    className={inputCls}
                  >
                    <option value="EG">Egypt</option>
                    <option value="SA">Saudi Arabia</option>
                    <option value="AE">UAE</option>
                    <option value="KW">Kuwait</option>
                    <option value="QA">Qatar</option>
                    <option value="BH">Bahrain</option>
                    <option value="OM">Oman</option>
                    <option value="JO">Jordan</option>
                    <option value="LB">Lebanon</option>
                    <option value="OTHER">Other</option>
                  </select>
                </div>
              </div>
            </section>

            {/* Shipping Method */}
            {form.city && (
              <section className="bg-white rounded-2xl border border-gray-100 p-6 shadow-sm">
                <div className="flex items-center gap-2 mb-5">
                  <div
                    className="w-6 h-6 rounded-full flex items-center justify-center text-white text-xs font-bold"
                    style={{ backgroundColor: "var(--color-primary)" }}
                  >
                    3
                  </div>
                  <h2 className="text-sm font-bold text-gray-900">
                    {t.checkout.shippingMethod || "Shipping Method"}
                  </h2>
                </div>
                {loadingRates ? (
                  <div className="text-center py-4 text-sm text-gray-500">
                    <div className="inline-block animate-spin rounded-full h-6 w-6 border-b-2 border-gray-900 mb-2"></div>
                    <p>{t.checkout.loadingShippingRates}</p>
                  </div>
                ) : shippingRates.length > 0 ? (
                  <div className="space-y-3">
                    {shippingRates.map((rate) => (
                      <button
                        key={rate.id}
                        type="button"
                        onClick={() => setSelectedShippingRate(rate)}
                        className={`w-full flex items-center justify-between gap-4 p-4 border-2 rounded-xl text-left transition-colors ${
                          selectedShippingRate?.id === rate.id
                            ? ""
                            : "border-gray-200 hover:border-gray-300"
                        }`}
                        style={
                          selectedShippingRate?.id === rate.id
                            ? {
                                borderColor: "var(--color-primary)",
                                backgroundColor:
                                  "color-mix(in srgb, var(--color-primary) 5%, transparent)",
                              }
                            : undefined
                        }
                      >
                        <div className="flex items-center gap-3">
                          <div
                            className={`w-5 h-5 rounded-full border-2 flex items-center justify-center flex-shrink-0 ${
                              selectedShippingRate?.id === rate.id ? "" : "border-gray-300"
                            }`}
                            style={
                              selectedShippingRate?.id === rate.id
                                ? { borderColor: "var(--color-primary)" }
                                : undefined
                            }
                          >
                            {selectedShippingRate?.id === rate.id && (
                              <div
                                className="w-2.5 h-2.5 rounded-full"
                                style={{ backgroundColor: "var(--color-primary)" }}
                              />
                            )}
                          </div>
                          <div>
                            <p className="font-medium text-gray-900">
                              {locale === "ar" && rate.name_ar ? rate.name_ar : rate.name}
                            </p>
                            {(locale === "ar" && rate.estimated_days_ar
                              ? rate.estimated_days_ar
                              : rate.estimated_days) && (
                              <p className="text-xs text-gray-500 mt-0.5">
                                {locale === "ar" && rate.estimated_days_ar
                                  ? rate.estimated_days_ar
                                  : rate.estimated_days}
                              </p>
                            )}
                          </div>
                        </div>
                        <div className="text-right">
                          <p className="font-semibold text-gray-900">
                            {rate.rate === 0
                              ? t.common.free || "FREE"
                              : `${formatPrice(rate.rate)} ${website?.currency || "EGP"}`}
                          </p>
                        </div>
                      </button>
                    ))}
                  </div>
                ) : (
                  <p className="text-sm text-amber-600">{t.checkout.noShippingRates}</p>
                )}
              </section>
            )}

            {/* Payment */}
            <section className="bg-white rounded-2xl border border-gray-100 p-6 shadow-sm">
              <div className="flex items-center gap-2 mb-5">
                <div
                  className="w-6 h-6 rounded-full flex items-center justify-center text-white text-xs font-bold"
                  style={{ backgroundColor: "var(--color-primary)" }}
                >
                  {form.city ? "4" : "3"}
                </div>
                <h2 className="text-sm font-bold text-gray-900">
                  {t.checkout.paymentMethod}
                </h2>
              </div>
              <div className="space-y-3">
                <button
                  type="button"
                  onClick={() => setPaymentMethod("cod")}
                  className={`w-full flex items-center gap-4 p-4 border-2 rounded-xl text-left transition-colors ${
                    paymentMethod === "cod"
                      ? ""
                      : "border-gray-200 hover:border-gray-300"
                  }`}
                  style={
                    paymentMethod === "cod"
                      ? {
                          borderColor: "var(--color-primary)",
                          backgroundColor:
                            "color-mix(in srgb, var(--color-primary) 5%, transparent)",
                        }
                      : undefined
                  }
                >
                  <div
                    className={`w-5 h-5 rounded-full border-2 flex items-center justify-center flex-shrink-0 ${
                      paymentMethod === "cod" ? "" : "border-gray-300"
                    }`}
                    style={
                      paymentMethod === "cod"
                        ? { borderColor: "var(--color-primary)" }
                        : undefined
                    }
                  >
                    {paymentMethod === "cod" && (
                      <div
                        className="w-2.5 h-2.5 rounded-full"
                        style={{ backgroundColor: "var(--color-primary)" }}
                      />
                    )}
                  </div>
                  <div className="flex items-center gap-3 flex-1">
                    <div className="w-9 h-9 rounded-xl bg-white border border-gray-100 flex items-center justify-center shadow-sm flex-shrink-0">
                      <svg
                        className="w-5 h-5 text-gray-600"
                        fill="none"
                        viewBox="0 0 24 24"
                        stroke="currentColor"
                        strokeWidth={1.5}
                      >
                        <path
                          strokeLinecap="round"
                          strokeLinejoin="round"
                          d="M17 9V7a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2m2 4h10a2 2 0 002-2v-6a2 2 0 00-2-2H9a2 2 0 00-2 2v6a2 2 0 002 2zm7-5a2 2 0 11-4 0 2 2 0 014 0z"
                        />
                      </svg>
                    </div>
                    <div>
                      <p className="text-sm font-semibold text-gray-800">
                        {t.checkout.cod}
                      </p>
                      <p className="text-xs text-gray-500">
                        {t.checkout.codHint}
                      </p>
                    </div>
                  </div>
                </button>
                {paymentEnabled && (
                  <button
                    type="button"
                    onClick={() => setPaymentMethod("online")}
                    className={`w-full flex items-center gap-4 p-4 border-2 rounded-xl text-left transition-colors ${
                      paymentMethod === "online"
                        ? ""
                        : "border-gray-200 hover:border-gray-300"
                    }`}
                    style={
                      paymentMethod === "online"
                        ? {
                            borderColor: "var(--color-primary)",
                            backgroundColor:
                              "color-mix(in srgb, var(--color-primary) 5%, transparent)",
                          }
                        : undefined
                    }
                  >
                    <div
                      className={`w-5 h-5 rounded-full border-2 flex items-center justify-center flex-shrink-0 ${
                        paymentMethod === "online" ? "" : "border-gray-300"
                      }`}
                      style={
                        paymentMethod === "online"
                          ? { borderColor: "var(--color-primary)" }
                          : undefined
                      }
                    >
                      {paymentMethod === "online" && (
                        <div
                          className="w-2.5 h-2.5 rounded-full"
                          style={{ backgroundColor: "var(--color-primary)" }}
                        />
                      )}
                    </div>
                    <div className="flex items-center gap-3 flex-1">
                      <div className="w-9 h-9 rounded-xl bg-white border border-gray-100 flex items-center justify-center shadow-sm flex-shrink-0">
                        <svg
                          className="w-5 h-5 text-gray-600"
                          fill="none"
                          viewBox="0 0 24 24"
                          stroke="currentColor"
                          strokeWidth={1.5}
                        >
                          <path
                            strokeLinecap="round"
                            strokeLinejoin="round"
                            d="M3 10h18M7 15h1m4 0h1m-7 4h12a3 3 0 003-3V8a3 3 0 00-3-3H6a3 3 0 00-3 3v8a3 3 0 003 3z"
                          />
                        </svg>
                      </div>
                      <div>
                        <p className="text-sm font-semibold text-gray-800">
                          {t.checkout.onlinePayment}
                        </p>
                        <p className="text-xs text-gray-500">
                          {t.checkout.onlinePaymentHint}
                        </p>
                      </div>
                    </div>
                  </button>
                )}
              </div>
            </section>

            {/* Notes */}
            <section className="bg-white rounded-2xl border border-gray-100 p-6 shadow-sm">
              <h2 className="text-sm font-bold text-gray-900 mb-4">
                {t.checkout.notes}{" "}
                <span className="text-gray-400 font-normal text-xs">
                  (optional)
                </span>
              </h2>
              <textarea
                value={form.notes}
                onChange={set("notes")}
                rows={3}
                placeholder={t.checkout.notesPlaceholder}
                className={inputCls + " resize-none"}
              />
            </section>
          </div>

          {/* ── Summary ── */}
          <div className="lg:col-span-1">
            <div className="bg-white rounded-2xl border border-gray-100 p-6 sticky top-20 shadow-sm">
              <h2 className="text-sm font-bold text-gray-900 mb-5">
                {t.checkout.orderSummary}
              </h2>
              <div className="space-y-2.5 text-sm text-gray-600 mb-5">
                {items.map((item) => (
                  <div
                    key={item.item_id}
                    className="flex justify-between gap-2"
                  >
                    <span className="truncate text-gray-500">
                      {item.name}{" "}
                      <span className="text-gray-400">×{item.quantity}</span>
                    </span>
                    <span className="font-medium text-gray-800 flex-shrink-0">
                      {formatPrice(item.price * item.quantity)}
                    </span>
                  </div>
                ))}
              </div>
              <div className="border-t border-gray-100 pt-4 mb-6 space-y-2">
                <div className="flex justify-between text-sm text-gray-600">
                  <span>{t.cart.subtotal || "Subtotal"}</span>
                  <span>{formatPrice(total())}</span>
                </div>
                {selectedShippingRate && (
                  <div className="flex justify-between text-sm text-gray-600">
                    <span>{t.checkout.shipping || "Shipping"}</span>
                    <span>
                      {selectedShippingRate.rate === 0
                        ? t.common.free || "FREE"
                        : formatPrice(selectedShippingRate.rate)}
                    </span>
                  </div>
                )}
                <div className="flex justify-between text-base font-bold text-gray-900 pt-2 border-t border-gray-100">
                  <span>{t.cart.total}</span>
                  <span style={{ color: "var(--color-primary)" }}>
                    {formatPrice(total() + (selectedShippingRate?.rate || 0))}
                  </span>
                </div>
                <p className="text-xs text-gray-400 mt-1">
                  {paymentMethod === "online"
                    ? t.checkout.onlinePayment
                    : t.checkout.cod}
                </p>
              </div>

              {error && (
                <div className="mb-4 p-3.5 bg-red-50 border border-red-200 rounded-xl flex items-start gap-2.5">
                  <svg
                    className="w-4 h-4 text-red-500 flex-shrink-0 mt-0.5"
                    fill="none"
                    viewBox="0 0 24 24"
                    stroke="currentColor"
                    strokeWidth={2}
                  >
                    <path
                      strokeLinecap="round"
                      strokeLinejoin="round"
                      d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"
                    />
                  </svg>
                  <p className="text-sm text-red-600">{error}</p>
                </div>
              )}

              <button
                type="submit"
                disabled={submitting}
                className="btn-primary w-full py-4 rounded-2xl font-bold text-sm shadow-md"
              >
                {submitting ? (
                  <span className="flex items-center justify-center gap-2">
                    <svg
                      className="w-4 h-4 animate-spin"
                      fill="none"
                      viewBox="0 0 24 24"
                    >
                      <circle
                        className="opacity-25"
                        cx="12"
                        cy="12"
                        r="10"
                        stroke="currentColor"
                        strokeWidth="4"
                      />
                      <path
                        className="opacity-75"
                        fill="currentColor"
                        d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"
                      />
                    </svg>
                    {t.checkout.placing}
                  </span>
                ) : (
                  t.checkout.placeOrder
                )}
              </button>

              {/* Trust badges */}
              <div className="mt-5 pt-5 border-t border-gray-100">
                <div className="flex items-center justify-center gap-1 mb-2">
                  <svg
                    className="w-3.5 h-3.5 text-gray-400"
                    fill="none"
                    viewBox="0 0 24 24"
                    stroke="currentColor"
                    strokeWidth={1.75}
                  >
                    <path
                      strokeLinecap="round"
                      strokeLinejoin="round"
                      d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z"
                    />
                  </svg>
                  <p className="text-[10px] text-gray-400 font-medium">
                    Secure & encrypted checkout
                  </p>
                </div>
              </div>
            </div>
          </div>
        </div>
      </form>
    </div>
  );
}
