"use client";

import { useEffect, useState } from "react";
import { useParams } from "next/navigation";
import {
  Calendar, CheckCircle, Phone, User, Mail,
  ArrowRight, Shield, MessageSquare, Stethoscope, ArrowLeft,
  CalendarPlus, Sparkles, Clock,
} from "lucide-react";
import TimeSlotPicker from "@/components/TimeSlotPicker";
import PhoneInput from "@/components/PhoneInput";

interface Treatment {
  id: string;
  name: string;
  duration: number;
  price: number | null;
}

interface ClinicInfo {
  id: string;
  name: string;
  slug: string;
  phone: string | null;
  timezone: string;
  quietHoursStart: number;
  quietHoursEnd: number;
}

type Step = "info" | "treatment" | "datetime" | "confirm";

const STEPS: Step[] = ["info", "treatment", "datetime", "confirm"];

// Pre-computed — no Math.random() in render
const CONFETTI = [
  { left: "50%", top: "48%", color: "#4f46e5", dx: -70, dy: -130, r: 110, delay: 0 },
  { left: "50%", top: "48%", color: "#7c3aed", dx: 90,  dy: -110, r: -80, delay: 0.08 },
  { left: "50%", top: "48%", color: "#10b981", dx: -110, dy: -80, r: 200, delay: 0.05 },
  { left: "50%", top: "48%", color: "#f59e0b", dx: 130, dy: -60,  r: -160, delay: 0.13 },
  { left: "50%", top: "48%", color: "#ef4444", dx: 10,  dy: -150, r: 90,  delay: 0.06 },
  { left: "50%", top: "48%", color: "#06b6d4", dx: -90, dy: -100, r: -220, delay: 0.11 },
  { left: "50%", top: "48%", color: "#a855f7", dx: 55,  dy: -140, r: 170, delay: 0.03 },
  { left: "50%", top: "48%", color: "#fb923c", dx: -130, dy: -65, r: -100, delay: 0.17 },
  { left: "50%", top: "48%", color: "#4f46e5", dx: 110, dy: -85,  r: 250, delay: 0.07 },
  { left: "50%", top: "48%", color: "#10b981", dx: -40, dy: -160, r: -55, delay: 0.14 },
  { left: "50%", top: "48%", color: "#7c3aed", dx: 150, dy: -45,  r: 310, delay: 0.09 },
  { left: "50%", top: "48%", color: "#f59e0b", dx: -115, dy: -90, r: -185, delay: 0.15 },
];

const GLOBAL_STYLES = `
  @keyframes slide-right {
    from { opacity: 0; transform: translateX(22px); }
    to   { opacity: 1; transform: translateX(0); }
  }
  @keyframes slide-left {
    from { opacity: 0; transform: translateX(-22px); }
    to   { opacity: 1; transform: translateX(0); }
  }
  @keyframes shimmer {
    from { transform: translateX(-120%) skewX(-15deg); }
    to   { transform: translateX(320%) skewX(-15deg); }
  }
  @keyframes dot-bounce {
    0%, 80%, 100% { transform: scale(0); opacity: 0; }
    40%            { transform: scale(1); opacity: 1; }
  }
  @keyframes check-pop {
    0%   { transform: scale(0) rotate(-20deg); opacity: 0; }
    60%  { transform: scale(1.18) rotate(4deg); opacity: 1; }
    100% { transform: scale(1) rotate(0deg); opacity: 1; }
  }
  @keyframes ring-expand {
    0%   { transform: scale(1); opacity: 0.6; }
    100% { transform: scale(2.8); opacity: 0; }
  }
  @keyframes slide-up-fade {
    from { opacity: 0; transform: translateY(14px); }
    to   { opacity: 1; transform: translateY(0); }
  }
  @keyframes confetti-fly {
    0%   { opacity: 1; transform: translate(0,0) rotate(0deg) scale(1); }
    100% { opacity: 0; transform: translate(var(--cx),var(--cy)) rotate(var(--cr)) scale(0.2); }
  }
  .step-forward { animation: slide-right 0.28s cubic-bezier(0.4,0,0.2,1) both; }
  .step-back    { animation: slide-left  0.28s cubic-bezier(0.4,0,0.2,1) both; }
  .shimmer-btn  { position: relative; overflow: hidden; }
  .shimmer-btn::after {
    content: "";
    position: absolute;
    inset: 0;
    width: 35%;
    background: linear-gradient(90deg, transparent, rgba(255,255,255,0.22), transparent);
    animation: shimmer 2.8s ease-in-out infinite;
  }
  input:focus { outline: none; }
`;

const CARD_SHADOW = "0 4px 48px rgba(79,70,229,0.09), 0 1px 4px rgba(0,0,0,0.05)";

export default function PublicBookingPage() {
  const params = useParams();
  const slug = params.slug as string;

  const [clinic, setClinic]       = useState<ClinicInfo | null>(null);
  const [treatments, setTreatments] = useState<Treatment[]>([]);
  const [loading, setLoading]     = useState(true);
  const [notFound, setNotFound]   = useState(false);

  const [name, setName]     = useState("");
  const [phone, setPhone]   = useState("");
  const [email, setEmail]   = useState("");
  const [selectedTreatment, setSelectedTreatment] = useState<Treatment | null>(null);
  const [dateTime, setDateTime] = useState("");
  const [step, setStep]         = useState<Step>("info");
  const [stepKey, setStepKey]   = useState(0);
  const [dir, setDir]           = useState<"forward" | "back">("forward");
  const [submitting, setSubmitting] = useState(false);
  const [success, setSuccess]   = useState(false);
  const [error, setError]       = useState("");

  useEffect(() => {
    fetch(`/api/book/${slug}`)
      .then((r) => { if (!r.ok) throw new Error(); return r.json(); })
      .then((d)  => { setClinic(d.clinic); setTreatments(d.treatments); })
      .catch(()  => setNotFound(true))
      .finally(() => setLoading(false));
  }, [slug]);

  const handleSubmit = async () => {
    if (!selectedTreatment || !name || !phone || !dateTime) return;
    setSubmitting(true);
    setError("");
    try {
      const res  = await fetch(`/api/book/${slug}`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          name, phone,
          email: email || undefined,
          treatmentId: selectedTreatment.id,
          dateTime: new Date(dateTime).toISOString(),
        }),
      });
      const data = await res.json();
      if (!res.ok) { setError(data.error || "Booking failed. Please try again."); return; }
      setSuccess(true);
    } catch {
      setError("Connection failed. Please try again.");
    } finally {
      setSubmitting(false);
    }
  };

  const goTo = (next: Step, d: "forward" | "back") => {
    setDir(d);
    setStep(next);
    setStepKey((k) => k + 1);
  };

  const currentIdx = STEPS.indexOf(step);
  const progressPct = { info: 25, treatment: 50, datetime: 75, confirm: 100 }[step];

  const canNext = (() => {
    if (step === "info")      return name.trim().length >= 2 && phone.trim().length >= 8;
    if (step === "treatment") return !!selectedTreatment;
    if (step === "datetime")  return !!dateTime;
    return true;
  })();

  // ── LOADING ──────────────────────────────────────────────
  if (loading) return (
    <div className="min-h-screen bg-[#f7f8fc] flex items-center justify-center">
      <style>{GLOBAL_STYLES}</style>
      <div className="text-center">
        <div className="w-14 h-14 rounded-2xl bg-gradient-to-br from-[#4f46e5] to-[#7c3aed] flex items-center justify-center mx-auto mb-5 shadow-lg shadow-[#4f46e5]/25">
          <Stethoscope size={24} className="text-white" />
        </div>
        <div className="flex items-center gap-1.5 justify-center mb-3">
          {[0, 1, 2].map((i) => (
            <div key={i} className="w-2 h-2 rounded-full bg-[#4f46e5]"
              style={{ animation: `dot-bounce 1.4s ease-in-out ${i * 0.16}s infinite` }} />
          ))}
        </div>
        <p className="text-[#4f46e5] font-semibold text-sm">Preparing your booking</p>
      </div>
    </div>
  );

  // ── NOT FOUND ─────────────────────────────────────────────
  if (notFound || !clinic) return (
    <div className="min-h-screen bg-[#f7f8fc] flex items-center justify-center p-5">
      <style>{GLOBAL_STYLES}</style>
      <div className="bg-white rounded-[24px] p-10 max-w-sm w-full text-center" style={{ boxShadow: CARD_SHADOW }}>
        <div className="text-6xl mb-5">🏥</div>
        <h1 className="text-xl font-black text-[#0f172a] mb-2">Clinic Not Found</h1>
        <p className="text-[#94a3b8] text-sm leading-relaxed">
          This booking link may have expired or is incorrect.<br />
          Contact your clinic for the correct link.
        </p>
      </div>
    </div>
  );

  // ── SUCCESS ───────────────────────────────────────────────
  if (success) return (
    <div className="min-h-screen bg-[#f0fdf4] flex items-center justify-center p-5 relative overflow-hidden">
      <style>{`
        ${GLOBAL_STYLES}
        @keyframes confetti-fly {
          0%   { opacity:1; transform: translate(0,0) rotate(0deg) scale(1); }
          100% { opacity:0; transform: translate(var(--cx),var(--cy)) rotate(var(--cr)) scale(0.2); }
        }
      `}</style>

      {CONFETTI.map((p, i) => (
        <div key={i} className="absolute w-3 h-2 rounded-[2px] pointer-events-none"
          style={{
            left: p.left, top: p.top,
            backgroundColor: p.color,
            "--cx": `${p.dx}px`, "--cy": `${p.dy}px`, "--cr": `${p.r}deg`,
            animation: `confetti-fly 1.1s cubic-bezier(0.25,0.46,0.45,0.94) ${p.delay}s both`,
          } as React.CSSProperties}
        />
      ))}

      <div className="bg-white rounded-[28px] p-8 max-w-md w-full relative z-10"
        style={{ boxShadow: "0 8px 64px rgba(16,185,129,0.12), 0 2px 8px rgba(0,0,0,0.06)" }}>

        {/* Animated checkmark */}
        <div className="flex items-center justify-center mb-7 relative h-28">
          <div className="absolute w-28 h-28 rounded-full bg-[#10b981]/12"
            style={{ animation: "ring-expand 2s ease-out 0.4s infinite" }} />
          <div className="absolute w-24 h-24 rounded-full bg-[#10b981]/10"
            style={{ animation: "ring-expand 2s ease-out 0.9s infinite" }} />
          <div className="relative z-10 w-20 h-20 rounded-full bg-gradient-to-br from-[#10b981] to-[#059669] flex items-center justify-center shadow-xl shadow-[#10b981]/30"
            style={{ animation: "check-pop 0.5s cubic-bezier(0.34,1.56,0.64,1) 0.1s both" }}>
            <CheckCircle size={36} className="text-white" strokeWidth={2.5} />
          </div>
        </div>

        <div style={{ animation: "slide-up-fade 0.4s ease-out 0.5s both", opacity: 0 }}>
          <h1 className="text-[28px] font-black text-[#0f172a] text-center mb-1 leading-tight">You&apos;re all set! 🎉</h1>
          <p className="text-[#94a3b8] text-sm text-center mb-6">
            Confirmed at <span className="font-bold text-[#0f172a]">{clinic.name}</span>
          </p>

          {/* Summary card */}
          <div className="rounded-2xl overflow-hidden border border-[#e2e8f0] mb-4">
            <div className="h-[3px] bg-gradient-to-r from-[#4f46e5] to-[#7c3aed]" />
            <div className="p-5 space-y-3.5">
              <Row icon={User}        label="Patient"    value={name} />
              <Row icon={Stethoscope} label="Treatment"  value={selectedTreatment?.name ?? ""} />
              <Row icon={Calendar}    label="Date & Time" value={
                `${new Date(dateTime).toLocaleDateString("en-US",{weekday:"long",month:"long",day:"numeric"})} at ${new Date(dateTime).toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:true})}`
              } />
            </div>
          </div>

          {/* WhatsApp */}
          <div className="flex items-center gap-3 rounded-2xl p-4 bg-[#f0fdf4] border border-[#10b981]/20 mb-4">
            <div className="w-9 h-9 rounded-full bg-[#10b981] flex items-center justify-center shrink-0">
              <MessageSquare size={16} className="text-white" />
            </div>
            <p className="text-[12px] text-[#065f46] font-medium leading-relaxed">
              Check WhatsApp for confirmation & reminders
            </p>
          </div>

          <button className="w-full h-12 rounded-xl border-[1.5px] border-[#e2e8f0] text-[#64748b] font-semibold text-sm hover:bg-[#f8fafc] transition-colors flex items-center justify-center gap-2">
            <CalendarPlus size={16} /> Add to Calendar
          </button>
        </div>
      </div>
    </div>
  );

  // ── BOOKING FORM ─────────────────────────────────────────
  return (
    <>
      <style>{GLOBAL_STYLES}</style>

      {/* Dot-grid background */}
      <div className="min-h-screen" style={{
        backgroundColor: "#f7f8fc",
        backgroundImage: "radial-gradient(circle, #dde1ef 1px, transparent 1px)",
        backgroundSize: "24px 24px",
      }}>
        {/* Top progress stripe */}
        <div className="fixed top-0 left-0 right-0 z-50 h-[3px] bg-[#e2e8f0]">
          <div className="h-full bg-gradient-to-r from-[#4f46e5] to-[#7c3aed] transition-all duration-500 ease-out"
            style={{ width: `${progressPct}%` }} />
        </div>

        {/* Sticky header */}
        <div className="sticky top-[3px] z-40 bg-white/90 backdrop-blur-md border-b border-[#f1f5f9]">
          <div className="max-w-[440px] mx-auto px-5 h-14 flex items-center justify-center gap-2.5">
            <div className="w-8 h-8 rounded-lg bg-gradient-to-br from-[#4f46e5] to-[#7c3aed] flex items-center justify-center">
              <span className="text-white font-black text-sm">{clinic.name.charAt(0)}</span>
            </div>
            <span className="font-bold text-[#0f172a] text-sm">{clinic.name}</span>
            <span className="text-[11px] text-[#94a3b8] font-semibold bg-[#f8fafc] px-2.5 py-1 rounded-full border border-[#e2e8f0]">
              {currentIdx + 1} / 4
            </span>
          </div>
        </div>

        {/* Page content */}
        <div className="min-h-[calc(100vh-3px-56px)] flex items-center justify-center px-4 py-10">
        <div className="w-full max-w-[440px]">
          {error && (
            <div className="bg-red-50 border border-red-200 rounded-xl p-4 mb-4 text-sm text-red-600 font-medium flex items-center gap-2">
              ⚠️ {error}
            </div>
          )}

          <div key={stepKey} className={dir === "forward" ? "step-forward" : "step-back"}>

            {/* ══ STEP 1: INFO ══ */}
            {step === "info" && (
              <div className="bg-white rounded-[24px] p-8 space-y-6" style={{ boxShadow: CARD_SHADOW }}>
                <StepHeader icon={User} title="Your Information" sub="We'll send your confirmation here" />

                <div className="space-y-4">
                  <Field label="Full Name" required>
                    <input type="text" value={name} onChange={(e) => setName(e.target.value)}
                      placeholder="Enter your full name" autoFocus
                      className="w-full h-[52px] px-4 rounded-xl border-[1.5px] border-[#e2e8f0] text-[15px] font-medium text-[#0f172a] placeholder-[#cbd5e1] bg-white transition-colors duration-150 focus:border-[#4f46e5]" />
                  </Field>
                  <Field label="WhatsApp Number" required hint={
                    <span className="flex items-center gap-1.5 mt-1.5 text-[12px] text-[#94a3b8]">
                      <MessageSquare size={11} className="text-[#10b981]" /> Reminders sent via WhatsApp
                    </span>
                  }>
                    <PhoneInput value={phone} onChange={setPhone} variant="booking" />
                  </Field>
                  <Field label="Email" optional>
                    <input type="email" value={email} onChange={(e) => setEmail(e.target.value)}
                      placeholder="you@example.com"
                      className="w-full h-[52px] px-4 rounded-xl border-[1.5px] border-[#e2e8f0] text-[15px] font-medium text-[#0f172a] placeholder-[#cbd5e1] bg-white transition-colors duration-150 focus:border-[#4f46e5]" />
                  </Field>
                </div>

                <CtaButton onClick={() => goTo("treatment", "forward")} disabled={!canNext}>
                  Continue <ArrowRight size={16} />
                </CtaButton>
                <Privacy />
              </div>
            )}

            {/* ══ STEP 2: TREATMENT ══ */}
            {step === "treatment" && (
              <div className="bg-white rounded-[24px] p-8 space-y-6" style={{ boxShadow: CARD_SHADOW }}>
                <StepHeader icon={Stethoscope} title="Choose a Treatment" sub="Select the service you need" />

                {treatments.length === 0 ? (
                  <div className="text-center py-10 text-[#94a3b8] text-sm">
                    No treatments available — contact the clinic directly.
                  </div>
                ) : (
                  <div className="space-y-2.5">
                    {treatments.map((t) => {
                      const sel = selectedTreatment?.id === t.id;
                      return (
                        <button key={t.id} onClick={() => setSelectedTreatment(t)} className="w-full text-left group">
                          <div className={`flex items-center gap-4 p-4 rounded-2xl border-[1.5px] transition-all duration-200 ${
                            sel
                              ? "border-[#4f46e5] bg-[#4f46e5]/[0.035] shadow-md shadow-[#4f46e5]/10"
                              : "border-[#e2e8f0] hover:border-[#c7d2fe] hover:shadow-sm bg-white"
                          }`}>
                            <div className={`w-11 h-11 rounded-xl flex items-center justify-center transition-all shrink-0 ${
                              sel
                                ? "bg-gradient-to-br from-[#4f46e5] to-[#7c3aed] shadow-md shadow-[#4f46e5]/25"
                                : "bg-[#f1f5f9] group-hover:bg-[#eef2ff]"
                            }`}>
                              <Stethoscope size={18} className={sel ? "text-white" : "text-[#94a3b8] group-hover:text-[#4f46e5] transition-colors"} />
                            </div>
                            <div className="flex-1 min-w-0">
                              <p className="text-[15px] font-bold text-[#0f172a] truncate">{t.name}</p>
                              <div className="flex items-center gap-2 mt-1 flex-wrap">
                                <span className="inline-flex items-center gap-1 text-[11px] font-semibold text-[#94a3b8] bg-[#f8fafc] px-2 py-0.5 rounded-full border border-[#e2e8f0]">
                                  <Clock size={10} /> {t.duration} min
                                </span>
                                {t.price !== null && t.price > 0 && (
                                  <span className="text-[11px] font-bold text-[#0f172a] bg-[#f1f5f9] px-2 py-0.5 rounded-full">
                                    ${t.price}
                                  </span>
                                )}
                                {t.price === 0 && (
                                  <span className="text-[11px] font-bold text-[#10b981] bg-[#10b981]/10 px-2 py-0.5 rounded-full">
                                    Free
                                  </span>
                                )}
                              </div>
                            </div>
                            {/* Radio circle */}
                            <div className={`w-5 h-5 rounded-full border-2 flex items-center justify-center shrink-0 transition-all ${
                              sel ? "border-[#4f46e5] bg-[#4f46e5]" : "border-[#e2e8f0]"
                            }`}>
                              {sel && <div className="w-2 h-2 rounded-full bg-white" />}
                            </div>
                          </div>
                        </button>
                      );
                    })}
                  </div>
                )}

                <div className="flex gap-3">
                  <BackButton onClick={() => goTo("info", "back")} />
                  <CtaButton onClick={() => goTo("datetime", "forward")} disabled={!canNext} flex2>
                    Continue <ArrowRight size={16} />
                  </CtaButton>
                </div>
              </div>
            )}

            {/* ══ STEP 3: DATE & TIME ══ */}
            {step === "datetime" && (
              <div className="bg-white rounded-[24px] p-8 space-y-6" style={{ boxShadow: CARD_SHADOW }}>
                <StepHeader icon={Calendar} title="Pick a Time" sub="Choose what works best for you" />

                {selectedTreatment && (
                  <div className="inline-flex items-center gap-2 bg-[#f8f8fd] border border-[#e2e8f0] rounded-xl px-3.5 py-2.5">
                    <Stethoscope size={13} className="text-[#4f46e5] shrink-0" />
                    <span className="text-[12px] font-semibold text-[#4f46e5]">
                      {selectedTreatment.name} · {selectedTreatment.duration} min
                      {selectedTreatment.price ? ` · $${selectedTreatment.price}` : ""}
                    </span>
                  </div>
                )}

                <TimeSlotPicker
                  value={dateTime}
                  onChange={setDateTime}
                  workStart={clinic.quietHoursEnd}
                  workEnd={clinic.quietHoursStart}
                  interval={30}
                  label="Choose your slot *"
                />

                <div className="flex gap-3">
                  <BackButton onClick={() => goTo("treatment", "back")} />
                  <CtaButton onClick={() => goTo("confirm", "forward")} disabled={!canNext} flex2>
                    Review Booking <ArrowRight size={16} />
                  </CtaButton>
                </div>
              </div>
            )}

            {/* ══ STEP 4: CONFIRM ══ */}
            {step === "confirm" && (
              <div className="bg-white rounded-[24px] p-8 space-y-6" style={{ boxShadow: CARD_SHADOW }}>
                <StepHeader icon={Sparkles} title="Confirm Booking" sub="Review your appointment details" />

                {/* Summary */}
                <div className="rounded-2xl overflow-hidden border border-[#e2e8f0]">
                  <div className="h-[3px] bg-gradient-to-r from-[#4f46e5] to-[#7c3aed]" />
                  <div className="p-5 space-y-4">
                    <Row icon={User}   label="Name"      value={name} />
                    <Row icon={Phone}  label="WhatsApp"  value={phone} />
                    {email && <Row icon={Mail} label="Email" value={email} />}
                    <div className="h-px bg-[#f1f5f9]" />
                    <Row icon={Stethoscope} label="Treatment" value={`${selectedTreatment?.name ?? ""}${selectedTreatment?.price ? ` — $${selectedTreatment.price}` : ""}`} />
                    <Row icon={Calendar}    label="Date & Time" value={
                      `${new Date(dateTime).toLocaleDateString("en-US",{weekday:"long",month:"long",day:"numeric"})} at ${new Date(dateTime).toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:true})}`
                    } />
                  </div>
                </div>

                {/* WhatsApp notice */}
                <div className="flex items-center gap-3 rounded-2xl p-4 bg-[#f0fdf4] border border-[#10b981]/20">
                  <div className="w-9 h-9 rounded-full bg-[#10b981] flex items-center justify-center shrink-0">
                    <MessageSquare size={16} className="text-white" />
                  </div>
                  <p className="text-[12px] text-[#065f46] font-medium leading-relaxed">
                    Confirmation & reminders will be sent to {phone}
                  </p>
                </div>

                <div className="flex gap-3">
                  <BackButton onClick={() => goTo("datetime", "back")} />
                  <button
                    onClick={handleSubmit}
                    disabled={submitting}
                    className="shimmer-btn flex-[2] h-[52px] rounded-xl bg-gradient-to-r from-[#10b981] to-[#059669] text-white font-bold text-[14px] shadow-lg shadow-[#10b981]/30 hover:shadow-[#10b981]/50 hover:-translate-y-0.5 transition-all disabled:opacity-50 disabled:hover:translate-y-0 disabled:shadow-none flex items-center justify-center gap-2"
                  >
                    {submitting ? (
                      <><div className="w-4 h-4 rounded-full border-2 border-white/30 border-t-white animate-spin" /> Booking...</>
                    ) : (
                      <>Confirm Appointment <ArrowRight size={16} /></>
                    )}
                  </button>
                </div>

                <Privacy label={`Shared only with ${clinic.name}`} />
              </div>
            )}

          </div>
        </div>
        </div>
      </div>
    </>
  );
}

// ── Shared sub-components ─────────────────────────────────

function StepHeader({ icon: Icon, title, sub }: { icon: React.ElementType; title: string; sub: string }) {
  return (
    <div>
      <div className="w-12 h-12 rounded-2xl bg-gradient-to-br from-[#4f46e5] to-[#7c3aed] flex items-center justify-center shadow-md shadow-[#4f46e5]/20 mb-5">
        <Icon size={20} className="text-white" />
      </div>
      <h2 className="text-[26px] font-black text-[#0f172a] leading-tight mb-1">{title}</h2>
      <p className="text-[13px] text-[#94a3b8]">{sub}</p>
    </div>
  );
}

function Field({ label, required, optional, hint, children }: {
  label: string; required?: boolean; optional?: boolean; hint?: React.ReactNode; children: React.ReactNode;
}) {
  return (
    <div>
      <label className="block text-[11px] uppercase tracking-[0.08em] font-semibold text-[#94a3b8] mb-1.5">
        {label}
        {required && <span className="text-[#ef4444] ml-0.5">*</span>}
        {optional && <span className="normal-case font-normal text-[#cbd5e1] ml-1">— optional</span>}
      </label>
      {children}
      {hint}
    </div>
  );
}

function Row({ icon: Icon, label, value }: { icon: React.ElementType; label: string; value: string }) {
  return (
    <div className="flex items-start gap-3">
      <Icon size={14} className="text-[#94a3b8] shrink-0 mt-0.5" />
      <div>
        <p className="text-[10px] uppercase tracking-[0.08em] text-[#94a3b8] font-semibold">{label}</p>
        <p className="text-[14px] font-bold text-[#0f172a] leading-snug">{value}</p>
      </div>
    </div>
  );
}

function CtaButton({ onClick, disabled, children, flex2 }: {
  onClick: () => void; disabled?: boolean; children: React.ReactNode; flex2?: boolean;
}) {
  return (
    <button
      onClick={onClick}
      disabled={disabled}
      className={`shimmer-btn ${flex2 ? "flex-[2]" : "w-full"} h-[52px] rounded-xl bg-gradient-to-r from-[#4f46e5] to-[#7c3aed] text-white font-bold text-[14px] shadow-lg shadow-[#4f46e5]/30 hover:shadow-[#4f46e5]/50 hover:-translate-y-0.5 transition-all disabled:opacity-40 disabled:shadow-none disabled:hover:translate-y-0 flex items-center justify-center gap-2`}
    >
      {children}
    </button>
  );
}

function BackButton({ onClick }: { onClick: () => void }) {
  return (
    <button
      onClick={onClick}
      className="flex-1 h-[52px] rounded-xl border-[1.5px] border-[#e2e8f0] text-[#64748b] font-semibold text-[14px] hover:bg-[#f8fafc] hover:border-[#c7d2fe] transition-all flex items-center justify-center gap-2"
    >
      <ArrowLeft size={15} /> Back
    </button>
  );
}

function Privacy({ label }: { label?: string }) {
  return (
    <div className="flex items-center justify-center gap-1.5 text-[11px] text-[#94a3b8]">
      <Shield size={11} /> {label ?? "Your information is private & secure"}
    </div>
  );
}
