// Avatar Picker — Gacha / Summon mechanic.
// Egg idle → click → shake → crack → avatar pop + star burst → re-roll or confirm.
const { useState, useEffect, useRef } = React;
const { X, RefreshCw, Check, Sparkles } = LucideReact;

/* ── Egg SVG ────────────────────────────────────────────────── */
const EggSVG = ({ phase }) => (
  <svg viewBox="0 0 120 148" width="120" height="148" style={{ filter: "drop-shadow(0 10px 24px rgba(0,0,0,0.10))" }}>
    {/* ground shadow */}
    <ellipse cx="60" cy="143" rx="24" ry="4.5" fill="rgba(0,0,0,0.07)" />
    {/* egg body */}
    <ellipse cx="60" cy="78" rx="43" ry="57" fill="#FFFDE8" />
    <ellipse cx="60" cy="78" rx="43" ry="57" fill="none" stroke="#EDE6B0" strokeWidth="2" />
    {/* shine */}
    <ellipse cx="41" cy="50" rx="9" ry="14" fill="white" opacity="0.55" transform="rotate(-22 41 50)" />
    {/* cracks — cracking phase only */}
    {phase === "cracking" && <>
      <path d="M 57 28 L 50 44 L 60 53 L 52 67" stroke="#C4B87A" strokeWidth="2.2" fill="none" strokeLinecap="round" strokeLinejoin="round" />
      <path d="M 70 35 L 76 50 L 66 59" stroke="#C4B87A" strokeWidth="2.2" fill="none" strokeLinecap="round" strokeLinejoin="round" />
    </>}
    {/* sleeping eyes — curved up like ^ */}
    <path d="M 43 81 Q 47 76 51 81" stroke="#B8921E" strokeWidth="2.5" fill="none" strokeLinecap="round" />
    <path d="M 69 81 Q 73 76 77 81" stroke="#B8921E" strokeWidth="2.5" fill="none" strokeLinecap="round" />
    {/* blush */}
    <circle cx="39" cy="90" r="8" fill="#FCA5A5" opacity="0.28" />
    <circle cx="81" cy="90" r="8" fill="#FCA5A5" opacity="0.28" />
    {/* smile */}
    <path d="M 51 96 Q 60 103 69 96" stroke="#B8921E" strokeWidth="2.2" fill="none" strokeLinecap="round" />
    {/* zzz — idle only */}
    {phase === "idle" && (
      <text x="85" y="50" style={{ fontFamily: "system-ui, sans-serif", fontSize: "13px", fontWeight: 700, fill: "#C8A832", opacity: 0.75 }}>z z</text>
    )}
  </svg>
);

/* ── Star Burst ─────────────────────────────────────────────── */
const STAR_EMOJIS = ["✨", "⭐", "🌟", "✨", "⭐", "🌟", "✨", "⭐"];
const StarBurst = ({ seed }) => (
  <div style={{ position: "absolute", inset: 0, pointerEvents: "none", overflow: "visible" }}>
    {STAR_EMOJIS.map((emoji, i) => {
      const angle = (i / STAR_EMOJIS.length) * 360 - 90;
      const rad   = angle * Math.PI / 180;
      const dist  = 82;
      const tx    = Math.round(Math.cos(rad) * dist);
      const ty    = Math.round(Math.sin(rad) * dist);
      return (
        <div
          key={seed + "-" + i}
          style={{
            position: "absolute",
            top: "50%",
            left: "50%",
            "--tx": tx + "px",
            "--ty": ty + "px",
            animation: `star-burst 0.9s ease-out ${i * 55}ms forwards`,
            fontSize: "20px",
            lineHeight: 1,
            opacity: 0,
            userSelect: "none",
          }}
        >
          {emoji}
        </div>
      );
    })}
  </div>
);

/* ── Avatar Picker ──────────────────────────────────────────── */
const AvatarPicker = ({ open, currentId, onSelect, onClose }) => {
  // phase: "idle" | "shaking" | "cracking" | "revealed"
  const [phase,      setPhase]      = useState("idle");
  const [revealedId, setRevealedId] = useState(null);
  const [rollCount,  setRollCount]  = useState(0);
  const [showStars,  setShowStars]  = useState(false);
  const [starSeed,   setStarSeed]   = useState(0);
  const lastIdRef = useRef(null);
  const busyRef   = useRef(false);

  // Reset when modal opens
  useEffect(() => {
    if (open) {
      setPhase("idle");
      setRevealedId(null);
      setRollCount(0);
      setShowStars(false);
      busyRef.current = false;
      lastIdRef.current = null;
    }
  }, [open]);

  // ESC to close
  useEffect(() => {
    const onKey = (e) => { if (e.key === "Escape" && open) onClose(); };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [open, onClose]);

  if (!open) return null;

  const summon = () => {
    if (busyRef.current) return;
    busyRef.current = true;
    setShowStars(false);
    setPhase("shaking");

    setTimeout(() => setPhase("cracking"), 620);

    setTimeout(() => {
      // Pick random, avoid same as last roll
      const pool   = (window.AVATARS || []).filter(a => a.id !== lastIdRef.current);
      const chosen = (pool.length ? pool : window.AVATARS)[Math.floor(Math.random() * (pool.length || 1))];
      lastIdRef.current = chosen?.id ?? "bunny";
      setRevealedId(chosen?.id ?? "bunny");
      setRollCount(c => c + 1);
      setPhase("revealed");
      setShowStars(true);
      setStarSeed(s => s + 1);
      setTimeout(() => setShowStars(false), 1400);
      busyRef.current = false;
    }, 1050);
  };

  const revealedAvatar = (window.AVATARS || []).find(a => a.id === revealedId);
  const eggAnimStyle = {
    idle:     "egg-bob 2.6s ease-in-out infinite",
    shaking:  "egg-shake 0.62s ease-in-out",
    cracking: "egg-crack 0.38s ease-in-out",
    revealed: "none",
  }[phase];

  return (
    <div
      className="fixed inset-0 z-50 flex items-center justify-center p-4"
      style={{ background: "rgba(27,26,23,0.35)", backdropFilter: "blur(8px)" }}
      onClick={onClose}
    >
      <div
        className="bg-[#FDFBF7] w-full max-w-[400px] overflow-hidden"
        onClick={e => e.stopPropagation()}
        style={{ borderRadius: "32px", boxShadow: "0 30px 80px -20px rgba(27,26,23,0.28), 0 0 0 1px rgba(27,26,23,0.05)" }}
      >
        {/* ── Header ── */}
        <div className="px-7 pt-6 pb-0 flex items-center justify-between">
          <div className="flex items-center gap-2 text-[11px] uppercase tracking-[0.18em] text-[#8B7E6A] font-medium">
            <Sparkles size={13} strokeWidth={2} />
            <span>
              {phase === "revealed"
                ? rollCount === 1 ? "ได้ตัวแรก!" : `ลองครั้งที่ ${rollCount}`
                : "Summon มาสคอท"}
            </span>
          </div>
          <button
            onClick={onClose}
            className="w-9 h-9 rounded-full flex items-center justify-center text-[#6B6457] hover:bg-[#F2EDE3] transition"
            aria-label="Close"
          >
            <X size={18} strokeWidth={2} />
          </button>
        </div>

        {/* ── Main ── */}
        <div className="px-7 py-8 flex flex-col items-center gap-5" style={{ minHeight: "300px", justifyContent: "center" }}>
          {phase !== "revealed" ? (
            /* ── Egg state ── */
            <>
              <button
                onClick={summon}
                style={{ background: "none", border: "none", padding: 0, cursor: "pointer", animation: eggAnimStyle, display: "block" }}
                aria-label="Summon มาสคอท"
              >
                <EggSVG phase={phase} />
              </button>
              <div style={{ textAlign: "center" }}>
                <p style={{ fontSize: "15px", fontWeight: 600, color: "#1B1A17", margin: 0 }}>
                  {phase === "idle" ? "แตะไข่เพื่อ Summon มาสคอท!" : "กำลัง Summon..."}
                </p>
                <p style={{ fontSize: "12px", color: "#8B7E6A", marginTop: "4px" }}>
                  {phase === "idle" ? "มีมาสคอต 12 ตัวให้สุ่ม ✨" : "โผล่ออกมาแล้ว..."}
                </p>
              </div>
            </>
          ) : (
            /* ── Revealed state ── */
            <>
              <div style={{ position: "relative", display: "inline-block" }}>
                <div
                  key={"avatar-" + rollCount}
                  style={{ animation: "avatar-pop 0.55s cubic-bezier(.2,.8,.2,1) forwards" }}
                >
                  <AvatarTile id={revealedId} size={116} ring ringClass="ring-4 ring-[#1B1A17]" />
                </div>
                {showStars && <StarBurst seed={starSeed} />}
              </div>
              <div style={{ textAlign: "center" }}>
                <p style={{ fontSize: "24px", fontWeight: 500, color: "#1B1A17", letterSpacing: "-0.01em", margin: 0, fontFamily: "Plus Jakarta Sans, sans-serif" }}>
                  {revealedAvatar?.name ?? "—"}
                </p>
                <p style={{ fontSize: "12px", color: "#8B7E6A", marginTop: "3px" }}>
                  {rollCount === 1 ? "ได้เลยในครั้งแรก!" : `Summon ไปแล้ว ${rollCount} ครั้ง`}
                </p>
              </div>
            </>
          )}
        </div>

        {/* ── Footer ── */}
        <div className="px-7 py-5 flex gap-2" style={{ borderTop: "1px solid #EFE9DC" }}>
          {phase === "revealed" ? (
            <>
              <button
                onClick={summon}
                className="hover:bg-[#F2EDE3] transition"
                style={{ flex: 1, height: "44px", borderRadius: "999px", fontSize: "14px", fontWeight: 500, color: "#1B1A17", border: "1px solid #DDD9CE", background: "transparent", cursor: "pointer", display: "flex", alignItems: "center", justifyContent: "center", gap: "6px" }}
              >
                <RefreshCw size={15} strokeWidth={2} />
                Summon ใหม่
              </button>
              <button
                onClick={() => { onSelect(revealedId); onClose(); }}
                className="hover:bg-black transition"
                style={{ flex: 1, height: "44px", borderRadius: "999px", fontSize: "14px", fontWeight: 600, color: "white", background: "#1B1A17", border: "none", cursor: "pointer", display: "flex", alignItems: "center", justifyContent: "center", gap: "6px" }}
              >
                <Check size={15} strokeWidth={2.5} />
                เลือกตัวนี้
              </button>
            </>
          ) : (
            <button
              onClick={onClose}
              className="hover:bg-[#F2EDE3] transition"
              style={{ flex: 1, height: "44px", borderRadius: "999px", fontSize: "14px", fontWeight: 500, color: "#1B1A17", border: "none", background: "transparent", cursor: "pointer" }}
            >
              ยกเลิก
            </button>
          )}
        </div>
      </div>
    </div>
  );
};

window.AvatarPicker = AvatarPicker;
