// BEGIN CHANGE: pagina Tasks (task_func.lua - story + daily)
"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 { ItemIcon } from "@/components/ItemIcon";
import { apiUrl } from "@/lib/api";

type ItemStack = { id: number; count: number; name: string };

type StoryTask = {
  id: number;
  name: string;
  level: number | null;
  count: number;
  points: number;
  exp: number;
  money: number;
  monsters: string[];
  requiredItems: ItemStack[];
  reward: ItemStack[];
  startStorage: number | null;
};

type DailyTask = {
  id: number;
  name: string;
  count: number;
  points: number;
  exp: number;
  money: number;
  monsters: string[];
  reward: ItemStack[];
};

type TasksPayload = {
  story: StoryTask[];
  daily: DailyTask[];
  ranks: { min: number; max: number | null; name: string }[];
  dailyByLevel: {
    levelMin: number;
    levelMax: number | null;
    dailyFrom: number;
    dailyTo: number;
  }[];
  npc: { name: string; hint: string };
};

type Tab = "story" | "daily" | "ranks";

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

function ItemList({ items }: { items: ItemStack[] }) {
  if (!items?.length) return <span className="text-muted">-</span>;
  return (
    <ul className="flex flex-wrap gap-2">
      {items.map((it) => (
        <li
          key={`${it.id}-${it.count}`}
          className="inline-flex items-center gap-1.5 rounded-lg border border-border/60 bg-background/50 px-2 py-1 text-xs"
          title={`ID ${it.id}`}
        >
          <ItemIcon id={it.id} alt={it.name} size={24} />
          <span>
            {it.count}x {it.name}
          </span>
        </li>
      ))}
    </ul>
  );
}

function MonsterList({ names }: { names: string[] }) {
  if (!names?.length) return <span className="text-muted">-</span>;
  return (
    <div className="flex flex-wrap gap-1.5">
      {names.map((m) => (
        <Link
          key={m}
          href={`/monster/?name=${encodeURIComponent(m)}`}
          className="rounded-md border border-border/50 bg-background/40 px-2 py-0.5 text-xs text-brand hover:underline"
        >
          {m}
        </Link>
      ))}
    </div>
  );
}

export default function TasksPage() {
  const { t } = useI18n();
  const [data, setData] = useState<TasksPayload | null>(null);
  const [status, setStatus] = useState<"loading" | "ok" | "error">("loading");
  const [tab, setTab] = useState<Tab>("story");
  const [query, setQuery] = useState("");

  useEffect(() => {
    fetch(apiUrl("tasks.php"))
      .then((r) => {
        if (!r.ok) throw new Error("http");
        return r.json();
      })
      .then((json: TasksPayload) => {
        setData(json);
        setStatus("ok");
      })
      .catch(() => setStatus("error"));
  }, []);

  const storyFiltered = useMemo(() => {
    const list = data?.story ?? [];
    const q = query.trim().toLowerCase();
    if (!q) return list;
    return list.filter(
      (t) =>
        t.name.toLowerCase().includes(q) ||
        String(t.id) === q ||
        t.monsters.some((m) => m.toLowerCase().includes(q)),
    );
  }, [data, query]);

  const dailyFiltered = useMemo(() => {
    const list = data?.daily ?? [];
    const q = query.trim().toLowerCase();
    if (!q) return list;
    return list.filter(
      (t) =>
        t.name.toLowerCase().includes(q) ||
        String(t.id) === q ||
        t.monsters.some((m) => m.toLowerCase().includes(q)),
    );
  }, [data, query]);

  const tabs: { id: Tab; label: string }[] = [
    { id: "story", label: t.tasksPage.tabStory },
    { id: "daily", label: t.tasksPage.tabDaily },
    { id: "ranks", label: t.tasksPage.tabRanks },
  ];

  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.tasksPage.title}</h1>
        <p className="mt-2 text-muted">{t.tasksPage.subtitle}</p>
        {data?.npc && (
          <p className="mt-2 text-sm text-muted">
            <span className="font-medium text-foreground">{data.npc.name}</span>
            {" - "}
            {t.tasksPage.npcHint}
          </p>
        )}
        <p className="mt-3 text-sm">
          <Link href="/highscores/?category=tasks" className="text-brand hover:underline">
            {t.tasksPage.rankingLink}
          </Link>
        </p>

        {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" && data && (
          <div className="mt-8 space-y-6">
            <div className="flex flex-wrap gap-2">
              {tabs.map((tb) => (
                <button
                  key={tb.id}
                  type="button"
                  onClick={() => setTab(tb.id)}
                  className={`rounded-lg border px-3 py-1.5 text-sm ${
                    tab === tb.id
                      ? "border-brand/50 bg-brand/15 font-medium text-foreground"
                      : "border-border text-muted hover:text-foreground"
                  }`}
                >
                  {tb.label}
                </button>
              ))}
            </div>

            {(tab === "story" || tab === "daily") && (
              <input
                value={query}
                onChange={(e) => setQuery(e.target.value)}
                placeholder={t.tasksPage.searchPlaceholder}
                className="w-full max-w-sm rounded-lg border border-border bg-panel px-4 py-2 text-sm outline-none focus:border-brand/60"
              />
            )}

            {tab === "story" && (
              <div className="space-y-4">
                <p className="text-sm text-muted">
                  {t.tasksPage.storyHint} ({storyFiltered.length})
                </p>
                {storyFiltered.map((task) => (
                  <article
                    key={task.id}
                    className="rounded-xl border border-border bg-panel p-5"
                  >
                    <div className="flex flex-wrap items-baseline justify-between gap-2">
                      <h2 className="text-lg font-semibold">
                        #{task.id} {task.name}
                      </h2>
                      <div className="flex flex-wrap gap-2 text-xs text-muted">
                        {task.level != null && (
                          <span className="rounded-md border border-border px-2 py-0.5">
                            {t.tasksPage.level} {task.level}+
                          </span>
                        )}
                        <span className="rounded-md border border-border px-2 py-0.5">
                          {fmtNum(task.count)} {t.tasksPage.kills}
                        </span>
                        <span className="rounded-md border border-brand/40 bg-brand/10 px-2 py-0.5 text-brand">
                          {task.points} {t.tasksPage.points}
                        </span>
                      </div>
                    </div>
                    <dl className="mt-4 grid gap-3 text-sm sm:grid-cols-2">
                      <div>
                        <dt className="text-muted">{t.tasksPage.monsters}</dt>
                        <dd className="mt-1">
                          <MonsterList names={task.monsters} />
                        </dd>
                      </div>
                      <div>
                        <dt className="text-muted">{t.tasksPage.requiredItems}</dt>
                        <dd className="mt-1">
                          <ItemList items={task.requiredItems} />
                        </dd>
                      </div>
                      <div>
                        <dt className="text-muted">{t.tasksPage.reward}</dt>
                        <dd className="mt-1">
                          <ItemList items={task.reward} />
                        </dd>
                      </div>
                      <div className="space-y-1">
                        <div className="flex justify-between gap-4 border-b border-border/30 pb-1">
                          <span className="text-muted">{t.tasksPage.exp}</span>
                          <span className="font-medium">{fmtNum(task.exp)}</span>
                        </div>
                        <div className="flex justify-between gap-4 border-b border-border/30 pb-1">
                          <span className="text-muted">{t.tasksPage.money}</span>
                          <span className="font-medium">{fmtNum(task.money)}</span>
                        </div>
                      </div>
                    </dl>
                  </article>
                ))}
                {storyFiltered.length === 0 && (
                  <p className="text-muted">{t.common.empty}</p>
                )}
              </div>
            )}

            {tab === "daily" && (
              <div className="space-y-4">
                <p className="text-sm text-muted">
                  {t.tasksPage.dailyHint} ({dailyFiltered.length})
                </p>
                {data.dailyByLevel?.length > 0 && (
                  <div className="overflow-x-auto rounded-xl border border-border bg-panel">
                    <table className="w-full min-w-[420px] text-left text-sm">
                      <thead className="text-muted">
                        <tr>
                          <th className="px-4 py-2 font-medium">{t.tasksPage.levelRange}</th>
                          <th className="px-4 py-2 font-medium">{t.tasksPage.dailyPool}</th>
                        </tr>
                      </thead>
                      <tbody>
                        {data.dailyByLevel.map((r) => (
                          <tr key={`${r.levelMin}-${r.dailyFrom}`} className="border-t border-border/40">
                            <td className="px-4 py-2">
                              {r.levelMin}
                              {r.levelMax != null ? ` - ${r.levelMax}` : "+"}
                            </td>
                            <td className="px-4 py-2 text-muted">
                              #{r.dailyFrom} - #{r.dailyTo}
                            </td>
                          </tr>
                        ))}
                      </tbody>
                    </table>
                  </div>
                )}
                {dailyFiltered.map((task) => (
                  <article
                    key={task.id}
                    className="rounded-xl border border-border bg-panel p-5"
                  >
                    <div className="flex flex-wrap items-baseline justify-between gap-2">
                      <h2 className="text-lg font-semibold">
                        #{task.id} {task.name}
                      </h2>
                      <div className="flex flex-wrap gap-2 text-xs text-muted">
                        <span className="rounded-md border border-border px-2 py-0.5">
                          {fmtNum(task.count)} {t.tasksPage.kills}
                        </span>
                        <span className="rounded-md border border-brand/40 bg-brand/10 px-2 py-0.5 text-brand">
                          {task.points} {t.tasksPage.points}
                        </span>
                      </div>
                    </div>
                    <dl className="mt-4 grid gap-3 text-sm sm:grid-cols-2">
                      <div>
                        <dt className="text-muted">{t.tasksPage.monsters}</dt>
                        <dd className="mt-1">
                          <MonsterList names={task.monsters} />
                        </dd>
                      </div>
                      <div>
                        <dt className="text-muted">{t.tasksPage.reward}</dt>
                        <dd className="mt-1">
                          <ItemList items={task.reward} />
                        </dd>
                      </div>
                      <div className="space-y-1 sm:col-span-2 sm:max-w-md">
                        <div className="flex justify-between gap-4 border-b border-border/30 pb-1">
                          <span className="text-muted">{t.tasksPage.exp}</span>
                          <span className="font-medium">{fmtNum(task.exp)}</span>
                        </div>
                        <div className="flex justify-between gap-4 border-b border-border/30 pb-1">
                          <span className="text-muted">{t.tasksPage.money}</span>
                          <span className="font-medium">{fmtNum(task.money)}</span>
                        </div>
                      </div>
                    </dl>
                  </article>
                ))}
                {dailyFiltered.length === 0 && (
                  <p className="text-muted">{t.common.empty}</p>
                )}
              </div>
            )}

            {tab === "ranks" && (
              <div className="overflow-x-auto rounded-xl border border-border bg-panel">
                <table className="w-full min-w-[360px] text-left text-sm">
                  <thead className="text-muted">
                    <tr>
                      <th className="px-4 py-3 font-medium">{t.tasksPage.rankName}</th>
                      <th className="px-4 py-3 font-medium">{t.tasksPage.pointsRange}</th>
                    </tr>
                  </thead>
                  <tbody>
                    {data.ranks.map((r) => (
                      <tr key={r.name} className="border-t border-border/40">
                        <td className="px-4 py-2 font-medium">{r.name}</td>
                        <td className="px-4 py-2 text-muted">
                          {r.min}
                          {r.max != null ? ` - ${r.max}` : "+"}
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            )}
          </div>
        )}
      </main>
      <Footer />
    </div>
  );
}
// END CHANGE
