// BEGIN CHANGE: pagina Addons em cards (bonus + Varkhal items/drops)
"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 { addonUrl, apiUrl } from "@/lib/api";

type DropMonster = { name: string; chance: number; countMax: number };

type AddonItem = {
  id: number;
  count: number;
  name: string;
  monsterCount: number;
  monsters: DropMonster[];
};

type AddonOffer = {
  addon: number;
  keyword: string;
  premium: boolean;
  cost: number;
  items: AddonItem[];
};

type AddonRow = {
  level: number;
  outfit: string;
  images: number[];
  bonus: string;
  npc?: string;
  offers: AddonOffer[];
};

function formatGp(n: number): string {
  if (n <= 0) return "";
  return n.toLocaleString("en-US") + " gp";
}

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

export default function AddonsPage() {
  const { t } = useI18n();
  const [rows, setRows] = useState<AddonRow[]>([]);
  const [hint, setHint] = useState("");
  const [npc, setNpc] = useState("");
  const [status, setStatus] = useState<"loading" | "ok" | "error">("loading");
  const [filter, setFilter] = useState("");
  const [openDrops, setOpenDrops] = useState<Record<string, boolean>>({});

  useEffect(() => {
    fetch(apiUrl("addons.php"))
      .then((r) => {
        if (!r.ok) throw new Error("http");
        return r.json();
      })
      .then((json) => {
        const data = (json.data ?? []).map((r: AddonRow) => ({
          ...r,
          offers: Array.isArray(r.offers) ? r.offers : [],
        }));
        setRows(data);
        setHint(json.hint ?? "");
        setNpc(json.npc ?? "");
        setStatus("ok");
      })
      .catch(() => setStatus("error"));
  }, []);

  const filtered = useMemo(() => {
    const q = filter.trim().toLowerCase();
    if (!q) return rows;
    return rows.filter((r) => {
      if (r.outfit.toLowerCase().includes(q)) return true;
      if (String(r.level).includes(q)) return true;
      return r.offers.some((o) =>
        o.items.some(
          (it) =>
            it.name.toLowerCase().includes(q) ||
            it.monsters.some((m) => m.name.toLowerCase().includes(q)),
        ),
      );
    });
  }, [rows, filter]);

  function toggleDrop(key: string) {
    setOpenDrops((prev) => ({ ...prev, [key]: !prev[key] }));
  }

  return (
    <div className="flex min-h-screen flex-col">
      <Navbar />
      <main className="mx-auto w-full max-w-6xl flex-1 px-6 py-14">
        <h1 className="text-3xl font-semibold tracking-tight">{t.addons.title}</h1>
        <p className="mt-2 text-muted">{t.addons.subtitle}</p>
        {hint && (
          <p className="mt-4 rounded-lg border border-brand/30 bg-brand/10 px-4 py-3 text-sm">
            {hint}
          </p>
        )}
        {npc && (
          <p className="mt-2 text-sm text-muted">
            {t.addons.npcLabel}: <span className="text-foreground font-medium">{npc}</span>
          </p>
        )}

        {status === "ok" && (
          <div className="mt-6">
            <input
              value={filter}
              onChange={(e) => setFilter(e.target.value)}
              placeholder={t.addons.filterPlaceholder}
              className="w-full max-w-md rounded-lg border border-border bg-panel px-4 py-2 text-sm outline-none focus:border-brand/60"
            />
          </div>
        )}

        {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.addons.noResults}</p>
        )}

        {status === "ok" && (
          <div className="mt-8 grid gap-5 sm:grid-cols-2">
            {filtered.map((r) => (
              <article
                key={`${r.level}-${r.outfit}`}
                className="flex flex-col rounded-xl border border-border bg-panel p-5"
              >
                <div className="flex items-start gap-4">
                  <div className="flex shrink-0 flex-wrap gap-1">
                    {r.images.map((id) => (
                      // eslint-disable-next-line @next/next/no-img-element
                      <img key={id} src={addonUrl(id)} alt="" className="h-12 w-12" />
                    ))}
                  </div>
                  <div className="min-w-0 flex-1">
                    <div className="flex flex-wrap items-baseline gap-x-3 gap-y-1">
                      <h2 className="text-lg font-semibold tracking-tight">{r.outfit}</h2>
                      {r.level > 0 && (
                        <span className="text-sm text-muted">
                          {t.addons.colLevel} {r.level}
                        </span>
                      )}
                    </div>
                    {r.bonus && (
                      <p className="mt-1 text-sm text-brand">
                        {t.addons.colBonus}: {r.bonus}
                      </p>
                    )}
                    <p className="mt-1 text-xs text-muted">{t.addons.fullOutfitHint}</p>
                  </div>
                </div>

                {r.offers.length === 0 ? (
                  <p className="mt-4 text-sm text-muted">{t.addons.noVarkhalOffer}</p>
                ) : (
                  <div className="mt-4 space-y-4">
                    {r.offers.map((offer) => (
                      <div
                        key={`${r.outfit}-${offer.addon}`}
                        className="rounded-lg border border-border/70 bg-background/40 p-3"
                      >
                        <div className="flex flex-wrap items-center gap-2 text-sm font-medium">
                          <span>
                            {offer.addon === 1 ? t.addons.firstAddon : t.addons.secondAddon}
                          </span>
                          {offer.premium && (
                            <span className="rounded border border-brand/40 bg-brand/10 px-1.5 py-0.5 text-xs text-brand">
                              {t.addons.premium}
                            </span>
                          )}
                          {offer.cost > 0 && (
                            <span className="text-xs text-muted">{formatGp(offer.cost)}</span>
                          )}
                        </div>
                        <p className="mt-1 text-xs text-muted">
                          {t.addons.sayKeyword}:{" "}
                          <span className="font-mono text-foreground">{offer.keyword}</span>
                        </p>

                        {offer.items.length === 0 && offer.cost > 0 ? (
                          <p className="mt-2 text-sm text-muted">{t.addons.goldOnly}</p>
                        ) : (
                          <ul className="mt-3 space-y-2">
                            {offer.items.map((it) => {
                              const dropKey = `${r.outfit}-${offer.addon}-${it.id}`;
                              const open = !!openDrops[dropKey];
                              return (
                                <li key={dropKey} className="text-sm">
                                  <div className="flex items-center gap-2">
                                    <ItemIcon id={it.id} alt={it.name} size={28} />
                                    <span className="min-w-0 flex-1">
                                      <span className="font-medium">
                                        {it.count}x {it.name}
                                      </span>
                                      <span className="ml-1 text-xs text-muted">#{it.id}</span>
                                    </span>
                                    <button
                                      type="button"
                                      onClick={() => toggleDrop(dropKey)}
                                      className="shrink-0 rounded border border-border px-2 py-0.5 text-xs text-muted transition-colors hover:border-brand/50 hover:text-foreground"
                                    >
                                      {it.monsterCount === 0
                                        ? t.addons.noDrops
                                        : open
                                          ? t.addons.hideDrops
                                          : t.addons.showDrops.replace(
                                              "{n}",
                                              String(it.monsterCount),
                                            )}
                                    </button>
                                  </div>
                                  {open && it.monsterCount > 0 && (
                                    <div className="mt-2 ml-9 space-y-1">
                                      {it.monsters.map((m) => (
                                        <div
                                          key={`${dropKey}-${m.name}`}
                                          className="flex flex-wrap items-baseline gap-x-2 text-xs text-muted"
                                        >
                                          <Link
                                            href={`/monster/?name=${encodeURIComponent(m.name)}`}
                                            className="text-foreground hover:text-brand"
                                          >
                                            {m.name}
                                          </Link>
                                          <span>
                                            {t.addons.chance}: {chancePct(m.chance)}
                                            {m.countMax > 1 ? ` (x${m.countMax})` : ""}
                                          </span>
                                        </div>
                                      ))}
                                      {it.monsterCount > it.monsters.length && (
                                        <Link
                                          href={`/item-drops`}
                                          className="inline-block text-xs text-brand hover:underline"
                                        >
                                          {t.addons.moreDrops.replace(
                                            "{n}",
                                            String(it.monsterCount - it.monsters.length),
                                          )}
                                        </Link>
                                      )}
                                    </div>
                                  )}
                                  {open && it.monsterCount === 0 && (
                                    <p className="mt-2 ml-9 text-xs text-muted">
                                      {t.addons.noMonsterDrop}
                                    </p>
                                  )}
                                </li>
                              );
                            })}
                          </ul>
                        )}
                      </div>
                    ))}
                  </div>
                )}
              </article>
            ))}
          </div>
        )}
      </main>
      <Footer />
    </div>
  );
}
// END CHANGE
