// app/portal/account/AccountPanel.tsx
"use client";

import { useEffect, useState } from "react";

type Me = {
    id: string;
    username: string;
    first_name?: string | null;
    last_name?: string | null;
    email?: string | null;
    location?: string | null;
    avatar?: { id: string; filename_download: string } | null;
};

export default function AccountPanel() {
    const [me, setMe] = useState<Me | null>(null);
    const [err, setErr] = useState<string | null>(null);
    const [loading, setLoading] = useState(true);

    useEffect(() => {
        let alive = true;
        (async () => {
            try {
                setErr(null);
                const r = await fetch("/api/account", { credentials: "include", cache: "no-store" });
                if (!r.ok) throw new Error(`Load failed (${r.status})`);
                const j = await r.json();
                if (alive) setMe(j);
            } catch (e: any) {
                if (alive) setErr(e?.message || "Failed to load account");
            } finally {
                if (alive) setLoading(false);
            }
        })();
        return () => { alive = false; };
    }, []);

    if (loading) return <div className="rounded-md border p-6 text-sm opacity-70">Loading…</div>;
    if (err) return <div className="rounded-md border p-6 text-red-600">Error: {err}</div>;
    if (!me) return null;

    return (
        <div className="space-y-6">
        <div className="rounded-md border p-4">
        <h2 className="text-lg font-semibold mb-2">Account</h2>
        <div className="grid sm:grid-cols-2 gap-3 text-sm">
        <div><div className="opacity-60">Username</div><div className="font-medium">{me.username}</div></div>
        <div><div className="opacity-60">First Name</div><div>{me.first_name || "—"}</div></div>
        <div><div className="opacity-60">Last Name</div><div>{me.last_name || "—"}</div></div>
        <div><div className="opacity-60">Email</div><div>{me.email || "—"}</div></div>
        <div><div className="opacity-60">Location</div><div>{me.location || "—"}</div></div>
        </div>
        <p className="mt-3 text-xs opacity-70">Usernames can’t be changed.</p>
        </div>

        {/* Place your edit forms here; they should only call the update APIs on submit,
            never during initial render. For password/avatar we can prompt for password
            inline or send to /auth/sign-in?reauth=1&next=/portal/account#security. */}
            </div>
    );
}
