// BEGIN CHANGE: /enchantments guide page
"use client";

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

type BenefitBand = {
  minLow: number;
  minHigh: number;
  maxLow: number;
  maxHigh: number;
};

type Benefit = {
  id: string;
  stat: string;
  label: string;
  summary: string;
  range?: BenefitBand;
  noElem?: BenefitBand;
  withElem?: BenefitBand;
  note?: string;
};

type Guide = {
  breakChance: number | string;
  breakChanceMin?: number;
  breakChanceMax?: number;
  chargeMin: number;
  chargeMax: number;
  benefits?: Benefit[];
};

type BonusEstimate = {
  stat: string;
  unit: string;
  min?: number;
  max?: number;
  noElem?: { min: number; max: number };
  withElem?: { min: number; max: number };
  note?: string;
};

type Preview = {
  bonusTier: number;
  costIndex: number;
  breakChance?: number;
  estimate: { id: string; count: number }[];
  bonusEstimate?: BonusEstimate | null;
};

const CATEGORY_IDS = ["melee", "dist", "wand", "shield", "spellbook"] as const;
const BAND_IDS = ["low", "mid", "high", "end"] as const;

export default function EnchantmentsPage() {
  const { t } = useI18n();
  const page = t.enchantmentsPage;
  const [guide, setGuide] = useState<Guide | null>(null);
  const [category, setCategory] = useState("melee");
  const [itemBand, setItemBand] = useState("mid");
  const [resets, setResets] = useState("0");
  const [preview, setPreview] = useState<Preview | null>(null);

  const selectClass =
    "mt-1 w-full rounded border border-border bg-panel px-2 py-1 text-foreground";

  useEffect(() => {
    fetch(apiUrl("enchantments.php"))
      .then((r) => r.json())
      .then((j) => setGuide(j.guide ?? null))
      .catch(() => setGuide(null));
  }, []);

  useEffect(() => {
    const qs = new URLSearchParams({ preview: "1", category, itemBand, resets });
    fetch(apiUrl(`enchantments.php?${qs}`))
      .then((r) => r.json())
      .then((j) => setPreview(j.preview ?? null))
      .catch(() => setPreview(null));
  }, [category, itemBand, resets]);

  const estimateLabel = (id: string) =>
    page.estimate[id as keyof typeof page.estimate] ?? id;

  return (
    <div className="flex min-h-screen flex-col">
      <Navbar />
      <main className="mx-auto w-full max-w-4xl flex-1 px-6 py-14">
        <h1 className="text-3xl font-semibold tracking-tight">{page.title}</h1>
        <p className="mt-2 text-muted">{page.subtitle}</p>

        <section className="mt-8 rounded-xl border border-border bg-panel p-5">
          <h2 className="text-lg font-semibold">{page.howTitle}</h2>
          <ol className="mt-3 list-decimal space-y-2 pl-5 text-sm text-muted">
            {page.howSteps.map((s, i) => (
              <li key={i}>{s}</li>
            ))}
          </ol>
          <p className="mt-4 text-sm text-muted">{page.previewHint}</p>
        </section>

        {/* BEGIN CHANGE: benefits / bonus ranges */}
        <section className="mt-6 rounded-xl border border-border bg-panel p-5">
          <h2 className="text-lg font-semibold">{page.benefitsTitle}</h2>
          <p className="mt-1 text-sm text-muted">{page.benefitsIntro}</p>
          <div className="mt-4 grid gap-3 sm:grid-cols-2">
            {(guide?.benefits ?? []).map((b) => (
              <div key={b.id} className="rounded-lg border border-border/70 bg-background/40 p-3 text-sm">
                <div className="font-medium text-foreground">{b.label}</div>
                <div className="mt-1 text-muted">{b.summary}</div>
                {b.noElem && b.withElem ? (
                  <ul className="mt-2 space-y-1 text-muted">
                    <li>
                      {page.benefitsNoElem}: +{b.noElem.minLow}-{b.noElem.maxLow} ({page.tierLow}) - +
                      {b.noElem.minHigh}-{b.noElem.maxHigh} ({page.tierHigh})
                    </li>
                    <li>
                      {page.benefitsWithElem}: +{b.withElem.minLow}-{b.withElem.maxLow} ({page.tierLow}) - +
                      {b.withElem.minHigh}-{b.withElem.maxHigh} ({page.tierHigh})
                    </li>
                  </ul>
                ) : b.range ? (
                  <p className="mt-2 text-muted">
                    {b.stat === "wandMult"
                      ? `${b.range.minLow.toFixed(2)}x-${b.range.maxLow.toFixed(1)}x (${page.tierLow}) - ${b.range.minHigh.toFixed(2)}x-${b.range.maxHigh.toFixed(1)}x (${page.tierHigh})`
                      : `+${b.range.minLow}-${b.range.maxLow} (${page.tierLow}) - +${b.range.minHigh}-${b.range.maxHigh} (${page.tierHigh})`}
                  </p>
                ) : null}
                {b.note ? <p className="mt-2 text-xs text-muted">{b.note}</p> : null}
              </div>
            ))}
          </div>
          <p className="mt-4 text-sm text-muted">{page.benefitsCharges}</p>
          <p className="mt-2 text-sm text-muted">{page.benefitsKnightNote}</p>
        </section>
        {/* END CHANGE */}

        <section className="mt-6 rounded-xl border border-border bg-panel p-5">
          <h2 className="text-lg font-semibold">{page.rulesTitle}</h2>
          <ul className="mt-3 list-disc space-y-2 pl-5 text-sm text-muted">
            {page.rules.map((r, i) => (
              <li key={i}>{r}</li>
            ))}
          </ul>
          {guide && (
            <p className="mt-4 text-sm text-muted">
              {page.chargesHint
                .replace("{min}", guide.chargeMin.toLocaleString())
                .replace("{max}", guide.chargeMax.toLocaleString())
                .replace(
                  "{pct}",
                  guide.breakChanceMin != null && guide.breakChanceMax != null
                    ? `${guide.breakChanceMin}-${guide.breakChanceMax}`
                    : String(guide.breakChance)
                )}
            </p>
          )}
        </section>

        <section className="mt-6 rounded-xl border border-border bg-panel p-5">
          <h2 className="text-lg font-semibold">{page.estimatorTitle}</h2>
          <p className="mt-1 text-sm text-muted">{page.estimatorHint}</p>
          <div className="mt-4 grid gap-3 sm:grid-cols-3">
            <label className="text-sm">
              {page.categoryLabel}
              <select className={selectClass} value={category} onChange={(e) => setCategory(e.target.value)}>
                {CATEGORY_IDS.map((id) => (
                  <option key={id} value={id}>
                    {page.categories[id]}
                  </option>
                ))}
              </select>
            </label>
            <label className="text-sm">
              {page.itemPowerLabel}
              <select className={selectClass} value={itemBand} onChange={(e) => setItemBand(e.target.value)}>
                {BAND_IDS.map((id) => (
                  <option key={id} value={id}>
                    {page.bands[id]}
                  </option>
                ))}
              </select>
            </label>
            <label className="text-sm">
              {page.resetsLabel}
              <select className={selectClass} value={resets} onChange={(e) => setResets(e.target.value)}>
                <option value="0">0</option>
                <option value="10">10</option>
                <option value="20">20</option>
                <option value="30">30+</option>
              </select>
            </label>
          </div>
          {preview && (
            <div className="mt-4 text-sm text-muted">
              <p>
                {page.bonusTier.replace("{tier}", String(preview.bonusTier))}
                {" | "}
                {page.costIndex.replace("{index}", String(preview.costIndex))}
                {preview.breakChance != null ? (
                  <>
                    {" | "}
                    {page.breakChanceLabel.replace("{pct}", String(preview.breakChance))}
                  </>
                ) : null}
              </p>
              {preview.bonusEstimate ? (
                <div className="mt-3 rounded-lg border border-border/70 bg-background/40 p-3">
                  <p className="font-medium text-foreground">{page.bonusEstimateTitle}</p>
                  {preview.bonusEstimate.noElem && preview.bonusEstimate.withElem ? (
                    <ul className="mt-2 list-disc pl-5 text-muted">
                      <li>
                        {page.benefitsNoElem}: +{preview.bonusEstimate.noElem.min} - +
                        {preview.bonusEstimate.noElem.max} atk
                      </li>
                      <li>
                        {page.benefitsWithElem}: +{preview.bonusEstimate.withElem.min} - +
                        {preview.bonusEstimate.withElem.max} atk
                      </li>
                    </ul>
                  ) : preview.bonusEstimate.unit === "x" ? (
                    <p className="mt-2 text-muted">
                      {preview.bonusEstimate.min}x - {preview.bonusEstimate.max}x {page.bonusEstimateWand}
                    </p>
                  ) : (
                    <p className="mt-2 text-muted">
                      +{preview.bonusEstimate.min} - +{preview.bonusEstimate.max} {preview.bonusEstimate.unit}
                    </p>
                  )}
                  {preview.bonusEstimate.note ? (
                    <p className="mt-2 text-xs text-muted">{preview.bonusEstimate.note}</p>
                  ) : null}
                </div>
              ) : null}
              <ul className="mt-2 list-disc pl-5">
                {preview.estimate.map((e) => (
                  <li key={e.id}>
                    {e.count.toLocaleString()} {estimateLabel(e.id)}
                  </li>
                ))}
              </ul>
            </div>
          )}
        </section>

        <div className="mt-6 text-sm">
          <Link href="/server-info" className="text-brand hover:underline">
            {page.linkServerInfo}
          </Link>
          {" - "}
          <Link href="/items" className="text-brand hover:underline">
            {page.linkItems}
          </Link>
        </div>
      </main>
      <Footer />
    </div>
  );
}
// END CHANGE
