// BEGIN CHANGE: pagina Trade Offline (paridade tradeoff.php)
"use client";

import { FormEvent, useCallback, 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 Filter = "all" | "vip" | "container" | "exchange";

type ContainerItem = {
  itemId: number;
  name: string;
  count: number;
  charges: number | null;
  duration: number | null;
};

type Cost = {
  mode: "gold" | "item";
  amount: number;
  display: string;
  unit: string;
  iconId: number;
  itemId: number | null;
  itemName: string | null;
  itemCount: number;
};

type Offer = {
  id: number;
  type: number;
  typeLabel: string;
  itemId: number;
  itemName: string;
  itemCount: number;
  itemCharges: number | null;
  itemDuration: number | null;
  itemDesc: string;
  date: number;
  player: { name: string; look: Look } | null;
  cost: Cost;
  buyCommand: string;
  container: ContainerItem[] | null;
};

type Cmd = { cmd: string; example: string; hint: string };

type ApiPayload = {
  page: number;
  pageSize: number;
  total: number;
  totalPages: number;
  filter: Filter;
  player: string;
  item: string;
  commands: Cmd[];
  deliveryHint: string;
  data: Offer[];
};

const FILTERS: Filter[] = ["all", "vip", "container", "exchange"];

export default function TradeOffPage() {
  const { t } = useI18n();
  const [status, setStatus] = useState<"loading" | "ok" | "error">("loading");
  const [payload, setPayload] = useState<ApiPayload | null>(null);
  const [page, setPage] = useState(1);
  const [filter, setFilter] = useState<Filter>("all");
  const [player, setPlayer] = useState("");
  const [item, setItem] = useState("");
  const [qPlayer, setQPlayer] = useState("");
  const [qItem, setQItem] = useState("");
  const [openContainers, setOpenContainers] = useState<Record<number, boolean>>({});

  const load = useCallback(() => {
    setStatus("loading");
    const params = new URLSearchParams({
      page: String(page),
      filter,
    });
    if (qPlayer.trim()) params.set("player", qPlayer.trim());
    if (qItem.trim()) params.set("item", qItem.trim());

    fetch(apiUrl(`tradeoff.php?${params.toString()}`))
      .then((r) => {
        if (!r.ok) throw new Error("http");
        return r.json();
      })
      .then((json: ApiPayload) => {
        setPayload(json);
        setStatus("ok");
      })
      .catch(() => setStatus("error"));
  }, [page, filter, qPlayer, qItem]);

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

  function onSearch(e: FormEvent) {
    e.preventDefault();
    setPage(1);
    setQPlayer(player);
    setQItem(item);
  }

  function setFilterAndReset(f: Filter) {
    setFilter(f);
    setPage(1);
  }

  function toggleContainer(id: number) {
    setOpenContainers((cur) => ({ ...cur, [id]: !cur[id] }));
  }

  const fmtDate = (epoch: number) =>
    epoch > 0 ? new Date(epoch * 1000).toLocaleString() : "-";

  const filterLabel = (f: Filter) => {
    if (f === "vip") return t.tradeoff.filterVip;
    if (f === "container") return t.tradeoff.filterContainer;
    if (f === "exchange") return t.tradeoff.filterExchange;
    return t.tradeoff.filterAll;
  };

  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.tradeoff.title}</h1>
        <p className="mt-2 text-muted">{t.tradeoff.subtitle}</p>

        {payload?.commands && (
          <section className="mt-6 rounded-xl border border-border bg-panel p-5">
            <h2 className="text-lg font-semibold">{t.tradeoff.commandsTitle}</h2>
            <div className="mt-3 grid gap-3 sm:grid-cols-2">
              {payload.commands.map((c) => (
                <div key={c.cmd} className="rounded-lg border border-border/60 bg-background/40 p-3 text-sm">
                  <code className="font-medium text-foreground">{c.cmd}</code>
                  <div className="mt-1 text-xs text-muted">
                    {t.tradeoff.example}: {c.example}
                  </div>
                  <div className="mt-1 text-xs text-muted">{c.hint}</div>
                </div>
              ))}
            </div>
            {payload.deliveryHint && (
              <p className="mt-4 rounded-lg border border-brand/30 bg-brand/10 px-3 py-2 text-sm">
                {t.tradeoff.deliveryHint}
              </p>
            )}
          </section>
        )}

        <div className="mt-6 flex flex-col gap-3 sm:flex-row sm:items-end sm:justify-between">
          <div className="flex flex-wrap gap-2">
            {FILTERS.map((f) => (
              <button
                key={f}
                type="button"
                onClick={() => setFilterAndReset(f)}
                className={`rounded-lg px-3 py-1.5 text-sm transition-colors ${
                  filter === f
                    ? "bg-brand/20 text-foreground"
                    : "border border-border text-muted hover:text-foreground"
                }`}
              >
                {filterLabel(f)}
              </button>
            ))}
          </div>

          <form onSubmit={onSearch} className="flex flex-wrap gap-2">
            <input
              className="rounded-lg border border-border bg-background px-3 py-1.5 text-sm"
              placeholder={t.tradeoff.searchPlayer}
              value={player}
              onChange={(e) => setPlayer(e.target.value)}
            />
            <input
              className="rounded-lg border border-border bg-background px-3 py-1.5 text-sm"
              placeholder={t.tradeoff.searchItem}
              value={item}
              onChange={(e) => setItem(e.target.value)}
            />
            <button
              type="submit"
              className="rounded-lg bg-brand px-3 py-1.5 text-sm font-medium text-background"
            >
              {t.tradeoff.search}
            </button>
          </form>
        </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" && payload && (
          <>
            <p className="mt-4 text-xs text-muted">
              {payload.total} {t.tradeoff.offers} - {t.tradeoff.page} {payload.page}/
              {payload.totalPages}
            </p>

            {/* BEGIN CHANGE: cards de oferta no lugar da tabela */}
            {payload.data.length === 0 ? (
              <p className="mt-3 rounded-xl border border-border bg-panel px-4 py-10 text-center text-muted">
                {t.tradeoff.empty}
              </p>
            ) : (
              <div className="mt-3 grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3">
                {payload.data.map((o) => {
                  const open = !!openContainers[o.id];
                  const isContainer = o.type === 2;
                  const badge =
                    o.cost.mode === "item"
                      ? t.tradeoff.filterExchange
                      : o.typeLabel !== "item"
                        ? o.typeLabel
                        : null;

                  return (
                    <article
                      key={o.id}
                      className="flex flex-col rounded-xl border border-border bg-panel p-4"
                    >
                      <div className="flex items-start gap-3">
                        <div className="relative flex h-14 w-14 shrink-0 items-center justify-center rounded-lg border border-border bg-background/40">
                          <ItemIcon id={o.itemId} size={32} alt={o.itemName} />
                          <span className="absolute -bottom-1 -right-1 rounded bg-background/90 px-1 text-[10px] font-semibold">
                            {isContainer ? o.container?.length ?? 0 : o.itemCount}
                          </span>
                        </div>
                        <div className="min-w-0 flex-1">
                          <div className="flex items-start justify-between gap-2">
                            <h3 className="truncate font-medium" title={o.itemName}>
                              {o.itemName}
                            </h3>
                            <span className="shrink-0 font-mono text-xs text-muted">
                              #{o.id}
                            </span>
                          </div>
                          {badge && (
                            <span className="mt-1 inline-block rounded bg-brand/15 px-1.5 py-0.5 text-[10px] uppercase tracking-wide text-brand">
                              {badge}
                            </span>
                          )}
                          <div className="mt-1 text-xs text-muted">{fmtDate(o.date)}</div>
                        </div>
                      </div>

                      {(o.itemDesc || o.itemCharges) && (
                        <div className="mt-3 text-xs text-muted">
                          {o.itemDesc ? <p className="line-clamp-3">{o.itemDesc}</p> : null}
                          {o.itemCharges ? <p>charges: {o.itemCharges}</p> : null}
                        </div>
                      )}

                      <dl className="mt-3 space-y-2 border-t border-border/40 pt-3 text-sm">
                        <div className="flex items-center justify-between gap-2">
                          <dt className="text-xs text-muted">{t.tradeoff.colPlayer}</dt>
                          <dd className="min-w-0 truncate">
                            {o.player ? (
                              <Link
                                href={`/character/?name=${encodeURIComponent(o.player.name)}`}
                                className="inline-flex items-center gap-2 text-brand hover:underline"
                              >
                                <Outfit look={o.player.look} size="inline" alt={o.player.name} />
                                {o.player.name}
                              </Link>
                            ) : (
                              <span className="text-muted">-</span>
                            )}
                          </dd>
                        </div>
                        <div className="flex items-center justify-between gap-2">
                          <dt className="text-xs text-muted">{t.tradeoff.colCost}</dt>
                          <dd className="inline-flex min-w-0 items-center gap-2">
                            <ItemIcon
                              id={o.cost.iconId}
                              size={24}
                              alt={o.cost.itemName || "gold"}
                            />
                            <span className="truncate font-medium">
                              {o.cost.mode === "gold"
                                ? `${o.cost.display} ${o.cost.unit}`
                                : `${o.cost.itemCount}x ${o.cost.itemName}`}
                            </span>
                          </dd>
                        </div>
                      </dl>

                      <div className="mt-3 border-t border-border/40 pt-3">
                        <div className="text-xs text-muted">{t.tradeoff.colBuy}</div>
                        <code className="mt-1 block rounded bg-background/60 px-2 py-1 text-xs">
                          {o.buyCommand}
                        </code>
                      </div>

                      {isContainer && o.container && o.container.length > 0 && (
                        <div className="mt-3">
                          <button
                            type="button"
                            onClick={() => toggleContainer(o.id)}
                            className="text-xs text-brand hover:underline"
                          >
                            {open ? t.tradeoff.containerContents : t.tradeoff.toggleContainer}
                          </button>
                          {open && (
                            <div className="mt-2 flex flex-wrap gap-2 rounded-lg border border-border/60 bg-background/30 p-2">
                              {o.container.map((c, idx) => (
                                <div
                                  key={`${o.id}-${c.itemId}-${idx}`}
                                  className="relative flex h-12 w-12 items-center justify-center rounded-lg border border-border bg-panel"
                                  title={c.name}
                                >
                                  <ItemIcon id={c.itemId} size={32} alt={c.name} />
                                  <span className="absolute bottom-0 right-0 rounded bg-background/90 px-1 text-[10px]">
                                    {c.count}
                                  </span>
                                </div>
                              ))}
                            </div>
                          )}
                        </div>
                      )}
                    </article>
                  );
                })}
              </div>
            )}
            {/* END CHANGE */}

            {payload.totalPages > 1 && (
              <div className="mt-4 flex flex-wrap items-center justify-center gap-2">
                <button
                  type="button"
                  disabled={page <= 1}
                  onClick={() => setPage((p) => Math.max(1, p - 1))}
                  className="rounded-lg border border-border px-3 py-1.5 text-sm disabled:opacity-40"
                >
                  {t.tradeoff.prev}
                </button>
                <span className="text-sm text-muted">
                  {page} / {payload.totalPages}
                </span>
                <button
                  type="button"
                  disabled={page >= payload.totalPages}
                  onClick={() => setPage((p) => Math.min(payload.totalPages, p + 1))}
                  className="rounded-lg border border-border px-3 py-1.5 text-sm disabled:opacity-40"
                >
                  {t.tradeoff.next}
                </button>
              </div>
            )}
          </>
        )}
      </main>
      <Footer />
    </div>
  );
}
// END CHANGE
