// BEGIN CHANGE: pagina /houses - precificacao por distancia ao templo
"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 { apiUrl } from "@/lib/api";

type HouseTier = {
  id: string;
  dMin: number;
  dMax: number | null;
  multiplier: string;
  examplePrice: number;
};

type FreeHouse = {
  id: number;
  name: string;
  town: string;
  size: number;
  beds: number;
  price: number;
  rent: number;
  guildHall: boolean;
};

type HousesPayload = {
  enabled: boolean;
  locationPricing: boolean;
  pricePerSquare: number;
  priceAsRent: boolean;
  levelToBuy: number;
  housesPerAccount: number;
  needPremium: boolean;
  temple: { x: number; y: number; z: number };
  distanceFormula: string;
  baseFormula: string;
  safeCap: number;
  tiers: HouseTier[];
  example: { size: number; beds: number; basePrice: number };
  stats: { total: number; free: number; rented: number };
  freeHouses: FreeHouse[];
};

function fmtGold(n: number): string {
  return n.toLocaleString("pt-BR");
}

export default function HousesPage() {
  const { t } = useI18n();
  const tr = t.housesPage;
  const [status, setStatus] = useState<"loading" | "ok" | "error">("loading");
  const [data, setData] = useState<HousesPayload | null>(null);

  useEffect(() => {
    let cancelled = false;
    (async () => {
      try {
        const r = await fetch(apiUrl("houses.php"));
        if (!r.ok) throw new Error("fail");
        const j = (await r.json()) as HousesPayload;
        if (cancelled) return;
        setData(j);
        setStatus("ok");
      } catch {
        if (!cancelled) setStatus("error");
      }
    })();
    return () => {
      cancelled = true;
    };
  }, []);

  const tierLabel = (id: string) =>
    (tr.tierLabels as Record<string, string>)[id] || id;

  return (
    <div className="flex min-h-screen flex-col">
      <Navbar />
      <main className="mx-auto w-full max-w-5xl flex-1 px-4 py-8">
        <div className="mb-6">
          <h1 className="text-2xl font-semibold tracking-tight">{tr.title}</h1>
          <p className="mt-2 text-sm text-muted">{tr.subtitle}</p>
          <p className="mt-3 text-sm">
            <Link href="/server-info" className="text-brand hover:underline">
              {tr.backServerInfo}
            </Link>
          </p>
        </div>

        {status === "loading" && (
          <p className="text-sm text-muted">{t.common.loading}</p>
        )}
        {status === "error" && (
          <p className="text-sm text-red-600">{tr.loadError}</p>
        )}

        {status === "ok" && data && (
          <div className="space-y-6">
            <section className="rounded-xl border border-border bg-card/40 p-5">
              <h2 className="text-lg font-semibold">{tr.rulesTitle}</h2>
              <ul className="mt-3 list-disc space-y-2 pl-5 text-sm text-muted">
                <li>
                  {tr.ruleLevel.replace("{level}", String(data.levelToBuy))}
                </li>
                <li>
                  {tr.rulePerAccount.replace(
                    "{n}",
                    String(data.housesPerAccount)
                  )}
                </li>
                <li>
                  {data.needPremium ? tr.rulePremiumOn : tr.rulePremiumOff}
                </li>
                <li>
                  {tr.ruleBase
                    .replace("{gp}", fmtGold(data.pricePerSquare))
                    .replace("{formula}", data.baseFormula)}
                </li>
                {data.locationPricing ? (
                  <li>{tr.ruleLocationOn}</li>
                ) : (
                  <li>{tr.ruleLocationOff}</li>
                )}
                {data.priceAsRent && <li>{tr.rulePriceAsRent}</li>}
                <li>{tr.ruleCap.replace("{cap}", fmtGold(data.safeCap))}</li>
              </ul>
              <p className="mt-4 font-mono text-xs text-brand">
                {data.distanceFormula}
              </p>
              <p className="mt-1 text-xs text-muted">
                {tr.templeNote
                  .replace("{x}", String(data.temple.x))
                  .replace("{y}", String(data.temple.y))
                  .replace("{z}", String(data.temple.z))}
              </p>
            </section>

            <section className="overflow-hidden rounded-xl border border-border">
              <div className="border-b border-border px-5 py-3">
                <h2 className="text-sm font-medium">{tr.tiersTitle}</h2>
                <p className="mt-1 text-xs text-muted">
                  {tr.tiersHint
                    .replace("{size}", String(data.example.size))
                    .replace("{base}", fmtGold(data.example.basePrice))}
                </p>
              </div>
              <div className="overflow-x-auto">
                <table className="w-full min-w-[520px] text-left text-sm">
                  <thead className="border-b border-border text-muted">
                    <tr>
                      <th className="px-4 py-2 font-medium">{tr.colTier}</th>
                      <th className="px-4 py-2 font-medium">{tr.colDistance}</th>
                      <th className="px-4 py-2 font-medium">{tr.colMult}</th>
                      <th className="px-4 py-2 font-medium">{tr.colExample}</th>
                    </tr>
                  </thead>
                  <tbody>
                    {data.tiers.map((tier) => (
                      <tr key={tier.id} className="border-t border-border/40">
                        <td className="px-4 py-2 font-medium">
                          {tierLabel(tier.id)}
                        </td>
                        <td className="px-4 py-2 tabular-nums text-muted">
                          {tier.dMax == null
                            ? `${tier.dMin}+`
                            : `${tier.dMin}-${tier.dMax}`}
                        </td>
                        <td className="px-4 py-2 font-mono text-muted">
                          {tier.multiplier}
                        </td>
                        <td className="px-4 py-2 tabular-nums text-muted">
                          {fmtGold(tier.examplePrice)}
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </section>

            <section className="rounded-xl border border-border bg-card/40 p-5">
              <h2 className="text-lg font-semibold">{tr.stockTitle}</h2>
              <p className="mt-2 text-sm text-muted">
                {tr.stockStats
                  .replace("{total}", String(data.stats.total))
                  .replace("{free}", String(data.stats.free))
                  .replace("{rented}", String(data.stats.rented))}
              </p>
              {data.freeHouses.length === 0 ? (
                <p className="mt-4 text-sm text-muted">{tr.stockEmpty}</p>
              ) : (
                <div className="mt-4 overflow-x-auto">
                  <table className="w-full min-w-[560px] text-left text-sm">
                    <thead className="border-b border-border text-muted">
                      <tr>
                        <th className="px-2 py-2 font-medium">{tr.colHouse}</th>
                        <th className="px-2 py-2 font-medium">{tr.colTown}</th>
                        <th className="px-2 py-2 font-medium">{tr.colSize}</th>
                        <th className="px-2 py-2 font-medium">{tr.colPrice}</th>
                        <th className="px-2 py-2 font-medium">{tr.colRent}</th>
                      </tr>
                    </thead>
                    <tbody>
                      {data.freeHouses.map((h) => (
                        <tr key={h.id} className="border-t border-border/40">
                          <td className="px-2 py-2">
                            {h.name}
                            {h.guildHall ? (
                              <span className="ml-2 text-xs text-muted">
                                ({tr.guildHall})
                              </span>
                            ) : null}
                          </td>
                          <td className="px-2 py-2 text-muted">{h.town}</td>
                          <td className="px-2 py-2 tabular-nums text-muted">
                            {h.size}
                            {h.beds > 0 ? ` (+${h.beds} beds)` : ""}
                          </td>
                          <td className="px-2 py-2 tabular-nums text-muted">
                            {fmtGold(h.price)}
                          </td>
                          <td className="px-2 py-2 tabular-nums text-muted">
                            {fmtGold(h.rent)}
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              )}
            </section>
          </div>
        )}
      </main>
      <Footer />
    </div>
  );
}
// END CHANGE
