import React, { createContext, useContext, useEffect, useState } from 'react';

const SidebarContext = createContext(null);

const STORAGE_KEY = 'mytruck_sidebar_open';

function defaultOpen() {
    if (typeof window === 'undefined') return true;
    const stored = window.localStorage.getItem(STORAGE_KEY);
    if (stored === '0') return false;
    if (stored === '1') return true;
    // First visit: closed on mobile, open on desktop
    return window.innerWidth >= 1024;
}

export function SidebarProvider({ children }) {
    const [open, setOpenState] = useState(defaultOpen);

    const setOpen = (v) => {
        const next = typeof v === 'function' ? v(open) : v;
        setOpenState(next);
        try { window.localStorage.setItem(STORAGE_KEY, next ? '1' : '0'); } catch (_) {}
    };

    // Auto-close on resize down to mobile, leave desktop state alone otherwise
    useEffect(() => {
        const onResize = () => {
            if (window.innerWidth < 1024) {
                setOpenState(false);
            }
        };
        window.addEventListener('resize', onResize);
        return () => window.removeEventListener('resize', onResize);
    }, []);

    return (
        <SidebarContext.Provider value={{ open, setOpen, toggle: () => setOpen((v) => !v) }}>
            {children}
        </SidebarContext.Provider>
    );
}

export function useSidebar() {
    return useContext(SidebarContext);
}
