"use client";

import { useState, useEffect, useRef, useCallback } from "react";
import { X, Coins, AlertCircle, Loader2 } from "lucide-react";
import { giftService, type Gift as GiftItem } from "@/services/giftService";
import { walletService } from "@/services/walletService";
import type { MappedReel } from "@/services/reelsListService";

interface GiftModalProps {
  reel: MappedReel;
  onClose: () => void;
}

type FlowState = "browse" | "confirm" | "sending" | "success" | "error";

/* ── confetti particle ───────────────────────────────────────────────────── */
interface Particle {
  id: number;
  x: number;
  y: number;
  vx: number;
  vy: number;
  color: string;
  size: number;
  rot: number;
  rotSpeed: number;
  life: number;
  shape: "square" | "circle" | "bar";
}

function useConfetti(active: boolean) {
  const [particles, setParticles] = useState<Particle[]>([]);
  const frameRef = useRef<number>(0);
  const colors = ["#f59e0b", "var(--accent)", "#fbbf24", "#fff", "#fb923c", "#fde68a"];

  useEffect(() => {
    if (!active) { setParticles([]); return; }

    const spawn = (): Particle[] =>
      Array.from({ length: 60 }, (_, i) => ({
        id: i,
        x: 40 + Math.random() * 20,
        y: 30 + Math.random() * 10,
        vx: (Math.random() - 0.5) * 8,
        vy: -(Math.random() * 10 + 6),
        color: colors[Math.floor(Math.random() * colors.length)],
        size: Math.random() * 6 + 4,
        rot: Math.random() * 360,
        rotSpeed: (Math.random() - 0.5) * 12,
        life: 1,
        shape: (["square", "circle", "bar"] as const)[Math.floor(Math.random() * 3)],
      }));

    let parts = spawn();
    setParticles(parts);

    const tick = () => {
      parts = parts
        .map((p) => ({
          ...p,
          x: p.x + p.vx * 0.6,
          y: p.y + p.vy * 0.6,
          vy: p.vy + 0.45,
          vx: p.vx * 0.97,
          rot: p.rot + p.rotSpeed,
          life: p.life - 0.015,
        }))
        .filter((p) => p.life > 0);
      setParticles([...parts]);
      if (parts.length > 0) frameRef.current = requestAnimationFrame(tick);
    };
    frameRef.current = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(frameRef.current);
  }, [active]);

  return particles;
}

/* ── gift card ───────────────────────────────────────────────────────────── */
function GiftCard({
  gift, selected, affordable, index, onClick,
}: {
  gift: GiftItem; selected: boolean; affordable: boolean; index: number; onClick: () => void;
}) {
  const [loaded, setLoaded] = useState(false);
  const [hovered, setHovered] = useState(false);

  return (
    <button
      type="button"
      onClick={affordable ? onClick : undefined}
      onMouseEnter={() => setHovered(true)}
      onMouseLeave={() => setHovered(false)}
      className="relative flex flex-col items-center gap-2 pt-3 pb-2.5 px-2 rounded-2xl transition-all"
      style={{
        background: selected
          ? "linear-gradient(160deg,rgba(245,158,11,0.22) 0%,rgba(var(--accent-rgb),0.08) 100%)"
          : hovered && affordable
          ? "rgba(255,255,255,0.06)"
          : "rgba(255,255,255,0.025)",
        border: selected
          ? "1.5px solid rgba(245,158,11,0.6)"
          : hovered && affordable
          ? "1.5px solid rgba(255,255,255,0.12)"
          : "1.5px solid rgba(255,255,255,0.06)",
        boxShadow: selected
          ? "0 0 0 3px rgba(245,158,11,0.15), 0 8px 28px rgba(245,158,11,0.18)"
          : "none",
        cursor: affordable ? "pointer" : "not-allowed",
        opacity: affordable ? 1 : 0.35,
        transform: selected ? "translateY(-3px) scale(1.04)" : hovered && affordable ? "translateY(-1px)" : "none",
        transition: "all 0.22s cubic-bezier(0.34,1.5,0.64,1)",
        animation: `gm-card-pop 0.45s cubic-bezier(0.34,1.6,0.64,1) both`,
        animationDelay: `${index * 60}ms`,
      }}
    >
      {/* Pulsing ring on selection */}
      {selected && (
        <div
          className="absolute inset-0 rounded-2xl pointer-events-none"
          style={{ animation: "gm-ring-pulse 1.5s ease-in-out infinite", border: "1.5px solid rgba(245,158,11,0.4)" }}
        />
      )}

      {/* GIF container */}
      <div
        className="relative rounded-xl overflow-hidden"
        style={{
          width: 68, height: 68,
          background: "rgba(255,255,255,0.04)",
          boxShadow: selected ? "0 4px 20px rgba(245,158,11,0.3)" : "0 2px 8px rgba(0,0,0,0.4)",
        }}
      >
        {!loaded && (
          <div className="absolute inset-0 flex items-center justify-center">
            <div className="w-5 h-5 rounded-full border-[1.5px] animate-spin"
              style={{ borderColor: "rgba(245,158,11,0.25)", borderTopColor: "#f59e0b" }} />
          </div>
        )}
        {/* eslint-disable-next-line @next/next/no-img-element */}
        <img
          src={gift.image}
          alt={gift.name}
          className="w-full h-full object-cover"
          style={{
            opacity: loaded ? 1 : 0,
            transition: "opacity 0.3s ease",
            transform: selected ? "scale(1.12)" : hovered && affordable ? "scale(1.06)" : "scale(1)",
            transition2: "transform 0.25s ease",
          } as React.CSSProperties}
          onLoad={() => setLoaded(true)}
        />
        {/* Gold sweep on select */}
        {selected && (
          <div
            className="absolute inset-0 pointer-events-none"
            style={{
              background: "linear-gradient(105deg,transparent 30%,rgba(245,158,11,0.14) 50%,transparent 70%)",
              animation: "gm-sweep 2.2s ease-in-out infinite",
            }}
          />
        )}
      </div>

      {/* Name */}
      <p
        className="text-[9px] font-bold text-center leading-tight truncate w-full"
        style={{ color: selected ? "#fbbf24" : "var(--text-muted)", letterSpacing: "0.01em" }}
      >
        {gift.name}
      </p>

      {/* Price pill */}
      <div
        className="flex items-center gap-[3px] px-2 py-[3px] rounded-full"
        style={{
          background: selected ? "rgba(245,158,11,0.2)" : "rgba(255,255,255,0.05)",
          border: `1px solid ${selected ? "rgba(245,158,11,0.35)" : "rgba(255,255,255,0.08)"}`,
        }}
      >
        <Coins size={7} color={selected ? "#fbbf24" : "var(--text-muted)"} strokeWidth={2.5} />
        <span
          className="text-[9px] font-black"
          style={{ color: selected ? "#fbbf24" : "var(--text-muted)", fontVariantNumeric: "tabular-nums" }}
        >
          {gift.price.toLocaleString()}
        </span>
      </div>
    </button>
  );
}

/* ── animated balance counter ────────────────────────────────────────────── */
function BalanceDisplay({ balance, flash }: { balance: number; flash: boolean }) {
  return (
    <div
      className="flex items-center gap-1.5 px-3 py-1.5 rounded-full"
      style={{
        background: flash ? "rgba(245,158,11,0.2)" : "rgba(245,158,11,0.08)",
        border: `1px solid ${flash ? "rgba(245,158,11,0.45)" : "rgba(245,158,11,0.15)"}`,
        transition: "all 0.4s ease",
        boxShadow: flash ? "0 0 16px rgba(245,158,11,0.3)" : "none",
      }}
    >
      <Coins size={11} color="#f59e0b" strokeWidth={2.5} />
      <span className="text-[11px] font-black" style={{ color: "#f59e0b", fontVariantNumeric: "tabular-nums" }}>
        {balance.toLocaleString()}
      </span>
    </div>
  );
}

/* ══════════════════════════════════════════════════════════════════════════
   MAIN EXPORT
══════════════════════════════════════════════════════════════════════════ */

export function GiftModal({ reel, onClose }: GiftModalProps) {
  const [gifts, setGifts]       = useState<GiftItem[]>([]);
  const [balance, setBalance]   = useState(0);
  const [selected, setSelected] = useState<GiftItem | null>(null);
  const [flow, setFlow]         = useState<FlowState>("browse");
  const [errorMsg, setErrorMsg] = useState("");
  const [loading, setLoading]   = useState(true);
  const [balFlash, setBalFlash] = useState(false);
  const [launchPos, setLaunchPos] = useState({ x: 50, y: 50 });
  const sendBtnRef = useRef<HTMLButtonElement>(null);

  const confettiActive = flow === "success";
  const particles = useConfetti(confettiActive);

  /* fetch data */
  useEffect(() => {
    setLoading(true);
    Promise.all([giftService.getGifts(), walletService.getBalance()])
      .then(([g, w]) => { setGifts(g); setBalance(w.walletBalance); })
      .catch(() => {})
      .finally(() => setLoading(false));
  }, []);

  /* scroll lock */
  useEffect(() => {
    document.body.style.overflow = "hidden";
    return () => { document.body.style.overflow = ""; };
  }, []);

  const canAfford = selected ? balance >= selected.price : false;

  const handleSelect = (g: GiftItem) => {
    setSelected((prev) => prev?.id === g.id ? null : g);
  };

  const handleSend = useCallback(async () => {
    if (!selected || !canAfford) return;

    /* capture button position for launch trajectory */
    if (sendBtnRef.current) {
      const r = sendBtnRef.current.getBoundingClientRect();
      const vw = window.innerWidth, vh = window.innerHeight;
      setLaunchPos({ x: ((r.left + r.width / 2) / vw) * 100, y: ((r.top + r.height / 2) / vh) * 100 });
    }

    setFlow("sending");
    try {
      const res = await giftService.sendGift({
        gift_id:    selected.id,
        channel_id: reel.channelId || reel.channelUserId,
        content_id: reel.id,
        price:      selected.price,
      });
      if (res.status === 200) {
        setBalance((b) => Math.max(0, b - selected.price));
        setBalFlash(true);
        setTimeout(() => setBalFlash(false), 800);
        setFlow("success");
      } else {
        throw new Error(res.message ?? "Failed");
      }
    } catch (e) {
      setFlow("error");
      setErrorMsg(e instanceof Error ? e.message : "Could not send gift.");
    }
  }, [selected, canAfford, reel]);

  return (
    <>
      {/* ── Backdrop ── */}
      <div
        className="fixed inset-0 z-[200]"
        style={{
          background: "rgba(0,0,0,0.8)",
          backdropFilter: "blur(12px)",
          animation: "gm-fade 0.2s ease both",
        }}
        onClick={flow === "browse" ? onClose : undefined}
      />

      {/* ── Confetti canvas ── */}
      {confettiActive && (
        <div className="fixed inset-0 z-[203] pointer-events-none overflow-hidden">
          {particles.map((p) => (
            <div
              key={p.id}
              className="absolute"
              style={{
                left: `${p.x}%`,
                top: `${p.y}%`,
                width: p.shape === "bar" ? p.size * 2.5 : p.size,
                height: p.shape === "bar" ? p.size * 0.6 : p.size,
                borderRadius: p.shape === "circle" ? "50%" : p.shape === "square" ? "2px" : "1px",
                background: p.color,
                transform: `rotate(${p.rot}deg)`,
                opacity: p.life,
                boxShadow: `0 0 ${p.size}px ${p.color}80`,
              }}
            />
          ))}
        </div>
      )}

      {/* ── Bottom sheet ── */}
      <div
        className="fixed z-[201] bottom-0 left-0 right-0 flex flex-col overflow-hidden"
        style={{
          maxWidth: "680px",
          margin: "0 auto",
          maxHeight: "84vh",
          borderRadius: "22px 22px 0 0",
          background: "var(--sheet-bg)",
          border: "1px solid var(--sheet-border)",
          borderBottom: "none",
          boxShadow: "0 -32px 80px rgba(0,0,0,0.8), inset 0 1px 0 rgba(255,255,255,0.06)",
          animation: "gm-sheet-up 0.42s cubic-bezier(0.22,1.2,0.36,1) both",
        }}
      >
        {/* Ambient amber glow at bottom of sheet */}
        <div
          className="absolute bottom-0 left-0 right-0 pointer-events-none"
          style={{
            height: 200,
            background: "radial-gradient(ellipse 80% 100% at 50% 100%,rgba(245,158,11,0.09) 0%,transparent 70%)",
          }}
        />

        {/* Drag handle */}
        <div className="flex justify-center pt-3 shrink-0">
          <div className="w-9 h-[3px] rounded-full" style={{ background: "var(--sheet-handle)" }} />
        </div>

        {/* ── HEADER ── */}
        <div
          className="flex items-center gap-3 px-4 py-3 shrink-0 relative"
          style={{ borderBottom: "1px solid var(--border)" }}
        >
          {/* Creator */}
          <div
            className="w-10 h-10 rounded-full overflow-hidden shrink-0 flex items-center justify-center text-sm font-black relative"
            style={{
              background: `hsl(${reel.hue},50%,22%)`,
              boxShadow: "0 0 0 2px rgba(245,158,11,0.35)",
            }}
          >
            {reel.channelImage
              // eslint-disable-next-line @next/next/no-img-element
              ? <img src={reel.channelImage} alt={reel.creator} className="w-full h-full object-cover" />
              : <span className="text-[#ffffff] text-sm">{reel.initial}</span>
            }
            {/* Amber ring pulse */}
            <div className="absolute inset-0 rounded-full pointer-events-none"
              style={{ animation: "gm-avatar-ring 2.5s ease-in-out infinite", border: "2px solid rgba(245,158,11,0.3)" }} />
          </div>

          <div className="flex-1 min-w-0">
            <p className="text-xs font-bold truncate leading-tight" style={{ color: "var(--text-primary)" }}>@{reel.creator}</p>
            <p className="text-[9px] mt-0.5" style={{ color: "#f59e0b", letterSpacing: "0.04em" }}>
              ✦ Send a gift
            </p>
          </div>

          <BalanceDisplay balance={balance} flash={balFlash} />

          {flow !== "sending" && (
            <button
              onClick={onClose}
              className="w-7 h-7 rounded-full flex items-center justify-center transition-all hover:bg-white/10 active:scale-90 ml-1"
              style={{ background: "rgba(255,255,255,0.07)" }}
            >
              <X size={13} color="#777" />
            </button>
          )}
        </div>

        {/* ════════════════════════════════════════
            FLOW: browse
        ════════════════════════════════════════ */}
        {flow === "browse" && (
          <>
            <div className="flex-1 overflow-y-auto px-4 pt-4 pb-2 relative" style={{ scrollbarWidth: "none" }}>
              {loading ? (
                <div className="flex flex-col items-center gap-3 py-14">
                  <div className="relative w-12 h-12">
                    <div className="absolute inset-0 rounded-full animate-spin"
                      style={{ border: "2px solid rgba(245,158,11,0.15)", borderTopColor: "#f59e0b" }} />
                    <div className="absolute inset-2 rounded-full animate-spin"
                      style={{ border: "1.5px solid rgba(245,158,11,0.1)", borderBottomColor: "var(--accent)", animationDirection: "reverse", animationDuration: "0.65s" }} />
                  </div>
                  <p className="text-[11px]" style={{ color: "var(--text-muted)" }}>Loading gifts…</p>
                </div>
              ) : gifts.length === 0 ? (
                <div className="flex flex-col items-center gap-3 py-14">
                  <p className="text-3xl">🎁</p>
                  <p className="text-[11px]" style={{ color: "var(--text-muted)" }}>No gifts available right now</p>
                </div>
              ) : (
                <>
                  <p className="text-[9px] font-black uppercase tracking-[0.12em] mb-3" style={{ color: "#3a3a3a" }}>
                    Choose a gift
                  </p>
                  <div className="grid grid-cols-4 gap-2">
                    {gifts.map((g, i) => (
                      <GiftCard
                        key={g.id}
                        gift={g}
                        selected={selected?.id === g.id}
                        affordable={balance >= g.price}
                        index={i}
                        onClick={() => handleSelect(g)}
                      />
                    ))}
                  </div>

                  {selected && !canAfford && (
                    <div
                      className="mt-3 flex items-center gap-2 px-3 py-2.5 rounded-2xl text-[11px]"
                      style={{
                        background: "rgba(244,63,94,0.07)",
                        color: "#f87171",
                        border: "1px solid rgba(244,63,94,0.15)",
                        animation: "gm-card-pop 0.3s ease both",
                      }}
                    >
                      <AlertCircle size={12} strokeWidth={2} />
                      <span>Need {(selected.price - balance).toLocaleString()} more coins to send this gift</span>
                    </div>
                  )}
                </>
              )}
            </div>

            {/* ── Footer CTA ── */}
            <div className="px-4 pb-7 pt-3 shrink-0 relative" style={{ borderTop: "1px solid var(--border)" }}>
              {/* Selected preview */}
              {selected && (
                <div
                  className="flex items-center gap-2.5 mb-3 px-3 py-2.5 rounded-2xl"
                  style={{
                    background: "rgba(245,158,11,0.07)",
                    border: "1px solid rgba(245,158,11,0.14)",
                    animation: "gm-card-pop 0.28s cubic-bezier(0.34,1.5,0.64,1) both",
                  }}
                >
                  {/* eslint-disable-next-line @next/next/no-img-element */}
                  <img src={selected.image} alt={selected.name}
                    className="w-8 h-8 rounded-xl object-cover shrink-0"
                    style={{ boxShadow: "0 2px 10px rgba(245,158,11,0.25)" }} />
                  <div className="flex-1 min-w-0">
                    <p className="text-[12px] font-bold truncate" style={{ color: "var(--text-primary)" }}>{selected.name}</p>
                    <p className="text-[9px]" style={{ color: "var(--text-muted)" }}>to @{reel.creator}</p>
                  </div>
                  <div className="flex items-center gap-1 px-2.5 py-1 rounded-full"
                    style={{ background: "rgba(245,158,11,0.15)", border: "1px solid rgba(245,158,11,0.3)" }}>
                    <Coins size={9} color="#fbbf24" strokeWidth={2.5} />
                    <span className="text-[10px] font-black" style={{ color: "#fbbf24" }}>
                      {selected.price.toLocaleString()}
                    </span>
                  </div>
                </div>
              )}

              <button
                ref={sendBtnRef}
                disabled={!selected || !canAfford}
                onClick={handleSend}
                className="w-full h-13 rounded-2xl text-[14px] font-black text-[#ffffff] relative overflow-hidden flex items-center justify-center gap-2.5 transition-all disabled:opacity-25 disabled:cursor-not-allowed"
                style={{
                  height: 52,
                  background: selected && canAfford
                    ? "linear-gradient(135deg,#f59e0b 0%,var(--accent) 60%,#dc6b10 100%)"
                    : "rgba(255,255,255,0.07)",
                  boxShadow: selected && canAfford
                    ? "0 0 32px rgba(245,158,11,0.35), 0 4px 20px rgba(0,0,0,0.4)"
                    : "none",
                  transform: selected && canAfford ? "none" : "none",
                  transition: "all 0.25s cubic-bezier(0.34,1.4,0.64,1)",
                }}
                onMouseDown={(e) => { if (selected && canAfford) (e.currentTarget as HTMLElement).style.transform = "scale(0.97)"; }}
                onMouseUp={(e) => { (e.currentTarget as HTMLElement).style.transform = "scale(1)"; }}
                onMouseLeave={(e) => { (e.currentTarget as HTMLElement).style.transform = "scale(1)"; }}
              >
                {/* Shimmer on ready */}
                {selected && canAfford && (
                  <div
                    className="absolute inset-0 pointer-events-none"
                    style={{
                      background: "linear-gradient(105deg,transparent 35%,rgba(255,255,255,0.14) 50%,transparent 65%)",
                      animation: "gm-btn-shimmer 2.5s ease-in-out infinite",
                    }}
                  />
                )}
                <span style={{ fontSize: 18 }}>🎁</span>
                <span>{selected ? `Send ${selected.name}` : "Select a gift first"}</span>
              </button>
            </div>
          </>
        )}

        {/* ════════════════════════════════════════
            FLOW: sending — gift launches upward
        ════════════════════════════════════════ */}
        {flow === "sending" && (
          <div className="flex flex-col items-center justify-center gap-6 py-12 px-6 flex-1 relative">
            {/* Orbiting rings */}
            <div className="relative flex items-center justify-center" style={{ width: 140, height: 140 }}>
              <div className="absolute inset-0 rounded-full"
                style={{ border: "1px solid rgba(245,158,11,0.12)", animation: "gm-orbit 3s linear infinite" }} />
              <div className="absolute rounded-full"
                style={{ width: 110, height: 110, border: "1px solid rgba(245,158,11,0.2)", animation: "gm-orbit 2s linear infinite reverse" }} />
              <div className="absolute rounded-full"
                style={{ width: 80, height: 80, border: "1px solid rgba(245,158,11,0.35)", animation: "gm-orbit 1.5s linear infinite" }} />

              {/* Floating gift */}
              {selected && (
                // eslint-disable-next-line @next/next/no-img-element
                <img
                  src={selected.image}
                  alt={selected.name}
                  className="relative rounded-2xl object-cover"
                  style={{
                    width: 64, height: 64,
                    boxShadow: "0 0 40px rgba(245,158,11,0.5), 0 8px 24px rgba(0,0,0,0.6)",
                    animation: "gm-launch-float 0.8s ease-in-out infinite",
                  }}
                />
              )}
            </div>

            <div className="text-center">
              <p className="text-sm font-bold tracking-tight" style={{ color: "var(--text-primary)" }}>Sending your gift…</p>
              <p className="text-[11px] mt-1.5" style={{ color: "var(--text-muted)" }}>
                Flying to @{reel.creator}
              </p>
            </div>

            {/* Progress dots */}
            <div className="flex items-center gap-2">
              {[0, 1, 2].map((i) => (
                <div
                  key={i}
                  className="w-1.5 h-1.5 rounded-full"
                  style={{
                    background: "#f59e0b",
                    animation: `gm-dot-pulse 1.2s ease-in-out ${i * 0.2}s infinite`,
                  }}
                />
              ))}
            </div>
          </div>
        )}

        {/* ════════════════════════════════════════
            FLOW: success
        ════════════════════════════════════════ */}
        {flow === "success" && (
          <div className="flex flex-col items-center gap-5 py-10 px-6 flex-1">
            {/* Big gift + burst ring */}
            <div className="relative flex items-center justify-center" style={{ width: 160, height: 160 }}>
              {/* Burst rings */}
              {[0, 1, 2].map((i) => (
                <div
                  key={i}
                  className="absolute rounded-full pointer-events-none"
                  style={{
                    inset: 0,
                    border: "2px solid rgba(245,158,11,0.5)",
                    animation: `gm-burst-ring 1s ease-out ${i * 0.15}s both`,
                  }}
                />
              ))}

              {/* Gift image */}
              {selected && (
                // eslint-disable-next-line @next/next/no-img-element
                <img
                  src={selected.image}
                  alt={selected.name}
                  className="relative rounded-3xl object-cover"
                  style={{
                    width: 96, height: 96,
                    boxShadow: "0 0 60px rgba(245,158,11,0.55), 0 12px 40px rgba(0,0,0,0.7)",
                    animation: "gm-success-pop 0.6s cubic-bezier(0.34,1.8,0.64,1) both",
                  }}
                />
              )}

              {/* Sparkle dots */}
              {[0, 45, 90, 135, 180, 225, 270, 315].map((deg, i) => (
                <div
                  key={deg}
                  className="absolute w-2 h-2 rounded-full pointer-events-none"
                  style={{
                    background: i % 2 === 0 ? "#f59e0b" : "#fbbf24",
                    top: "50%",
                    left: "50%",
                    transformOrigin: "0 0",
                    transform: `rotate(${deg}deg) translateX(68px) translateY(-50%)`,
                    animation: `gm-sparkle-fly 0.7s cubic-bezier(0.34,1.5,0.64,1) ${i * 0.05}s both`,
                    boxShadow: `0 0 6px #f59e0b`,
                  }}
                />
              ))}
            </div>

            <div className="text-center">
              <p className="text-xl font-black tracking-tight" style={{ color: "var(--text-primary)", letterSpacing: "-0.02em" }}>
                Gift Sent! 🎉
              </p>
              <p className="text-[12px] mt-1.5 leading-relaxed" style={{ color: "var(--text-muted)" }}>
                You gifted{" "}
                <span style={{ color: "#fbbf24", fontWeight: 700 }}>{selected?.name}</span>
                {" "}to{" "}
                <span style={{ color: "var(--text-primary)", fontWeight: 600 }}>@{reel.creator}</span>
              </p>
              <p className="text-[10px] mt-1" style={{ color: "var(--text-muted)" }}>
                {selected && `– ${selected.price.toLocaleString()} coins`}
              </p>
            </div>

            <button
              onClick={onClose}
              className="px-10 py-3 rounded-2xl text-sm font-black text-black active:scale-95 relative overflow-hidden"
              style={{
                background: "linear-gradient(135deg,#f59e0b,var(--accent))",
                boxShadow: "0 4px 24px rgba(245,158,11,0.4)",
                animation: "gm-card-pop 0.5s cubic-bezier(0.34,1.5,0.64,1) 0.4s both",
                opacity: 0,
              }}
            >
              <div
                className="absolute inset-0 pointer-events-none"
                style={{
                  background: "linear-gradient(105deg,transparent 35%,rgba(255,255,255,0.2) 50%,transparent 65%)",
                  animation: "gm-btn-shimmer 2s ease-in-out infinite",
                }}
              />
              Done ✓
            </button>
          </div>
        )}

        {/* ════════════════════════════════════════
            FLOW: error
        ════════════════════════════════════════ */}
        {flow === "error" && (
          <div className="flex flex-col items-center gap-5 py-12 px-6 flex-1">
            <div
              className="w-16 h-16 rounded-full flex items-center justify-center"
              style={{
                background: "rgba(244,63,94,0.08)",
                border: "2px solid rgba(244,63,94,0.25)",
                boxShadow: "0 0 32px rgba(244,63,94,0.15)",
              }}
            >
              <AlertCircle size={28} color="#f43f5e" strokeWidth={1.6} />
            </div>
            <div className="text-center">
              <p className="text-sm font-bold" style={{ color: "var(--text-primary)" }}>Couldn't send gift</p>
              <p className="text-[11px] mt-1.5" style={{ color: "var(--text-muted)" }}>{errorMsg}</p>
            </div>
            <div className="flex gap-3">
              <button
                onClick={() => { setFlow("browse"); setErrorMsg(""); }}
                className="px-6 py-2.5 rounded-2xl text-[12px] font-bold text-[#ffffff] active:scale-95 transition-all"
                style={{
                  background: "linear-gradient(135deg,#f59e0b,var(--accent))",
                  boxShadow: "0 4px 18px rgba(245,158,11,0.3)",
                }}
              >
                Try Again
              </button>
              <button
                onClick={onClose}
                className="px-6 py-2.5 rounded-2xl text-[12px] font-semibold transition-all"
                style={{ background: "rgba(255,255,255,0.06)", color: "#888" }}
              >
                Cancel
              </button>
            </div>
          </div>
        )}
      </div>

      <style>{`
        @keyframes gm-fade        { from{opacity:0} to{opacity:1} }
        @keyframes gm-sheet-up    { from{transform:translateY(100%)} to{transform:translateY(0)} }
        @keyframes gm-card-pop    { from{opacity:0;transform:translateY(10px) scale(0.9)} to{opacity:1;transform:translateY(0) scale(1)} }
        @keyframes gm-ring-pulse  { 0%,100%{transform:scale(1);opacity:1} 50%{transform:scale(1.06);opacity:0.6} }
        @keyframes gm-sweep       { 0%{background-position:-200% 0} 100%{background-position:200% 0} }
        @keyframes gm-avatar-ring { 0%,100%{opacity:0.3;transform:scale(1)} 50%{opacity:0.7;transform:scale(1.08)} }
        @keyframes gm-btn-shimmer { 0%{transform:translateX(-100%) skewX(-15deg)} 100%{transform:translateX(300%) skewX(-15deg)} }
        @keyframes gm-orbit       { from{transform:rotate(0deg)} to{transform:rotate(360deg)} }
        @keyframes gm-launch-float{ 0%,100%{transform:translateY(0) scale(1)} 50%{transform:translateY(-10px) scale(1.05)} }
        @keyframes gm-dot-pulse   { 0%,80%,100%{transform:scale(0.6);opacity:0.4} 40%{transform:scale(1.2);opacity:1} }
        @keyframes gm-success-pop { from{opacity:0;transform:scale(0.4) rotate(-10deg)} to{opacity:1;transform:scale(1) rotate(0)} }
        @keyframes gm-burst-ring  { 0%{transform:scale(0.5);opacity:1} 100%{transform:scale(2.5);opacity:0} }
        @keyframes gm-sparkle-fly { from{opacity:0;transform:rotate(var(--deg)) translateX(20px) translateY(-50%)} to{opacity:1;transform:rotate(var(--deg)) translateX(68px) translateY(-50%)} }
      `}</style>
    </>
  );
}
