import { useState, useCallback, useEffect, useMemo } from "react";
import { X, Upload, Phone, ChevronDown, ShieldCheck, Minus, Plus, Ban, Download, Copy, Check } from "lucide-react";
import { createOrder, type Order, currentTicketPrice, EARLY_PRICE, GATE_PRICE, normalizePhoneE164 } from "@/lib/ticketStore";
import { useSiteSettings } from "@/hooks/useSiteSettings";
import { canSellTickets, lockCopy, scrollToInsider } from "@/lib/siteMode";
import TicketLockModal from "./TicketLockModal";

const COUNTRY_CODES: { dial: string; label: string }[] = [
  { dial: "+232", label: "🇸🇱 Sierra Leone (+232)" },
  { dial: "+1", label: "🇺🇸 United States / Canada (+1)" },
  { dial: "+44", label: "🇬🇧 United Kingdom (+44)" },
  { dial: "+234", label: "🇳🇬 Nigeria (+234)" },
  { dial: "+233", label: "🇬🇭 Ghana (+233)" },
  { dial: "+231", label: "🇱🇷 Liberia (+231)" },
  { dial: "+224", label: "🇬🇳 Guinea (+224)" },
  { dial: "+225", label: "🇨🇮 Côte d'Ivoire (+225)" },
  { dial: "+221", label: "🇸🇳 Senegal (+221)" },
  { dial: "+220", label: "🇬🇲 Gambia (+220)" },
  { dial: "+27", label: "🇿🇦 South Africa (+27)" },
  { dial: "+254", label: "🇰🇪 Kenya (+254)" },
  { dial: "+971", label: "🇦🇪 UAE (+971)" },
  { dial: "+91", label: "🇮🇳 India (+91)" },
  { dial: "+86", label: "🇨🇳 China (+86)" },
  { dial: "+33", label: "🇫🇷 France (+33)" },
  { dial: "+49", label: "🇩🇪 Germany (+49)" },
  { dial: "+39", label: "🇮🇹 Italy (+39)" },
  { dial: "+34", label: "🇪🇸 Spain (+34)" },
  { dial: "+32", label: "🇧🇪 Belgium (+32)" },
  { dial: "+31", label: "🇳🇱 Netherlands (+31)" },
  { dial: "+46", label: "🇸🇪 Sweden (+46)" },
  { dial: "+90", label: "🇹🇷 Turkey (+90)" },
  { dial: "+966", label: "🇸🇦 Saudi Arabia (+966)" },
  { dial: "+61", label: "🇦🇺 Australia (+61)" },
  { dial: "+7", label: "🇷🇺 Russia (+7)" },
  { dial: "+81", label: "🇯🇵 Japan (+81)" },
  { dial: "+82", label: "🇰🇷 South Korea (+82)" },
  { dial: "+55", label: "🇧🇷 Brazil (+55)" },
  { dial: "+20", label: "🇪🇬 Egypt (+20)" },
  { dial: "+212", label: "🇲🇦 Morocco (+212)" },
  { dial: "+353", label: "🇮🇪 Ireland (+353)" },
  { dial: "+351", label: "🇵🇹 Portugal (+351)" },
  { dial: "+41", label: "🇨🇭 Switzerland (+41)" },
  { dial: "+43", label: "🇦🇹 Austria (+43)" },
  { dial: "+45", label: "🇩🇰 Denmark (+45)" },
  { dial: "+47", label: "🇳🇴 Norway (+47)" },
  { dial: "+358", label: "🇫🇮 Finland (+358)" },
];

function normalizeWithCountry(input: string, dial: string): string {
  if (!input) return "";
  let raw = input.replace(/[^\d+]/g, "");
  // If the user typed a full international number with '+', use that as-is
  if (raw.startsWith("+")) {
    const digits = raw.slice(1);
    return digits.length >= 7 && digits.length <= 15 ? `+${digits}` : "";
  }
  // Sierra Leone handled by existing strict normalizer
  if (dial === "+232") return normalizePhoneE164(input);
  // Generic: strip leading zero (trunk prefix) and prepend the selected country code
  if (raw.startsWith("0")) raw = raw.slice(1);
  if (raw.length < 6 || raw.length > 14) return "";
  return `${dial}${raw}`;
}
import { downloadTicketAsImage } from "@/lib/downloadTicket";
import AccessCard from "./AccessCard";
import orangeMoneyLogo from "@/assets/orange-money.webp";
import afrimoneyLogo from "@/assets/afrimoney.webp";

type Step = "instructions" | "form" | "submitting" | "pending" | "confirmed" | "rejected";

interface TicketFlowProps {
  open: boolean;
  onClose: () => void;
}

const UNIT_PRICE = currentTicketPrice();
const MAX_QTY = 8;

const PaymentOption = ({
  title,
  dialCode,
  number,
  copyValue,
  menuLabel,
  logoSrc,
  logoAlt,
  sendLabel = "Send Money",
}: {
  title: string;
  dialCode: string;
  number: string;
  copyValue: string;
  menuLabel: string;
  logoSrc: string;
  logoAlt: string;
  sendLabel?: string;
}) => {
  const [copied, setCopied] = useState(false);
  const [showInAppFallback, setShowInAppFallback] = useState(false);
  const [fallbackCopied, setFallbackCopied] = useState(false);

  const copyText = async (value: string) => {
    try {
      await navigator.clipboard.writeText(value);
    } catch {
      const ta = document.createElement("textarea");
      ta.value = value;
      document.body.appendChild(ta);
      ta.select();
      try { document.execCommand("copy"); } catch {/* noop */}
      document.body.removeChild(ta);
    }
  };

  const handleCopy = async () => {
    await copyText(copyValue);
    setCopied(true);
    setTimeout(() => setCopied(false), 1800);
  };

  const isInAppBrowser = () => {
    if (typeof navigator === "undefined") return false;
    const ua = navigator.userAgent || "";
    return /Instagram|FBAN|FBAV|FB_IAB|FBIOS|Messenger|TikTok|musical_ly|Bytedance|Snapchat|Line\/|Twitter|LinkedInApp|Pinterest/i.test(ua);
  };

  const handleMenuClick = (e: React.MouseEvent) => {
    if (isInAppBrowser()) {
      e.preventDefault();
      setShowInAppFallback(true);
      return;
    }
    e.preventDefault();
    window.location.href = telHref;
  };

  const handleFallbackCopy = async () => {
    await copyText(dialCode);
    setFallbackCopied(true);
    setTimeout(() => setFallbackCopied(false), 1800);
  };

  const steps = [
    `Dial ${dialCode}`,
    `Select ${sendLabel}`,
    "Enter number",
    "Enter amount",
    "Confirm",
  ];

  // tel: with USSD — encode '#' as %23, keep '*' as-is for best dialer compatibility
  const telHref = `tel:${dialCode.replace(/#/g, "%23")}`;

  return (
    <div className="bg-muted/20 rounded-xl p-5 border border-border/15 space-y-4">
      <div className="flex items-center gap-3">
        <img
          src={logoSrc}
          alt={logoAlt}
          width={32}
          height={32}
          loading="lazy"
          decoding="async"
          className="w-8 h-8 rounded-md bg-white object-contain p-1 shrink-0"
        />
        <p className="text-sm font-display font-semibold text-foreground/90">{title}</p>
      </div>

      <div>
        <p className="text-[10px] text-muted-foreground uppercase tracking-[0.2em] font-body mb-1">Send to</p>
        <p className="text-base font-display font-bold tracking-wider text-foreground select-all">{number}</p>
      </div>

      <div>
        <p className="text-[10px] text-muted-foreground uppercase tracking-[0.2em] font-body mb-2">Steps</p>
        <ol className="space-y-1 text-xs font-body text-foreground/75 list-decimal list-inside">
          {steps.map((s) => <li key={s}>{s}</li>)}
        </ol>
      </div>

      <div className="grid grid-cols-2 gap-2">
        <button
          type="button"
          onClick={handleCopy}
          className="inline-flex items-center justify-center gap-1.5 bg-muted/40 hover:bg-muted/60 border border-border/20 text-foreground text-xs font-display font-semibold tracking-wider uppercase rounded-lg px-3 py-2.5 transition-colors"
        >
          {copied ? <Check size={12} /> : <Copy size={12} />}
          {copied ? "Copied ✓" : "Copy Number"}
        </button>
        <a
          href={telHref}
          onClick={handleMenuClick}
          className="inline-flex items-center justify-center gap-1.5 bg-primary/10 hover:bg-primary/20 border border-primary/20 text-primary text-xs font-display font-semibold tracking-wider uppercase rounded-lg px-3 py-2.5 transition-colors"
        >
          <Phone size={12} />
          {menuLabel}
        </a>
      </div>

      {showInAppFallback && (
        <div
          className="fixed inset-0 z-[100] flex items-center justify-center bg-black/80 backdrop-blur-sm p-4 animate-fade-in"
          onClick={() => setShowInAppFallback(false)}
        >
          <div
            className="bg-background border border-border/30 rounded-2xl p-6 max-w-sm w-full shadow-2xl space-y-5"
            onClick={(e) => e.stopPropagation()}
          >
            <div className="text-center space-y-2">
              <p className="section-label">The Escape</p>
              <h3 className="text-xl font-display font-bold text-foreground">Complete Your Payment</h3>
              <p className="text-sm text-foreground/70 font-body leading-relaxed">
                Tap "Copy Payment Code" below, then paste it into your phone dialer to complete payment.
              </p>
            </div>

            <div className="bg-muted/30 border border-border/20 rounded-lg py-3 text-center">
              <p className="text-2xl font-display font-bold tracking-wider text-foreground select-all">{dialCode}</p>
            </div>

            <div className="space-y-2">
              <button
                type="button"
                onClick={handleFallbackCopy}
                className="w-full inline-flex items-center justify-center gap-2 bg-primary text-primary-foreground hover:bg-primary/90 text-sm font-display font-semibold tracking-wider uppercase rounded-lg px-4 py-3 transition-colors"
              >
                {fallbackCopied ? <Check size={14} /> : <Copy size={14} />}
                {fallbackCopied ? "Copied ✓" : "Copy Payment Code"}
              </button>
              <button
                type="button"
                onClick={() => setShowInAppFallback(false)}
                className="w-full inline-flex items-center justify-center gap-2 bg-muted/40 hover:bg-muted/60 border border-border/20 text-foreground text-sm font-display font-semibold tracking-wider uppercase rounded-lg px-4 py-3 transition-colors"
              >
                I've Made Payment
              </button>
            </div>

            <p className="text-center text-[11px] text-muted-foreground font-body">
              Tip: For the best experience, open in your browser.
            </p>
          </div>
        </div>
      )}
    </div>
  );
};

const TicketFlow = ({ open, onClose }: TicketFlowProps) => {
  const { settings } = useSiteSettings();
  const ticketsOk = canSellTickets(settings);
  const lock = lockCopy(settings);
  const handleLockCta = () => {
    onClose();
    if (lock.ctaAction === "insider") scrollToInsider();
  };
  const [step, setStep] = useState<Step>("instructions");
  const [buyerName, setBuyerName] = useState("");
  const [phone, setPhone] = useState("");
  const [email, setEmail] = useState("");
  const [paymentMethod, setPaymentMethod] = useState("orange");
  const [quantity, setQuantity] = useState(1);
  const [guestNames, setGuestNames] = useState<string[]>([""]); // index 1+
  const [txnId, setTxnId] = useState("");
  const [screenshot, setScreenshot] = useState<File | null>(null);
  const [countryDial, setCountryDial] = useState("+232");

  const [order, setOrder] = useState<Order | null>(null);
  const [submitError, setSubmitError] = useState<string | null>(null);
  const [submitting, setSubmitting] = useState(false);

  const totalAmount = quantity * UNIT_PRICE;

  // Sync guestNames length with quantity (guestNames[0] is "Guest 2")
  useEffect(() => {
    setGuestNames((prev) => {
      const needed = Math.max(0, quantity - 1);
      if (prev.length === needed) return prev;
      const next = prev.slice(0, needed);
      while (next.length < needed) next.push("");
      return next;
    });
  }, [quantity]);

  const reset = useCallback(() => {
    setStep("instructions");
    setBuyerName(""); setPhone(""); setEmail(""); setTxnId("");
    setPaymentMethod("orange"); setScreenshot(null);
    setQuantity(1); setGuestNames([]);
    setCountryDial("+232");
    setOrder(null);
    setSubmitError(null);
    setSubmitting(false);
  }, []);

  const handleClose = useCallback(() => {
    onClose();
    setTimeout(reset, 300);
  }, [onClose, reset]);

  const allGuestsFilled = useMemo(
    () => guestNames.every((n) => n.trim().length > 0),
    [guestNames],
  );

  const phoneCanonical = useMemo(() => normalizeWithCountry(phone, countryDial), [phone, countryDial]);
  const phoneValid = phoneCanonical.length > 0;

  const emailValid = !email.trim() || /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email.trim());

  const isFormValid =
    buyerName.trim() &&
    phoneValid &&
    emailValid &&
    txnId.trim() &&
    quantity >= 1 &&
    guestNames.length === Math.max(0, quantity - 1) &&
    allGuestsFilled &&
    !!screenshot;

  const handleSubmit = useCallback(async () => {
    if (!isFormValid || submitting) return;
    setSubmitError(null);
    setSubmitting(true);
    setStep("submitting");
    const allNames = [buyerName.trim(), ...guestNames.map((g) => g.trim())];

    const timeoutMs = 20000;
    let timedOut = false;
    const timer = setTimeout(() => { timedOut = true; }, timeoutMs);

    try {
      const newOrder = await Promise.race([
        createOrder({
          buyerName: buyerName.trim(),
          phone: phoneCanonical || phone.trim(),
          email: email.trim(),
          paymentMethod,
          txnId: txnId.trim(),
          quantity,
          unitPrice: UNIT_PRICE,
          guestNames: allNames,
          screenshotFile: screenshot,
        }),
        new Promise<null>((resolve) => setTimeout(() => resolve(null), timeoutMs)),
      ]);
      clearTimeout(timer);

      if (!newOrder) {
        const msg = timedOut
          ? "Request timed out. Check your connection and try again."
          : "Payment failed. Try again.";
        console.error("[TicketFlow] createOrder returned null", { timedOut });
        setSubmitError(msg);
        setStep("form");
        return;
      }
      setOrder(newOrder);
      setStep("pending");
    } catch (err) {
      clearTimeout(timer);
      console.error("[TicketFlow] submit error:", err);
      setSubmitError("Payment failed. Try again.");
      setStep("form");
    } finally {
      setSubmitting(false);
    }
  }, [isFormValid, submitting, buyerName, guestNames, phone, phoneCanonical, email, paymentMethod, txnId, quantity, screenshot]);


  if (!open) return null;

  // Gate by Website State Manager — keeps ticket infra intact, just intercepts the UI.
  if (!ticketsOk) {
    return (
      <TicketLockModal
        open={open}
        onClose={onClose}
        label={lock.label}
        title={lock.title}
        message={lock.message}
        cta={lock.cta}
        onCta={handleLockCta}
      />
    );
  }

  const inputCls =
    "w-full bg-muted/30 border border-border/20 rounded-lg px-4 py-3 text-sm font-body text-foreground placeholder:text-muted-foreground/40 focus:outline-none focus:border-primary/40 transition-colors";
  const labelCls =
    "text-[10px] text-muted-foreground uppercase tracking-[0.2em] font-body block mb-1.5";

  return (
    <div className="fixed inset-0 z-50 flex items-end sm:items-center justify-center" onClick={handleClose}>
      <div className="absolute inset-0 bg-background/90 backdrop-blur-md" />
      <div
        onClick={(e) => e.stopPropagation()}
        className="relative w-full sm:max-w-md max-h-[92vh] overflow-y-auto bg-card border border-border/30 rounded-t-3xl sm:rounded-2xl animate-fade-in-up shadow-2xl"
      >
        <button
          onClick={handleClose}
          className="absolute top-4 right-4 z-10 text-muted-foreground/60 hover:text-foreground transition-colors"
          aria-label="Close"
        >
          <X size={18} strokeWidth={1.5} />
        </button>

        {/* Step 1: Payment Options */}
        {step === "instructions" && (
          <div className="p-8 pt-10">
            <div className="text-center mb-8">
              <div className="divider-line mb-6" />
              <p className="section-label mb-2">Get Your Tickets</p>
              <h3 className="text-xl font-display font-bold tracking-wide mb-2">Get your tickets</h3>
              <p className="text-muted-foreground text-sm font-body">
                Pay first, then submit your details to verify your ticket{quantity > 1 ? "s" : ""}.
              </p>
            </div>

            <div className="bg-muted/20 border border-border/15 rounded-xl p-4 mb-5 text-center">
              <p className="text-[10px] uppercase tracking-[0.3em] text-muted-foreground font-body mb-1">Nostalgia · The Warehouse</p>
              <p className="text-sm font-display font-semibold text-foreground/85">June 13 · 2026 · 9:00 PM</p>
            </div>

            <div className="grid grid-cols-2 gap-3 mb-6">
              <div className={`rounded-lg p-3 border text-center ${UNIT_PRICE === EARLY_PRICE ? "border-primary/30 bg-primary/5" : "border-border/15 bg-muted/15"}`}>
                <p className="text-[10px] uppercase tracking-[0.25em] text-muted-foreground font-body">Early</p>
                <p className="text-base font-display font-bold text-foreground">NLe {EARLY_PRICE}</p>
              </div>
              <div className={`rounded-lg p-3 border text-center ${UNIT_PRICE === GATE_PRICE ? "border-primary/30 bg-primary/5" : "border-border/15 bg-muted/15"}`}>
                <p className="text-[10px] uppercase tracking-[0.25em] text-muted-foreground font-body">Gate</p>
                <p className="text-base font-display font-bold text-foreground">NLe {GATE_PRICE}</p>
              </div>
            </div>

            <p className="text-center text-[10px] uppercase tracking-[0.3em] text-primary/70 font-body mb-6">
              · Limited tickets · Early tickets selling fast ·
            </p>

            <div className="space-y-4 mb-4">
              <PaymentOption
                title="Pay with Orange Money"
                dialCode="*144#"
                number="073 529 025"
                copyValue="073529025"
                menuLabel="Open Orange Menu"
                logoSrc={orangeMoneyLogo}
                logoAlt="Orange Money"
                sendLabel="Money Transfer"
              />
              <PaymentOption
                title="Pay with Afrimoney"
                dialCode="*161#"
                number="030 339 317"
                copyValue="030339317"
                menuLabel="Open Afrimoney Menu"
                logoSrc={afrimoneyLogo}
                logoAlt="Afrimoney"
              />
            </div>

            <p className="text-[11px] text-center text-muted-foreground/70 font-body mb-6 leading-relaxed">
              Other payment options will be added soon.
            </p>

            <button onClick={() => setStep("form")} className="btn-escape rounded-sm w-full">
              I'VE MADE PAYMENT
            </button>
          </div>
        )}

        {/* Step 2: Form */}
        {step === "form" && (
          <div className="p-8 pt-10">
            <div className="text-center mb-7">
              <p className="section-label mb-2">Order Details</p>
              <h3 className="text-xl font-display font-bold tracking-wide">Confirm your order</h3>
            </div>

            <div className="space-y-4">
              <div>
                <label className={labelCls}>Buyer Full Name <span className="text-primary">*</span></label>
                <input
                  type="text"
                  value={buyerName}
                  onChange={(e) => setBuyerName(e.target.value)}
                  placeholder="Your full name"
                  className={inputCls}
                />
              </div>
              <div>
                <label className={labelCls}>WhatsApp Number <span className="text-primary">*</span></label>
                <div className="flex gap-2">
                  <div className="relative shrink-0 w-[7.5rem]">
                    <select
                      value={countryDial}
                      onChange={(e) => setCountryDial(e.target.value)}
                      className={`${inputCls} appearance-none pr-8`}
                      aria-label="Country code"
                    >
                      {COUNTRY_CODES.map((c) => (
                        <option key={c.dial} value={c.dial}>{c.label}</option>
                      ))}
                    </select>
                    <ChevronDown size={14} className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground/50 pointer-events-none" />
                  </div>
                  <input
                    type="tel"
                    value={phone}
                    onChange={(e) => setPhone(e.target.value)}
                    placeholder={countryDial === "+232" ? "07X XXX XXX" : "Phone number"}
                    className={`${inputCls} flex-1`}
                  />
                </div>
                {phone.trim() && (
                  <p className={`text-[10px] font-body mt-1.5 tracking-wide ${phoneValid ? "text-muted-foreground/60" : "text-destructive"}`}>
                    {phoneValid ? `Saved as ${phoneCanonical}` : "Please enter a valid phone number for the selected country."}
                  </p>
                )}
                <p className="text-[10px] font-body mt-1 text-muted-foreground/50 leading-relaxed">
                  We'll send your access code here on WhatsApp. You can type a local number (e.g. 073123456) — we'll auto-format it.
                </p>
              </div>
              <div>
                <label className={labelCls}>Email <span className="text-muted-foreground/40">(optional)</span></label>
                <input
                  type="email"
                  value={email}
                  onChange={(e) => setEmail(e.target.value)}
                  placeholder="you@email.com (optional)"
                  className={inputCls}
                />
                {!emailValid && (
                  <p className="text-[10px] font-body mt-1.5 tracking-wide text-destructive/70">Enter a valid email or leave blank</p>
                )}
                {!email.trim() && emailValid && (
                  <p className="text-[10px] font-body mt-1.5 tracking-wide text-muted-foreground/60">No email? We'll send your confirmation via WhatsApp.</p>
                )}
              </div>

              <div>
                <label className={labelCls}>Payment Method <span className="text-primary">*</span></label>
                <div className="relative">
                  <select
                    value={paymentMethod}
                    onChange={(e) => setPaymentMethod(e.target.value)}
                    className={`${inputCls} appearance-none pr-10`}
                  >
                    <option value="orange">Orange Money</option>
                    <option value="afrimoney">Afrimoney</option>
                  </select>
                  <ChevronDown
                    size={14}
                    className="absolute right-4 top-1/2 -translate-y-1/2 text-muted-foreground/50 pointer-events-none"
                  />
                </div>
              </div>

              {/* Quantity */}
              <div>
                <label className={labelCls}>Ticket Quantity <span className="text-primary">*</span></label>
                <div className="flex items-center justify-between bg-muted/30 border border-border/20 rounded-lg px-3 py-2">
                  <button
                    type="button"
                    onClick={() => setQuantity((q) => Math.max(1, q - 1))}
                    className="w-9 h-9 flex items-center justify-center rounded-md bg-muted/40 hover:bg-muted/60 text-foreground/80 transition"
                    aria-label="Decrease quantity"
                  >
                    <Minus size={14} />
                  </button>
                  <span className="font-display font-bold text-lg tabular-nums text-foreground">{quantity}</span>
                  <button
                    type="button"
                    onClick={() => setQuantity((q) => Math.min(MAX_QTY, q + 1))}
                    className="w-9 h-9 flex items-center justify-center rounded-md bg-muted/40 hover:bg-muted/60 text-foreground/80 transition"
                    aria-label="Increase quantity"
                  >
                    <Plus size={14} />
                  </button>
                </div>
              </div>

              {/* Pricing */}
              <div className="bg-muted/20 rounded-lg p-4 border border-border/15 flex justify-between text-sm">
                <div>
                  <p className="text-[10px] uppercase tracking-[0.25em] text-muted-foreground font-body mb-1">
                    Unit price
                  </p>
                  <p className="font-display font-semibold text-foreground/80">NLe {UNIT_PRICE}</p>
                </div>
                <div className="text-right">
                  <p className="text-[10px] uppercase tracking-[0.25em] text-muted-foreground font-body mb-1">
                    Total
                  </p>
                  <p className="font-display font-bold text-foreground">NLe {totalAmount}</p>
                </div>
              </div>

              {/* Guest names (only when qty > 1) */}
              {quantity > 1 && (
                <div className="space-y-3 pt-2">
                  <p className="text-[10px] uppercase tracking-[0.25em] text-muted-foreground font-body">
                    Ticket holders <span className="text-primary">*</span>
                  </p>
                  <p className="text-[11px] text-foreground/55 font-body -mt-1">
                    Enter the name for each ticket holder. Each name appears on its own access card.
                  </p>
                  <div className="bg-muted/15 rounded-lg p-3 border border-border/15 text-xs text-foreground/55 font-body">
                    Ticket 1 — {buyerName.trim() || "Buyer name"}
                  </div>
                  {guestNames.map((g, i) => (
                    <div key={i}>
                      <label className={labelCls}>
                        Guest Name {i + 2} <span className="text-primary">*</span>
                      </label>
                      <input
                        type="text"
                        value={g}
                        onChange={(e) => {
                          const next = [...guestNames];
                          next[i] = e.target.value;
                          setGuestNames(next);
                        }}
                        placeholder={`Full name for ticket ${i + 2}`}
                        className={inputCls}
                      />
                    </div>
                  ))}
                </div>
              )}

              <div>
                <label className={labelCls}>Transaction ID <span className="text-primary">*</span></label>
                <input
                  type="text"
                  value={txnId}
                  onChange={(e) => setTxnId(e.target.value)}
                  placeholder="e.g. MP240613..."
                  className={inputCls}
                />
              </div>

              <div>
                <label className={labelCls}>
                  Payment Screenshot <span className="text-primary">*</span>
                </label>
                <label className={`flex items-center justify-center gap-2 w-full bg-muted/20 border border-dashed rounded-lg px-4 py-3 cursor-pointer transition-colors ${screenshot ? "border-primary/40" : "border-border/30 hover:border-primary/30"}`}>
                  <Upload size={14} className="text-muted-foreground/60" />
                  <span className="text-sm font-body text-muted-foreground/70 truncate max-w-[220px]">
                    {screenshot ? screenshot.name : "Upload proof (required)"}
                  </span>
                  <input
                    type="file"
                    accept="image/*"
                    className="hidden"
                    onChange={(e) => setScreenshot(e.target.files?.[0] || null)}
                  />
                </label>
                <p className="text-[10px] font-body mt-2 text-muted-foreground/60 leading-relaxed">
                  Upload a clear screenshot showing:
                  <br />· transaction ID
                  <br />· receiver number
                  <br />· amount paid
                </p>
              </div>
            </div>

            {submitError && (
              <div className="mt-4 rounded-lg border border-destructive/30 bg-destructive/10 px-4 py-3">
                <p className="text-destructive text-xs font-body leading-relaxed">{submitError}</p>
              </div>
            )}

            <div className="mt-8 space-y-3">
              <button
                onClick={handleSubmit}
                disabled={!isFormValid || submitting}
                className="btn-escape rounded-sm w-full disabled:opacity-30 disabled:pointer-events-none inline-flex items-center justify-center gap-2"
              >
                {submitting && <span className="w-4 h-4 border-2 border-current border-t-transparent rounded-full animate-spin" />}
                {submitting ? "SUBMITTING…" : "SUBMIT PAYMENT"}
              </button>
              <button
                onClick={() => setStep("instructions")}
                disabled={submitting}
                className="w-full text-center text-muted-foreground/50 text-xs font-body tracking-wider uppercase hover:text-foreground/60 transition-colors py-2 disabled:opacity-40"
              >
                Back
              </button>
            </div>
          </div>
        )}

        {/* Step 3: Submitting */}
        {step === "submitting" && (
          <div className="p-8 py-20 text-center">
            <div className="w-10 h-10 border-2 border-primary/30 border-t-primary rounded-full animate-spin mx-auto mb-8" />
            <p className="text-foreground/80 font-display font-semibold tracking-wide mb-2">Submitting…</p>
            <p className="text-muted-foreground/50 text-sm font-body">This will only take a moment.</p>
          </div>
        )}

        {/* Step 4: Pending — single clear message */}
        {step === "pending" && order && (
          <div className="p-8 pt-10 text-center">
            <div className="w-12 h-12 rounded-full bg-accent/10 border border-accent/30 flex items-center justify-center mx-auto mb-6">
              <ShieldCheck size={20} className="text-accent" />
            </div>
            <p className="section-label mb-2">Pending</p>
            <h3 className="text-xl font-display font-bold tracking-wide mb-3">Payment pending</h3>
            <p className="text-muted-foreground text-sm font-body mb-8 max-w-xs mx-auto leading-relaxed">
              We are currently checking your payment. Once approved, you can check status on the website to download your access card(s).
            </p>

            <div className="bg-muted/20 border border-border/15 rounded-xl p-4 mb-6 text-left">
              <p className="text-[10px] uppercase tracking-[0.25em] text-muted-foreground font-body mb-2">
                Order summary
              </p>
              <div className="flex justify-between text-sm font-body text-foreground/80">
                <span>{order.quantity} ticket{order.quantity > 1 ? "s" : ""}</span>
                <span className="font-display font-bold">NLe {order.totalAmount}</span>
              </div>
              <p className="text-[11px] text-muted-foreground/60 font-body mt-2">Txn ID · {order.txnId}</p>
            </div>

            <button onClick={handleClose} className="btn-escape rounded-sm w-full">
              DONE
            </button>
          </div>
        )}

        {/* Step 6: Confirmed */}
        {step === "confirmed" && order && (
          <div className="p-6 sm:p-8 pt-10">
            <div className="text-center mb-8">
              <div className="w-12 h-12 rounded-full bg-primary/10 border border-primary/30 flex items-center justify-center mx-auto mb-5">
                <ShieldCheck size={20} className="text-primary" />
              </div>
              <p className="section-label mb-2">Confirmed</p>
              <h3 className="text-xl font-display font-bold tracking-wide mb-2">Payment confirmed</h3>
              <p className="text-muted-foreground text-sm font-body">
                {order.quantity} ticket{order.quantity > 1 ? "s" : ""} issued · NLe {order.totalAmount}
              </p>
            </div>

            <div className="space-y-5 mb-6">
              {order.tickets.map((t) => (
                <div key={t.code} className="space-y-3">
                  <AccessCard ticket={t} />
                  <button
                    onClick={() => downloadTicketAsImage(t)}
                    className="mx-auto flex items-center justify-center gap-2 text-xs font-display uppercase tracking-[0.2em] text-primary border border-primary/30 bg-primary/10 hover:bg-primary/20 rounded-md px-4 py-2.5 transition w-full max-w-sm"
                  >
                    <Download size={12} /> Download Ticket
                  </button>
                </div>
              ))}
            </div>

            <div className="bg-muted/15 border border-border/15 rounded-lg p-4 mb-6 text-center">
              <p className="text-xs text-foreground/75 font-body leading-relaxed">
                Save or download your ticket and present it at entry.
              </p>
              <p className="text-[11px] text-muted-foreground/70 font-body mt-1.5">
                Do <span className="text-destructive/80">NOT</span> share your ticket with anyone. Each code can only be used once.
              </p>
            </div>
            <p className="text-center text-muted-foreground/30 text-[10px] uppercase tracking-[0.2em] font-body mb-6">
              {order.email ? "A confirmation has been sent to your email." : "Confirmation sent via WhatsApp."}
            </p>

            <button onClick={handleClose} className="btn-escape rounded-sm w-full">
              BACK TO HOME
            </button>
            <p className="text-center text-muted-foreground/20 text-[10px] uppercase tracking-[0.2em] font-body mt-6">
              Demo ticket — not a real transaction
            </p>
          </div>
        )}

        {/* Step 7: Rejected */}
        {step === "rejected" && order && (
          <div className="p-8 pt-10 text-center">
            <div className="w-12 h-12 rounded-full bg-destructive/10 border border-destructive/20 flex items-center justify-center mx-auto mb-6">
              <Ban size={20} className="text-destructive" />
            </div>
            <p className="section-label mb-2">Rejected</p>
            <h3 className="text-xl font-display font-bold tracking-wide mb-3">Payment not verified</h3>
            <p className="text-muted-foreground text-sm font-body mb-8 max-w-xs mx-auto">
              We couldn't verify this transaction. Please contact support with your transaction ID.
            </p>
            <button onClick={handleClose} className="btn-escape rounded-sm w-full">CLOSE</button>
          </div>
        )}
      </div>
    </div>
  );
};

export default TicketFlow;
