use leptos::prelude::*;

#[derive(Debug, Clone)]
pub struct HeaderItems {
    pub left: Vec<HeaderItem>,
    pub middle: Vec<HeaderItem>,
    pub right: Vec<HeaderItem>,
}

#[derive(Debug, Clone)]
pub struct HeaderItem {
    pub text: String,
    pub link: Option<String>,
}

/// Header with background color etc.
#[component]
pub fn StyledHeader(#[prop(into)] items: Signal<HeaderItems>) -> impl IntoView {
    view! {
        <div class="text-black bg-orange-300 border-b-2 border-b-orange-400">
            // <div class="container mx-auto" >
            <Header items />
        // </div>
        </div>
    }
}

/// Function header without styling
#[component]
pub fn Header(#[prop(into)] items: Signal<HeaderItems>) -> impl IntoView {
    let left = move || items.read().left.clone();
    let middle = move || items.read().middle.clone();
    let right = move || items.read().right.clone();

    view! {
        <div class="grid p-4 text-xl font-semibold grid-cols-[1fr_3fr_1fr]">
            // Left side of header
            <div class="justify-self-start">
                <Items items=Signal::derive(left) />
            </div>

            // Expanding space in the middle
            <div class="justify-self-center font-semibold">
                <Items items=Signal::derive(middle) />
            </div>

            // Right side of header
            <div class="justify-self-end">
                <Items items=Signal::derive(right) />
            </div>
        </div>
    }
}

#[component]
fn Items(#[prop(into)] items: Signal<Vec<HeaderItem>>) -> impl IntoView {
    let items = move || items.get().into_iter().map(|item| view! { <Item item /> }).collect_view();
    view! { <div class="flex gap-4">{items}</div> }
}

#[component]
fn Item(item: HeaderItem) -> impl IntoView {
    let text = item.text;
    let link = item.link;

    if let Some(link) = link {
        view! {
            <a href=link>
                <span class="whitespace-nowrap">{text}</span>
            </a>
        }
        .into_any()
    } else {
        view! { <span class="whitespace-nowrap">{text}</span> }.into_any()
    }
}
