<!--
    Component: ThemeDecorator
    Storybook decorator that initializes ThemeManager for theme-related stories.
    Ensures theme management works correctly in Storybook's iframe environment.
    Includes a floating theme toggle for universal theme switching across all stories.
-->
<script lang="ts">
import { themeManager } from '$features/ChangeAppTheme';
import type { ResponsiveManager } from '$shared/lib';
import { IconButton } from '$shared/ui';
import MoonIcon from '@lucide/svelte/icons/moon';
import SunIcon from '@lucide/svelte/icons/sun';
import { getContext } from 'svelte';
import {
    onDestroy,
    onMount,
} from 'svelte';

interface Props {
    children: import('svelte').Snippet;
}

let { children }: Props = $props();

// Get responsive context (set by Decorator)
const responsive = getContext<ResponsiveManager>('responsive');

// Initialize themeManager on mount
onMount(() => {
    themeManager.init();

    // Add keyboard shortcut for theme toggle (Cmd/Ctrl+Shift+D)
    const handleKeyDown = (e: KeyboardEvent) => {
        if ((e.metaKey || e.ctrlKey) && e.shiftKey && e.key === 'D') {
            e.preventDefault();
            themeManager.toggle();
        }
    };

    document.addEventListener('keydown', handleKeyDown);

    return () => {
        document.removeEventListener('keydown', handleKeyDown);
    };
});

// Clean up themeManager when story unmounts
onDestroy(() => {
    themeManager.destroy();
});

const theme = $derived(themeManager.value);
const themeLabel = $derived(theme === 'light' ? 'Light' : 'Dark');
</script>

<!-- Floating Theme Toggle -->
<div
    class="fixed top-4 right-4 z-50 flex items-center gap-2 px-3 py-2 bg-card border border-border shadow-lg rounded-lg"
    title="Toggle theme (Cmd/Ctrl+Shift+D)"
>
    <span class="text-xs font-medium text-muted-foreground">Theme: {themeLabel}</span>
    <IconButton
        onclick={() => themeManager.toggle()}
        size={responsive?.isMobile ? 'sm' : 'md'}
        variant="ghost"
        title="Toggle theme"
    >
        {#snippet icon()}
            {#if theme === 'light'}
                <MoonIcon class="size-4" />
            {:else}
                <SunIcon class="size-4" />
            {/if}
        {/snippet}
    </IconButton>
</div>

<!-- Story Content -->
{@render children()}
