// BEGIN CHANGE: pagina Items (gear relevante do items.xml)
"use client";

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

type WandInfo = {
  level: number | null;
  mana: number | null;
  manaPercent: number | null;
  mlMult: number | null;
  mlMultMax: number | null;
  levelDiv: number | null;
  levelMult: number | null;
};

type ItemRow = {
  id: number;
  name: string;
  attack: number | null;
  defense: number | null;
  armor: number | null;
  weaponType: string | null;
  slotType: string | null;
  description: string | null;
  weight: number | null;
  wand?: WandInfo | null;
};

function formatWandDmg(w: WandInfo | null | undefined): string | null {
  if (!w || w.mlMult == null) return null;
  const ml =
    w.mlMultMax != null && w.mlMultMax !== w.mlMult
      ? `ML x ${w.mlMult}-${w.mlMultMax}`
      : `ML x ${w.mlMult}`;
  if (w.levelDiv != null) {
    return `${ml} + lvl/${w.levelDiv}`;
  }
  if (w.levelMult != null && w.levelMult > 0) {
    return `${ml} + lvl x ${w.levelMult}`;
  }
  return ml;
}

// BEGIN CHANGE: categoriza item por tipo/slot para filtro na pagina
function itemCategory(it: ItemRow): string {
  const w = (it.weaponType || "").toLowerCase();
  const s = (it.slotType || "").toLowerCase();
  // BEGIN CHANGE: aba Imbuements (scrolls 12742-12748)
  if (w === "imbuement" || (it.id >= 12742 && it.id <= 12748)) return "imbuement";
  // END CHANGE
  // weaponType do items.xml manda; metadado wand so conta se nao for melee tipado
  // (evita Vip Elite Sword sumir da aba Swords por comentario legado em weapons.xml)
  if (w === "sword") return "sword";
  if (w === "axe") return "axe";
  if (w === "club") return "club";
  if (w === "distance") return s === "ammo" ? "ammunition" : "distance";
  if (w === "ammunition" || s === "ammo") return "ammunition";
  if (s === "shield" || w === "shield") return "shield";
  if (it.wand || w === "wand" || w === "rod") return "wand";
  if (s === "head") return "helmet";
  if (s === "body") return "armor";
  if (s === "legs") return "legs";
  if (s === "feet") return "boots";
  if (s === "necklace") return "amulet";
  if (s === "ring") return "ring";
  if (w !== "") return "weapon";
  return "other";
}

const CATEGORY_ORDER = [
  "all",
  "imbuement",
  "sword",
  "axe",
  "club",
  "distance",
  "ammunition",
  "wand",
  "shield",
  "helmet",
  "armor",
  "legs",
  "boots",
  "amulet",
  "ring",
  "weapon",
  "other",
];

const CATEGORY_LABEL: Record<string, string> = {
  all: "All",
  imbuement: "Imbuements",
  sword: "Swords",
  axe: "Axes",
  club: "Clubs",
  distance: "Bows / Crossbows",
  ammunition: "Ammunition",
  wand: "Wands / Rods",
  shield: "Shields",
  helmet: "Helmets",
  armor: "Armors",
  legs: "Legs",
  boots: "Boots",
  amulet: "Amulets",
  ring: "Rings",
  weapon: "Other weapons",
  other: "Other",
};

export default function ItemsPage() {
  const { t } = useI18n();
  const [rows, setRows] = useState<ItemRow[]>([]);
  const [total, setTotal] = useState(0);
  const [query, setQuery] = useState("");
  const [category, setCategory] = useState("all");
  const [status, setStatus] = useState<"loading" | "ok" | "error">("loading");

  useEffect(() => {
    fetch(apiUrl("items.php?limit=5000"))
      .then((r) => {
        if (!r.ok) throw new Error("http " + r.status);
        return r.json();
      })
      .then((json) => {
        setRows(json.data ?? []);
        setTotal(json.totalRelevant ?? 0);
        setStatus("ok");
      })
      .catch(() => setStatus("error"));
  }, []);

  const categoriesPresent = useMemo(() => {
    const set = new Set(rows.map((it) => itemCategory(it)));
    return CATEGORY_ORDER.filter((c) => c === "all" || set.has(c));
  }, [rows]);

  const filtered = useMemo(() => {
    const q = query.trim().toLowerCase();
    return rows.filter((it) => {
      if (category !== "all" && itemCategory(it) !== category) return false;
      if (!q) return true;
      return it.name.toLowerCase().includes(q) || String(it.id) === q;
    });
  }, [rows, query, category]);

  return (
    <div className="flex min-h-screen flex-col">
      <Navbar />
      <main className="mx-auto w-full max-w-5xl flex-1 px-6 py-14">
        <h1 className="text-3xl font-semibold tracking-tight">{t.itemsCatalog.title}</h1>
        <p className="mt-2 text-muted">
          {t.itemsCatalog.subtitle}{" "}
          {status === "ok" && <span className="text-brand">{total}</span>}
        </p>
        {/* BEGIN CHANGE: link para biblioteca de Imbuements */}
        <p className="mt-2 text-sm">
          <Link href="/imbuements" className="text-brand hover:underline">
            {t.imbuementsPage.title}
          </Link>
        </p>
        {/* END CHANGE */}

        <input
          value={query}
          onChange={(e) => setQuery(e.target.value)}
          placeholder={t.itemsCatalog.searchPlaceholder}
          className="mt-6 w-full max-w-sm rounded-lg border border-border bg-panel px-4 py-2 text-sm outline-none focus:border-brand/60"
        />

        {/* BEGIN CHANGE: filtro por categoria de equipamento */}
        {status === "ok" && (
          <div className="mt-4 flex flex-wrap gap-2">
            {categoriesPresent.map((c) => (
              <button
                key={c}
                onClick={() => setCategory(c)}
                className={`rounded-full border px-3 py-1 text-xs transition ${
                  category === c
                    ? "border-brand bg-brand/20 text-brand"
                    : "border-border bg-panel text-muted hover:border-brand/50"
                }`}
              >
                {c === "imbuement" ? t.itemsCatalog.catImbuement : (CATEGORY_LABEL[c] ?? c)}
              </button>
            ))}
          </div>
        )}
        {/* END CHANGE */}

        {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 === "ok" && filtered.length === 0 && <p className="mt-8 text-muted">{t.common.empty}</p>}

        {status === "ok" && filtered.length > 0 && (
          <div className="mt-8 overflow-x-auto rounded-xl border border-border bg-panel">
            <table className="w-full text-left text-sm">
              <thead className="text-muted">
                <tr>
                  <th className="px-4 py-3">ID</th>
                  <th className="px-4 py-3">{t.itemsCatalog.colName}</th>
                  <th className="px-4 py-3">{t.itemsCatalog.colAttack}</th>
                  <th className="px-4 py-3">{t.itemsCatalog.colWand}</th>
                  <th className="px-4 py-3">{t.itemsCatalog.colDefense}</th>
                  <th className="px-4 py-3">{t.itemsCatalog.colArmor}</th>
                  <th className="px-4 py-3">{t.itemsCatalog.colSlot}</th>
                  <th className="px-4 py-3">{t.itemsCatalog.colType}</th>
                </tr>
              </thead>
              <tbody>
                {filtered.map((it) => (
                  <tr key={it.id} className="border-t border-border/50 align-middle">
                    <td className="px-4 py-2 font-mono text-muted">{it.id}</td>
                    <td className="px-4 py-2">
                      {/* BEGIN CHANGE: icone do item na listagem */}
                      <div className="flex items-start gap-3">
                        <div className="mt-0.5 grid h-8 w-8 shrink-0 place-items-center">
                          <ItemIcon id={it.id} alt={it.name} size={32} />
                        </div>
                        <div className="min-w-0">
                          <div className="font-medium">{it.name}</div>
                          {it.description && (
                            <div className="mt-1 text-xs text-muted">{it.description}</div>
                          )}
                        </div>
                      </div>
                      {/* END CHANGE */}
                    </td>
                    <td className="px-4 py-2">{it.attack ?? "-"}</td>
                    <td className="px-4 py-2 text-xs text-muted">
                      {(() => {
                        const dmg = formatWandDmg(it.wand);
                        if (!dmg && !it.wand) return "-";
                        const bits: string[] = [];
                        if (dmg) bits.push(dmg);
                        if (it.wand?.level != null) bits.push(`lvl ${it.wand.level}`);
                        if (it.wand?.mana != null) bits.push(`mana ${it.wand.mana}`);
                        if (it.wand?.manaPercent != null) bits.push(`${it.wand.manaPercent}% mana`);
                        return bits.length ? bits.join(" | ") : "-";
                      })()}
                    </td>
                    <td className="px-4 py-2">{it.defense ?? "-"}</td>
                    <td className="px-4 py-2">{it.armor ?? "-"}</td>
                    <td className="px-4 py-2 text-muted">{it.slotType || "-"}</td>
                    <td className="px-4 py-2 text-muted">{it.weaponType || "-"}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </main>
      <Footer />
    </div>
  );
}
// END CHANGE
