import { redirect } from "next/navigation";
import { createClient } from "@/lib/supabase/server";
import { NotesList } from "@/components/NotesList";
import { SignOutButton } from "@/components/SignOutButton";

export default async function DashboardPage() {
  const supabase = await createClient();

  const { data: { user }, error: authError } = await supabase.auth.getUser();
  if (authError || !user) redirect("/auth/login");

  const { data: notes, error: notesError } = await supabase
    .from("notes")
    .select("id, body, created_at")
    .eq("user_id", user.id)
    .order("created_at", { ascending: false });

  return (
    <div className="dashboard">
      <header className="topbar">
        <div className="topbar-brand">
          FIRESIDE <span>TEST</span>
        </div>
        <div className="topbar-user">
          <span>{user.email}</span>
          <SignOutButton />
        </div>
      </header>

      <main className="main-content">
        <div className="stack-badge">
          <span className="badge active">Forgejo</span>
          <span className="badge active">Dokploy</span>
          <span className="badge active">Supabase Auth ✓</span>
          <span className="badge active">Supabase DB ✓</span>
          <span className="badge">Next.js 15 SSR</span>
        </div>

        <p className="section-label">// personal notes — user_id: {user.id.slice(0, 8)}…</p>

        {notesError && (
          <div className="error-msg">DB error: {notesError.message}</div>
        )}

        <NotesList initialNotes={notes ?? []} userId={user.id} />
      </main>
    </div>
  );
}
