// BEGIN CHANGE: pagina Raids (agenda raid.lua + Random_Raids)
"use client";

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

type RaidRow = {
  name: string;
  tipo: string;
  day: string;
  hour: number;
  minute: number;
  monster: string;
};

type RandomPayload = {
  cityBosses: { name: string; message: string }[];
  durationMin: number;
  chancePercent: number;
  intervalHint: string;
  expMonster: { name: string; message: string; durationMin: number; chance: number } | null;
};

const DAY_ORDER = ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"];

export default function RaidsPage() {
  const { t } = useI18n();
  const [schedule, setSchedule] = useState<RaidRow[]>([]);
  const [random, setRandom] = useState<RandomPayload | null>(null);
  const [day, setDay] = useState<string>("all");
  const [status, setStatus] = useState<"loading" | "ok" | "error">("loading");

  useEffect(() => {
    fetch(apiUrl("raids.php"))
      .then((r) => {
        if (!r.ok) throw new Error("http " + r.status);
        return r.json();
      })
      .then((json) => {
        setSchedule(json.schedule ?? []);
        setRandom(json.random ?? null);
        setStatus("ok");
      })
      .catch(() => setStatus("error"));
  }, []);

  const filtered = useMemo(() => {
    if (day === "all") return schedule;
    return schedule.filter((r) => r.day === day);
  }, [schedule, day]);

  const dayLabel = (d: string) => {
    const map: Record<string, string> = {
      monday: t.raids.monday,
      tuesday: t.raids.tuesday,
      wednesday: t.raids.wednesday,
      thursday: t.raids.thursday,
      friday: t.raids.friday,
      saturday: t.raids.saturday,
      sunday: t.raids.sunday,
    };
    return map[d] || d;
  };

  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.raids.title}</h1>
        <p className="mt-2 text-muted">{t.raids.subtitle}</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" && (
          <div className="mt-8 space-y-8">
            <div className="flex flex-wrap gap-2">
              <button
                type="button"
                onClick={() => setDay("all")}
                className={`rounded-lg border px-3 py-1.5 text-sm ${day === "all" ? "border-brand text-brand" : "border-border text-muted"}`}
              >
                {t.raids.allDays}
              </button>
              {DAY_ORDER.map((d) => (
                <button
                  key={d}
                  type="button"
                  onClick={() => setDay(d)}
                  className={`rounded-lg border px-3 py-1.5 text-sm ${day === d ? "border-brand text-brand" : "border-border text-muted"}`}
                >
                  {dayLabel(d)}
                </button>
              ))}
            </div>

            <section className="rounded-xl border border-border bg-panel p-6">
              <h2 className="mb-4 text-base font-semibold">{t.raids.scheduleTitle}</h2>
              {filtered.length === 0 ? (
                <p className="text-sm text-muted">{t.common.empty}</p>
              ) : (
                <div className="overflow-x-auto">
                  <table className="w-full text-left text-sm">
                    <thead className="text-muted">
                      <tr>
                        <th className="py-2 pr-4">{t.raids.colDay}</th>
                        <th className="py-2 pr-4">{t.raids.colTime}</th>
                        <th className="py-2 pr-4">{t.raids.colName}</th>
                        <th className="py-2 pr-4">{t.raids.colType}</th>
                        <th className="py-2">{t.raids.colMonster}</th>
                      </tr>
                    </thead>
                    <tbody>
                      {filtered.map((r, i) => (
                        <tr key={`${r.day}-${r.hour}-${r.name}-${i}`} className="border-t border-border/50">
                          <td className="py-2 pr-4">{dayLabel(r.day)}</td>
                          <td className="py-2 pr-4 font-mono">
                            {String(r.hour).padStart(2, "0")}:{String(r.minute).padStart(2, "0")}
                          </td>
                          <td className="py-2 pr-4 font-medium">{r.name}</td>
                          <td className="py-2 pr-4 text-muted">{r.tipo}</td>
                          <td className="py-2">{r.monster}</td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              )}
            </section>

            {random && (
              <section className="rounded-xl border border-border bg-panel p-6">
                <h2 className="mb-2 text-base font-semibold">{t.raids.randomTitle}</h2>
                <p className="mb-4 text-sm text-muted">
                  {t.raids.randomHint
                    .replace("{chance}", String(random.chancePercent))
                    .replace("{min}", String(random.durationMin))}
                </p>
                <ul className="space-y-2 text-sm">
                  {random.cityBosses.map((b) => (
                    <li key={b.name} className="border-b border-border/40 pb-2">
                      <div className="font-medium text-brand">{b.name}</div>
                      {b.message && <div className="text-muted">{b.message}</div>}
                    </li>
                  ))}
                </ul>
                {random.expMonster && (
                  <div className="mt-4 rounded-lg border border-border/60 p-4 text-sm">
                    <div className="font-semibold">{t.raids.expMonster}</div>
                    <div className="mt-1 text-brand">{random.expMonster.name}</div>
                    <div className="text-muted">{random.expMonster.message}</div>
                  </div>
                )}
              </section>
            )}
          </div>
        )}
      </main>
      <Footer />
    </div>
  );
}
// END CHANGE
