// BEGIN CHANGE: Admin Anti-Bot Log (z_antibot_log) + staff guide
"use client";

import { useCallback, useEffect, useState } from "react";
import Link from "next/link";
import { apiUrl } from "@/lib/api";
import { CollapsiblePanel } from "@/components/CollapsiblePanel";

type Row = {
  id: number;
  playerId: number;
  playerName: string;
  playerLevel: number;
  playerResets: number;
  playerSalvar: number;
  context: string;
  triggerSource: string;
  status: string;
  outcome: string;
  qualifyingKills: number;
  bossKills: number;
  expGained: number;
  huntElapsedSeconds: number;
  sessionElapsedSeconds: number;
  challengeType: string;
  challengeQuestion: string;
  expectedAnswer: string;
  playerAnswer: string;
  failReason: string;
  mobProfile: string;
  punishedKill: boolean;
  forced: boolean;
  pos: string;
  spawnPos: string;
  announcedAt: number;
  spawnedAt: number;
  resolvedAt: number;
};

const OUTCOMES = [
  "",
  "success",
  "timeout",
  "wrong_answer",
  "wrong_direction",
  "punished_kill",
  "punished_temple",
  "aborted",
  "spawn_failed",
  "failed",
];

function fmtDuration(sec: number): string {
  if (sec <= 0) return "-";
  const m = Math.floor(sec / 60);
  const s = sec % 60;
  if (m >= 60) {
    const h = Math.floor(m / 60);
    const rm = m % 60;
    return `${h}h ${rm}m`;
  }
  return m > 0 ? `${m}m ${s}s` : `${s}s`;
}

function fmtExp(n: number): string {
  if (n <= 0) return "-";
  if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(2)}M`;
  if (n >= 1_000) return `${(n / 1_000).toFixed(1)}k`;
  return String(n);
}

function outcomeLabel(o: string): string {
  switch (o) {
    case "success":
      return "Acertou";
    case "timeout":
      return "Sem resposta";
    case "wrong_answer":
      return "Resposta errada";
    case "wrong_direction":
      return "Direcao errada";
    case "punished_kill":
      return "Morto (hunt)";
    case "punished_temple":
      return "Templo (trainer)";
    case "aborted":
      return "Cancelado";
    case "spawn_failed":
      return "Spawn falhou";
    case "failed":
      return "Falhou";
    default:
      return o || "-";
  }
}

function AdminAntibotGuide() {
  return (
    <CollapsiblePanel
      id="admin-antibot-guide"
      title="Guia interno - Anti-Bot (GM Bot-Killer)"
      titleClassName="font-medium"
      defaultOpen={false}
    >
      <p className="text-sm text-muted">
        Documentacao interna para staff. <strong className="text-foreground">Nao existe pagina publica</strong>{" "}
        com estas regras - players nao devem ver thresholds no site.
      </p>

      <div className="mt-3 rounded-md border border-amber-500/40 bg-amber-500/5 px-3 py-2 text-xs text-muted">
        Isencao rapida: <span className="text-foreground">players.salvar &gt;= 1</span> desliga anti-bot e protege do
        dbcleaner. Valor cacheado no login - relog apos mudar no DB.
      </div>

      <div className="mt-4 grid gap-3 lg:grid-cols-2 text-sm">
        <section className="rounded-md border border-border/60 p-3">
          <p className="font-medium">Quem entra</p>
          <ul className="mt-2 list-disc space-y-1 pl-5 text-muted">
            <li>
              Level &gt;= 600 <span className="text-foreground">ou</span> 1+ reset (RR) - com reset, qualquer level
            </li>
            <li>salvar &lt; 1 e anti_bot_enabled</li>
            <li>Fora de PZ (exceto trainer tiles 23000 / 24000)</li>
            <li>Players comuns (group &lt;= 2)</li>
          </ul>
        </section>

        <section className="rounded-md border border-border/60 p-3">
          <p className="font-medium">Dois caminhos para qualificar</p>
          <ul className="mt-2 list-disc space-y-1 pl-5 text-muted">
            <li>
              <span className="text-foreground">Respawn:</span> 50 kills qualificados + 1M EXP
            </li>
            <li>
              <span className="text-foreground">Boss:</span> 20 kills de boss da lista + 1M EXP
            </li>
            <li>Task farmando 1 mob repetido pode acionar (respawn)</li>
            <li>Contagem comeca no 1o kill apos login - sem delay inicial</li>
          </ul>
        </section>
      </div>

      <section className="mt-4 rounded-md border border-border/60 p-3 text-sm">
        <p className="font-medium">Contagem de respawn (valores atuais do config)</p>
        <div className="mt-3 overflow-x-auto">
          <table className="w-full min-w-[28rem] text-left text-xs">
            <thead>
              <tr className="border-b border-border text-muted">
                <th className="py-1 pr-3">Regra</th>
                <th className="py-1">Valor</th>
              </tr>
            </thead>
            <tbody className="text-muted">
              <tr>
                <td className="py-1 pr-3">Kills qualificados</td>
                <td className="py-1 tabular-nums text-foreground">50</td>
              </tr>
              <tr>
                <td className="py-1 pr-3">Janela recente (ultimos kills)</td>
                <td className="py-1 tabular-nums text-foreground">50</td>
              </tr>
              <tr>
                <td className="py-1 pr-3">Nomes distintos no spawn (top volume)</td>
                <td className="py-1 tabular-nums text-foreground">7 (min. 10 kills/nome na janela)</td>
              </tr>
              <tr>
                <td className="py-1 pr-3">Intervalo max entre kills qualificados</td>
                <td className="py-1 tabular-nums text-foreground">15 s</td>
              </tr>
              <tr>
                <td className="py-1 pr-3">EXP minima (respawn e boss)</td>
                <td className="py-1 tabular-nums text-foreground">1.000.000</td>
              </tr>
              <tr>
                <td className="py-1 pr-3">Timer apos qualificar (hunt)</td>
                <td className="py-1 tabular-nums text-foreground">5 min</td>
              </tr>
              <tr>
                <td className="py-1 pr-3">Idle sem matar (reset)</td>
                <td className="py-1 tabular-nums text-foreground">35 min</td>
              </tr>
              <tr>
                <td className="py-1 pr-3">Trainer (23000/24000)</td>
                <td className="py-1 tabular-nums text-foreground">1 h min + hits no dummy</td>
              </tr>
            </tbody>
          </table>
        </div>
        <ul className="mt-3 list-disc space-y-1 pl-5 text-xs text-muted">
          <li>Kill fora do top 7 / volume baixo: ignorado, sem reset.</li>
          <li>Troca de respawn: nomes antigos saem da janela quando param de ser mortos.</li>
          <li>Pausa &gt; 15 s desde o ultimo qualificado: aquele kill nao conta; progresso congela ate reset da sessao.</li>
        </ul>
      </section>

      <div className="mt-4 grid gap-3 md:grid-cols-2 text-sm">
        <section className="rounded-md border border-border/60 p-3">
          <p className="font-medium">Fluxo do desafio</p>
          <ol className="mt-2 list-decimal space-y-1 pl-5 text-muted">
            <li>Aviso + imobiliza (noMove)</li>
            <li>Spawna GM Bot-Killer + charada (math / palavra / direcao)</li>
            <li>Resposta no Say - 90 s</li>
            <li>Acerto: libera; erro/timeout/afastar: punicao</li>
          </ol>
          <p className="mt-2 text-xs text-muted">
            Hunt: morte letal. Trainer: teleporte ao templo. Sem ban/kick.
          </p>
        </section>

        <section className="rounded-md border border-border/60 p-3">
          <p className="font-medium">QA in-game (access 6)</p>
          <pre className="mt-2 overflow-x-auto rounded bg-background/80 p-2 text-xs text-foreground">
{`/antibot
/antibot NomeDoChar
/antibot stop [nome]`}
          </pre>
          <p className="mt-2 text-xs text-muted">
            Reload: <code className="text-foreground">/reload config</code>,{" "}
            <code className="text-foreground">/reload lib</code>,{" "}
            <code className="text-foreground">/reload creaturescripts</code>
          </p>
          <p className="mt-2 text-xs text-muted">
            Log DB: <code className="text-foreground">z_antibot_log</code> (lista abaixo). Legado:{" "}
            <code className="text-foreground">data/logs/antibot_spawn.log</code>
          </p>
        </section>
      </div>

      <p className="mt-3 text-xs text-muted">
        Repo servidor: <code className="text-foreground">otx2_reseted/docs/antibot-system.md</code> -{" "}
        <code className="text-foreground">data/lib/antibot.lua</code>,{" "}
        <code className="text-foreground">config.lua</code> (anti_bot_*).
      </p>
    </CollapsiblePanel>
  );
}

export function AdminAntibot({ token }: { token: string }) {
  const [rows, setRows] = useState<Row[]>([]);
  const [q, setQ] = useState("");
  const [outcome, setOutcome] = useState("");
  const [status, setStatus] = useState<"loading" | "ok" | "error">("loading");
  const [err, setErr] = useState("");

  const load = useCallback(async () => {
    setStatus("loading");
    setErr("");
    const qs = new URLSearchParams({ tool: "antibot_log", limit: "100" });
    if (q.trim()) qs.set("name", q.trim());
    if (outcome) qs.set("outcome", outcome);
    try {
      const r = await fetch(apiUrl(`admin-panel.php?${qs.toString()}`), {
        headers: { Authorization: `Bearer ${token}` },
      });
      const json = await r.json().catch(() => ({}));
      if (!r.ok) {
        setErr(json.error || "Falha ao carregar log");
        setStatus("error");
        return;
      }
      setRows(json.data ?? []);
      setStatus("ok");
    } catch {
      setErr("Falha de rede");
      setStatus("error");
    }
  }, [token, q, outcome]);

  useEffect(() => {
    void load();
  }, [load]);

  return (
    <div className="space-y-4">
      <div>
        <h2 className="text-xl font-semibold">Anti-Bot</h2>
        <p className="mt-1 text-sm text-muted">
          Log de disparos do GM Bot-Killer (`z_antibot_log`) e guia interno para staff. Regras nao sao publicas.
        </p>
      </div>

      <AdminAntibotGuide />

      <div className="border-t border-border pt-4">
        <h3 className="text-lg font-medium">Log de disparos</h3>
      </div>

      <div className="flex flex-wrap gap-2">
        <input
          className="rounded-md border border-border bg-background px-3 py-2 text-sm"
          placeholder="Nome do player"
          value={q}
          onChange={(e) => setQ(e.target.value)}
        />
        <select
          className="rounded-md border border-border bg-background px-3 py-2 text-sm"
          value={outcome}
          onChange={(e) => setOutcome(e.target.value)}
        >
          {OUTCOMES.map((o) => (
            <option key={o || "all"} value={o}>
              {o ? outcomeLabel(o) : "Todos os resultados"}
            </option>
          ))}
        </select>
        <button
          type="button"
          className="rounded-md bg-brand px-3 py-2 text-sm text-white"
          onClick={() => void load()}
        >
          Filtrar
        </button>
      </div>

      {status === "loading" && <p className="text-sm text-muted">Carregando...</p>}
      {status === "error" && <p className="text-sm text-red-600">{err}</p>}
      {status === "ok" && rows.length === 0 && (
        <p className="text-sm text-muted">Nenhum registro ainda. Disparos novos passam a aparecer apos `/reload lib` no servidor.</p>
      )}

      {status === "ok" && rows.length > 0 && (
        <div className="space-y-3">
          {rows.map((r) => (
            <div key={r.id} className="rounded-xl border border-border p-4 text-sm">
              <div className="flex flex-wrap items-center gap-x-3 gap-y-1">
                <span className="font-semibold">
                  <Link href={`/character/?name=${encodeURIComponent(r.playerName)}`} className="text-brand hover:underline">
                    {r.playerName}
                  </Link>
                </span>
                <span className="text-muted">#{r.id}</span>
                <span className="rounded bg-muted/20 px-2 py-0.5 text-xs">{outcomeLabel(r.outcome)}</span>
                {r.forced && <span className="rounded bg-amber-500/20 px-2 py-0.5 text-xs">/antibot</span>}
                <span className="text-muted ml-auto">
                  {r.announcedAt > 0 ? new Date(r.announcedAt * 1000).toLocaleString() : "-"}
                </span>
              </div>

              <div className="mt-3 grid gap-2 sm:grid-cols-2 lg:grid-cols-4">
                <div>
                  <span className="text-muted">Level / RR / salvar</span>
                  <p>{r.playerLevel} / {r.playerResets} / {r.playerSalvar}</p>
                </div>
                <div>
                  <span className="text-muted">Contexto</span>
                  <p>{r.context} ({r.triggerSource})</p>
                </div>
                <div>
                  <span className="text-muted">Kills qualif. / boss</span>
                  <p>{r.qualifyingKills} / {r.bossKills}</p>
                </div>
                <div>
                  <span className="text-muted">EXP / hunt / sessao</span>
                  <p>
                    {fmtExp(r.expGained)} / {fmtDuration(r.huntElapsedSeconds)} / {fmtDuration(r.sessionElapsedSeconds)}
                  </p>
                </div>
              </div>

              {(r.challengeType || r.challengeQuestion) && (
                <div className="mt-2 rounded-lg bg-muted/10 p-2">
                  <p className="text-muted text-xs">Desafio ({r.challengeType || "-"})</p>
                  <p className="mt-1">{r.challengeQuestion || "-"}</p>
                  <p className="mt-1 text-xs text-muted">
                    Esperado: <span className="text-foreground">{r.expectedAnswer || "-"}</span>
                    {" - "}
                    Player: <span className="text-foreground">{r.playerAnswer || "-"}</span>
                  </p>
                </div>
              )}

              {r.mobProfile && (
                <p className="mt-2 text-xs text-muted">
                  Perfil mobs: <span className="text-foreground">{r.mobProfile}</span>
                </p>
              )}

              {(r.failReason || r.pos !== "-" || r.spawnPos !== "-") && (
                <p className="mt-2 text-xs text-muted">
                  {r.failReason ? <>Motivo: {r.failReason}. </> : null}
                  {r.pos !== "-" ? <>Player: {r.pos}. </> : null}
                  {r.spawnPos !== "-" ? <>GM: {r.spawnPos}</> : null}
                </p>
              )}
            </div>
          ))}
        </div>
      )}
    </div>
  );
}
// END CHANGE
