// SPDX-License-Identifier: Apache-2.0
//! Confirmation dialog. Renders only when `open` is true. Focuses the
//! primary action when shown; closes on Escape.

use leptos::ev::KeyboardEvent;
use leptos::prelude::*;

#[component]
pub fn ConfirmDialog(
    /// Reactive open state — close by setting to false.
    open: RwSignal<bool>,
    /// Dialog title.
    title: &'static str,
    /// Body text (single paragraph).
    body: &'static str,
    /// Primary action label.
    confirm_label: &'static str,
    /// Cancel action label.
    #[prop(default = "Cancel")]
    cancel_label: &'static str,
    /// Whether confirm is destructive.
    #[prop(default = false)]
    destructive: bool,
    /// Confirm callback.
    on_confirm: Callback<()>,
) -> impl IntoView {
    let close = move || open.set(false);
    let confirm = move || {
        on_confirm.run(());
        open.set(false);
    };

    let on_key = move |ev: KeyboardEvent| {
        if ev.key() == "Escape" {
            close();
        }
    };

    let primary_class = if destructive {
        "btn btn--danger"
    } else {
        "btn"
    };

    view! {
        <Show when=move || open.get() fallback=|| ()>
            <div
                class="modal-backdrop"
                role="dialog"
                aria-modal="true"
                aria-labelledby="confirm-title"
                on:keydown=on_key.clone()
            >
                <div class="modal">
                    <h2 id="confirm-title" class="modal__title">{title}</h2>
                    <p class="modal__body">{body}</p>
                    <div class="action-bar">
                        <button
                            type="button"
                            class="btn btn--ghost"
                            on:click=move |_| close()
                        >{cancel_label}</button>
                        <button
                            type="button"
                            class=primary_class
                            on:click=move |_| confirm()
                        >{confirm_label}</button>
                    </div>
                </div>
            </div>
        </Show>
    }
}
