<script lang="ts">
    import { writable } from "svelte/store";
    import Sidebar from "../../components/Sidebar.svelte";
    import { onMount } from "svelte";
    import { supabase } from "$lib/supabaseClient";
    import { goto } from "$app/navigation";
    import type { Session } from "@supabase/supabase-js";

    export let data;

    let notifications = 3;
    let user = {
        name: "John Doe",
        avatar: "https://i.pravatar.cc/40",
    };
    let userdata: any = null;

    const session = writable<Session | null>(null);

    onMount(async () => {
        const {
            data: { session: currentSession },
        } = await supabase.auth.getSession();

        session.set(currentSession || null);

        supabase.auth.onAuthStateChange((event, sessionValue) => {
            session.set(sessionValue);
            if (!sessionValue) goto("/login");
        });

        const userStr = localStorage.getItem("user");
        if (userStr) {
            userdata = JSON.parse(userStr);
        } else {
            goto("/login");
        }

        user.name = userdata.full_name || "Guest";
        user.avatar = userdata.profile_picture || "https://i.pravatar.cc/40";
    });
</script>

<div class="flex h-screen">
    <Sidebar />

    <!-- Main Content -->
    <div class="flex-1 flex flex-col bg-gray-100 overflow-hidden">
        <!-- Navbar -->
        <div
            class="flex items-center justify-between bg-white shadow px-6 py-3 border-b"
        >
            <div class="text-lg font-semibold text-gray-700">Dashboard</div>

            <div class="flex items-center gap-6">
                <!-- Notifications -->
                <div class="relative">
                    <button class="text-gray-600 hover:text-gray-800 text-xl">
                        🔔
                    </button>
                    {#if notifications > 0}
                        <span
                            class="absolute -top-1 -right-1 bg-red-500 text-white text-xs w-5 h-5 flex items-center justify-center rounded-full"
                            >{notifications}</span
                        >
                    {/if}
                </div>

                <!-- Profile -->
                <div class="flex items-center gap-2">
                    <img
                        src={user.avatar}
                        alt="User Avatar"
                        class="w-8 h-8 rounded-full"
                    />
                    <span class="text-sm font-medium text-gray-700"
                        >{user.name}</span
                    >
                </div>
            </div>
        </div>

        <!-- Page Content -->
        <div class="flex-1 p-6 overflow-y-auto">
            <slot />
        </div>
    </div>
</div>
