// BEGIN CHANGE: pagina News (z_news_tickers via API PHP)
"use client";

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 News = { date: number; text: string; author: string; imageId: number };

export default function NewsPage() {
  const { t } = useI18n();
  const [rows, setRows] = useState<News[]>([]);
  const [status, setStatus] = useState<"loading" | "ok" | "error">("loading");

  useEffect(() => {
    fetch(apiUrl("news.php"))
      .then((r) => {
        if (!r.ok) throw new Error("http " + r.status);
        return r.json();
      })
      .then((json) => {
        setRows(json.data ?? []);
        setStatus("ok");
      })
      .catch(() => setStatus("error"));
  }, []);

  const fmtDate = (epoch: number) =>
    epoch > 0 ? new Date(epoch * 1000).toLocaleDateString() : "-";

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

        <div className="mt-8 space-y-4">
          {status === "loading" && <p className="text-muted">{t.common.loading}</p>}
          {status === "error" && <p className="text-muted">{t.common.error}</p>}
          {status === "ok" && rows.length === 0 && <p className="text-muted">{t.common.empty}</p>}
          {status === "ok" &&
            rows.map((n, i) => (
              <article key={i} className="rounded-xl border border-border bg-panel p-6">
                <div className="mb-2 flex items-center gap-3 text-xs text-muted">
                  <span>{fmtDate(n.date)}</span>
                  <span>&middot;</span>
                  <span>
                    {t.news.by} {n.author}
                  </span>
                </div>
                {/* Texto autorado pela staff no cpanel legado (contem HTML confiavel) */}
                <div
                  className="text-sm leading-relaxed [&_a]:text-brand [&_a]:underline"
                  dangerouslySetInnerHTML={{ __html: n.text }}
                />
                {/* fim texto news */}
              </article>
            ))}
        </div>
      </main>
      <Footer />
    </div>
  );
}
// END CHANGE
