"use client";

import { useEffect, useMemo, useRef, useState } from "react";
import Link from "next/link";
import { Timer, Trophy, Play, RotateCcw, CheckCircle2, XCircle, Zap, Star, Moon, Sun, Heart, Flower2, Crown, Gem, Leaf, Music4 } from "lucide-react";
import { submitContestResult, submitGameResult } from "@/lib/actions";
import { faNum } from "@/lib/jalali";

const faDigit = (n: number | string) => String(n).replace(/[0-9]/g, (d) => "۰۱۲۳۴۵۶۷۸۹"[+d]);

/* ================= مسابقه ================= */
export function ContestTaker({ contestId, title, timeMin, questions }: {
  contestId: number; title: string; timeMin: number;
  questions: { q: string; options: string[]; answerIndex: number }[];
}) {
  const [idx, setIdx] = useState(-1); // -1 = شروع
  const [answers, setAnswers] = useState<number[]>([]);
  const [left, setLeft] = useState(timeMin * 60);
  const [result, setResult] = useState<{ score: number; saved: boolean } | null>(null);
  const startedAt = useRef<number>(0);

  const finish = async (ans: number[]) => {
    let s = 0;
    questions.forEach((q, i) => { if (ans[i] === q.answerIndex) s++; });
    const dur = Math.round((Date.now() - startedAt.current) / 1000);
    const res = await submitContestResult(contestId, s, questions.length, dur);
    setResult({ score: s, saved: !!res.ok });
  };

  useEffect(() => {
    if (idx < 0 || result) return;
    const t = setInterval(() => setLeft((v) => {
      if (v <= 1) { clearInterval(t); finish(answers); return 0; }
      return v - 1;
    }), 1000);
    return () => clearInterval(t);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [idx >= 0, result]);

  if (idx < 0) return <Intro title={title} meta={`${faNum(questions.length)} سؤال — ${faNum(timeMin)} دقیقه`} onStart={() => { startedAt.current = Date.now(); setIdx(0); }} />;

  if (result) {
    const pct = Math.round((result.score / questions.length) * 100);
    return (
      <div className="anim-pop rounded-3xl border border-amber-300 bg-white p-8 text-center shadow-2xl">
        <Trophy size={52} className="mx-auto text-amber-500" />
        <h2 className="mt-3 text-2xl font-black text-emerald-950">پایان مسابقه!</h2>
        <div className="mx-auto mt-5 w-fit rounded-2xl bg-gradient-to-br from-amber-400 to-amber-600 px-8 py-4 text-white shadow-lg">
          <div className="text-4xl font-black">{faNum(pct)}٪</div>
          <div className="text-xs font-bold opacity-90">{faNum(result.score)} صحیح از {faNum(questions.length)}</div>
        </div>
        <p className="mt-4 flex items-center justify-center gap-1.5 text-xs font-bold text-emerald-800/70">{result.saved ? <><CheckCircle2 size={14} className="text-emerald-600" /> نتیجه در سامانه ثبت شد</> : ""}</p>
        <Link href="/" className="mt-5 inline-flex items-center gap-1.5 rounded-xl bg-emerald-700 px-6 py-3 text-sm font-black text-white">صفحهٔ اصلی</Link>
      </div>
    );
  }

  const q = questions[idx];
  const mm = Math.floor(left / 60), ss = String(left % 60).padStart(2, "0");
  return (
    <div className="rounded-3xl border border-emerald-900/10 bg-white p-6 shadow-xl">
      <div className="mb-4 flex items-center justify-between">
        <div className="flex items-center gap-1.5 text-sm font-black text-emerald-950" dir="ltr">
          <Timer size={16} className={left < 60 ? "text-red-500" : "text-emerald-700"} /> {faDigit(`${mm}:${ss}`)}
        </div>
        <div className="text-xs font-bold text-emerald-800/60">سؤال {faNum(idx + 1)} از {faNum(questions.length)}</div>
      </div>
      <div className="mb-5 h-2 overflow-hidden rounded-full bg-emerald-900/10" dir="ltr">
        <div className="h-full rounded-full bg-gradient-to-r from-amber-400 to-emerald-600 transition-all" style={{ width: `${((idx) / questions.length) * 100}%` }} />
      </div>
      <p className="mb-5 min-h-14 text-base font-extrabold leading-8 text-emerald-950">{q.q}</p>
      <div className="grid gap-2.5 sm:grid-cols-2">
        {q.options.map((op, i) => (
          <button key={i}
            onClick={() => {
              const na = [...answers]; na[idx] = i; setAnswers(na);
              if (idx + 1 < questions.length) setIdx(idx + 1);
              else finish(na);
            }}
            className="rounded-xl border-2 border-emerald-900/12 bg-white px-4 py-3.5 text-right text-sm font-bold text-emerald-950 transition hover:border-amber-500 hover:bg-amber-50 active:scale-[0.98]">
            <span className="ml-2 inline-grid size-6 place-items-center rounded-md bg-emerald-700 text-[11px] text-white">{faNum(i + 1)}</span>
            {op}
          </button>
        ))}
      </div>
      <button onClick={() => finish(answers)} className="mt-4 text-xs font-bold text-red-600 hover:underline">اتمام زودهنگام مسابقه</button>
    </div>
  );
}

/* ================= قاب بازی ================= */
function Intro({ title, meta, onStart }: { title: string; meta: string; onStart: () => void }) {
  return (
    <div className="anim-pop rounded-3xl border border-emerald-900/10 bg-white p-8 text-center shadow-2xl">
      <div className="mx-auto mb-4 grid size-16 place-items-center rounded-2xl bg-gradient-to-br from-amber-400 to-amber-600 text-white shadow-lg"><Play size={28} /></div>
      <h2 className="text-2xl font-black text-emerald-950">{title}</h2>
      <p className="mt-2 text-sm font-bold text-emerald-800/60">{meta}</p>
      <button onClick={onStart} className="btn-gold mt-6 rounded-2xl px-10 py-3.5 text-base font-black text-white transition active:scale-[0.97]">شروع!</button>
    </div>
  );
}
function GameOver({ score, onReplay }: { score: number; onReplay: () => void; }) {
  return (
    <div className="anim-pop rounded-3xl border border-amber-300 bg-white p-8 text-center shadow-2xl">
      <Trophy size={52} className="mx-auto text-amber-500" />
      <h2 className="mt-3 text-xl font-black text-emerald-950">پایان بازی</h2>
      <div className="mx-auto mt-4 w-fit rounded-2xl bg-gradient-to-br from-emerald-700 to-emerald-900 px-10 py-4 text-white shadow-lg">
        <div className="text-xs font-bold text-emerald-100/80">امتیاز شما</div>
        <div className="mt-0.5 text-4xl font-black">{faNum(Math.max(0, Math.round(score)))}</div>
      </div>
      <div className="mt-6 flex justify-center gap-3">
        <button onClick={onReplay} className="inline-flex items-center gap-1.5 rounded-xl bg-emerald-700 px-5 py-3 text-sm font-black text-white"><RotateCcw size={15} /> دوباره</button>
        <Link href="/" className="inline-flex items-center gap-1.5 rounded-xl border border-emerald-900/15 bg-white px-5 py-3 text-sm font-black text-emerald-800">صفحهٔ اصلی</Link>
      </div>
    </div>
  );
}

export function GameRunner({ gameId, title, engine, level, words }: {
  gameId: number; title: string; engine: string; level: number; words: string[];
}) {
  const [phase, setPhase] = useState<"intro" | "play" | "over">("intro");
  const [score, setScore] = useState(0);
  const save = async (sc: number) => {
    setScore(sc);
    await submitGameResult(gameId, Math.max(0, Math.round(sc)));
    setPhase("over");
  };
  if (phase === "intro") return <Intro title={title} meta={`سطح ${faNum(level)}`} onStart={() => setPhase("play")} />;
  if (phase === "over") return <GameOver score={score} onReplay={() => setPhase("play")} />;
  switch (engine) {
    case "timestable": return <TimesTable level={level} onFinish={save} />;
    case "memory": return <MemoryGame level={level} onFinish={save} />;
    case "scramble": return <ScrambleGame words={words} onFinish={save} />;
    case "reaction": return <ReactionGame onFinish={save} />;
    default: return <SpeedMath level={level} onFinish={save} />;
  }
}

/* ---------- سرعت ریاضی ---------- */
function SpeedMath({ level, onFinish }: { level: number; onFinish: (s: number) => void }) {
  const gen = () => {
    const r = Math.random;
    const ops = level === 1 ? ["+", "-"] : level === 2 ? ["+", "-", "×"] : ["+", "-", "×", "÷"];
    const op = ops[Math.floor(r() * ops.length)];
    const max = level === 1 ? 20 : level === 2 ? 50 : 99;
    let a = 1 + Math.floor(r() * max), b = 1 + Math.floor(r() * (op === "×" ? (level === 2 ? 9 : 12) : max));
    if (op === "-") { if (b > a) [a, b] = [b, a]; }
    if (op === "÷") { b = 2 + Math.floor(r() * 9); a = b * (1 + Math.floor(r() * (level === 3 ? 15 : 9))); }
    const ans = op === "+" ? a + b : op === "-" ? a - b : op === "×" ? a * b : a / b;
    return { text: `${faDigit(a)} ${op} ${faDigit(b)} = ؟`, ans };
  };
  const [q, setQ] = useState(gen);
  const [inp, setInp] = useState("");
  const [left, setLeft] = useState(60);
  const [correct, setCorrect] = useState(0);
  const [flash, setFlash] = useState<"ok" | "no" | null>(null);
  const inputRef = useRef<HTMLInputElement>(null);

  useEffect(() => {
    const t = setInterval(() => setLeft((v) => { if (v <= 1) { clearInterval(t); return 0; } return v - 1; }), 1000);
    return () => clearInterval(t);
  }, []);
  useEffect(() => { if (left === 0) onFinish(correct); }, [left, correct, onFinish]);
  useEffect(() => { inputRef.current?.focus(); }, [q]);

  const check = () => {
    if (!inp.trim()) return;
    const val = Number(inp.replace(/[۰-۹]/g, (d) => String("۰۱۲۳۴۵۶۷۸۹".indexOf(d))));
    if (val === q.ans) { setCorrect((c) => c + 1); setFlash("ok"); } else setFlash("no");
    setTimeout(() => setFlash(null), 250);
    setInp("");
    setQ(gen());
  };
  return (
    <div className={`rounded-3xl border-4 p-8 text-center shadow-2xl transition ${flash === "ok" ? "border-emerald-400 bg-emerald-50" : flash === "no" ? "border-red-400 bg-red-50" : "border-emerald-900/10 bg-white"}`}>
      <div className="mb-4 flex items-center justify-between text-sm font-black text-emerald-900">
        <span className="flex items-center gap-1" dir="ltr"><Timer size={15} /> {faDigit(left)}</span>
        <span className="flex items-center gap-1"><Zap size={15} className="text-amber-500" /> صحیح: {faNum(correct)}</span>
      </div>
      <div className="rounded-2xl bg-emerald-950 py-8 text-4xl font-black tracking-wider text-amber-300 shadow-inner">{q.text}</div>
      <div className="mx-auto mt-6 flex max-w-xs gap-2">
        <input ref={inputRef} value={inp} onChange={(e) => setInp(e.target.value)} onKeyDown={(e) => e.key === "Enter" && check()}
          inputMode="numeric" placeholder="؟" className="w-full rounded-xl border-2 border-emerald-900/15 px-4 py-3.5 text-center text-2xl font-black outline-none focus:border-emerald-600" dir="ltr" />
        <button onClick={check} className="btn-gold rounded-xl px-5 font-black text-white">✓</button>
      </div>
    </div>
  );
}

/* ---------- جدول ضرب ---------- */
function TimesTable({ level, onFinish }: { level: number; onFinish: (s: number) => void }) {
  const qs = useMemo(() => {
    const out: { a: number; b: number }[] = [];
    const maxA = level === 1 ? 6 : 12;
    for (let i = 0; i < 10; i++) out.push({ a: 2 + Math.floor(Math.random() * (maxA - 1)), b: 1 + Math.floor(Math.random() * 9) });
    return out;
  }, [level]);
  const [idx, setIdx] = useState(0);
  const [answers, setAnswers] = useState<string[]>([]);
  const q = qs[idx];
  if (idx >= qs.length) return <TimesResult qs={qs} answers={answers} onFinish={onFinish} />;
  return (
    <div className="rounded-3xl border border-emerald-900/10 bg-white p-8 text-center shadow-2xl">
      <div className="mb-4 text-xs font-bold text-emerald-800/60">سؤال {faNum(idx + 1)} از {faNum(qs.length)}</div>
      <div className="rounded-2xl bg-amber-50 py-8 text-3xl font-black text-emerald-950 ring-1 ring-amber-200">{faDigit(q.a)} × {faDigit(q.b)} = ؟</div>
      <form className="mx-auto mt-6 flex max-w-xs gap-2" onSubmit={(e) => {
        e.preventDefault();
        const fd = new FormData(e.currentTarget);
        setAnswers((a) => [...a, String(fd.get("v") ?? "")]);
        setIdx(idx + 1);
        e.currentTarget.reset();
      }}>
        <input name="v" required autoFocus inputMode="numeric" className="w-full rounded-xl border-2 border-emerald-900/15 px-4 py-3.5 text-center text-2xl font-black outline-none focus:border-emerald-600" dir="ltr" />
        <button className="btn-gold rounded-xl px-5 font-black text-white">✓</button>
      </form>
    </div>
  );
}
function TimesResult({ qs, answers, onFinish }: { qs: { a: number; b: number }[]; answers: string[]; onFinish: (s: number) => void }) {
  let ok = 0;
  qs.forEach((q, i) => { const v = Number((answers[i] ?? "").replace(/[۰-۹]/g, (d) => String("۰۱۲۳۴۵۶۷۸۹".indexOf(d)))); if (v === q.a * q.b) ok++; });
  useEffect(() => { onFinish(ok * 10); }, []); // eslint-disable-line
  return null;
}

/* ---------- حافظه تصویری ---------- */
const MEM_ICONS = [Star, Moon, Sun, Heart, Zap, Flower2, Crown, Gem, Leaf, Music4];
function MemoryGame({ level, onFinish }: { level: number; onFinish: (s: number) => void }) {
  const pairs = level === 1 ? 6 : level === 2 ? 8 : 10;
  const cards = useMemo(() => {
    const sel = Array.from({ length: pairs }, (_, i) => i);
    const arr = [...sel, ...sel].map((g, i) => ({ id: i, g }));
    for (let i = arr.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * (i + 1)); [arr[i], arr[j]] = [arr[j], arr[i]]; }
    return arr;
  }, [pairs]);
  const [open, setOpen] = useState<number[]>([]);
  const [matched, setMatched] = useState<number[]>([]);
  const [flips, setFlips] = useState(0);
  const [start] = useState(Date.now());

  const click = (i: number) => {
    if (open.includes(i) || matched.includes(cards[i].g)) return;
    const next = [...open, i];
    setOpen(next);
    if (next.length === 2) {
      setFlips((f) => f + 1);
      if (cards[next[0]].g === cards[next[1]].g) {
        const g = cards[next[0]].g;
        setMatched((m) => [...m, g]);
        setOpen([]);
        if (matched.length + 1 === pairs) {
          const t = (Date.now() - start) / 1000;
          onFinish(pairs * 100 - flips * 5 - t);
        }
      } else setTimeout(() => setOpen([]), 700);
    }
  };
  return (
    <div className="rounded-3xl border border-emerald-900/10 bg-white p-6 shadow-2xl">
      <div className="mb-4 flex justify-between text-xs font-bold text-emerald-800/70">
        <span>جفت‌های یافت‌شده: {faNum(matched.length)} / {faNum(pairs)}</span>
        <span>حرکت‌ها: {faNum(flips)}</span>
      </div>
      <div className="grid grid-cols-4 gap-2.5" dir="ltr">
        {cards.map((c, i) => {
          const Icon = MEM_ICONS[c.g];
          const isOpen = open.includes(i) || matched.includes(c.g);
          return (
            <button key={c.id} onClick={() => click(i)}
              className={`grid aspect-square place-items-center rounded-2xl transition-all duration-300 ${isOpen ? "bg-amber-100 text-amber-700 ring-2 ring-amber-400" : "bg-gradient-to-br from-emerald-700 to-emerald-900 text-transparent hover:brightness-110"}`}>
              <Icon size={pairs >= 8 ? 26 : 32} strokeWidth={isOpen ? 2.2 : 0.4} />
            </button>
          );
        })}
      </div>
    </div>
  );
}

/* ---------- کلمه بهم‌ریخته ---------- */
function ScrambleGame({ words, onFinish }: { words: string[]; onFinish: (s: number) => void }) {
  const list = useMemo(() => (words.length ? words : ["مدرسه", "کتاب"]).slice(0, 8), [words]);
  const scramble = (w: string): string => {
    const a = w.split("");
    for (let i = a.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * (i + 1)); [a[i], a[j]] = [a[j], a[i]]; }
    return a.join("") === w ? scramble(w) : a.join("");
  };
  const [idx, setIdx] = useState(0);
  const [score, setScore] = useState(0);
  const [shown] = useState(() => list.map(scramble));
  const [guess, setGuess] = useState("");
  const [fb, setFb] = useState<null | boolean>(null);
  const check = () => {
    const ok = guess.trim() === list[idx];
    setFb(ok);
    if (ok) setScore((s) => s + 20);
    setTimeout(() => {
      setFb(null); setGuess("");
      if (idx + 1 < list.length) setIdx(idx + 1);
      else onFinish(score + (ok ? 20 : 0));
    }, 800);
  };
  return (
    <div className="rounded-3xl border border-emerald-900/10 bg-white p-8 text-center shadow-2xl">
      <div className="mb-4 flex justify-between text-xs font-bold text-emerald-800/70">
        <span>کلمهٔ {faNum(idx + 1)} از {faNum(list.length)}</span>
        <span>امتیاز: {faNum(score)}</span>
      </div>
      <p className="mb-2 text-xs font-bold text-emerald-800/60">حروف بهم‌ریخته را مرتب کنید:</p>
      <div className="mx-auto mb-6 flex max-w-md flex-wrap justify-center gap-2" dir="rtl">
        {shown[idx].split("").map((ch, i) => (
          <span key={i} className="anim-float grid size-12 place-items-center rounded-xl bg-gradient-to-br from-emerald-700 to-emerald-900 text-2xl font-black text-amber-300 shadow" style={{ animationDelay: `${i * 0.15}s`, animationDuration: "3s" }}>{ch}</span>
        ))}
      </div>
      <div className="mx-auto flex max-w-xs gap-2">
        <input value={guess} onChange={(e) => setGuess(e.target.value)} onKeyDown={(e) => e.key === "Enter" && check()}
          autoFocus placeholder="حدس..." className={`w-full rounded-xl border-2 px-4 py-3 text-center text-xl font-black outline-none transition ${fb === true ? "border-emerald-500 bg-emerald-50" : fb === false ? "border-red-400 bg-red-50" : "border-emerald-900/15 focus:border-emerald-600"}`} />
        <button onClick={check} className="btn-gold rounded-xl px-5 font-black text-white">✓</button>
      </div>
      {fb === true && <p className="mt-3 flex items-center justify-center gap-1 text-sm font-black text-emerald-600"><CheckCircle2 size={16} /> آفرین!</p>}
      {fb === false && <p className="mt-3 flex items-center justify-center gap-1 text-sm font-black text-red-600"><XCircle size={16} /> درست نبود: «{list[idx]}»</p>}
    </div>
  );
}

/* ---------- واکنش سریع ---------- */
function ReactionGame({ onFinish }: { onFinish: (s: number) => void }) {
  const [state, setState] = useState<"wait" | "ready" | "click" | "done">("wait");
  const [round, setRound] = useState(0);
  const [times, setTimes] = useState<number[]>([]);
  const tRef = useRef<number>(0);
  const timeout = useRef<ReturnType<typeof setTimeout> | null>(null);

  const startRound = () => {
    setState("wait");
    timeout.current = setTimeout(() => { tRef.current = Date.now(); setState("click"); }, 900 + Math.random() * 2800);
  };
  useEffect(() => { startRound(); return () => { if (timeout.current) clearTimeout(timeout.current); }; }, []); // eslint-disable-line

  const handle = () => {
    if (state === "wait") { if (timeout.current) clearTimeout(timeout.current); startRound(); return; }
    if (state !== "click") return;
    const ms = Date.now() - tRef.current;
    const nt = [...times, ms];
    setTimes(nt);
    setState("ready");
    setTimeout(() => {
      if (nt.length < 5) startRound();
      else {
        const avg = nt.reduce((a, b) => a + b, 0) / nt.length;
        setState("done");
        onFinish(Math.max(0, 1000 - avg));
      }
    }, 900);
  };
  const avg = times.length ? Math.round(times.reduce((a, b) => a + b, 0) / times.length) : 0;
  return (
    <div className="rounded-3xl border border-emerald-900/10 bg-white p-6 shadow-2xl text-center">
      <div className="mb-4 flex justify-between text-xs font-bold text-emerald-800/70">
        <span>دور {faNum(Math.min(times.length + 1, 5))} از {faNum(5)}</span>
        {times.length > 0 && <span>میانگین: {faNum(avg)} میلی‌ثانیه</span>}
      </div>
      <button onClick={handle}
        className={`h-56 w-full rounded-3xl text-xl font-black text-white shadow-inner transition sm:h-64 ${state === "click" ? "bg-emerald-500" : state === "wait" ? "bg-red-400" : "bg-amber-400"}`}>
        {state === "click" ? "الان ضربه بزن!" : state === "wait" ? "صبر کن... سبز شد بزن" : times.length ? `${faNum(times[times.length - 1])} میلی‌ثانیه` : "آماده شو..."}
      </button>
      <div className="mt-4 flex justify-center gap-1.5">
        {Array.from({ length: 5 }).map((_, i) => (
          <span key={i} className={`size-3 rounded-full ${i < times.length ? "bg-emerald-500" : "bg-emerald-900/15"}`} />
        ))}
      </div>
    </div>
  );
}
