
'use client';

import Link from 'next/link';
import { useEffect, useState } from 'react';
import { createBrowserClient } from '@supabase/ssr' // Use ssr browser client
import { User } from '@supabase/supabase-js';
import { useRouter } from 'next/navigation';

export default function UserMenu() {
    const [user, setUser] = useState<User | null>(null);
    const router = useRouter();
    const supabase = createBrowserClient(
        process.env.NEXT_PUBLIC_SUPABASE_URL!,
        process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!
    );

    useEffect(() => {
        // Check active session
        const getUser = async () => {
            const { data: { user } } = await supabase.auth.getUser();
            setUser(user);
        };

        getUser();

        // Listen for auth changes
        const { data: { subscription } } = supabase.auth.onAuthStateChange((_event, session) => {
            setUser(session?.user ?? null);
        });

        return () => {
            subscription.unsubscribe();
        };
    }, []);

    const handleLogout = async () => {
        await supabase.auth.signOut();
        setUser(null);
        router.push('/');
        router.refresh();
    };

    if (user) {
        return (
            <div className="flex items-center space-x-4">
                <Link
                    href="/mypage"
                    className="text-gray-700 hover:text-indigo-600 transition font-medium"
                >
                    마이페이지
                </Link>
                <button
                    onClick={handleLogout}
                    className="bg-gray-100 hover:bg-gray-200 text-gray-700 px-4 py-2 rounded-lg transition text-sm font-medium"
                >
                    로그아웃
                </button>
            </div>
        );
    }

    return (
        <div className="flex items-center space-x-4">
            <Link
                href="/login"
                className="bg-indigo-600 hover:bg-indigo-700 text-white px-4 py-2 rounded-lg transition text-sm font-bold shadow-md hover:shadow-lg"
            >
                로그인 / 회원가입
            </Link>
        </div>
    );
}
