// RandomGroup.jsx — slot-machine reveal of the agent's FIXED assigned group
// (the spin is cosmetic; the result comes from the persisted backend assignment,
//  so it never changes between visits)
function RandomGroup({ go, state, set, data }) {
  const groups = data.groups;

  // the agent's fixed group, decided at login from the persisted assignment
  const targetName = state.groupName || (state.me && data.assignments[state.me.id]) || groups[0].name;
  const targetIdx = Math.max(0, groups.findIndex((g) => g.name === targetName));

  const [phase, setPhase] = React.useState("idle"); // idle | spin | done
  const [idx, setIdx] = React.useState(targetIdx);
  const timer = React.useRef(null);

  const spin = () => {
    if (phase === "spin") return;
    setPhase("spin");
    let t = 0, speed = 60;
    const tick = () => {
      setIdx((i) => (i + 1) % groups.length);
      t += speed; speed += 7;
      if (t < 1700) timer.current = setTimeout(tick, speed);
      else {
        // land on the FIXED assigned group — no re-randomisation
        setIdx(targetIdx);
        set({ herd: groups[targetIdx] });
        setPhase("done");
      }
    };
    tick();
  };
  React.useEffect(() => () => clearTimeout(timer.current), []);

  const herd = groups[idx];
  return (
    <div className="min-h-[100dvh] w-full px-6 pt-12 pb-9 flex flex-col justify-between font-serif">
      <div>
        <button onClick={() => go("select")}
          className="self-start inline-flex items-center gap-1.5 -ml-1 mb-2 px-2.5 py-1.5 rounded-full
                     text-[13.5px] font-semibold text-safari-sun/90 hover:bg-white/10 transition-colors">
          <Icon name="arrow" className="w-4 h-4 rotate-180" /> กลับ
        </button>
        <FlowDots step={2} />
        <h1 className="text-[28px] font-semibold text-safari-grass mt-4 mb-0.5 text-center">
          {phase === "done" ? "ยินดีต้อนรับสู่..." : "สุ่มเข้าฝูง"}
        </h1>
        <p className="text-center text-[14px] text-safari-sun/85">
          {phase === "done" ? "ฝูงของคุณถูกเลือกแล้ว!" : "แตะปุ่มเพื่อเสี่ยงทายฝูงซาฟารี"}
        </p>
      </div>

      <div className="flex flex-col items-center gap-4">
        <div
          className={[
            "w-[230px] h-[230px] rounded-[36px] relative flex flex-col items-center justify-center transition-all duration-300",
            phase === "done" ? "scale-[1.04] ring-[6px] ring-safari-sun shadow-[0_20px_50px_rgba(0,0,0,0.5)]"
                             : phase === "spin" ? "scale-95 shadow-[0_16px_40px_rgba(0,0,0,0.45)]"
                             : "shadow-[0_16px_40px_rgba(0,0,0,0.45)]",
          ].join(" ")}
          style={{ background: `radial-gradient(circle at 40% 30%, ${herd.from}, ${herd.to})` }}>
          <div className={`text-[96px] leading-none ${phase === "spin" ? "blur-[1.5px]" : ""}`}>{herd.emoji}</div>
          <div className="font-display text-[22px] text-safari-grass mt-1.5 tracking-wide">{herd.en}</div>
          {phase === "done" && (
            <div className="absolute -top-3.5 -right-2.5 bg-safari-sun text-safari-mahogany font-serif font-bold text-[13px]
                            px-3 py-1.5 rounded-full rotate-[8deg] shadow-[0_4px_10px_rgba(0,0,0,0.3)]">YOU!</div>
          )}
        </div>
        <div className="text-[26px] font-bold text-safari-grass">{herd.name}</div>
        {phase === "done" && (
          <p className="text-[13.5px] text-safari-sun/90 text-center leading-snug">
            มีบั๊ดดี้รออยู่ในฝูงนี้<br />ค่อย ๆ เผยตัวให้รู้จักทุกสัปดาห์
          </p>
        )}
      </div>

      <div>
        {phase !== "done" ? (
          <SafariButton color="red" onClick={spin}>
            {phase === "spin" ? "กำลังสุ่ม..." : <>สุ่มเลย! <Icon name="dice" className="w-5 h-5" /></>}
          </SafariButton>
        ) : (
          <SafariButton color="gold" onClick={() => go("hint")}>
            ดูการ์ดบั๊ดดี้ <Icon name="arrow" className="w-5 h-5" />
          </SafariButton>
        )}
        <PageFooter />
      </div>
    </div>
  );
}

window.RandomGroup = RandomGroup;
