"use client";

import React, { useEffect, useRef, useState, useCallback } from "react";
import {
  X,
  Volume2,
  VolumeX,
  Sparkles,
  Check,
  RotateCcw,
  Coins,
} from "lucide-react";
import type { CrateTier, CrateReward } from "@/lib/crates-catalog";
import { RARITY_CONFIG } from "@/lib/crates-catalog";

interface CsCrateSpinnerProps {
  isOpen: boolean;
  crate: CrateTier;
  winningReward: CrateReward | null;
  duplicateRefund?: number;
  onFinish?: () => void;
  onClose: () => void;
  onEquip?: (reward: CrateReward) => void;
  equippedSuccess?: boolean;
  onOpenAnother?: () => void;
  canOpenAnother?: boolean;
  remainingCredits?: number;
}

const SLOT_WIDTH = 150; // 140px card + 10px margins
const WINNING_INDEX = 48; // Index where the winning item sits on the strip
const TOTAL_CARDS = 62; // Total cards on the reel
const SPIN_DURATION_MS = 5400; // CS2 style 5.4s spin duration

export default function CsCrateSpinner({
  isOpen,
  crate,
  winningReward,
  duplicateRefund,
  onFinish,
  onClose,
  onEquip,
  equippedSuccess = false,
  onOpenAnother,
  canOpenAnother = false,
  remainingCredits,
}: CsCrateSpinnerProps) {
  const [phase, setPhase] = useState<"idle" | "spinning" | "landed" | "revealed">("idle");
  const [reelItems, setReelItems] = useState<CrateReward[]>([]);
  const [muted, setMuted] = useState(false);
  const [translateX, setTranslateX] = useState(0);

  const containerRef = useRef<HTMLDivElement>(null);
  const audioCtxRef = useRef<AudioContext | null>(null);
  const lastTickCardRef = useRef<number>(-1);
  const animFrameRef = useRef<number | null>(null);

  // Initialize Web Audio API for ticking & win fanfare
  const getAudioContext = useCallback(() => {
    if (typeof window === "undefined") return null;
    if (!audioCtxRef.current) {
      const AudioCtx = window.AudioContext || (window as unknown as { webkitAudioContext: typeof AudioContext }).webkitAudioContext;
      if (AudioCtx) {
        audioCtxRef.current = new AudioCtx();
      }
    }
    if (audioCtxRef.current && audioCtxRef.current.state === "suspended") {
      audioCtxRef.current.resume();
    }
    return audioCtxRef.current;
  }, []);

  // Play CS2-style click tick
  const playTickSound = useCallback(() => {
    if (muted) return;
    try {
      const ctx = getAudioContext();
      if (!ctx) return;
      const osc = ctx.createOscillator();
      const gain = ctx.createGain();

      osc.type = "triangle";
      osc.frequency.setValueAtTime(950, ctx.currentTime);
      osc.frequency.exponentialRampToValueAtTime(140, ctx.currentTime + 0.025);

      gain.gain.setValueAtTime(0.09, ctx.currentTime);
      gain.gain.exponentialRampToValueAtTime(0.001, ctx.currentTime + 0.025);

      osc.connect(gain);
      gain.connect(ctx.destination);

      osc.start();
      osc.stop(ctx.currentTime + 0.028);
    } catch {}
  }, [muted, getAudioContext]);

  // Play triumphant win sound on landing
  const playWinSound = useCallback((rarity: string) => {
    if (muted) return;
    try {
      const ctx = getAudioContext();
      if (!ctx) return;
      const now = ctx.currentTime;

      // Chord frequencies based on rarity
      const isRare = ["rare", "epic", "legendary", "mythic"].includes(rarity);
      const chord = isRare ? [523.25, 659.25, 783.99, 1046.5] : [440, 554.37, 659.25];

      chord.forEach((freq, idx) => {
        const osc = ctx.createOscillator();
        const gain = ctx.createGain();
        osc.type = "sine";
        osc.frequency.setValueAtTime(freq, now + idx * 0.06);

        gain.gain.setValueAtTime(0.08, now + idx * 0.06);
        gain.gain.exponentialRampToValueAtTime(0.001, now + idx * 0.06 + 0.65);

        osc.connect(gain);
        gain.connect(ctx.destination);

        osc.start(now + idx * 0.06);
        osc.stop(now + idx * 0.06 + 0.7);
      });
    } catch {}
  }, [muted, getAudioContext]);

  // Populate strip and launch spin when winningReward is set
  useEffect(() => {
    if (!isOpen || !winningReward) {
      setPhase("idle");
      setTranslateX(0);
      return;
    }

    // Build the 62-card reel
    const loot = crate.lootTable.map((l) => l.reward);
    const strip: CrateReward[] = [];
    for (let i = 0; i < TOTAL_CARDS; i++) {
      if (i === WINNING_INDEX) {
        strip.push(winningReward);
      } else {
        const rand = loot[Math.floor(Math.random() * loot.length)];
        strip.push(rand);
      }
    }
    setReelItems(strip);
    setPhase("spinning");
    setTranslateX(0);
    lastTickCardRef.current = -1;

    // Small delay to allow initial layout render before applying transition transform
    const startTimer = setTimeout(() => {
      const container = containerRef.current;
      const containerWidth = container ? container.clientWidth : 700;

      // Card center position for winning index
      const cardCenter = WINNING_INDEX * SLOT_WIDTH + SLOT_WIDTH / 2;
      // Slight organic jitter between -38px and +38px so it doesn't land dead center
      const jitter = (Math.random() - 0.5) * 76;
      const targetX = Math.round(cardCenter - containerWidth / 2 + jitter);

      setTranslateX(targetX);

      // Track card crossing for tick audio
      const startTime = performance.now();
      const trackTick = () => {
        const elapsed = performance.now() - startTime;
        if (elapsed < SPIN_DURATION_MS) {
          // CS2 ease progress approximation: 1 - Math.pow(1 - t, 3.8)
          const t = Math.min(1, elapsed / SPIN_DURATION_MS);
          const ease = 1 - Math.pow(1 - t, 3.8);
          const currentX = ease * targetX;
          const currentCenterOffset = currentX + containerWidth / 2;
          const currentCardIdx = Math.floor(currentCenterOffset / SLOT_WIDTH);

          if (currentCardIdx !== lastTickCardRef.current && currentCardIdx >= 0) {
            lastTickCardRef.current = currentCardIdx;
            playTickSound();
          }

          animFrameRef.current = requestAnimationFrame(trackTick);
        }
      };

      animFrameRef.current = requestAnimationFrame(trackTick);
    }, 60);

    // Landed event at end of transition
    const landTimer = setTimeout(() => {
      if (animFrameRef.current) cancelAnimationFrame(animFrameRef.current);
      setPhase("landed");
      playWinSound(winningReward.rarity);
      onFinish?.();
    }, SPIN_DURATION_MS + 80);

    // Full reveal event
    const revealTimer = setTimeout(() => {
      setPhase("revealed");
    }, SPIN_DURATION_MS + 850);

    return () => {
      clearTimeout(startTimer);
      clearTimeout(landTimer);
      clearTimeout(revealTimer);
      if (animFrameRef.current) cancelAnimationFrame(animFrameRef.current);
    };
  }, [isOpen, winningReward, crate, playTickSound, playWinSound, onFinish]);

  if (!isOpen) return null;

  const winningRarity = winningReward ? RARITY_CONFIG[winningReward.rarity] : RARITY_CONFIG.common;

  return (
    <div className="csSpinnerOverlay">
      <div className="csSpinnerModal">
        {/* Top Header */}
        <div className="csSpinnerHeader">
          <div className="csSpinnerTitle">
            <span className="csSpinnerCrateBadge" style={{ borderColor: crate.color, color: crate.color }}>
              {crate.name}
            </span>
            <h3>Case Opening</h3>
          </div>

          <div className="csSpinnerControls">
            {typeof remainingCredits === "number" && (
              <span className="csBalanceBadge">
                <Coins size={13} />
                <span>{remainingCredits.toLocaleString()}</span>
              </span>
            )}
            <button
              type="button"
              className="csIconBtn"
              onClick={() => setMuted((m) => !m)}
              title={muted ? "Unmute" : "Mute"}
            >
              {muted ? <VolumeX size={16} /> : <Volume2 size={16} />}
            </button>
            <button
              type="button"
              className="csIconBtn"
              onClick={onClose}
              disabled={phase === "spinning"}
              title="Close"
            >
              <X size={16} />
            </button>
          </div>
        </div>

        {/* Carousel Spinning Reel */}
        <div className="csCarouselArea" ref={containerRef}>
          {/* Top and Bottom CS2 Needle Pointers */}
          <div className="csCenterNeedleWrap">
            <div className="csNeedleTop" />
            <div className="csNeedleLine" />
            <div className="csNeedleBottom" />
          </div>

          {/* Left & Right Shadow Gradients */}
          <div className="csReelFadeLeft" />
          <div className="csReelFadeRight" />

          {/* Scrolling Strip */}
          <div
            className="csCardsStrip"
            style={{
              transform: `translate3d(-${translateX}px, 0, 0)`,
              transition: phase === "spinning" ? `transform ${SPIN_DURATION_MS}ms cubic-bezier(0.12, 0.8, 0.22, 1)` : "none",
            }}
          >
            {reelItems.map((item, idx) => {
              const rarity = RARITY_CONFIG[item.rarity];
              const isWinner = idx === WINNING_INDEX && (phase === "landed" || phase === "revealed");

              return (
                <div
                  key={`${item.id}-${idx}`}
                  className={`csItemCard ${isWinner ? "winnerCardGlow" : ""}`}
                  style={{
                    borderBottomColor: rarity.color,
                    background: isWinner
                      ? `linear-gradient(180deg, ${rarity.bg} 0%, rgba(13, 16, 24, 0.95) 100%)`
                      : "rgba(18, 22, 33, 0.75)",
                    boxShadow: isWinner ? `0 0 35px ${rarity.glow}` : "none",
                  }}
                >
                  <div className="csCardRarityStripe" style={{ background: rarity.color }} />
                  <div className="csCardVisual">
                    {item.previewUrl ? (
                      // eslint-disable-next-line @next/next/no-img-element
                      <img src={item.previewUrl} alt="" className="csCardImg" />
                    ) : (
                      <span className="csCardIcon">{item.icon || "🎁"}</span>
                    )}
                  </div>
                  <div className="csCardInfo">
                    <span className="csCardName" title={item.name}>
                      {item.name}
                    </span>
                    <span className="csCardType" style={{ color: rarity.color }}>
                      {rarity.label}
                    </span>
                  </div>
                </div>
              );
            })}
          </div>
        </div>

        {/* Revealed Win Dialog */}
        {phase === "revealed" && winningReward && (
          <div className="csWonContainer animateFadeIn">
            <div
              className="csWonHeader"
              style={{
                borderColor: winningRarity.border,
                background: winningRarity.bg,
              }}
            >
              <div className="csWonBadgeRow">
                <span
                  className="csWonRarityPill"
                  style={{
                    background: winningRarity.bg,
                    color: winningRarity.color,
                    borderColor: winningRarity.border,
                  }}
                >
                  {winningRarity.label} Drop
                </span>
                {duplicateRefund && (
                  <span className="csDuplicatePill">
                    <Coins size={12} />
                    <span>Duplicate: +{duplicateRefund} Credits</span>
                  </span>
                )}
              </div>

              <h2 className="csWonName" style={{ color: winningRarity.color }}>
                {winningReward.name}
              </h2>
              <p className="csWonDesc">{winningReward.description}</p>
            </div>

            {/* Actions */}
            <div className="csWonActions">
              {winningReward.itemId &&
                !duplicateRefund &&
                ["avatar_frame", "avatar_decoration", "card_frame"].includes(winningReward.type) &&
                onEquip && (
                  <button
                    type="button"
                    className="csEquipBtn"
                    onClick={() => onEquip(winningReward)}
                    disabled={equippedSuccess}
                  >
                    {equippedSuccess ? <Check size={14} /> : <Sparkles size={14} />}
                    <span>{equippedSuccess ? "Equipped on profile" : "Equip to profile"}</span>
                  </button>
                )}

              {canOpenAnother && onOpenAnother && (
                <button type="button" className="csAnotherBtn" onClick={onOpenAnother}>
                  <RotateCcw size={14} />
                  <span>Open Another ({crate.price} Credits)</span>
                </button>
              )}

              <button type="button" className="csDoneBtn" onClick={onClose}>
                Done
              </button>
            </div>
          </div>
        )}

        {/* Spinning Status Footer */}
        {phase === "spinning" && (
          <div className="csSpinningNotice">
            <div className="csSpinLoader" />
            <span>Decelerating vault roll...</span>
          </div>
        )}
      </div>

      <style jsx>{`
        .csSpinnerOverlay {
          position: fixed;
          inset: 0;
          z-index: 9999;
          display: flex;
          align-items: center;
          justify-content: center;
          background: rgba(3, 4, 8, 0.88);
          backdrop-filter: blur(14px);
          -webkit-backdrop-filter: blur(14px);
          padding: 16px;
          animation: csFadeIn 0.25s ease-out forwards;
        }
        @keyframes csFadeIn {
          from { opacity: 0; }
          to { opacity: 1; }
        }

        .csSpinnerModal {
          position: relative;
          width: 100%;
          max-width: 880px;
          background: #090c14;
          border: 1px solid rgba(0, 0, 0, 0.12);
          border-radius: 18px;
          box-shadow: 0 24px 60px -10px rgba(0, 0, 0, 0.85), 0 0 40px rgba(248, 227, 227, 0.08);
          padding: 24px;
          display: flex;
          flex-direction: column;
          gap: 18px;
          overflow: hidden;
        }

        .csSpinnerHeader {
          display: flex;
          align-items: center;
          justify-content: space-between;
          padding-bottom: 12px;
          border-bottom: 1px solid rgba(0, 0, 0, 0.08);
        }
        .csSpinnerTitle {
          display: flex;
          align-items: center;
          gap: 12px;
        }
        .csSpinnerTitle h3 {
          font-size: 17px;
          font-weight: 700;
          color: #c80404;
          margin: 0;
          letter-spacing: -0.01em;
        }
        .csSpinnerCrateBadge {
          font-size: 11px;
          font-weight: 700;
          text-transform: uppercase;
          letter-spacing: 0.06em;
          padding: 3px 10px;
          border-radius: 999px;
          border: 1px solid;
          background: rgba(0, 0, 0, 0.03);
        }

        .csSpinnerControls {
          display: flex;
          align-items: center;
          gap: 8px;
        }
        .csBalanceBadge {
          display: inline-flex;
          align-items: center;
          gap: 6px;
          padding: 4px 10px;
          border-radius: 8px;
          background: rgba(0, 0, 0, 0.04);
          border: 1px solid rgba(0, 0, 0, 0.08);
          color: #9b0707;
          font-size: 12px;
          font-weight: 700;
        }
        .csIconBtn {
          display: inline-flex;
          align-items: center;
          justify-content: center;
          width: 34px;
          height: 34px;
          border-radius: 10px;
          background: rgba(0, 0, 0, 0.05);
          border: 1px solid rgba(0, 0, 0, 0.1);
          color: #551212;
          cursor: pointer;
          transition: all 0.15s ease;
        }
        .csIconBtn:hover:not(:disabled) {
          color: #000;
          background: rgba(0, 0, 0, 0.1);
          border-color: rgba(0, 0, 0, 0.2);
        }
        .csIconBtn:disabled {
          opacity: 0.4;
          cursor: not-allowed;
        }

        /* Carousel Box */
        .csCarouselArea {
          position: relative;
          width: 100%;
          height: 200px;
          background: #06080e;
          border: 1px solid rgba(0, 0, 0, 0.12);
          border-radius: 14px;
          overflow: hidden;
          display: flex;
          align-items: center;
        }

        /* Center Needles */
        .csCenterNeedleWrap {
          position: absolute;
          inset: 0;
          pointer-events: none;
          z-index: 20;
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: space-between;
        }
        .csNeedleTop {
          width: 0;
          height: 0;
          border-left: 10px solid transparent;
          border-right: 10px solid transparent;
          border-top: 14px solid #faefef;
          filter: drop-shadow(0 2px 8px rgba(250, 239, 239, 0.8));
        }
        .csNeedleLine {
          width: 2px;
          height: 100%;
          background: linear-gradient(180deg, #faefef 0%, rgba(250, 239, 239, 0.6) 50%, #faefef 100%);
          box-shadow: 0 0 10px rgba(250, 239, 239, 0.7);
        }
        .csNeedleBottom {
          width: 0;
          height: 0;
          border-left: 10px solid transparent;
          border-right: 10px solid transparent;
          border-bottom: 14px solid #faefef;
          filter: drop-shadow(0 -2px 8px rgba(250, 239, 239, 0.8));
        }

        /* Fades */
        .csReelFadeLeft,
        .csReelFadeRight {
          position: absolute;
          top: 0;
          bottom: 0;
          width: 18%;
          pointer-events: none;
          z-index: 10;
        }
        .csReelFadeLeft {
          left: 0;
          background: linear-gradient(90deg, #06080e 0%, rgba(6, 8, 14, 0) 100%);
        }
        .csReelFadeRight {
          right: 0;
          background: linear-gradient(270deg, #06080e 0%, rgba(6, 8, 14, 0) 100%);
        }

        /* Cards Strip */
        .csCardsStrip {
          display: flex;
          align-items: center;
          will-change: transform;
          padding-left: 8px;
        }

        .csItemCard {
          flex: none;
          width: 140px;
          height: 165px;
          margin: 0 5px;
          border-radius: 12px;
          border: 1px solid rgba(0, 0, 0, 0.08);
          border-bottom: 4px solid;
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: space-between;
          padding: 10px 8px 12px;
          position: relative;
          overflow: hidden;
          box-sizing: border-box;
          transition: transform 0.2s ease, box-shadow 0.2s ease;
        }

        .csCardRarityStripe {
          position: absolute;
          top: 0;
          left: 0;
          right: 0;
          height: 2px;
          opacity: 0.85;
        }

        .csCardVisual {
          width: 80px;
          height: 80px;
          display: flex;
          align-items: center;
          justify-content: center;
          margin-top: 10px;
        }
        .csCardImg {
          max-width: 100%;
          max-height: 100%;
          object-fit: contain;
          filter: drop-shadow(0 4px 10px rgba(0, 0, 0, 0.6));
        }
        .csCardIcon {
          font-size: 42px;
          line-height: 1;
          filter: drop-shadow(0 4px 8px rgba(0, 0, 0, 0.5));
        }

        .csCardInfo {
          width: 100%;
          text-align: center;
          display: flex;
          flex-direction: column;
          gap: 2px;
        }
        .csCardName {
          font-size: 12px;
          font-weight: 700;
          color: #9b0707;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
        }
        .csCardType {
          font-size: 10px;
          font-weight: 600;
          text-transform: uppercase;
          letter-spacing: 0.05em;
        }

        .winnerCardGlow {
          transform: scale(1.05);
          z-index: 15;
          animation: winnerPulse 1.2s ease-in-out infinite alternate;
        }
        @keyframes winnerPulse {
          from { filter: brightness(1); }
          to { filter: brightness(1.2); }
        }

        /* Won View */
        .csWonContainer {
          display: flex;
          flex-direction: column;
          gap: 16px;
        }
        .csWonHeader {
          border: 1px solid;
          border-radius: 14px;
          padding: 18px;
          text-align: center;
          display: flex;
          flex-direction: column;
          align-items: center;
          gap: 6px;
        }
        .csWonBadgeRow {
          display: flex;
          align-items: center;
          gap: 8px;
          margin-bottom: 4px;
        }
        .csWonRarityPill {
          font-size: 11px;
          font-weight: 700;
          text-transform: uppercase;
          padding: 3px 10px;
          border-radius: 999px;
          border: 1px solid;
        }
        .csDuplicatePill {
          display: inline-flex;
          align-items: center;
          gap: 5px;
          font-size: 11px;
          font-weight: 600;
          color: #fbf1f1;
          background: rgba(251, 241, 241, 0.12);
          border: 1px solid rgba(251, 241, 241, 0.25);
          padding: 3px 9px;
          border-radius: 999px;
        }
        .csWonName {
          font-size: 22px;
          font-weight: 800;
          margin: 0;
          letter-spacing: -0.01em;
        }
        .csWonDesc {
          font-size: 13px;
          color: #551212;
          max-width: 480px;
          margin: 0;
        }

        .csWonActions {
          display: flex;
          align-items: center;
          justify-content: center;
          gap: 10px;
          flex-wrap: wrap;
        }
        .csEquipBtn {
          display: inline-flex;
          align-items: center;
          gap: 7px;
          padding: 10px 18px;
          border-radius: 12px;
          font-size: 13px;
          font-weight: 700;
          color: #000;
          background: #f6dbdb;
          border: 1px solid #fae5e5;
          cursor: pointer;
          transition: all 0.15s ease;
        }
        .csEquipBtn:hover:not(:disabled) {
          background: #ebbdbd;
        }
        .csEquipBtn:disabled {
          background: rgba(246, 219, 219, 0.3);
          border-color: rgba(250, 229, 229, 0.3);
          color: #fdeeee;
          cursor: default;
        }
        .csAnotherBtn {
          display: inline-flex;
          align-items: center;
          gap: 7px;
          padding: 10px 18px;
          border-radius: 12px;
          font-size: 13px;
          font-weight: 700;
          color: #c80404;
          background: rgba(0, 0, 0, 0.08);
          border: 1px solid rgba(0, 0, 0, 0.15);
          cursor: pointer;
          transition: all 0.15s ease;
        }
        .csAnotherBtn:hover {
          background: rgba(0, 0, 0, 0.14);
          border-color: rgba(0, 0, 0, 0.25);
        }
        .csDoneBtn {
          padding: 10px 18px;
          border-radius: 12px;
          font-size: 13px;
          font-weight: 600;
          color: #551212;
          background: transparent;
          border: 1px solid rgba(0, 0, 0, 0.1);
          cursor: pointer;
          transition: all 0.15s ease;
        }
        .csDoneBtn:hover {
          color: #000;
          background: rgba(0, 0, 0, 0.05);
        }

        .csSpinningNotice {
          display: flex;
          align-items: center;
          justify-content: center;
          gap: 10px;
          color: #551212;
          font-size: 12.5px;
          font-weight: 500;
          padding-top: 4px;
        }
        .csSpinLoader {
          width: 14px;
          height: 14px;
          border: 2px solid rgba(0, 0, 0, 0.15);
          border-top-color: #f8e3e3;
          border-radius: 50%;
          animation: spin 0.8s linear infinite;
        }
        @keyframes spin {
          to { transform: rotate(360deg); }
        }
      `}</style>
    </div>
  );
}
