//! Tab components for tabbed interfaces.

use leptos::prelude::*;

/// A single tab definition.
#[derive(Clone)]
pub struct Tab {
    /// Unique identifier for this tab.
    pub id: &'static str,
    /// Display label for the tab button.
    pub label: &'static str,
}

impl Tab {
    /// Create a new tab.
    pub const fn new(id: &'static str, label: &'static str) -> Self {
        Self { id, label }
    }
}

/// Tab bar component for switching between tabs.
///
/// # Example
///
/// ```ignore
/// let (active_tab, set_active_tab) = signal("tab1");
///
/// view! {
///     <TabBar
///         tabs=vec![
///             Tab::new("tab1", "First Tab"),
///             Tab::new("tab2", "Second Tab"),
///         ]
///         active=active_tab
///         on_select=Callback::new(move |id| set_active_tab.set(id))
///     />
///
///     <Show when=move || active_tab.get() == "tab1">
///         <p>"First tab content"</p>
///     </Show>
///     <Show when=move || active_tab.get() == "tab2">
///         <p>"Second tab content"</p>
///     </Show>
/// }
/// ```
#[component]
pub fn TabBar(
    /// List of tabs to display.
    tabs: Vec<Tab>,
    /// Currently active tab ID.
    #[prop(into)]
    active: Signal<&'static str>,
    /// Callback when a tab is selected.
    on_select: Callback<&'static str>,
) -> impl IntoView {
    view! {
        <div class="flex border-b border-gray-700 mb-4" role="tablist">
            <For
                each=move || tabs.clone()
                key=|tab| tab.id
                children=move |tab: Tab| {
                    let tab_id = tab.id;
                    let on_select = on_select.clone();
                    let is_active = move || active.get() == tab_id;

                    view! {
                        <button
                            type="button"
                            role="tab"
                            aria-selected=is_active
                            class=move || tab_button_class(is_active())
                            on:click=move |_| on_select.run(tab_id)
                        >
                            {tab.label}
                        </button>
                    }
                }
            />
        </div>
    }
}

/// Generate the CSS class for a tab button based on active state.
fn tab_button_class(is_active: bool) -> String {
    format!(
        "px-4 py-2 font-medium transition-colors border-b-2 -mb-px {}",
        if is_active {
            "text-blue-400 border-blue-400"
        } else {
            "text-gray-400 border-transparent hover:text-gray-300"
        }
    )
}
