// BEGIN CHANGE: ficha de monstro (DB + loot/ataques do XML do server)
"use client";

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

type Loot = { id: number; name: string; chance: number; countMax: number };
type Attack = { name: string; min: number | null; max: number | null; chance: number | null };
type Detail = {
  name: string;
  description: string;
  exp: number;
  health: number;
  race: string;
  immunities: string;
  voices: string;
  summonable: boolean;
  convinceable: boolean;
  look: Look;
  hasXml: boolean;
  xml: {
    loot: Loot[];
    attacks: Attack[];
    armor: number | null;
    defense: number | null;
    elements: Record<string, number>;
    speed: number | null;
  } | null;
};

export default function MonsterDetailPage() {
  const { t } = useI18n();
  const [data, setData] = useState<Detail | null>(null);
  const [status, setStatus] = useState<"loading" | "ok" | "error" | "notfound">("loading");

  useEffect(() => {
    const name = new URLSearchParams(window.location.search).get("name") ?? "";
    if (!name) {
      setStatus("notfound");
      return;
    }
    fetch(apiUrl(`monster.php?name=${encodeURIComponent(name)}`))
      .then((r) => {
        if (r.status === 404) {
          setStatus("notfound");
          return null;
        }
        if (!r.ok) throw new Error("http " + r.status);
        return r.json();
      })
      .then((json) => {
        if (!json) return;
        setData(json.data);
        setStatus("ok");
      })
      .catch(() => setStatus("error"));
  }, []);

  const chancePct = (c: number) => (c > 0 ? `${(c / 1000).toFixed(1)}%` : "-");

  return (
    <div className="flex min-h-screen flex-col">
      <Navbar />
      <main className="mx-auto w-full max-w-3xl flex-1 px-6 py-14">
        <Link href="/monsters" className="text-sm text-muted hover:text-brand">
          &larr; {t.monsters.back}
        </Link>

        {status === "loading" && <p className="mt-8 text-muted">{t.common.loading}</p>}
        {status === "error" && <p className="mt-8 text-muted">{t.common.error}</p>}
        {status === "notfound" && <p className="mt-8 text-muted">{t.common.empty}</p>}

        {status === "ok" && data && (
          <div className="mt-6 space-y-6">
            <div className="flex items-center gap-5 rounded-xl border border-border bg-panel p-6">
              <Outfit look={data.look} size="profile" alt={data.name} />
              <div>
                <h1 className="text-3xl font-semibold tracking-tight">{data.name}</h1>
                <p className="mt-1 text-sm text-muted">{data.description}</p>
                <div className="mt-3 flex flex-wrap gap-3 text-sm">
                  <span className="rounded-lg bg-brand/10 px-2 py-1 text-brand">
                    {t.monsters.exp}: {data.exp.toLocaleString()}
                  </span>
                  <span className="rounded-lg bg-background px-2 py-1 text-muted">
                    {t.monsters.health}: {data.health.toLocaleString()}
                  </span>
                  <span className="rounded-lg bg-background px-2 py-1 text-muted">
                    {t.monsters.race}: {data.race}
                  </span>
                </div>
              </div>
            </div>

            {data.immunities && (
              <div className="rounded-xl border border-border bg-panel p-5 text-sm">
                <div className="mb-1 font-semibold">{t.monsters.immunities}</div>
                <div className="text-muted">{data.immunities}</div>
              </div>
            )}

            {data.xml && (
              <>
                <div className="rounded-xl border border-border bg-panel p-5 text-sm">
                  <div className="mb-3 font-semibold">{t.monsters.attacks}</div>
                  {data.xml.armor != null && (
                    <div className="mb-2 text-muted">
                      {t.monsters.armor}: {data.xml.armor} &middot; {t.monsters.defense}:{" "}
                      {data.xml.defense ?? "-"}
                    </div>
                  )}
                  <ul className="space-y-1">
                    {data.xml.attacks.map((a, i) => (
                      <li key={i} className="flex justify-between border-b border-border/40 py-1">
                        <span>{a.name}</span>
                        <span className="text-muted">
                          {a.min != null ? `${a.min} / ${a.max}` : "-"}
                          {a.chance != null ? ` (${a.chance}%)` : ""}
                        </span>
                      </li>
                    ))}
                  </ul>
                </div>

                <div className="rounded-xl border border-border bg-panel p-5 text-sm">
                  <div className="mb-3 font-semibold">{t.monsters.loot}</div>
                  {data.xml.loot.length === 0 ? (
                    <p className="text-muted">{t.monsters.noLoot}</p>
                  ) : (
                    <ul className="space-y-1">
                      {data.xml.loot.map((l, i) => (
                        <li
                          key={i}
                          className="flex items-center justify-between gap-3 border-b border-border/40 py-1.5"
                        >
                          <span className="inline-flex min-w-0 items-center gap-2">
                            <ItemIcon id={l.id} alt={l.name} size={32} />
                            <span className="truncate">
                              {l.name}
                              {l.countMax > 1 ? ` (x${l.countMax})` : ""}
                            </span>
                          </span>
                          <span className="shrink-0 text-muted">
                            {t.monsters.chance}: {chancePct(l.chance)}
                          </span>
                        </li>
                      ))}
                    </ul>
                  )}
                </div>
              </>
            )}

            {!data.hasXml && (
              <p className="text-sm text-muted">{t.monsters.noLoot}</p>
            )}
          </div>
        )}
      </main>
      <Footer />
    </div>
  );
}
// END CHANGE
