// BEGIN CHANGE: landing com cards dos widgets do latestnews
"use client";

import Link from "next/link";
import { useEffect, useState } from "react";
import { useI18n } from "@/i18n/LanguageProvider";
import { useAuth } from "@/auth/AuthProvider";
import { Navbar } from "@/components/Navbar";
import { Footer } from "@/components/Footer";
import { PlayerName } from "@/components/PlayerName";
import { Outfit } from "@/components/Outfit";
import { GuildWarsList, type WarRow } from "@/components/GuildWarsList";
import { ItemIcon } from "@/components/ItemIcon";
import { apiUrl, guildLogoUrl, type Look } from "@/lib/api";

type TopGuild = { id: number; name: string; logo: string; kills: number };
type TopKiller = { name: string; frags: number; look: Look };
type Killer =
  | { type: "monster"; monster: string; count: number; look: Look | null; itemId: number | null }
  | { type: "player"; player: string; count: number; deleted: boolean; look: Look | null }
  | {
      type: "summon";
      monster: string;
      player: string;
      count: number;
      monsterLook: Look | null;
      monsterItem: number | null;
      playerLook: Look | null;
    };
type LastKill = {
  date: number;
  level: number;
  name: string;
  look: Look;
  killers: Killer[];
};
type Caster = {
  name: string;
  level: number;
  reset: number;
  viewers: number;
  vocation: string;
  look: Look;
};
type HomeVideo = { id: number; title: string; youtubeId: string; created: number };
type DominionGuild = { id: number; name: string; logo: string };

function fmtTs(epoch: number) {
  if (!epoch) return "-";
  return new Date(epoch * 1000).toLocaleString();
}

function KillerChip({ killer }: { killer: Killer }) {
  const countPrefix = killer.count > 1 ? `${killer.count}x ` : "";
  if (killer.type === "monster") {
    return (
      <span className="inline-flex items-center gap-1.5">
        {killer.look && killer.look.looktype > 0 ? (
          <Outfit look={killer.look} size="inline" alt={killer.monster} />
        ) : killer.itemId ? (
          <ItemIcon id={killer.itemId} size={28} alt={killer.monster} />
        ) : null}
        <span>
          {countPrefix}
          {killer.monster}
        </span>
      </span>
    );
  }
  if (killer.type === "player") {
    return (
      <span className="inline-flex items-center gap-1.5">
        {killer.look && <Outfit look={killer.look} size="inline" alt={killer.player} />}
        {killer.deleted ? (
          <span>{killer.player}</span>
        ) : (
          <Link
            href={`/character/?name=${encodeURIComponent(killer.player)}`}
            className="font-medium text-brand hover:underline"
          >
            {killer.player}
          </Link>
        )}
      </span>
    );
  }
  return (
    <span className="inline-flex flex-wrap items-center gap-1.5">
      {killer.monsterLook && killer.monsterLook.looktype > 0 ? (
        <Outfit look={killer.monsterLook} size="inline" alt={killer.monster} />
      ) : killer.monsterItem ? (
        <ItemIcon id={killer.monsterItem} size={28} alt={killer.monster} />
      ) : null}
      <span>
        {countPrefix}
        {killer.monster}
      </span>
      <span className="text-muted">summoned by</span>
      <Link
        href={`/character/?name=${encodeURIComponent(killer.player)}`}
        className="inline-flex items-center gap-1.5 font-medium text-brand hover:underline"
      >
        {killer.playerLook && <Outfit look={killer.playerLook} size="inline" alt={killer.player} />}
        {killer.player}
      </Link>
    </span>
  );
}

function HomeCard({
  title,
  subtitle,
  action,
  children,
}: {
  title: string;
  subtitle: string;
  action?: React.ReactNode;
  children: React.ReactNode;
}) {
  return (
    <section className="overflow-hidden rounded-xl border border-border bg-panel">
      <div className="flex items-start justify-between gap-3 border-b border-border px-5 py-4">
        <div>
          <h2 className="text-lg font-semibold tracking-tight">{title}</h2>
          <p className="mt-0.5 text-sm text-muted">{subtitle}</p>
        </div>
        {action}
      </div>
      <div className="p-5">{children}</div>
    </section>
  );
}

function DominionCard({
  label,
  hint,
  empty,
  guild,
  tone,
}: {
  label: string;
  hint: string;
  empty: string;
  guild: DominionGuild | null;
  tone: "castle" | "favela";
}) {
  const accents =
    tone === "castle"
      ? {
          ring: "hover:border-amber-400/50",
          badge: "bg-amber-500/15 text-amber-300",
          glow: "from-amber-500/20 via-transparent to-transparent",
          bar: "bg-amber-400",
        }
      : {
          ring: "hover:border-lime-400/50",
          badge: "bg-lime-500/15 text-lime-300",
          glow: "from-lime-500/20 via-transparent to-transparent",
          bar: "bg-lime-400",
        };

  const inner = (
    <>
      <div className={`absolute inset-x-0 top-0 h-24 bg-gradient-to-b ${accents.glow}`} />
      <div className={`absolute left-0 top-0 h-full w-1 ${accents.bar}`} />
      <div className="relative">
        <span className={`inline-flex rounded-md px-2.5 py-1 text-xs font-semibold tracking-wide ${accents.badge}`}>
          {label}
        </span>
        <p className="mt-2 text-xs text-muted">{hint}</p>
        {guild ? (
          <div className="mt-5 flex flex-col items-center text-center">
            {/* eslint-disable-next-line @next/next/no-img-element */}
            <img
              src={guildLogoUrl(guild.logo)}
              alt={guild.name}
              width={104}
              height={104}
              className="h-[104px] w-[104px] object-contain drop-shadow-md transition-transform duration-300 group-hover:scale-105"
              onError={(e) => {
                (e.target as HTMLImageElement).src = guildLogoUrl("default_main_logo.gif");
              }}
            />
            <h3 className="mt-4 max-w-full truncate text-base font-semibold group-hover:text-brand">
              {guild.name}
            </h3>
          </div>
        ) : (
          <div className="mt-8 flex min-h-[140px] flex-col items-center justify-center text-center">
            {/* BEGIN CHANGE: empty dominion placeholder - (nunca ?; anti falso encoding) */}
            <div className="grid h-16 w-16 place-items-center rounded-full border border-dashed border-border text-muted">
              -
            </div>
            {/* END CHANGE */}
            <p className="mt-3 text-sm text-muted">{empty}</p>
          </div>
        )}
      </div>
    </>
  );

  const className = `group relative overflow-hidden rounded-xl border border-border bg-panel p-6 transition-colors ${accents.ring}`;

  if (guild) {
    return (
      <Link href={`/guild/?id=${guild.id}`} className={className}>
        {inner}
      </Link>
    );
  }
  return <div className={className}>{inner}</div>;
}

export default function Home() {
  const { t } = useI18n();
  const { account, token } = useAuth();
  const isAdmin = !!account?.isAdmin;

  const [status, setStatus] = useState<"loading" | "ok" | "error">("loading");
  const [guilds, setGuilds] = useState<TopGuild[]>([]);
  const [wars, setWars] = useState<WarRow[]>([]);
  const [killers, setKillers] = useState<TopKiller[]>([]);
  const [lastKills, setLastKills] = useState<LastKill[]>([]);
  const [casting, setCasting] = useState<Caster[]>([]);
  const [contacts, setContacts] = useState<{
    telegram: { url: string; configured: boolean };
    discord: { url: string; configured: boolean };
    email: { address: string; configured: boolean };
  } | null>(null);
  const [videos, setVideos] = useState<HomeVideo[]>([]);
  const [castle, setCastle] = useState<DominionGuild | null>(null);
  const [favela, setFavela] = useState<DominionGuild | null>(null);
  const [hero, setHero] = useState<{
    badge: string;
    titlePre: string;
    titleBrand: string;
    subtitle: string;
  } | null>(null);
  // BEGIN CHANGE: contagem de players online ficou so no Navbar
  // END CHANGE
  // BEGIN CHANGE: bans ativos na home
  type HomeBan = {
    id: number;
    reason: string;
    comment: string;
    added: number;
    expires: number;
    player: { name: string; look: Look };
    bannedBy: { name: string; look: Look } | null;
  };
  const [bans, setBans] = useState<HomeBan[]>([]);
  // END CHANGE
  // BEGIN CHANGE: monster boost do dia
  type MonsterBoost = {
    monster: string;
    loot: number;
    exp: number;
    date: number;
    look: Look | null;
    description?: string;
    monsterExp?: number;
    monsterHealth?: number;
    race?: string;
    lootItems?: { id: number; name: string; chance: number; countMax: number }[];
  };
  const [monsterBoost, setMonsterBoost] = useState<MonsterBoost | null>(null);
  // END CHANGE
  // BEGIN CHANGE: ultimo player criado (card de boas-vindas) - item 3
  type LatestPlayer = {
    name: string;
    level: number;
    vocation: string;
    created: number;
    look: Look;
  };
  const [latestPlayer, setLatestPlayer] = useState<LatestPlayer | null>(null);
  // END CHANGE
  const [videoTitle, setVideoTitle] = useState("");
  const [videoUrl, setVideoUrl] = useState("");
  const [videoBusy, setVideoBusy] = useState(false);
  const [videoMsg, setVideoMsg] = useState("");

  // BEGIN CHANGE: card Loja aponta para /shop (antes era "#")
  const cardHrefs = ["/highscores", "/shop", "/download", "/guilds"];
  // END CHANGE

  function loadHome() {
    fetch(apiUrl("home.php"))
      .then((r) => {
        if (!r.ok) throw new Error("http " + r.status);
        return r.json();
      })
      .then((json) => {
        setGuilds(json.topGuilds ?? []);
        setWars(json.wars ?? []);
        setKillers(json.topKillers ?? []);
        setLastKills(json.lastKills ?? []);
        setCasting(json.casting ?? []);
        setContacts(
          json.contacts ?? {
            telegram: {
              url: json.telegram?.url ?? "",
              configured: !!json.telegram?.configured,
            },
            discord: { url: "", configured: false },
            email: { address: "", configured: false },
          }
        );
        setVideos(json.videos ?? []);
        setCastle(json.castle ?? null);
        setFavela(json.favela ?? null);
        setHero(json.hero ?? null);
        // BEGIN CHANGE
        setBans(Array.isArray(json.bans) ? json.bans : []);
        // END CHANGE
        // BEGIN CHANGE
        setMonsterBoost(json.monsterBoost ?? null);
        // END CHANGE
        // BEGIN CHANGE: item 3
        setLatestPlayer(json.latestPlayer ?? null);
        // END CHANGE
        setStatus("ok");
      })
      .catch(() => setStatus("error"));
  }

  useEffect(() => {
    loadHome();
  }, []);

  async function addVideo(e: React.FormEvent) {
    e.preventDefault();
    if (!token || videoBusy) return;
    setVideoBusy(true);
    setVideoMsg("");
    try {
      const r = await fetch(apiUrl("home-videos.php"), {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          Authorization: `Bearer ${token}`,
        },
        body: JSON.stringify({ action: "add", title: videoTitle, url: videoUrl }),
      });
      const json = await r.json();
      if (!r.ok) throw new Error(json.error || "fail");
      setVideos(json.data ?? []);
      setVideoTitle("");
      setVideoUrl("");
    } catch (err) {
      setVideoMsg(err instanceof Error ? err.message : "error");
    } finally {
      setVideoBusy(false);
    }
  }

  async function removeVideo(id: number) {
    if (!token || videoBusy) return;
    setVideoBusy(true);
    setVideoMsg("");
    try {
      const r = await fetch(apiUrl("home-videos.php"), {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          Authorization: `Bearer ${token}`,
        },
        body: JSON.stringify({ action: "delete", id }),
      });
      const json = await r.json();
      if (!r.ok) throw new Error(json.error || "fail");
      setVideos(json.data ?? []);
    } catch (err) {
      setVideoMsg(err instanceof Error ? err.message : "error");
    } finally {
      setVideoBusy(false);
    }
  }

  return (
    <div className="flex min-h-screen flex-col">
      <Navbar />

      <main className="flex-1">
        {/* BEGIN CHANGE: hero com brand-art + texto CMS (fonte do site) */}
        <section className="relative overflow-hidden">
          <div className="relative mx-auto w-full max-w-6xl px-4 py-10 sm:px-6 sm:py-14 lg:py-16">
            {/* Vinheta suave (elipse) - sem card/borda quadrada */}
            <div
              className="pointer-events-none absolute inset-4 -z-10 sm:inset-6"
              style={{
                background:
                  "radial-gradient(ellipse 70% 60% at 50% 45%, rgba(18,22,31,0.55) 0%, rgba(18,22,31,0.22) 45%, transparent 72%)",
              }}
              aria-hidden
            />
            <div className="grid items-center md:grid-cols-2">
              <div className="relative flex min-h-[200px] items-center justify-center px-4 py-4 sm:min-h-[240px] md:min-h-[300px] md:px-6">
                {/* eslint-disable-next-line @next/next/no-img-element */}
                <img
                  src="/brand-art/wa-site-hero-banner.png"
                  alt="White Antidote"
                  className="h-auto max-h-[240px] w-auto max-w-[260px] object-contain drop-shadow-[0_0_28px_rgba(67,214,160,0.18)] sm:max-h-[280px] sm:max-w-[300px] md:max-h-[320px] md:max-w-[340px]"
                />
              </div>
              <div className="flex flex-col items-center justify-center px-6 py-8 text-center md:items-start md:px-8 md:py-10 md:text-left lg:px-10">
                <h1 className="max-w-xl text-3xl font-semibold leading-tight tracking-tight sm:text-4xl lg:text-5xl">
                  {(hero?.titlePre && hero.titlePre.trim()) || t.hero.titlePre}{" "}
                  <span className="text-brand">
                    {(hero?.titleBrand && hero.titleBrand.trim()) || t.hero.titleBrand}
                  </span>
                </h1>
                <p className="mt-4 max-w-lg text-base text-muted sm:text-lg">
                  {(hero?.subtitle && hero.subtitle.trim()) || t.hero.subtitle}
                </p>
                <div className="mt-8 flex w-full max-w-sm flex-col gap-3 sm:max-w-none sm:flex-row md:justify-start">
                  <Link
                    href="/create-account"
                    className="rounded-lg bg-brand px-6 py-3 text-sm font-medium text-background transition-opacity hover:opacity-90"
                  >
                    {t.hero.playNow}
                  </Link>
                  <Link
                    href="/highscores"
                    className="rounded-lg border border-border bg-panel/80 px-6 py-3 text-sm font-medium backdrop-blur transition-colors hover:border-brand/50"
                  >
                    {t.hero.viewHighscores}
                  </Link>
                </div>
              </div>
            </div>
          </div>
        </section>
        {/* END CHANGE */}

        <div className="mx-auto grid w-full max-w-6xl grid-cols-1 gap-4 px-4 pb-10 sm:gap-5 sm:px-6 lg:grid-cols-2">
          {status === "loading" && (
            <p className="text-muted lg:col-span-2">{t.common.loading}</p>
          )}
          {status === "error" && (
            <p className="text-muted lg:col-span-2">{t.common.error}</p>
          )}

          {status === "ok" && (
            <>
              {/* Castle / Favela */}
              <div className="lg:col-span-2">
                <div className="mb-3">
                  <h2 className="text-lg font-semibold tracking-tight">{t.home.dominionTitle}</h2>
                  <p className="mt-0.5 text-sm text-muted">{t.home.dominionSubtitle}</p>
                </div>
                <div className="grid grid-cols-1 gap-5 sm:grid-cols-2">
                  <DominionCard
                    label={t.home.castleWar}
                    hint={t.home.dominating}
                    empty={t.home.noOwner}
                    guild={castle}
                    tone="castle"
                  />
                  <DominionCard
                    label={t.home.favelaWar}
                    hint={t.home.dominating}
                    empty={t.home.noOwner}
                    guild={favela}
                    tone="favela"
                  />
                </div>
              </div>

              {/* BEGIN CHANGE: card do ultimo player criado (item 3) */}
              {latestPlayer && (
                <div className="lg:col-span-2">
                  <HomeCard
                    title={t.home.newPlayerTitle}
                    subtitle={t.home.newPlayerSubtitle}
                    action={
                      <Link
                        href={`/character/?name=${encodeURIComponent(latestPlayer.name)}`}
                        className="shrink-0 text-sm text-brand hover:underline"
                      >
                        {t.home.viewAll}
                      </Link>
                    }
                  >
                    <div className="flex items-center gap-4">
                      <Outfit look={latestPlayer.look} size="profile" alt={latestPlayer.name} />
                      <div className="min-w-0">
                        <p className="text-lg font-semibold text-brand">
                          {t.home.newPlayerWelcome.replace("{name}", latestPlayer.name)}
                        </p>
                        <div className="mt-1 flex flex-wrap gap-2 text-xs">
                          <span className="rounded-md bg-brand/10 px-2 py-1 text-brand">
                            {latestPlayer.vocation}
                          </span>
                          <span className="rounded-md bg-background px-2 py-1 text-muted">
                            Lv {latestPlayer.level}
                          </span>
                        </div>
                        {latestPlayer.created > 0 && (
                          <p className="mt-2 text-xs text-muted">
                            {t.home.newPlayerJoined} {fmtTs(latestPlayer.created)}
                          </p>
                        )}
                      </div>
                    </div>
                  </HomeCard>
                </div>
              )}
              {/* END CHANGE */}

              {/* BEGIN CHANGE: Monster Boost do dia */}
              <div className="lg:col-span-2">
                <HomeCard
                  title={t.home.monsterBoostTitle}
                  subtitle={t.home.monsterBoostSubtitle}
                  action={
                    monsterBoost ? (
                      <Link
                        href={`/monster/?name=${encodeURIComponent(monsterBoost.monster)}`}
                        className="shrink-0 text-sm text-brand hover:underline"
                      >
                        {t.home.monsterBoostView}
                      </Link>
                    ) : null
                  }
                >
                  {!monsterBoost ? (
                    <p className="text-sm text-muted">{t.home.monsterBoostEmpty}</p>
                  ) : (
                    <div className="space-y-5">
                      <div className="flex flex-col gap-5 sm:flex-row sm:items-start sm:justify-between">
                        <div className="flex min-w-0 items-center gap-4">
                          {monsterBoost.look && monsterBoost.look.looktype > 0 ? (
                            <Outfit
                              look={monsterBoost.look}
                              size="profile"
                              alt={monsterBoost.monster}
                            />
                          ) : (
                            <div className="grid h-16 w-16 place-items-center rounded-full border border-dashed border-border text-muted">
                              -
                            </div>
                          )}
                          <div className="min-w-0">
                            <Link
                              href={`/monster/?name=${encodeURIComponent(monsterBoost.monster)}`}
                              className="block truncate text-xl font-semibold tracking-tight text-brand hover:underline"
                            >
                              {monsterBoost.monster}
                            </Link>
                            {monsterBoost.description ? (
                              <p className="mt-1 line-clamp-2 text-sm text-muted">
                                {monsterBoost.description}
                              </p>
                            ) : null}
                            <div className="mt-2 flex flex-wrap gap-2 text-xs">
                              <span className="rounded-md bg-brand/10 px-2 py-1 text-brand">
                                {t.monsters.exp}: {(monsterBoost.monsterExp ?? 0).toLocaleString()}
                              </span>
                              <span className="rounded-md bg-background px-2 py-1 text-muted">
                                {t.monsters.health}:{" "}
                                {(monsterBoost.monsterHealth ?? 0).toLocaleString()}
                              </span>
                              {monsterBoost.race ? (
                                <span className="rounded-md bg-background px-2 py-1 text-muted">
                                  {t.monsters.race}: {monsterBoost.race}
                                </span>
                              ) : null}
                            </div>
                          </div>
                        </div>
                        <div className="flex w-full gap-3 sm:w-auto">
                          <div className="flex-1 rounded-lg border border-border bg-background/40 px-4 py-3 text-center sm:min-w-[7.5rem] sm:flex-none">
                            <p className="text-xs uppercase tracking-wide text-muted">
                              {t.home.monsterBoostLoot}
                            </p>
                            <p className="mt-1 text-lg font-semibold text-emerald-300">
                              +{monsterBoost.loot}%
                            </p>
                          </div>
                          <div className="flex-1 rounded-lg border border-border bg-background/40 px-4 py-3 text-center sm:min-w-[7.5rem] sm:flex-none">
                            <p className="text-xs uppercase tracking-wide text-muted">
                              {t.home.monsterBoostExp}
                            </p>
                            <p className="mt-1 text-lg font-semibold text-sky-300">
                              +{monsterBoost.exp}%
                            </p>
                          </div>
                        </div>
                      </div>

                      {(monsterBoost.lootItems?.length ?? 0) > 0 ? (
                        <div>
                          <h3 className="mb-2 text-sm font-semibold">{t.monsters.loot}</h3>
                          <ul className="grid gap-1 sm:grid-cols-2">
                            {monsterBoost.lootItems!.map((l, i) => (
                              <li
                                key={`${l.id}-${i}`}
                                className="flex items-center justify-between gap-2 rounded-lg border border-border/50 bg-background/30 px-2.5 py-1.5 text-sm"
                              >
                                <span className="inline-flex min-w-0 items-center gap-2">
                                  <ItemIcon id={l.id} alt={l.name} size={28} />
                                  <span className="truncate">
                                    {l.name}
                                    {l.countMax > 1 ? ` (x${l.countMax})` : ""}
                                  </span>
                                </span>
                                <span className="shrink-0 text-xs text-muted">
                                  {l.chance > 0 ? `${(l.chance / 1000).toFixed(1)}%` : "-"}
                                </span>
                              </li>
                            ))}
                          </ul>
                        </div>
                      ) : null}
                    </div>
                  )}
                </HomeCard>
              </div>
              {/* END CHANGE */}

              {/* TOP Guilds */}
              <HomeCard
                title={t.home.topGuildsTitle}
                subtitle={t.home.topGuildsSubtitle}
                action={
                  <Link href="/guilds" className="shrink-0 text-sm text-brand hover:underline">
                    {t.home.viewAllGuilds}
                  </Link>
                }
              >
                {guilds.length === 0 ? (
                  <p className="text-sm text-muted">{t.common.empty}</p>
                ) : (
                  <div className="grid grid-cols-1 gap-4 sm:grid-cols-3">
                    {guilds.map((g, i) => (
                      <Link
                        key={g.id}
                        href={`/guild/?id=${g.id}`}
                        className="group relative overflow-hidden rounded-lg border border-border/70 bg-background/40 p-4 text-center transition-colors hover:border-brand/40"
                      >
                        <div className="absolute left-2 top-2 rounded-md bg-brand/15 px-2 py-0.5 text-xs font-semibold text-brand">
                          #{i + 1}
                        </div>
                        {/* eslint-disable-next-line @next/next/no-img-element */}
                        <img
                          src={guildLogoUrl(g.logo)}
                          alt={g.name}
                          width={88}
                          height={88}
                          className="mx-auto h-[88px] w-[88px] object-contain"
                          onError={(e) => {
                            (e.target as HTMLImageElement).src = guildLogoUrl("default_main_logo.gif");
                          }}
                        />
                        <h3 className="mt-3 truncate text-sm font-semibold group-hover:text-brand">
                          {g.name}
                        </h3>
                        <p className="mt-1 text-xs text-muted">
                          <span className="font-medium text-foreground">{g.kills}</span> {t.home.kills}
                        </p>
                      </Link>
                    ))}
                  </div>
                )}
              </HomeCard>

              {/* Guild Wars */}
              <HomeCard
                title={t.home.warsTitle}
                subtitle={t.home.warsSubtitle}
                action={
                  <Link href="/wars" className="shrink-0 text-sm text-brand hover:underline">
                    {t.home.viewAllWars}
                  </Link>
                }
              >
                <div className="-mx-1 max-h-[320px] overflow-y-auto">
                  <GuildWarsList wars={wars} />
                </div>
              </HomeCard>

              {/* TOP Killers */}
              <HomeCard title={t.home.topKillersTitle} subtitle={t.home.topKillersSubtitle}>
                {killers.length === 0 ? (
                  <p className="text-sm text-muted">{t.common.empty}</p>
                ) : (
                  <div className="grid grid-cols-1 gap-4 sm:grid-cols-3">
                    {killers.map((k, i) => (
                      <div
                        key={k.name}
                        className="relative rounded-lg border border-border/70 bg-background/40 p-4 text-center"
                      >
                        <div className="absolute left-2 top-2 rounded-md bg-brand/15 px-2 py-0.5 text-xs font-semibold text-brand">
                          #{i + 1}
                        </div>
                        <div className="flex flex-col items-center gap-2 pt-2">
                          <Outfit look={k.look} size="grid" alt={k.name} />
                          <Link
                            href={`/character/?name=${encodeURIComponent(k.name)}`}
                            className="truncate text-sm font-medium hover:text-brand"
                          >
                            {k.name}
                          </Link>
                        </div>
                        <p className="mt-2 text-xs text-muted">
                          <span className="font-medium text-foreground">{k.frags}</span> {t.home.frags}
                        </p>
                      </div>
                    ))}
                  </div>
                )}
              </HomeCard>

              {/* Last Kills */}
              <HomeCard
                title={t.home.lastKillsTitle}
                subtitle={t.home.lastKillsSubtitle}
                action={
                  <Link href="/last-kills" className="text-sm text-brand hover:underline">
                    {t.home.viewAll}
                  </Link>
                }
              >
                {lastKills.length === 0 ? (
                  <p className="text-sm text-muted">{t.common.empty}</p>
                ) : (
                  <ul className="divide-y divide-border/50">
                    {lastKills.map((d) => (
                      <li key={`${d.name}-${d.date}`} className="py-3 first:pt-0 last:pb-0">
                        <div className="text-xs text-muted">{fmtTs(d.date)}</div>
                        <div className="mt-1 flex flex-wrap items-center gap-2 text-sm">
                          <PlayerName name={d.name} look={d.look} size="inline" />
                          <span className="text-muted">
                            {t.home.diedAt} <b className="text-foreground">{d.level}</b>
                          </span>
                          {d.killers.length > 0 && (
                            <>
                              <span className="text-muted">{t.home.by}</span>
                              {d.killers.map((k, idx) => (
                                <span key={idx} className="inline-flex items-center gap-1">
                                  {idx > 0 && <span className="text-muted">,</span>}
                                  <KillerChip killer={k} />
                                </span>
                              ))}
                            </>
                          )}
                        </div>
                      </li>
                    ))}
                  </ul>
                )}
              </HomeCard>

              {/* Casting */}
              <HomeCard
                title={t.home.castingTitle}
                subtitle={t.home.castingSubtitle}
                action={
                  <Link href="/casting" className="text-sm text-brand hover:underline">
                    {t.home.viewAll}
                  </Link>
                }
              >
                {casting.length === 0 ? (
                  <p className="text-sm text-muted">{t.home.castingEmpty}</p>
                ) : (
                  <ul className="divide-y divide-border/50">
                    {casting.map((c) => (
                      <li
                        key={c.name}
                        className="flex items-center justify-between gap-3 py-3 first:pt-0 last:pb-0"
                      >
                        <div>
                          <PlayerName name={c.name} look={c.look} size="inline" />
                          <div className="mt-1 text-xs text-muted">
                            {c.vocation} | R{c.reset} | Lv {c.level}
                          </div>
                        </div>
                        <div className="shrink-0 text-xs text-muted">
                          {c.viewers}/50 {t.home.viewers}
                        </div>
                      </li>
                    ))}
                  </ul>
                )}
              </HomeCard>

              {/* BEGIN CHANGE: bans ativos (so se houver) */}
              {bans.length > 0 && (
                <HomeCard title={t.home.bansTitle} subtitle={t.home.bansSubtitle}>
                  <ul className="divide-y divide-border/50">
                    {bans.map((b) => (
                      <li key={b.id} className="flex items-start gap-3 py-3 first:pt-0 last:pb-0">
                        <Outfit look={b.player.look} size="inline" alt={b.player.name} />
                        <div className="min-w-0 text-sm">
                          <Link
                            href={`/character/?name=${encodeURIComponent(b.player.name)}`}
                            className="font-medium text-brand hover:underline"
                          >
                            {b.player.name}
                          </Link>
                          <div className="text-xs text-muted">
                            {b.reason}
                            {b.comment ? ` - ${b.comment}` : ""}
                          </div>
                          <div className="mt-1 text-xs text-muted">
                            {fmtTs(b.added)}
                            {b.expires === -1
                              ? ` - ${t.home.banPermanent}`
                              : b.expires > 0
                                ? ` - ${t.home.banExpires} ${fmtTs(b.expires)}`
                                : ""}
                          </div>
                        </div>
                      </li>
                    ))}
                  </ul>
                </HomeCard>
              )}
              {/* END CHANGE */}

              {/* Contatos */}
              <HomeCard title={t.home.contactsTitle} subtitle={t.home.contactsSubtitle}>
                <ul className="space-y-3">
                  <li>
                    {contacts?.telegram?.configured ? (
                      <a
                        href={contacts.telegram.url}
                        target="_blank"
                        rel="noopener noreferrer"
                        className="flex items-center gap-3 rounded-lg border border-border bg-background/40 px-4 py-3 text-sm font-medium transition-colors hover:border-brand/40 hover:text-brand"
                      >
                        <span className="grid h-10 w-10 place-items-center rounded-full bg-[#229ED9]/15 text-xs font-semibold text-[#229ED9]">
                          TG
                        </span>
                        <span>
                          <span className="block">{t.home.contactTelegram}</span>
                          <span className="text-xs font-normal text-muted">{t.home.telegramCta}</span>
                        </span>
                      </a>
                    ) : (
                      <div className="flex items-center gap-3 rounded-lg border border-border/60 px-4 py-3 text-sm text-muted">
                        <span className="grid h-10 w-10 place-items-center rounded-full bg-background text-xs">
                          TG
                        </span>
                        <span>
                          <span className="block text-foreground/80">{t.home.contactTelegram}</span>
                          <span className="text-xs">{t.home.telegramMissing}</span>
                        </span>
                      </div>
                    )}
                  </li>
                  <li>
                    {contacts?.discord?.configured ? (
                      <a
                        href={contacts.discord.url}
                        target="_blank"
                        rel="noopener noreferrer"
                        className="flex items-center gap-3 rounded-lg border border-border bg-background/40 px-4 py-3 text-sm font-medium transition-colors hover:border-brand/40 hover:text-brand"
                      >
                        <span className="grid h-10 w-10 place-items-center rounded-full bg-[#5865F2]/15 text-xs font-semibold text-[#5865F2]">
                          DC
                        </span>
                        <span>
                          <span className="block">{t.home.contactDiscord}</span>
                          <span className="text-xs font-normal text-muted">{t.home.discordCta}</span>
                        </span>
                      </a>
                    ) : (
                      <div className="flex items-center gap-3 rounded-lg border border-border/60 px-4 py-3 text-sm text-muted">
                        <span className="grid h-10 w-10 place-items-center rounded-full bg-background text-xs">
                          DC
                        </span>
                        <span>
                          <span className="block text-foreground/80">{t.home.contactDiscord}</span>
                          <span className="text-xs">{t.home.discordMissing}</span>
                        </span>
                      </div>
                    )}
                  </li>
                  <li>
                    {contacts?.email?.configured ? (
                      <a
                        href={`mailto:${contacts.email.address}`}
                        className="flex items-center gap-3 rounded-lg border border-border bg-background/40 px-4 py-3 text-sm font-medium transition-colors hover:border-brand/40 hover:text-brand"
                      >
                        <span className="grid h-10 w-10 place-items-center rounded-full bg-brand/15 text-xs font-semibold text-brand">
                          @
                        </span>
                        <span>
                          <span className="block">{t.home.contactEmail}</span>
                          <span className="text-xs font-normal text-muted break-all">
                            {contacts.email.address}
                          </span>
                        </span>
                      </a>
                    ) : (
                      <div className="flex items-center gap-3 rounded-lg border border-border/60 px-4 py-3 text-sm text-muted">
                        <span className="grid h-10 w-10 place-items-center rounded-full bg-background text-xs">
                          @
                        </span>
                        <span>
                          <span className="block text-foreground/80">{t.home.contactEmail}</span>
                          <span className="text-xs">{t.home.emailMissing}</span>
                        </span>
                      </div>
                    )}
                  </li>
                </ul>
              </HomeCard>

              {/* Videos */}
              <div className="lg:col-span-2">
              <HomeCard title={t.home.videosTitle} subtitle={t.home.videosSubtitle}>
                {videos.length === 0 ? (
                  <p className="text-sm text-muted">{t.home.videosEmpty}</p>
                ) : (
                  // BEGIN CHANGE: embed YouTube full-width + absolute fill (globals height:auto quebrava)
                  <div className="grid grid-cols-1 gap-4">
                    {videos.map((v) => (
                      <div key={v.id} className="overflow-hidden rounded-lg border border-border/70">
                        <div className="flex items-center justify-between gap-2 border-b border-border/70 px-3 py-2">
                          <div className="truncate text-sm font-medium">{v.title}</div>
                          {isAdmin && (
                            <button
                              type="button"
                              onClick={() => removeVideo(v.id)}
                              disabled={videoBusy}
                              className="shrink-0 text-xs text-muted hover:text-brand disabled:opacity-50"
                            >
                              {t.home.videoRemove}
                            </button>
                          )}
                        </div>
                        <div className="relative aspect-video bg-black/40">
                          <iframe
                            title={v.title}
                            src={`https://www.youtube.com/embed/${encodeURIComponent(v.youtubeId)}`}
                            className="absolute inset-0 h-full w-full border-0"
                            allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
                            allowFullScreen
                          />
                        </div>
                      </div>
                    ))}
                  </div>
                  // END CHANGE
                )}

                {isAdmin && (
                  <form onSubmit={addVideo} className="mt-5 space-y-3 border-t border-border pt-4">
                    <p className="text-xs text-muted">{t.home.videoAdminHint}</p>
                    <div>
                      <label className="mb-1 block text-xs text-muted">{t.home.videoTitleLabel}</label>
                      <input
                        value={videoTitle}
                        onChange={(e) => setVideoTitle(e.target.value)}
                        className="w-full rounded-lg border border-border bg-background/50 px-3 py-2 text-sm"
                        maxLength={120}
                      />
                    </div>
                    <div>
                      <label className="mb-1 block text-xs text-muted">{t.home.videoUrlLabel}</label>
                      <input
                        value={videoUrl}
                        onChange={(e) => setVideoUrl(e.target.value)}
                        className="w-full rounded-lg border border-border bg-background/50 px-3 py-2 text-sm"
                        placeholder="https://youtu.be/..."
                        required
                      />
                    </div>
                    {videoMsg && <p className="text-xs text-red-400">{videoMsg}</p>}
                    <button
                      type="submit"
                      disabled={videoBusy}
                      className="rounded-lg bg-brand px-4 py-2 text-sm font-medium text-background disabled:opacity-50"
                    >
                      {t.home.videoAdd}
                    </button>
                  </form>
                )}
              </HomeCard>
              </div>
            </>
          )}
        </div>

        <section className="mx-auto grid w-full max-w-6xl grid-cols-1 gap-4 px-4 pb-20 sm:grid-cols-2 sm:gap-5 sm:px-6 sm:pb-28 lg:grid-cols-4">
          {t.cards.map((card, i) => (
            <Link
              key={card.title}
              href={cardHrefs[i] ?? "#"}
              className="group rounded-xl border border-border bg-panel p-6 transition-colors hover:border-brand/40"
            >
              <div className="mb-4 grid h-10 w-10 place-items-center rounded-lg bg-brand/10 text-brand transition-colors group-hover:bg-brand/20">
                +
              </div>
              <h3 className="mb-2 text-base font-semibold">{card.title}</h3>
              <p className="text-sm text-muted">{card.desc}</p>
            </Link>
          ))}
        </section>
      </main>

      <Footer />
    </div>
  );
}
// END CHANGE
