"use client";

import { motion } from "framer-motion";
import {
  Bot,
  ChevronLeft,
  ChevronRight,
  Globe,
  LogIn,
  LogOut,
  Play,
  ShoppingBag,
  Trophy,
  User,
  Users,
} from "lucide-react";
import { useEffect, useState } from "react";
import { Zap } from "lucide-react";
import { useGameStore, hasActiveMatch } from "@/lib/game-store";
import { pushNotification } from "@/lib/notification-store";
import { useSessionStore } from "@/lib/session-store";
import { useUIStore, type Screen } from "@/lib/ui-store";
import { useI18n } from "@/lib/i18n";
import { getService } from "@/lib/online/service";
import { sound } from "@/lib/sound";
import { SPEED_TARGET_SCORE } from "@/lib/online/gamification";
import { SUIT_SYMBOL } from "@/lib/hokm/types";
import { cn } from "@/lib/cn";
import { TopBar } from "./online/TopBar";

export function HomeScreen() {
  const { t, toggle, locale } = useI18n();
  const newMatch = useGameStore((s) => s.newMatch);
  const goGame = useUIStore((s) => s.goGame);
  const go = useUIStore((s) => s.go);
  const profile = useSessionStore((s) => s.profile);
  const isAuthed = useSessionStore((s) => s.isAuthed);
  const signOut = useSessionStore((s) => s.signOut);

  const nav = (screen: Screen) => {
    sound.init();
    sound.play("click");
    go(screen);
  };

  const [speed, setSpeed] = useState(false);

  const playVsComputer = () => {
    // One game at a time: resume the running match instead of starting a new one.
    if (hasActiveMatch()) {
      useGameStore.getState().resume();
      goGame("home");
      pushNotification({
        kind: "system",
        titleFa: "بازی در جریان",
        titleEn: "Game in progress",
        bodyFa: "ابتدا بازی فعلی را تمام کنید یا تسلیم شوید.",
        bodyEn: "Finish or forfeit your current game first.",
        icon: "🎮",
      });
      return;
    }
    const you = profile?.displayName || t("seat.you");
    newMatch({
      names: [you, "آرش", "کیان", "نیلوفر"],
      targetScore: speed ? SPEED_TARGET_SCORE : 7,
      speed,
    });
    goGame("home");
  };

  const playOnline = () => nav(isAuthed ? "online" : "auth");
  const Chevron = locale === "fa" ? ChevronLeft : ChevronRight;

  return (
    <main className="persian-pattern relative h-dvh w-full overflow-y-auto overscroll-contain safe-top safe-x safe-bottom">
      <FloatingSuits />
      <div className="relative z-10 mx-auto w-full max-w-md p-4 sm:p-6 flex flex-col min-h-dvh">
        <div className="pt-1">
          <TopBar />
        </div>

        {/* logo */}
        <motion.div
          initial={{ opacity: 0, y: 16 }}
          animate={{ opacity: 1, y: 0 }}
          className="flex flex-col items-center text-center mt-3 mb-4 sm:mt-5 sm:mb-6"
        >
          <div className="size-12 sm:size-16 rounded-2xl gold-border flex items-center justify-center bg-navy-900 mb-2 sm:mb-3 shadow-lg">
            <span className="gold-text text-3xl sm:text-4xl font-black leading-none">♠</span>
          </div>
          <h1 className="gold-text text-4xl sm:text-5xl font-black tracking-tight">
            {t("app.title")}
          </h1>
          <p className="text-cream/60 mt-1 text-sm">{t("app.subtitle")}</p>
          <OnlinePlayers />
        </motion.div>

        {/* HERO: play online */}
        <div className="relative">
          {/* glow */}
          <div className="pointer-events-none absolute -inset-2 rounded-[28px] bg-gold-500/25 blur-2xl" />
          <motion.button
            initial={{ opacity: 0, y: 14 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ delay: 0.05 }}
            whileTap={{ scale: 0.985 }}
            onClick={playOnline}
            className="press-3d btn-gold relative w-full rounded-3xl px-5 py-4 sm:py-5 flex items-center gap-4 text-start"
          >
            <span className="grid size-12 sm:size-14 shrink-0 place-items-center rounded-2xl bg-black/15 text-[#2a1f04]">
              <Play className="size-7" fill="currentColor" />
            </span>
            <span className="flex-1 min-w-0">
              <span className="block text-2xl font-black text-[#2a1f04] leading-tight">
                {t("menu.online")}
              </span>
              <span className="block text-xs text-[#2a1f04]/70">{t("menu.onlineDesc")}</span>
            </span>
            <Chevron className="size-6 text-[#2a1f04]/70 shrink-0" />
          </motion.button>
        </div>

        {/* vs computer */}
        <div className="mt-3">
          <PrimaryCard
            icon={<Bot className="size-6" />}
            title={t("menu.vsComputer")}
            desc={speed ? t("speed.desc") : t("menu.vsComputerDesc")}
            onClick={playVsComputer}
          />
          {/* Normal / Speed mode picker */}
          <div className="mt-2 glass rounded-2xl p-1 flex gap-1">
            <button
              onClick={() => setSpeed(false)}
              className={cn(
                "flex-1 rounded-xl py-2 text-xs font-bold transition flex items-center justify-center gap-1.5",
                !speed ? "btn-gold" : "text-cream/60 hover:text-cream"
              )}
            >
              {t("speed.normal")}
            </button>
            <button
              onClick={() => setSpeed(true)}
              className={cn(
                "flex-1 rounded-xl py-2 text-xs font-bold transition flex items-center justify-center gap-1.5",
                speed ? "btn-gold" : "text-cream/60 hover:text-cream"
              )}
            >
              <Zap className={cn("size-3.5", speed && "fill-current")} />
              {t("speed.label")}
            </button>
          </div>
        </div>

        {/* tiles */}
        <div className="grid grid-cols-4 gap-2.5 mt-3 sm:mt-4">
          <Tile icon={<User className="size-5" />} label={t("menu.profile")} tint="teal" onClick={() => nav("profile")} />
          <Tile icon={<Users className="size-5" />} label={t("menu.friends")} tint="sky" onClick={() => nav(isAuthed ? "friends" : "auth")} />
          <Tile icon={<Trophy className="size-5" />} label={t("menu.leaderboard")} tint="gold" onClick={() => nav("leaderboard")} />
          <Tile icon={<ShoppingBag className="size-5" />} label={t("menu.shop")} tint="rose" onClick={() => nav("shop")} />
        </div>

        <div className="flex-1" />

        {/* footer */}
        <div className="flex items-center justify-between gap-2 pt-4 sm:pt-6 pb-2">
          {isAuthed ? (
            <button
              onClick={signOut}
              className="glass rounded-full px-4 py-2 text-sm flex items-center gap-2 hover:bg-navy-800/80 transition"
            >
              <LogOut className="size-4 text-rose-300" />
              {t("menu.signOut")}
            </button>
          ) : (
            <button
              onClick={() => go("auth")}
              className="btn-gold rounded-full px-4 py-2 text-sm flex items-center gap-2"
            >
              <LogIn className="size-4" />
              {t("menu.signIn")}
            </button>
          )}
          <button
            onClick={toggle}
            className="glass rounded-full px-4 py-2 text-sm flex items-center gap-2 hover:bg-navy-800/80 transition"
          >
            <Globe className="size-4 text-gold-400" />
            {t("home.lang")}
          </button>
        </div>
      </div>
    </main>
  );
}

function PrimaryCard({
  icon,
  title,
  desc,
  onClick,
  primary,
}: {
  icon: React.ReactNode;
  title: string;
  desc: string;
  onClick: () => void;
  primary?: boolean;
}) {
  return (
    <motion.button
      whileTap={{ scale: 0.985 }}
      onClick={onClick}
      className={
        "press-3d w-full rounded-3xl px-5 py-4 flex items-center gap-4 text-start " +
        (primary ? "btn-gold" : "glass")
      }
    >
      <span
        className={
          "grid size-12 shrink-0 place-items-center rounded-2xl " +
          (primary ? "bg-black/15 text-[#2a1f04]" : "bg-teal-500/15 text-teal-300")
        }
      >
        {icon}
      </span>
      <span className="flex-1">
        <span className={"block text-lg font-black " + (primary ? "text-[#2a1f04]" : "text-cream")}>
          {title}
        </span>
        <span className={"block text-xs " + (primary ? "text-[#2a1f04]/70" : "text-cream/55")}>
          {desc}
        </span>
      </span>
    </motion.button>
  );
}

const TILE_TINTS: Record<string, string> = {
  teal: "bg-teal-500/15 text-teal-400",
  sky: "bg-sky-500/15 text-sky-400",
  gold: "bg-gold-500/15 text-gold-400",
  rose: "bg-rose-500/15 text-rose-400",
};

function Tile({
  icon,
  label,
  tint = "gold",
  onClick,
}: {
  icon: React.ReactNode;
  label: string;
  tint?: keyof typeof TILE_TINTS;
  onClick: () => void;
}) {
  return (
    <motion.button
      whileTap={{ scale: 0.94 }}
      onClick={onClick}
      className="press-3d glass rounded-2xl py-3 flex flex-col items-center gap-2"
    >
      <span className={"grid size-10 place-items-center rounded-xl " + TILE_TINTS[tint]}>
        {icon}
      </span>
      <span className="text-[11px] font-semibold text-cream/85">{label}</span>
    </motion.button>
  );
}

function OnlinePlayers() {
  const { t, locale } = useI18n();
  const [count, setCount] = useState<number | null>(null);

  useEffect(() => {
    let alive = true;
    const tick = async () => {
      try {
        const n = await getService().getOnlineCount();
        if (alive) setCount(n);
      } catch {
        /* ignore */
      }
    };
    tick();
    const id = setInterval(tick, 8000);
    return () => {
      alive = false;
      clearInterval(id);
    };
  }, []);

  if (count == null) return null;
  const n = new Intl.NumberFormat(locale === "fa" ? "fa-IR" : "en-US").format(count);
  return (
    <div className="mt-3 inline-flex items-center gap-2 glass rounded-full px-3 py-1.5">
      <span className="relative flex size-2.5">
        <span className="absolute inline-flex h-full w-full rounded-full bg-teal-400 opacity-70 animate-ping" />
        <span className="relative inline-flex size-2.5 rounded-full bg-teal-400" />
      </span>
      <span className="text-xs text-cream/85">{t("home.onlineCount", { n })}</span>
    </div>
  );
}

function FloatingSuits() {
  const suits = Object.values(SUIT_SYMBOL);
  const items = Array.from({ length: 8 }, (_, i) => ({
    s: suits[i % 4],
    left: `${(i * 13 + 6) % 95}%`,
    delay: i * 0.7,
    dur: 9 + (i % 4) * 2,
    size: 28 + (i % 3) * 18,
  }));
  return (
    <div className="pointer-events-none absolute inset-0 overflow-hidden">
      {items.map((it, i) => (
        <span
          key={i}
          className="float-suit absolute text-gold-500/10 font-black"
          style={{
            left: it.left,
            fontSize: it.size,
            animationDuration: `${it.dur}s`,
            animationDelay: `${it.delay}s`,
          }}
        >
          {it.s}
        </span>
      ))}
    </div>
  );
}
