"use client";

import { useState, useEffect, useCallback, useRef } from "react";
import { useRouter } from "next/navigation";
import { avatarUrl } from "@/lib/media";
import MediaImage from "@/components/shared/media-image";
// R16 D.1: route hardcoded "EUR" suffixes through the cookie-aware
// formatter so the footer's CurrencySelector actually changes the
// numbers users see on the plan wizard.
import { formatCurrency } from "@/lib/format";

/* ---------- constants ---------- */

const OCCASIONS = [
  "Birthday",
  "Bachelor/Bachelorette Party",
  "Business Entertainment",
  "Couples Night",
  "Solo Adventure",
  "Other",
];

const DURATIONS = [
  "1 hour",
  "2 hours",
  "3 hours",
  "4 hours",
  "Overnight",
  "Weekend",
];

function buildTimeSlots(): string[] {
  const slots: string[] = [];
  for (let h = 10; h <= 25; h++) {
    const hour = h % 24;
    slots.push(`${String(hour).padStart(2, "0")}:00`);
    slots.push(`${String(hour).padStart(2, "0")}:30`);
    if (h === 25) break; // stop after 02:00
  }
  // We want 10:00 through 02:00 next day
  // 10:00..23:30 then 00:00..02:00
  return slots.slice(0, slots.indexOf("02:30"));
}

const TIME_SLOTS = buildTimeSlots();

/* ---------- types ---------- */

interface CityOption {
  id: number;
  name: string;
  slug: string;
  country_name: string | null;
}

interface Escort {
  id: number;
  id_aw: string | null;
  username: string | null;
  profile_photo: string | null;
  avatarMediaUrls: string[];
  city: string | null;
  country: string | null;
  rate?: number;
  reason?: string;
}

/* ---------- step indicator ---------- */

const STEPS = ["Details", "Escorts", "Review", "Send"];

function StepIndicator({ current }: { current: number }) {
  return (
    <div className="flex items-center justify-center gap-1 sm:gap-2 mb-8">
      {STEPS.map((label, i) => {
        const isActive = i === current;
        const isDone = i < current;
        return (
          <div key={label} className="flex items-center gap-1 sm:gap-2">
            {i > 0 && (
              <div
                className={`hidden sm:block w-8 md:w-12 h-px ${
                  isDone ? "bg-gold" : "bg-white/10"
                }`}
              />
            )}
            <div className="flex flex-col items-center gap-1">
              <div
                className={`w-8 h-8 rounded-full flex items-center justify-center text-sm font-bold transition-all ${
                  isActive
                    ? "bg-gold text-black"
                    : isDone
                    ? "bg-gold/20 text-gold border border-gold/40"
                    : "bg-surface-light text-text-muted border border-white/10"
                }`}
              >
                {isDone ? (
                  <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2.5} d="M5 13l4 4L19 7" />
                  </svg>
                ) : (
                  i + 1
                )}
              </div>
              <span
                className={`text-[10px] sm:text-xs font-medium ${
                  isActive ? "text-gold" : isDone ? "text-gold/60" : "text-text-muted"
                }`}
              >
                {label}
              </span>
            </div>
          </div>
        );
      })}
    </div>
  );
}

/* ---------- main component ---------- */

export default function PlanWizard() {
  const router = useRouter();
  const [step, setStep] = useState(0);
  const [animating, setAnimating] = useState(false);
  const [fadeClass, setFadeClass] = useState("opacity-100");

  // Step 1 state
  const [occasion, setOccasion] = useState("Birthday");
  const [cityQuery, setCityQuery] = useState("");
  const [cityOptions, setCityOptions] = useState<CityOption[]>([]);
  const [selectedCity, setSelectedCity] = useState<CityOption | null>(null);
  const [showCityDropdown, setShowCityDropdown] = useState(false);
  const [date, setDate] = useState("");
  const [time, setTime] = useState("19:00");
  const [duration, setDuration] = useState("2 hours");
  const [guests, setGuests] = useState(2);
  const [budget, setBudget] = useState("");
  const [specialRequests, setSpecialRequests] = useState("");
  const cityRef = useRef<HTMLDivElement>(null);

  // Step 2 state
  const [escorts, setEscorts] = useState<Escort[]>([]);
  const [selectedEscorts, setSelectedEscorts] = useState<Escort[]>([]);
  const [loadingEscorts, setLoadingEscorts] = useState(false);
  const [aiSuggesting, setAiSuggesting] = useState(false);
  const [escortError, setEscortError] = useState("");

  // Step 4 state
  const [sending, setSending] = useState(false);
  const [sendResult, setSendResult] = useState<{ sent: number; failed: number } | null>(null);
  const [sendError, setSendError] = useState("");

  // Global error
  const [error, setError] = useState("");

  /* ---------- step transitions ---------- */

  const goTo = useCallback(
    (next: number) => {
      if (animating) return;
      setAnimating(true);
      setFadeClass("opacity-0 translate-y-2");
      setTimeout(() => {
        setStep(next);
        setFadeClass("opacity-0 -translate-y-2");
        requestAnimationFrame(() => {
          setFadeClass("opacity-100 translate-y-0");
          setAnimating(false);
        });
      }, 200);
    },
    [animating]
  );

  /* ---------- city autocomplete ---------- */

  useEffect(() => {
    if (cityQuery.length < 2) {
      setCityOptions([]);
      return;
    }
    const controller = new AbortController();
    const timer = setTimeout(async () => {
      try {
        const res = await fetch(
          `/api/search/options/cities/autocomplete?q=${encodeURIComponent(cityQuery)}`,
          { signal: controller.signal }
        );
        const data = await res.json();
        setCityOptions(data);
        setShowCityDropdown(true);
      } catch {
        // ignore aborts
      }
    }, 250);
    return () => {
      clearTimeout(timer);
      controller.abort();
    };
  }, [cityQuery]);

  // Close dropdown on outside click
  useEffect(() => {
    function handleClick(e: MouseEvent) {
      if (cityRef.current && !cityRef.current.contains(e.target as Node)) {
        setShowCityDropdown(false);
      }
    }
    document.addEventListener("mousedown", handleClick);
    return () => document.removeEventListener("mousedown", handleClick);
  }, []);

  /* ---------- fetch escorts for step 2 ---------- */

  const fetchEscorts = useCallback(async () => {
    if (!selectedCity) return;
    setLoadingEscorts(true);
    setEscortError("");
    try {
      const res = await fetch(`/api/ai/plan?city=${encodeURIComponent(selectedCity.name)}`);
      const json = await res.json();
      if (json.error) {
        setEscortError(json.error);
      } else {
        setEscorts(json.data || []);
      }
    } catch {
      setEscortError("Failed to load escorts. Please try again.");
    } finally {
      setLoadingEscorts(false);
    }
  }, [selectedCity]);

  /* ---------- AI suggest ---------- */

  const handleAiSuggest = async () => {
    if (!selectedCity) return;
    setAiSuggesting(true);
    setEscortError("");
    try {
      const res = await fetch("/api/ai/plan", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          occasion,
          city: selectedCity.name,
          date: date || null,
          guests,
          budget: budget ? Number(budget) : null,
          special_requests: specialRequests.trim() || null,
        }),
      });
      const json = await res.json();
      if (json.error) {
        setEscortError(json.error);
      } else if (json.data?.escorts) {
        // Auto-select the AI recommended escorts
        const aiEscorts: Escort[] = json.data.escorts.map(
          (e: Escort & { location?: string }) => ({
            id: e.id,
            id_aw: e.id_aw,
            username: e.username,
            profile_photo: e.profile_photo,
            city: e.city,
            country: e.country,
            rate: e.rate || 0,
            reason: e.reason || "",
          })
        );

        // Merge into escort list if not already present
        setEscorts((prev) => {
          const ids = new Set(prev.map((p) => p.id));
          const newOnes = aiEscorts.filter((e) => !ids.has(e.id));
          return [...prev, ...newOnes];
        });

        setSelectedEscorts(aiEscorts.slice(0, 5));
      }
    } catch {
      setEscortError("AI suggestion failed. Please select manually.");
    } finally {
      setAiSuggesting(false);
    }
  };

  /* ---------- toggle escort selection ---------- */

  const toggleEscort = (escort: Escort) => {
    setSelectedEscorts((prev) => {
      const exists = prev.find((e) => e.id === escort.id);
      if (exists) return prev.filter((e) => e.id !== escort.id);
      if (prev.length >= 5) return prev; // max 5
      return [...prev, escort];
    });
  };

  /* ---------- send plan ---------- */

  const handleSend = async () => {
    setSending(true);
    setSendError("");
    setSendResult(null);
    try {
      const res = await fetch("/api/plan/send", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          escort_ids: selectedEscorts.map((e) => e.id),
          occasion,
          city: selectedCity?.name || cityQuery,
          date: date || "Flexible",
          time: time || null,
          duration,
          guests,
          budget: budget || null,
          special_requests: specialRequests.trim() || null,
        }),
      });
      const json = await res.json();
      if (json.error) {
        setSendError(json.error);
      } else {
        setSendResult({ sent: json.sent, failed: json.failed });
      }
    } catch {
      setSendError("Failed to send plan. Please try again.");
    } finally {
      setSending(false);
    }
  };

  /* ---------- reset ---------- */

  const resetWizard = () => {
    setStep(0);
    setFadeClass("opacity-100 translate-y-0");
    setOccasion("Birthday");
    setCityQuery("");
    setSelectedCity(null);
    setDate("");
    setTime("19:00");
    setDuration("2 hours");
    setGuests(2);
    setBudget("");
    setSpecialRequests("");
    setEscorts([]);
    setSelectedEscorts([]);
    setSendResult(null);
    setSendError("");
    setError("");
  };

  /* ---------- computed ---------- */

  const estimatedTotal = selectedEscorts.reduce((sum, e) => sum + (e.rate || 0), 0);

  /* ---------- validation ---------- */

  const canProceedStep1 = !!selectedCity && !!occasion;

  /* ================================================================
     RENDER
     ================================================================ */

  return (
    <div className="max-w-3xl mx-auto px-4 py-6">
      {/* Header */}
      <div className="text-center mb-6">
        <h1 className="text-2xl md:text-3xl font-bold text-white">
          Plan Your Experience
        </h1>
        <p className="text-text-muted text-sm mt-1">
          Create a personalised occasion plan and send it directly to escorts.
        </p>
      </div>

      {/* Step Indicator */}
      <StepIndicator current={step} />

      {/* Step Content */}
      <div
        className={`transition-all duration-200 ease-in-out ${fadeClass}`}
      >
        {/* ======================== STEP 1: Details ======================== */}
        {step === 0 && (
          <div className="bg-surface rounded-xl border border-white/5 p-5 sm:p-6 space-y-5">
            <h2 className="text-lg font-semibold text-white">Occasion Details</h2>

            {/* Occasion */}
            <div>
              <label className="block text-sm font-medium text-white mb-1.5">
                Occasion Type
              </label>
              <select
                value={occasion}
                onChange={(e) => setOccasion(e.target.value)}
                className="w-full bg-surface-light border border-white/10 rounded-lg px-4 py-2.5 text-white focus:outline-none focus:ring-2 focus:ring-gold/50 focus:border-gold"
              >
                {OCCASIONS.map((o) => (
                  <option key={o} value={o}>
                    {o}
                  </option>
                ))}
              </select>
            </div>

            {/* City */}
            <div ref={cityRef} className="relative">
              <label className="block text-sm font-medium text-white mb-1.5">
                City
              </label>
              <input
                type="text"
                value={selectedCity ? `${selectedCity.name}${selectedCity.country_name ? `, ${selectedCity.country_name}` : ""}` : cityQuery}
                onChange={(e) => {
                  setCityQuery(e.target.value);
                  setSelectedCity(null);
                }}
                onFocus={() => {
                  if (cityOptions.length > 0) setShowCityDropdown(true);
                }}
                placeholder="Start typing a city..."
                className="w-full bg-surface-light border border-white/10 rounded-lg px-4 py-2.5 text-white placeholder-text-muted focus:outline-none focus:ring-2 focus:ring-gold/50 focus:border-gold"
              />
              {showCityDropdown && cityOptions.length > 0 && (
                <div className="absolute z-50 mt-1 w-full bg-surface-light border border-white/10 rounded-lg shadow-lg max-h-48 overflow-y-auto">
                  {cityOptions.map((c) => (
                    <button
                      key={c.id}
                      type="button"
                      onClick={() => {
                        setSelectedCity(c);
                        setCityQuery(c.name);
                        setShowCityDropdown(false);
                      }}
                      className="w-full text-left px-4 py-2.5 hover:bg-white/5 text-white text-sm transition-colors"
                    >
                      {c.name}
                      {c.country_name && (
                        <span className="text-text-muted ml-1">
                          , {c.country_name}
                        </span>
                      )}
                    </button>
                  ))}
                </div>
              )}
            </div>

            {/* Date & Time */}
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
              <div>
                <label className="block text-sm font-medium text-white mb-1.5">
                  Date
                </label>
                <input
                  type="date"
                  value={date}
                  onChange={(e) => setDate(e.target.value)}
                  className="w-full bg-surface-light border border-white/10 rounded-lg px-4 py-2.5 text-white focus:outline-none focus:ring-2 focus:ring-gold/50 focus:border-gold"
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-white mb-1.5">
                  Start Time
                </label>
                <select
                  value={time}
                  onChange={(e) => setTime(e.target.value)}
                  className="w-full bg-surface-light border border-white/10 rounded-lg px-4 py-2.5 text-white focus:outline-none focus:ring-2 focus:ring-gold/50 focus:border-gold"
                >
                  {TIME_SLOTS.map((t) => (
                    <option key={t} value={t}>
                      {t}
                    </option>
                  ))}
                </select>
              </div>
            </div>

            {/* Duration */}
            <div>
              <label className="block text-sm font-medium text-white mb-1.5">
                Duration
              </label>
              <div className="grid grid-cols-3 sm:grid-cols-6 gap-2">
                {DURATIONS.map((d) => (
                  <button
                    key={d}
                    type="button"
                    onClick={() => setDuration(d)}
                    className={`px-3 py-2 rounded-lg text-xs sm:text-sm font-medium transition-all border ${
                      duration === d
                        ? "bg-gold/15 text-gold border-gold/40"
                        : "bg-surface-light text-text-muted border-white/10 hover:border-white/20"
                    }`}
                  >
                    {d}
                  </button>
                ))}
              </div>
            </div>

            {/* Guests */}
            <div>
              <label className="block text-sm font-medium text-white mb-1.5">
                Number of Guests:{" "}
                <span className="text-gold font-bold">{guests}</span>
              </label>
              <input
                type="range"
                min={1}
                max={10}
                value={guests}
                onChange={(e) => setGuests(Number(e.target.value))}
                className="w-full h-2 bg-surface-light rounded-lg appearance-none cursor-pointer accent-gold"
              />
              <div className="flex justify-between text-xs text-text-muted mt-1">
                <span>1</span>
                <span>10</span>
              </div>
            </div>

            {/* Budget */}
            <div>
              <label className="block text-sm font-medium text-white mb-1.5">
                Budget
              </label>
              <input
                type="number"
                min={0}
                value={budget}
                onChange={(e) => setBudget(e.target.value)}
                placeholder="e.g. 500"
                className="w-full bg-surface-light border border-white/10 rounded-lg px-4 py-2.5 text-white placeholder-text-muted focus:outline-none focus:ring-2 focus:ring-gold/50 focus:border-gold"
              />
            </div>

            {/* Special Requests */}
            <div>
              <label className="block text-sm font-medium text-white mb-1.5">
                Special Requests
              </label>
              <textarea
                value={specialRequests}
                onChange={(e) => setSpecialRequests(e.target.value)}
                rows={3}
                maxLength={500}
                placeholder="Any specific preferences, requirements, or details..."
                className="w-full bg-surface-light border border-white/10 rounded-lg px-4 py-2.5 text-white placeholder-text-muted focus:outline-none focus:ring-2 focus:ring-gold/50 focus:border-gold resize-none"
              />
              <p className="text-xs text-text-muted mt-1">
                {specialRequests.length}/500
              </p>
            </div>

            {error && <p className="text-red-400 text-sm">{error}</p>}

            {/* Next */}
            <button
              type="button"
              disabled={!canProceedStep1}
              onClick={() => {
                setError("");
                fetchEscorts();
                goTo(1);
              }}
              className="w-full bg-gold hover:bg-gold-light text-black font-bold px-6 py-3 rounded-lg transition-all shadow-glow hover:shadow-lg disabled:opacity-40 disabled:cursor-not-allowed"
            >
              Next: Select Escorts
            </button>
          </div>
        )}

        {/* ======================== STEP 2: Select Escorts ======================== */}
        {step === 1 && (
          <div className="space-y-4">
            {/* Header bar */}
            <div className="bg-surface rounded-xl border border-white/5 p-4 sm:p-5 flex flex-col sm:flex-row sm:items-center justify-between gap-3">
              <div>
                <h2 className="text-lg font-semibold text-white">
                  Select Escorts
                </h2>
                <p className="text-text-muted text-sm">
                  {selectedCity?.name || cityQuery} &middot; Max 5 escorts
                </p>
              </div>
              <button
                type="button"
                onClick={handleAiSuggest}
                disabled={aiSuggesting}
                className="flex items-center gap-2 bg-purple-600/20 hover:bg-purple-600/30 text-purple-300 border border-purple-500/30 font-medium px-4 py-2 rounded-lg transition-all text-sm disabled:opacity-50"
              >
                {aiSuggesting ? (
                  <>
                    <div className="w-4 h-4 border-2 border-purple-300 border-t-transparent rounded-full animate-spin" />
                    Suggesting...
                  </>
                ) : (
                  <>
                    <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9.663 17h4.673M12 3v1m6.364 1.636l-.707.707M21 12h-1M4 12H3m3.343-5.657l-.707-.707m2.828 9.9a5 5 0 117.072 0l-.548.547A3.374 3.374 0 0014 18.469V19a2 2 0 11-4 0v-.531c0-.895-.356-1.754-.988-2.386l-.548-.547z" />
                    </svg>
                    AI Suggest
                  </>
                )}
              </button>
            </div>

            {/* Selected count bar */}
            {selectedEscorts.length > 0 && (
              <div className="bg-gold/10 border border-gold/20 rounded-lg px-4 py-2.5 flex items-center justify-between">
                <span className="text-gold text-sm font-medium">
                  {selectedEscorts.length} escort{selectedEscorts.length !== 1 ? "s" : ""} selected
                </span>
                {estimatedTotal > 0 && (
                  <span className="text-gold text-sm font-bold">
                    Est. {formatCurrency(estimatedTotal)}
                  </span>
                )}
              </div>
            )}

            {escortError && (
              <p className="text-red-400 text-sm bg-red-400/10 border border-red-400/20 rounded-lg px-4 py-2">
                {escortError}
              </p>
            )}

            {/* Escort grid */}
            {loadingEscorts ? (
              <div className="flex flex-col items-center justify-center py-16 gap-3">
                <div className="w-8 h-8 border-2 border-gold border-t-transparent rounded-full animate-spin" />
                <p className="text-text-muted text-sm">Loading escorts...</p>
              </div>
            ) : escorts.length === 0 ? (
              <div className="bg-surface rounded-xl border border-white/5 p-8 text-center">
                <p className="text-text-muted">
                  No escorts found in {selectedCity?.name || cityQuery}.
                </p>
                <p className="text-text-muted text-sm mt-1">
                  Try a different city or use AI Suggest for broader recommendations.
                </p>
              </div>
            ) : (
              <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 gap-3">
                {escorts.map((escort) => {
                  const isSelected = selectedEscorts.some((e) => e.id === escort.id);
                  return (
                    <button
                      key={escort.id}
                      type="button"
                      onClick={() => toggleEscort(escort)}
                      className={`relative bg-surface rounded-xl overflow-hidden border-2 transition-all text-left group ${
                        isSelected
                          ? "border-gold shadow-[0_0_12px_rgba(212,175,55,0.2)]"
                          : "border-white/5 hover:border-white/15"
                      }`}
                    >
                      {/* Selection badge */}
                      {isSelected && (
                        <div className="absolute top-2 left-2 z-10 w-6 h-6 bg-gold rounded-full flex items-center justify-center">
                          <svg className="w-3.5 h-3.5 text-black" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={3} d="M5 13l4 4L19 7" />
                          </svg>
                        </div>
                      )}

                      {/* Photo */}
                      <div className="aspect-[3/4] bg-black/50 relative">
                        <MediaImage
                          srcs={escort.avatarMediaUrls.length > 0
                            ? escort.avatarMediaUrls
                            : (escort.profile_photo ? [avatarUrl(escort.profile_photo, escort.id_aw)] : [])}
                          alt={escort.username || "Escort"}
                          fill
                          sizes="(max-width:640px) 50vw, (max-width:1024px) 33vw, 25vw"
                          className="object-cover"
                        />
                        {escort.rate && escort.rate > 0 && (
                          <span className="absolute bottom-2 right-2 bg-black/70 text-gold text-[11px] font-bold px-2 py-0.5 rounded">
                            {formatCurrency(Number(escort.rate ?? 0))}
                          </span>
                        )}
                      </div>

                      {/* Info */}
                      <div className="p-2.5">
                        <p className="font-semibold text-white text-sm truncate group-hover:text-gold transition-colors">
                          {escort.username || "Escort"}
                        </p>
                        <p className="text-text-muted text-xs truncate">
                          {[escort.city, escort.country].filter(Boolean).join(", ")}
                        </p>
                      </div>
                    </button>
                  );
                })}
              </div>
            )}

            {/* Navigation */}
            <div className="flex gap-3 pt-2">
              <button
                type="button"
                onClick={() => goTo(0)}
                className="flex-1 bg-surface-light hover:bg-white/10 text-white font-semibold px-6 py-3 rounded-lg transition-all border border-white/10"
              >
                Back
              </button>
              <button
                type="button"
                disabled={selectedEscorts.length === 0}
                onClick={() => goTo(2)}
                className="flex-1 bg-gold hover:bg-gold-light text-black font-bold px-6 py-3 rounded-lg transition-all shadow-glow hover:shadow-lg disabled:opacity-40 disabled:cursor-not-allowed"
              >
                Next: Review
              </button>
            </div>
          </div>
        )}

        {/* ======================== STEP 3: Review ======================== */}
        {step === 2 && (
          <div className="space-y-4">
            {/* Plan summary card */}
            <div className="bg-surface rounded-xl border border-white/5 p-5 sm:p-6 space-y-4">
              <h2 className="text-lg font-semibold text-white">
                Review Your Plan
              </h2>

              <div className="grid grid-cols-2 gap-x-6 gap-y-3 text-sm">
                <div>
                  <p className="text-text-muted">Occasion</p>
                  <p className="text-white font-medium">{occasion}</p>
                </div>
                <div>
                  <p className="text-text-muted">Location</p>
                  <p className="text-white font-medium">
                    {selectedCity
                      ? `${selectedCity.name}${selectedCity.country_name ? `, ${selectedCity.country_name}` : ""}`
                      : cityQuery}
                  </p>
                </div>
                <div>
                  <p className="text-text-muted">Date &amp; Time</p>
                  <p className="text-white font-medium">
                    {date || "Flexible"} at {time}
                  </p>
                </div>
                <div>
                  <p className="text-text-muted">Duration</p>
                  <p className="text-white font-medium">{duration}</p>
                </div>
                <div>
                  <p className="text-text-muted">Guests</p>
                  <p className="text-white font-medium">{guests}</p>
                </div>
                <div>
                  <p className="text-text-muted">Budget</p>
                  <p className="text-white font-medium">
                    {budget ? formatCurrency(Number(budget)) : "Not set"}
                  </p>
                </div>
              </div>

              {specialRequests && (
                <div className="text-sm">
                  <p className="text-text-muted">Special Requests</p>
                  <p className="text-white/80 mt-0.5">{specialRequests}</p>
                </div>
              )}
            </div>

            {/* Selected escorts */}
            <div className="bg-surface rounded-xl border border-white/5 p-5 sm:p-6 space-y-3">
              <div className="flex items-center justify-between">
                <h3 className="text-base font-semibold text-white">
                  Selected Escorts ({selectedEscorts.length})
                </h3>
                {estimatedTotal > 0 && (
                  <span className="text-gold font-bold text-sm">
                    Est. {formatCurrency(estimatedTotal)}
                  </span>
                )}
              </div>

              <div className="space-y-2">
                {selectedEscorts.map((escort) => (
                  <div
                    key={escort.id}
                    className="flex items-center gap-3 bg-surface-light rounded-lg p-2.5"
                  >
                    <MediaImage
                      srcs={escort.avatarMediaUrls.length > 0
                        ? escort.avatarMediaUrls
                        : (escort.profile_photo ? [avatarUrl(escort.profile_photo, escort.id_aw)] : [])}
                      alt={escort.username || "Escort"}
                      width={40}
                      height={40}
                      className="w-10 h-10 rounded-full object-cover shrink-0"
                    />
                    <div className="min-w-0 flex-1">
                      <p className="text-white text-sm font-medium truncate">
                        {escort.username || "Escort"}
                      </p>
                      <p className="text-text-muted text-xs truncate">
                        {[escort.city, escort.country].filter(Boolean).join(", ")}
                      </p>
                    </div>
                    {escort.rate && escort.rate > 0 && (
                      <span className="text-gold text-sm font-bold shrink-0">
                        {formatCurrency(Number(escort.rate ?? 0))}
                      </span>
                    )}
                  </div>
                ))}
              </div>
            </div>

            {/* Edit buttons */}
            <div className="flex gap-3">
              <button
                type="button"
                onClick={() => goTo(0)}
                className="flex-1 bg-surface-light hover:bg-white/10 text-white font-medium px-4 py-2.5 rounded-lg transition-all border border-white/10 text-sm"
              >
                Edit Details
              </button>
              <button
                type="button"
                onClick={() => goTo(1)}
                className="flex-1 bg-surface-light hover:bg-white/10 text-white font-medium px-4 py-2.5 rounded-lg transition-all border border-white/10 text-sm"
              >
                Change Escorts
              </button>
            </div>

            {/* Send */}
            <button
              type="button"
              onClick={() => {
                goTo(3);
                // Slight delay so the animation finishes before we start sending
                setTimeout(handleSend, 300);
              }}
              className="w-full bg-gold hover:bg-gold-light text-black font-bold px-6 py-3.5 rounded-lg transition-all shadow-glow hover:shadow-lg"
            >
              Send Plan to {selectedEscorts.length} Escort{selectedEscorts.length !== 1 ? "s" : ""}
            </button>
          </div>
        )}

        {/* ======================== STEP 4: Sending ======================== */}
        {step === 3 && (
          <div className="bg-surface rounded-xl border border-white/5 p-8 sm:p-10 text-center space-y-6">
            {sending && !sendResult && !sendError && (
              <>
                <div className="w-16 h-16 mx-auto border-3 border-gold border-t-transparent rounded-full animate-spin" />
                <div>
                  <p className="text-white text-lg font-semibold">
                    Sending your plan...
                  </p>
                  <p className="text-text-muted text-sm mt-1">
                    Contacting {selectedEscorts.length} escort{selectedEscorts.length !== 1 ? "s" : ""}
                  </p>
                </div>
              </>
            )}

            {sendResult && (
              <>
                <div className="w-16 h-16 mx-auto bg-green-500/15 rounded-full flex items-center justify-center">
                  <svg className="w-8 h-8 text-green-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
                  </svg>
                </div>
                <div>
                  <p className="text-white text-xl font-bold">
                    Plan Sent!
                  </p>
                  <p className="text-text-muted mt-1">
                    Successfully sent to {sendResult.sent} escort{sendResult.sent !== 1 ? "s" : ""}.
                    {sendResult.failed > 0 && (
                      <span className="text-red-400">
                        {" "}
                        {sendResult.failed} failed.
                      </span>
                    )}
                  </p>
                  <p className="text-text-muted text-sm mt-2">
                    Check your messages for responses.
                  </p>
                </div>
                <div className="flex flex-col sm:flex-row gap-3 pt-2">
                  <button
                    type="button"
                    onClick={() => router.push("/messages")}
                    className="flex-1 bg-gold hover:bg-gold-light text-black font-bold px-6 py-3 rounded-lg transition-all shadow-glow"
                  >
                    Go to Messages
                  </button>
                  <button
                    type="button"
                    onClick={resetWizard}
                    className="flex-1 bg-surface-light hover:bg-white/10 text-white font-semibold px-6 py-3 rounded-lg transition-all border border-white/10"
                  >
                    Plan Another
                  </button>
                </div>
              </>
            )}

            {sendError && (
              <>
                <div className="w-16 h-16 mx-auto bg-red-500/15 rounded-full flex items-center justify-center">
                  <svg className="w-8 h-8 text-red-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                  </svg>
                </div>
                <div>
                  <p className="text-white text-lg font-semibold">
                    Something went wrong
                  </p>
                  <p className="text-red-400 text-sm mt-1">{sendError}</p>
                </div>
                <div className="flex flex-col sm:flex-row gap-3 pt-2">
                  <button
                    type="button"
                    onClick={() => {
                      setSendError("");
                      handleSend();
                    }}
                    className="flex-1 bg-gold hover:bg-gold-light text-black font-bold px-6 py-3 rounded-lg transition-all"
                  >
                    Retry
                  </button>
                  <button
                    type="button"
                    onClick={() => goTo(2)}
                    className="flex-1 bg-surface-light hover:bg-white/10 text-white font-semibold px-6 py-3 rounded-lg transition-all border border-white/10"
                  >
                    Back to Review
                  </button>
                </div>
              </>
            )}
          </div>
        )}
      </div>
    </div>
  );
}
