"use client";

import { motion } from "framer-motion";
import {
  Bot,
  Globe,
  LogIn,
  LogOut,
  ShoppingBag,
  Trophy,
  User,
  Users,
  Wifi,
} from "lucide-react";
import { useEffect, useState } from "react";
import { useGameStore } from "@/lib/game-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 { SUIT_SYMBOL } from "@/lib/hokm/types";
import { TopBar } from "./online/TopBar";

export function HomeScreen() {
  const { t, toggle } = 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 playVsComputer = () => {
    const you = profile?.displayName || t("seat.you");
    newMatch({ names: [you, "آرش", "کیان", "نیلوفر"], targetScore: 7 });
    goGame("home");
  };

  const playOnline = () => nav(isAuthed ? "online" : "auth");

  return (
    <main className="persian-pattern relative min-h-dvh w-full overflow-y-auto">
      <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-6 mb-7"
        >
          <div className="size-16 rounded-2xl gold-border flex items-center justify-center bg-navy-900 mb-3 shadow-lg">
            <span className="gold-text text-4xl font-black leading-none">♠</span>
          </div>
          <h1 className="gold-text 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>

        {/* primary actions */}
        <div className="space-y-3">
          <PrimaryCard
            icon={<Wifi className="size-6" />}
            title={t("menu.online")}
            desc={t("menu.onlineDesc")}
            onClick={playOnline}
            primary
          />
          <PrimaryCard
            icon={<Bot className="size-6" />}
            title={t("menu.vsComputer")}
            desc={t("menu.vsComputerDesc")}
            onClick={playVsComputer}
          />
        </div>

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

        <div className="flex-1" />

        {/* footer */}
        <div className="flex items-center justify-between gap-2 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.98 }}
      whileHover={{ y: -2 }}
      onClick={onClick}
      className={
        "w-full rounded-2xl p-4 flex items-center gap-4 text-start transition " +
        (primary
          ? "btn-gold"
          : "glass hover:bg-navy-800/80")
      }
    >
      <span
        className={
          "size-12 rounded-xl flex items-center justify-center shrink-0 " +
          (primary ? "bg-black/15 text-[#2a1f04]" : "bg-navy-900 gold-border text-gold-400")
        }
      >
        {icon}
      </span>
      <span>
        <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>
  );
}

function Tile({
  icon,
  label,
  onClick,
}: {
  icon: React.ReactNode;
  label: string;
  onClick: () => void;
}) {
  return (
    <motion.button
      whileTap={{ scale: 0.95 }}
      onClick={onClick}
      className="glass rounded-2xl py-3 flex flex-col items-center gap-1.5 hover:bg-navy-800/80 transition"
    >
      <span className="text-gold-400">{icon}</span>
      <span className="text-[11px] text-cream/80">{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>
  );
}
