/* eslint-disable */
// Pack opening: plays a pre-rendered video of the whole reveal, chosen by
// pack tier (animation style) + drawn card, so it matches the server's draw.
//
//   file:  animations/OUT_<PackTier>_<CardNum>.webm
//   tier:  cozy→Common  shimmer→Rare  moonlit→Epic  starlight→Legendary
//          craft→Minecraft (eigene Animation pro Minecraft-Karte, 01–18)
//   num:   card.num "001/010" → "01" … "010/010" → "10" ("018/018" → "18")
//
// Inventory is server-authoritative: /api/open already wrote owned_cards
// before mount, so we just play the clip and refresh the parent on close.

const { useRef: usePoRef, useState: usePoState, useEffect: usePoEffect } = React;

// pack.id or tier_key → animation-style prefix in the video filenames.
const PACK_TIER_PREFIX = {
  cozy: "Common", shimmer: "Rare", moonlit: "Epic", starlight: "Legendary",
  common: "Common", rare: "Rare", epic: "Epic", legend: "Legendary",
  craft: "Minecraft", minecraft: "Minecraft",
};
// Stable order, fallback when a card lacks a parseable num.
const CARD_ID_ORDER = ["c01", "c02", "c03", "c04", "r01", "r02", "r03", "e01", "e02", "l01"];

function poTierPrefix(pack, card) {
  // Minecraft-Karten haben nur Minecraft-Animationen (egal aus welchem Pack).
  if (card && card.rarity === "special") return "Minecraft";
  if (!pack) return "Common";
  return PACK_TIER_PREFIX[pack.id] ||
         PACK_TIER_PREFIX[pack.tierKey] ||
         PACK_TIER_PREFIX[pack.tier_key] ||
         PACK_TIER_PREFIX[pack.tier] ||
         "Common";
}
function poCardNum(card) {
  const n = card && card.num ? parseInt(String(card.num), 10) : NaN;
  const max = card && card.rarity === "special" ? 18 : 10;
  if (Number.isFinite(n) && n >= 1 && n <= max) return String(n).padStart(2, "0");
  const idx = card ? CARD_ID_ORDER.indexOf(card.id) : -1;
  return String((idx >= 0 ? idx : 0) + 1).padStart(2, "0");
}
function poVideoSrc(pack, card) {
  return "animations/OUT_" + poTierPrefix(pack, card) + "_" + poCardNum(card) + ".webm";
}

function PackOpening({ pack, cards, onClose }) {
  const card = (cards && cards[0]) || null;
  const videoRef = usePoRef(null);
  const [phase, setPhase] = usePoState("idle");   // idle | playing | done
  const src = poVideoSrc(pack, card);

  const rarityLabel = (window.RARITY_LABEL && card && window.RARITY_LABEL[card.rarity]) ||
                      (card ? card.rarity : "");

  function start() {
    if (phase !== "idle") return;
    setPhase("playing");
    const v = videoRef.current;
    if (!v) { setPhase("done"); return; }
    v.currentTime = 0;
    const p = v.play();
    if (p && p.catch) p.catch(() => setPhase("done"));  // playback blocked → skip to result
  }
  function skip() {
    const v = videoRef.current;
    if (v && isFinite(v.duration) && v.duration > 0) v.currentTime = Math.max(0, v.duration - 0.04);
    else setPhase("done");
  }
  function onEnded() { setPhase("done"); }

  // Nudge to the first frame so idle shows the pack, not a black box
  // (some browsers don't paint a frame until play).
  function onLoaded() {
    const v = videoRef.current;
    if (v && phase === "idle" && v.currentTime === 0) { try { v.currentTime = 0.04; } catch (e) {} }
  }

  function onStageClick() {
    if (phase === "idle") start();
    else if (phase === "playing") skip();
  }

  usePoEffect(() => {
    function onKey(e) {
      if (e.key === "Escape") { onClose(); return; }
      if (e.key === " " || e.key === "Enter") {
        e.preventDefault();
        if (phase === "idle") start();
        else if (phase === "playing") skip();
        else if (phase === "done") onClose();
      }
    }
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [phase]);

  return (
    <div className={`po3d-overlay po-video-overlay ${card && card.rarity === "special" ? "po-mc" : ""}`}>
      <button className="po-close" onClick={onClose} title="Schließen">✕</button>

      <div className="po-video-stage" onClick={onStageClick}>
        <video
          ref={videoRef}
          className="po-video"
          src={src}
          playsInline
          preload="auto"
          onLoadedData={onLoaded}
          onEnded={onEnded}
        />
        {phase === "idle" && <div className="po-hint po-video-hint">Klick zum Öffnen</div>}
        {phase === "playing" && <div className="po-hint po-video-hint">Klick zum Überspringen</div>}
      </div>

      {phase === "done" && (
        <div className="po-video-result">
          {card && window.TCGCard && (
            <div className="po-result-card">
              {card.isNew && <div className="po-new-badge">Neu</div>}
              <TCGCard card={card} size={300} flipped interactive />
            </div>
          )}
          {card && (
            <div className="po-video-caption">
              <span className={"po-rarity po-rarity-" + card.rarity}>{rarityLabel}</span>
              <strong>{card.name}</strong>
            </div>
          )}
          <div className="po-actions show">
            <button className="btn" onClick={onClose}>Schließen</button>
            <button className="btn btn-primary" onClick={onClose}>Weiter sammeln</button>
          </div>
        </div>
      )}
    </div>
  );
}

Object.assign(window, { PackOpening });
