// BEGIN CHANGE: guia de vocacoes (canvas-style) carregado do DB
"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 { apiUrl } from "@/lib/api";
import { CollapsiblePanel } from "@/components/CollapsiblePanel";
import { useAuth } from "@/auth/AuthProvider";

type LangText = { pt: string; en: string; es: string };
type LangList = { pt: string[]; en: string[]; es: string[] };

type ProportionalDefenseCfg = {
  enabled: boolean;
  armorRef: number;
  armorLevelFactor: number;
  defenseRef: number;
  defenseLevelFactor: number;
  maxArmorPercent: number;
  maxDefensePercent: number;
  maxPhysicalMitigationPercent: number;
  maxAbsorbPercent: number;
  showDefenseMitigationText?: boolean;
};

type VocGuide = {
  id: number;
  slug: string;
  name: string;
  family: string;
  tier: "base" | "advanced" | string;
  createChoice?: boolean;
  scores: { damage: number; heal: number; sustain: number; difficulty: number; team?: number; control?: number };
  teamRole?: LangText;
  stats: {
    gainHp: number;
    gainMana: number;
    attackSpeed: number;
    formulas: string;
    burstNote: LangText;
    healNote: LangText;
  };
  playstyle: LangText;
  pros: LangList;
  cons: LangList;
};

type GuidePayload = {
  version?: number;
  updatedAt?: number;
  profile?: string;
  verdict: LangText;
  vocations: VocGuide[];
};

function pickText(lang: "pt" | "en" | "es", v: LangText | undefined, fallback = "") {
  if (!v) return fallback;
  return v[lang] || v.en || v.pt || fallback;
}

function pickList(lang: "pt" | "en" | "es", v: LangList | undefined) {
  if (!v) return [] as string[];
  return v[lang] || v.en || v.pt || [];
}

function ScoreBar({ label, value, accent }: { label: string; value: number; accent?: string }) {
  const w = Math.max(0, Math.min(100, value));
  return (
    <div>
      <div className="mb-1 flex justify-between text-xs text-muted">
        <span>{label}</span>
        <span className="font-medium text-foreground">{value}</span>
      </div>
      <div className="h-2 overflow-hidden rounded-full bg-background">
        <div
          className={`h-full rounded-full ${accent ?? "bg-brand"}`}
          style={{ width: `${w}%` }}
        />
      </div>
    </div>
  );
}

export default function VocationsPage() {
  const { t, lang } = useI18n();
  const { account } = useAuth();
  const isDefenseAdmin = (account?.pageAccess ?? 0) >= 6;
  const L = (lang === "en" || lang === "es" ? lang : "pt") as "pt" | "en" | "es";
  const [status, setStatus] = useState<"loading" | "ok" | "error">("loading");
  const [guide, setGuide] = useState<GuidePayload | null>(null);
  const [selected, setSelected] = useState<number | null>(null);
  // BEGIN CHANGE: spells da vocacao selecionada
  type SpellRow = {
    name: string;
    words: string;
    type: string;
    mana: number;
    level: number;
    magicLevel: number;
    soul: number;
    premium: boolean;
  };
  const [spells, setSpells] = useState<SpellRow[]>([]);
  // BEGIN CHANGE: potions com lista de vocation ids (filtro por selected)
  type PotionRow = {
    id: number;
    name: string;
    level: number;
    vocations: number[];
    vocStr: string;
    health: number[] | null;
    mana: number[] | null;
    percent: number | null;
    finitePercent: number | null;
  };
  const [potions, setPotions] = useState<PotionRow[]>([]);
  // END CHANGE
  const [heals, setHeals] = useState<{ name: string; words: string; formula: string | null }[]>([]);
  // BEGIN CHANGE: proportional armor/defense knobs from serverinfo
  const [defenseCfg, setDefenseCfg] = useState<ProportionalDefenseCfg | null>(null);
  // END CHANGE

  useEffect(() => {
    fetch(apiUrl("vocation-guide.php"))
      .then((r) => {
        if (!r.ok) throw new Error("http");
        return r.json();
      })
      .then((json) => {
        setGuide(json.data ?? null);
        const first = (json.data?.vocations ?? []).find((v: VocGuide) => v.createChoice);
        setSelected(first?.id ?? json.data?.vocations?.[0]?.id ?? null);
        setStatus("ok");
      })
      .catch(() => setStatus("error"));
  }, []);

  // BEGIN CHANGE: load proportional defense knobs (admin calibration only)
  useEffect(() => {
    if (!isDefenseAdmin) {
      setDefenseCfg(null);
      return;
    }
    fetch(apiUrl("serverinfo.php"))
      .then((r) => (r.ok ? r.json() : null))
      .then((json) => {
        const cfg = json?.systems?.proportionalArmorDefense;
        if (cfg && typeof cfg === "object") setDefenseCfg(cfg as ProportionalDefenseCfg);
      })
      .catch(() => setDefenseCfg(null));
  }, [isDefenseAdmin]);
  // END CHANGE

  // BEGIN CHANGE: carrega spells ao trocar vocacao
  useEffect(() => {
    if (!selected) {
      setSpells([]);
      return;
    }
    fetch(apiUrl(`spells.php?vocation=${selected}`))
      .then((r) => (r.ok ? r.json() : null))
      .then((json) => setSpells(json?.data ?? []))
      .catch(() => setSpells([]));
  }, [selected]);
  // END CHANGE

  // BEGIN CHANGE: potions + heal formulas
  useEffect(() => {
    fetch(apiUrl("potions.php"))
      .then((r) => (r.ok ? r.json() : null))
      .then((json) => setPotions(json?.data ?? []))
      .catch(() => setPotions([]));
    fetch(apiUrl("potions.php?resource=heals"))
      .then((r) => (r.ok ? r.json() : null))
      .then((json) => setHeals(json?.data ?? []))
      .catch(() => setHeals([]));
  }, []);
  // END CHANGE

  const base = useMemo(
    () => (guide?.vocations ?? []).filter((v) => v.tier === "base" || v.createChoice),
    [guide]
  );
  const advanced = useMemo(
    () => (guide?.vocations ?? []).filter((v) => v.tier === "advanced"),
    [guide]
  );
  const current = useMemo(
    () => (guide?.vocations ?? []).find((v) => v.id === selected) ?? null,
    [guide, selected]
  );

  // BEGIN CHANGE: potions so da vocacao selecionada (vazio = todas)
  const potionsForVoc = useMemo(() => {
    if (selected == null) return [] as PotionRow[];
    return potions.filter(
      (p) => !p.vocations?.length || p.vocations.includes(selected)
    );
  }, [potions, selected]);
  // END CHANGE

  // BEGIN CHANGE: knob roles with actionable examples (PT accents)
  const defenseKnobs = useMemo(() => {
    if (!defenseCfg) return [] as { key: string; value: string; role: string }[];
    const role: Record<string, string> =
      L === "en"
        ? {
            enable: "Master toggle (false = classic flat only)",
            armorRef: "Armor denominator base - lower = stronger set (ex. 80->60)",
            armorLevelFactor: "How much level inflates armor denom - lower keeps % at high level",
            defenseRef: "Shield+weapon denominator base - lower = stronger (summed def)",
            defenseLevelFactor: "How much level inflates shield/weapon denom",
            maxArmor: "Armor layer cap % - raises ceiling when score/denom is already high",
            maxDefense: "Shield/weapon layer cap %",
            maxPhys: "Combined physical/melee floor after absorb - lower if EK/RP too tanky",
            maxAbsorb: "Absorb layer cap % (jewelry; existing)",
          }
        : L === "es"
          ? {
              enable: "Toggle maestro (false = solo flat clásico)",
              armorRef: "Base del denominador de armor - bajar = set más fuerte (ej. 80->60)",
              armorLevelFactor: "Cuánto el level infla el denom de armor - bajar mantiene % en high level",
              defenseRef: "Base denom shield+arma - bajar = más fuerte (def sumada)",
              defenseLevelFactor: "Cuánto el level infla el denom shield/arma",
              maxArmor: "Tope capa armor % - sube el techo cuando score/denom ya es alto",
              maxDefense: "Tope capa shield/arma %",
              maxPhys: "Piso physical/melee tras absorb - bajar si EK/RP tanquean demasiado",
              maxAbsorb: "Tope capa absorb % (joyas; existente)",
            }
          : {
              enable: "Liga/desliga a fórmula (false = só flat clássico)",
              armorRef: "Base do denominador de armor - menor = set mais forte (ex. 80->60)",
              armorLevelFactor: "Quanto o level infla o denom de armor - menor mantém % no high level",
              defenseRef: "Base denom shield+arma - menor = mais forte (def somada)",
              defenseLevelFactor: "Quanto o level infla o denom shield/arma",
              maxArmor: "Teto da camada armor % - sobe o teto quando score/denom já é alto",
              maxDefense: "Teto da camada shield/arma %",
              maxPhys: "Piso physical/melee após absorb - baixe se EK/RP tankarem demais",
              maxAbsorb: "Teto da camada absorb % (joias; já existia)",
            };
  // END CHANGE
    return [
      { key: "enableProportionalArmorDefense", value: defenseCfg.enabled ? "true" : "false", role: role.enable },
      { key: "proportionalArmorRef", value: String(defenseCfg.armorRef), role: role.armorRef },
      { key: "proportionalArmorLevelFactor", value: String(defenseCfg.armorLevelFactor), role: role.armorLevelFactor },
      { key: "proportionalDefenseRef", value: String(defenseCfg.defenseRef), role: role.defenseRef },
      { key: "proportionalDefenseLevelFactor", value: String(defenseCfg.defenseLevelFactor), role: role.defenseLevelFactor },
      { key: "maxProportionalArmorPercent", value: String(defenseCfg.maxArmorPercent), role: role.maxArmor },
      { key: "maxProportionalDefensePercent", value: String(defenseCfg.maxDefensePercent), role: role.maxDefense },
      { key: "maxPhysicalMitigationPercent", value: String(defenseCfg.maxPhysicalMitigationPercent), role: role.maxPhys },
      { key: "maxAbsorbPercent", value: String(defenseCfg.maxAbsorbPercent), role: role.maxAbsorb },
      {
        key: "showDefenseMitigationText",
        value: defenseCfg.showDefenseMitigationText ? "true" : "false",
        role:
          L === "en"
            ? "Floating DEF N when shield+armor block > 1 HP"
            : L === "es"
              ? "Texto DEF N cuando shield+armor bloquean > 1 HP"
              : "Texto DEF N quando shield+armor bloqueiam > 1 HP",
      },
    ];
  }, [defenseCfg, L]);

  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">
        <div className="flex flex-wrap items-end justify-between gap-3">
          <div>
            <h1 className="text-3xl font-semibold tracking-tight">{t.vocationsGuide.title}</h1>
            <p className="mt-2 max-w-2xl text-muted">{t.vocationsGuide.subtitle}</p>
          </div>
          <Link
            href="/create-account"
            className="rounded-lg bg-brand px-4 py-2 text-sm font-medium text-background hover:opacity-90"
          >
            {t.vocationsGuide.createCta}
          </Link>
        </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" && guide && (
          <div className="mt-8 space-y-8">
            <section className="rounded-xl border border-border bg-panel p-5">
              <h2 className="text-sm font-semibold uppercase tracking-wide text-muted">
                {t.vocationsGuide.verdict}
              </h2>
              <p className="mt-2 text-sm leading-relaxed">{pickText(L, guide.verdict)}</p>
              {guide.profile && (
                <p className="mt-3 text-xs text-muted">
                  {t.vocationsGuide.profile}: {guide.profile}
                </p>
              )}
            </section>

            {/* BEGIN CHANGE: doc defesa - player publico + admin calibracao/build */}
            <CollapsiblePanel
              id="vocations-proportional-defense"
              title={t.vocationsGuide.defenseTitle}
              defaultOpen={false}
              titleClassName="text-lg font-semibold"
            >
              <div className="space-y-5 p-5 text-sm leading-relaxed">
                <p className="text-muted">{t.vocationsGuide.defenseSubtitle}</p>
                <div>
                  <h3 className="font-semibold text-foreground">{t.vocationsGuide.defenseWhatTitle}</h3>
                  <p className="mt-1 text-muted">{t.vocationsGuide.defenseWhatBody}</p>
                </div>
                <div>
                  <h3 className="font-semibold text-foreground">{t.vocationsGuide.defenseAppliesTitle}</h3>
                  <p className="mt-1 text-muted">{t.vocationsGuide.defenseAppliesBody}</p>
                </div>
                <div>
                  <h3 className="font-semibold text-foreground">{t.vocationsGuide.defenseVocTitle}</h3>
                  <p className="mt-1 text-muted">{t.vocationsGuide.defenseVocBody}</p>
                </div>
                {/* BEGIN CHANGE: set vs shield balance rationale (public) */}
                <div>
                  <h3 className="font-semibold text-foreground">{t.vocationsGuide.defenseBalanceTitle}</h3>
                  <p className="mt-1 text-muted">{t.vocationsGuide.defenseBalanceBody}</p>
                </div>
                {/* END CHANGE */}

                {isDefenseAdmin && (
                  <div className="space-y-5 border-t border-border pt-5">
                    {/* BEGIN CHANGE: admin formula + numeric example + calibrate scenarios */}
                    <h3 className="text-base font-semibold text-foreground">
                      {t.vocationsGuide.defenseAdminTitle}
                    </h3>
                    <div>
                      <h4 className="font-semibold text-foreground">{t.vocationsGuide.defenseFormulaTitle}</h4>
                      <p className="mt-1 text-muted">{t.vocationsGuide.defenseFormulaBody}</p>
                    </div>
                    <div className="rounded-lg border border-border/60 bg-background/40 px-3 py-3">
                      <h4 className="font-semibold text-foreground">{t.vocationsGuide.defenseExampleTitle}</h4>
                      <p className="mt-1 text-muted">{t.vocationsGuide.defenseExampleBody}</p>
                    </div>
                    <div>
                      <h4 className="mb-2 font-semibold text-foreground">{t.vocationsGuide.defenseKnobsTitle}</h4>
                      {defenseKnobs.length === 0 ? (
                        <p className="text-muted">{t.common.loading}</p>
                      ) : (
                        <div className="overflow-x-auto rounded-lg border border-border">
                          <table className="w-full text-sm">
                            <thead>
                              <tr className="border-b border-border bg-background/40 text-left text-muted">
                                <th className="px-3 py-2 font-medium">{t.vocationsGuide.defenseKnob}</th>
                                <th className="px-3 py-2 font-medium">{t.vocationsGuide.defenseValue}</th>
                                <th className="px-3 py-2 font-medium">{t.vocationsGuide.defenseRole}</th>
                              </tr>
                            </thead>
                            <tbody>
                              {defenseKnobs.map((row) => (
                                <tr key={row.key} className="border-b border-border/40">
                                  <td className="px-3 py-2 font-mono text-xs">{row.key}</td>
                                  <td className="px-3 py-2 font-semibold">{row.value}</td>
                                  <td className="px-3 py-2 text-muted">{row.role}</td>
                                </tr>
                              ))}
                            </tbody>
                          </table>
                        </div>
                      )}
                    </div>
                    <div>
                      <h4 className="font-semibold text-foreground">{t.vocationsGuide.defenseCalibrateTitle}</h4>
                      <p className="mt-1 whitespace-pre-line text-muted">{t.vocationsGuide.defenseCalibrateBody}</p>
                    </div>
                    <div>
                      <h4 className="font-semibold text-foreground">{t.vocationsGuide.defenseCompileTitle}</h4>
                      <p className="mt-1 text-muted">{t.vocationsGuide.defenseCompileBody}</p>
                    </div>
                    <p className="rounded-lg border border-border/60 bg-background/40 px-3 py-2 text-xs text-muted">
                      {t.vocationsGuide.defenseSustainNote}
                    </p>
                    {/* END CHANGE */}
                  </div>
                )}
              </div>
            </CollapsiblePanel>
            {/* END CHANGE */}

            <section>
              <h2 className="mb-3 text-lg font-semibold">{t.vocationsGuide.starterTitle}</h2>
              <div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-4">
                {base.map((v) => (
                  <button
                    key={v.id}
                    type="button"
                    onClick={() => setSelected(v.id)}
                    className={`rounded-xl border p-4 text-left transition-colors ${
                      selected === v.id
                        ? "border-brand bg-brand/10"
                        : "border-border bg-panel hover:border-brand/40"
                    }`}
                  >
                    <div className="text-xs uppercase tracking-wide text-muted">{v.family}</div>
                    <div className="mt-1 text-base font-semibold">{v.name}</div>
                    <div className="mt-3 space-y-2">
                      <ScoreBar label={t.vocationsGuide.damage} value={v.scores.damage} />
                      <ScoreBar label={t.vocationsGuide.heal} value={v.scores.heal} accent="bg-emerald-500" />
                      <ScoreBar label={t.vocationsGuide.sustain} value={v.scores.sustain} accent="bg-sky-500" />
                      {/* BEGIN CHANGE: eixo control nas cards iniciais */}
                      <ScoreBar
                        label={t.vocationsGuide.control}
                        value={v.scores.control ?? 0}
                        accent="bg-orange-500"
                      />
                      {/* END CHANGE */}
                      <ScoreBar
                        label={t.vocationsGuide.team}
                        value={v.scores.team ?? 0}
                        accent="bg-violet-500"
                      />
                    </div>
                  </button>
                ))}
              </div>
            </section>

            {current && (
              <section className="overflow-hidden rounded-xl border border-border bg-panel">
                <div className="border-b border-border px-5 py-4">
                  <h2 className="text-xl font-semibold">{current.name}</h2>
                  <p className="mt-1 text-sm text-muted">{pickText(L, current.playstyle)}</p>
                </div>
                <div className="grid grid-cols-1 gap-0 lg:grid-cols-3">
                  <div className="space-y-3 border-b border-border p-5 lg:border-b-0 lg:border-r">
                    <h3 className="text-sm font-semibold">{t.vocationsGuide.scores}</h3>
                    <ScoreBar label={t.vocationsGuide.damage} value={current.scores.damage} />
                    <ScoreBar label={t.vocationsGuide.heal} value={current.scores.heal} accent="bg-emerald-500" />
                    <ScoreBar label={t.vocationsGuide.sustain} value={current.scores.sustain} accent="bg-sky-500" />
                    {/* BEGIN CHANGE: eixo control no detalhe */}
                    <ScoreBar
                      label={t.vocationsGuide.control}
                      value={current.scores.control ?? 0}
                      accent="bg-orange-500"
                    />
                    {/* END CHANGE */}
                    <ScoreBar
                      label={t.vocationsGuide.team}
                      value={current.scores.team ?? 0}
                      accent="bg-violet-500"
                    />
                    <ScoreBar
                      label={t.vocationsGuide.difficulty}
                      value={current.scores.difficulty}
                      accent="bg-amber-500"
                    />
                    {current.teamRole && (
                      <div className="rounded-lg border border-border/60 bg-background/40 px-3 py-2 text-xs leading-relaxed text-muted">
                        <span className="font-semibold text-foreground">{t.vocationsGuide.teamRole}: </span>
                        {pickText(L, current.teamRole)}
                      </div>
                    )}
                  </div>
                  <div className="space-y-3 border-b border-border p-5 text-sm lg:border-b-0 lg:border-r">
                    <h3 className="text-sm font-semibold">{t.vocationsGuide.stats}</h3>
                    <p>
                      <span className="text-muted">HP/MP gain:</span> {current.stats.gainHp} /{" "}
                      {current.stats.gainMana}
                    </p>
                    <p>
                      <span className="text-muted">Atk speed:</span> {current.stats.attackSpeed}
                    </p>
                    <p>
                      <span className="text-muted">Formulas:</span> {current.stats.formulas}
                    </p>
                    <p>
                      <span className="text-muted">{t.vocationsGuide.burst}:</span>{" "}
                      {pickText(L, current.stats.burstNote)}
                    </p>
                    <p>
                      <span className="text-muted">{t.vocationsGuide.healNote}:</span>{" "}
                      {pickText(L, current.stats.healNote)}
                    </p>
                  </div>
                  <div className="grid grid-cols-1 gap-4 p-5 sm:grid-cols-2 lg:grid-cols-1">
                    <div>
                      <h3 className="mb-2 text-sm font-semibold text-emerald-400">
                        {t.vocationsGuide.pros}
                      </h3>
                      <ul className="space-y-1.5 text-sm text-muted">
                        {pickList(L, current.pros).map((x) => (
                          <li key={x} className="flex gap-2">
                            <span className="text-emerald-400">+</span>
                            <span>{x}</span>
                          </li>
                        ))}
                      </ul>
                    </div>
                    <div>
                      <h3 className="mb-2 text-sm font-semibold text-amber-400">
                        {t.vocationsGuide.cons}
                      </h3>
                      <ul className="space-y-1.5 text-sm text-muted">
                        {pickList(L, current.cons).map((x) => (
                          <li key={x} className="flex gap-2">
                            <span className="text-amber-400">-</span>
                            <span>{x}</span>
                          </li>
                        ))}
                      </ul>
                    </div>
                  </div>
                </div>
              </section>
            )}

            {/* BEGIN CHANGE: spells da vocacao selecionada */}
            {current && (
              <section className="overflow-hidden rounded-xl border border-border bg-panel">
                <div className="border-b border-border px-5 py-4">
                  <h2 className="text-lg font-semibold">
                    {t.vocationsGuide.spellsTitle} - {current.name}
                  </h2>
                  <p className="mt-1 text-sm text-muted">{t.vocationsGuide.spellsSubtitle}</p>
                </div>
                {spells.length === 0 ? (
                  <p className="p-5 text-sm text-muted">{t.common.empty}</p>
                ) : (
                  <div className="overflow-x-auto">
                    <table className="w-full text-sm">
                      <thead>
                        <tr className="border-b border-border text-left text-muted">
                          <th className="px-4 py-2 font-medium">{t.vocationsGuide.spellName}</th>
                          <th className="px-4 py-2 font-medium">{t.vocationsGuide.spellWords}</th>
                          <th className="px-4 py-2 font-medium">{t.vocationsGuide.spellType}</th>
                          <th className="px-4 py-2 font-medium">Mana</th>
                          <th className="px-4 py-2 font-medium">Lv</th>
                          <th className="px-4 py-2 font-medium">ML</th>
                          <th className="px-4 py-2 font-medium">Soul</th>
                          <th className="px-4 py-2 font-medium">PACC</th>
                        </tr>
                      </thead>
                      <tbody>
                        {spells.map((s) => (
                          <tr key={`${s.name}-${s.words}`} className="border-b border-border/40">
                            <td className="px-4 py-2 font-medium">{s.name}</td>
                            <td className="px-4 py-2 text-muted">{s.words}</td>
                            <td className="px-4 py-2 text-muted">{s.type}</td>
                            <td className="px-4 py-2">{s.mana}</td>
                            <td className="px-4 py-2">{s.level}</td>
                            <td className="px-4 py-2">{s.magicLevel}</td>
                            <td className="px-4 py-2">{s.soul}</td>
                            <td className="px-4 py-2">{s.premium ? "yes" : "-"}</td>
                          </tr>
                        ))}
                      </tbody>
                    </table>
                  </div>
                )}
              </section>
            )}
            {/* END CHANGE */}

            {/* BEGIN CHANGE: potions filtradas pela vocacao selecionada */}
            {current && (
            <section className="overflow-hidden rounded-xl border border-border bg-panel">
              <div className="border-b border-border px-5 py-4">
                <h2 className="text-lg font-semibold">Potions - {current.name}</h2>
                <p className="mt-1 text-sm text-muted">
                  Usaveis por esta vocacao (ou por todas). Valores de potions.lua.
                </p>
              </div>
              {potionsForVoc.length === 0 ? (
                <p className="p-5 text-sm text-muted">{t.common.empty}</p>
              ) : (
                <div className="overflow-x-auto">
                  <table className="w-full text-sm">
                    <thead>
                      <tr className="border-b border-border text-left text-muted">
                        <th className="px-4 py-2 font-medium">Item</th>
                        <th className="px-4 py-2 font-medium">Lv</th>
                        <th className="px-4 py-2 font-medium">HP</th>
                        <th className="px-4 py-2 font-medium">MP</th>
                        <th className="px-4 py-2 font-medium">%</th>
                        <th className="px-4 py-2 font-medium">Finite %</th>
                        <th className="px-4 py-2 font-medium">Voc</th>
                      </tr>
                    </thead>
                    <tbody>
                      {potionsForVoc.map((p) => (
                        <tr key={p.id} className="border-b border-border/40">
                          <td className="px-4 py-2 font-medium">
                            {p.name} <span className="text-muted">#{p.id}</span>
                          </td>
                          <td className="px-4 py-2">{p.level || "-"}</td>
                          <td className="px-4 py-2">{p.health ? `${p.health[0]}-${p.health[1]}` : "-"}</td>
                          <td className="px-4 py-2">{p.mana ? `${p.mana[0]}-${p.mana[1]}` : "-"}</td>
                          <td className="px-4 py-2">{p.percent ?? "-"}</td>
                          <td className="px-4 py-2">{p.finitePercent ?? "-"}</td>
                          <td className="px-4 py-2 text-muted">{p.vocStr || "all"}</td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              )}
            </section>
            )}
            {/* END CHANGE */}

            <section className="overflow-hidden rounded-xl border border-border bg-panel">
              <div className="border-b border-border px-5 py-4">
                <h2 className="text-lg font-semibold">Heal formulas</h2>
                <p className="mt-1 text-sm text-muted">Extraido dos scripts em data/spells/scripts/healing.</p>
              </div>
              {heals.length === 0 ? (
                <p className="p-5 text-sm text-muted">{t.common.empty}</p>
              ) : (
                <div className="overflow-x-auto">
                  <table className="w-full text-sm">
                    <thead>
                      <tr className="border-b border-border text-left text-muted">
                        <th className="px-4 py-2 font-medium">Spell</th>
                        <th className="px-4 py-2 font-medium">Words</th>
                        <th className="px-4 py-2 font-medium">Formula</th>
                      </tr>
                    </thead>
                    <tbody>
                      {heals.map((h) => (
                        <tr key={`${h.name}-${h.words}`} className="border-b border-border/40">
                          <td className="px-4 py-2 font-medium">{h.name}</td>
                          <td className="px-4 py-2 text-muted">{h.words || "-"}</td>
                          <td className="px-4 py-2 font-mono text-xs">{h.formula || "-"}</td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              )}
            </section>

            {advanced.length > 0 && (
              <section>
                <h2 className="mb-2 text-lg font-semibold">{t.vocationsGuide.advancedTitle}</h2>
                <p className="mb-4 text-sm text-muted">{t.vocationsGuide.advancedHint}</p>
                <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
                  {advanced.map((v) => (
                    <button
                      key={v.id}
                      type="button"
                      onClick={() => setSelected(v.id)}
                      className={`rounded-xl border p-4 text-left transition-colors ${
                        selected === v.id
                          ? "border-brand bg-brand/10"
                          : "border-border bg-panel hover:border-brand/40"
                      }`}
                    >
                      <div className="flex items-center justify-between gap-2">
                        <h3 className="font-semibold">{v.name}</h3>
                        <span className="rounded bg-background px-2 py-0.5 text-xs text-muted">
                          {v.stats.formulas}
                        </span>
                      </div>
                      <p className="mt-2 text-xs text-muted">{pickText(L, v.playstyle)}</p>
                      <div className="mt-3 grid grid-cols-5 gap-2 text-center text-xs">
                        <div>
                          <div className="text-muted">{t.vocationsGuide.damage}</div>
                          <div className="font-semibold">{v.scores.damage}</div>
                        </div>
                        <div>
                          <div className="text-muted">{t.vocationsGuide.heal}</div>
                          <div className="font-semibold">{v.scores.heal}</div>
                        </div>
                        <div>
                          <div className="text-muted">{t.vocationsGuide.sustain}</div>
                          <div className="font-semibold">{v.scores.sustain}</div>
                        </div>
                        {/* BEGIN CHANGE: control nas avancadas */}
                        <div>
                          <div className="text-muted">{t.vocationsGuide.control}</div>
                          <div className="font-semibold">{v.scores.control ?? 0}</div>
                        </div>
                        {/* END CHANGE */}
                        <div>
                          <div className="text-muted">{t.vocationsGuide.team}</div>
                          <div className="font-semibold">{v.scores.team ?? 0}</div>
                        </div>
                      </div>
                    </button>
                  ))}
                </div>
              </section>
            )}
          </div>
        )}
      </main>
      <Footer />
    </div>
  );
}
// END CHANGE
