//! Tab bar component rendered at the top of the app.

use leptos::prelude::*;

use crate::AppTab;

/// Renders the horizontal tab bar.
///
/// Clicking a tab activates it.  The Library tab has no close button;
/// PDF tabs show a `×` close button on hover.
#[component]
pub fn TabBar(
    tabs: RwSignal<Vec<AppTab>>,
    active_tab: RwSignal<usize>,
) -> impl IntoView {
    view! {
        <div class="tab-bar">
            {move || {
                tabs.get().into_iter().enumerate().map(|(i, tab)| {
                    let is_active = i == active_tab.get();
                    match tab {
                        AppTab::Library => view! {
                            <button
                                class="tab tab-library"
                                class:tab-active=is_active
                                on:click=move |_| active_tab.set(i)
                            >
                                "Library"
                            </button>
                        }.into_any(),
                        AppTab::Pdf { title, .. } => view! {
                            <span
                                class="tab tab-pdf"
                                class:tab-active=is_active
                                on:click=move |_| active_tab.set(i)
                            >
                                <span class="tab-label">{title}</span>
                                <button
                                    class="tab-close"
                                    on:click=move |ev| {
                                        ev.stop_propagation();
                                        tabs.update(|t| { t.remove(i); });
                                        active_tab.update(|a| *a = (*a).min(
                                            tabs.with_untracked(|t| t.len().saturating_sub(1))
                                        ));
                                    }
                                >
                                    "×"
                                </button>
                            </span>
                        }.into_any(),
                    }
                }).collect::<Vec<_>>()
            }}
        </div>
    }
}
