use leptos::prelude::*;
use crate::components::layout::sidebar::Sidebar;
use crate::components::layout::toolbar::Toolbar;
use crate::components::layout::footer::Footer;
use crate::components::ui::sidenav::{SidenavWrapper, Sidenav, SidenavInset};
use wasm_bindgen::JsCast;

#[component]
pub fn Protected(children: Children) -> impl IntoView {
    let (collapsed, set_collapsed) = signal(false);

    // Responsive Sidebar Logic
    Effect::new(move |_| {
        let window = web_sys::window().expect("window missing");
        
        // Initial check
        let width = window.inner_width().unwrap().as_f64().unwrap_or(1920.0);
        if width < 1280.0 {
            set_collapsed.set(true);
        } else {
            set_collapsed.set(false);
        }

        // Listener
        let closure = wasm_bindgen::closure::Closure::<dyn FnMut(_)>::new(move |_: web_sys::Event| {
            let window = web_sys::window().expect("window missing");
            let width = window.inner_width().unwrap().as_f64().unwrap_or(1920.0);
            if width < 1280.0 {
                set_collapsed.set(true);
            } else {
                set_collapsed.set(false);
            }
        });
        
        let _ = window.add_event_listener_with_callback("resize", closure.as_ref().unchecked_ref());
        closure.forget(); // Leak memory intentionally for global listener (or store in a cleanup handle if needed, but for layout component it's fine)
    });

    view! {
        <SidenavWrapper attr:style="--sidenav-width:16rem; --sidenav-width-icon:3rem;">
            // Masaüstü Sidenav
            <Sidenav 
                data_collapsible=crate::components::ui::sidenav::SidenavCollapsible::Icon 
                data_state=if collapsed.get() { crate::components::ui::sidenav::SidenavState::Collapsed } else { crate::components::ui::sidenav::SidenavState::Expanded }
            >
                <Sidebar />
            </Sidenav>

            // İçerik Alanı
            <SidenavInset class="flex flex-col h-screen overflow-hidden">
                // Toolbar (Üst Bar)
                <Toolbar on_toggle_sidebar=Callback::new(move |_| set_collapsed.update(|c| *c = !*c)) />
                
                // Ana İçerik
                <main class="flex-1 overflow-y-auto relative bg-background flex flex-col">
                    <div class="flex-1">
                        {children()}
                    </div>
                    <Footer />
                </main>
            </SidenavInset>
        </SidenavWrapper>
    }
}
