"""Modal-based card stack settings with card count slider (auto toggle), width slider, and optional scale slider."""

# AUTOGENERATED! DO NOT EDIT! File to edit: ../../nbs/components/settings_modal.ipynb.

# %% auto #0
__all__ = ['render_settings_trigger', 'render_card_stack_settings_modal']

# %% ../../nbs/components/settings_modal.ipynb #sm-imports
from typing import Any

from fasthtml.common import Div, Span, Input, Dialog, Button, Form, H3, Label, FT

from cjm_fasthtml_daisyui.components.actions.modal import modal, modal_box, modal_backdrop
from cjm_fasthtml_daisyui.components.actions.button import (
    btn, btn_sizes, btn_styles, btn_modifiers,
)
from cjm_fasthtml_daisyui.components.data_input.range_slider import range_dui, range_sizes
from cjm_fasthtml_daisyui.components.data_input.toggle import toggle, toggle_sizes
from cjm_fasthtml_daisyui.utilities.semantic_colors import text_dui, border_dui

from cjm_fasthtml_tailwind.utilities.spacing import p, m
from cjm_fasthtml_tailwind.utilities.sizing import w, max_w
from cjm_fasthtml_tailwind.utilities.typography import font_size, font_weight
from cjm_fasthtml_tailwind.utilities.flexbox_and_grid import (
    flex_display, items, gap, justify, flex_direction,
)
from cjm_fasthtml_tailwind.utilities.layout import position, right, top
from cjm_fasthtml_tailwind.utilities.borders import border
from cjm_fasthtml_tailwind.core.base import combine_classes

from cjm_fasthtml_lucide_icons.factory import lucide_icon

from ..core.config import CardStackConfig
from ..core.html_ids import CardStackHtmlIds

# %% ../../nbs/components/settings_modal.ipynb #sm-section-label
def _render_section_label(
    text: str,  # label text
) -> Span:      # styled label element
    """Render a settings section label."""
    return Span(
        text,
        cls=combine_classes(font_size.sm, font_weight.medium, text_dui.base_content),
    )

# %% ../../nbs/components/settings_modal.ipynb #sm-slider-with-labels
def _render_slider_with_labels(
    slider_id: str,   # HTML ID for the range input
    min_val: int,      # slider minimum
    max_val: int,      # slider maximum
    step_val: int,     # slider step
    current_val: int,  # current value
    low_label: str,    # label for low end
    high_label: str,   # label for high end
    oninput: str,      # JS oninput handler
    disabled: bool = False,  # whether slider is disabled
) -> Div:              # slider row with end labels
    """Render a range slider with low/high labels."""
    label_cls = combine_classes(font_size.xs, text_dui.base_content.opacity(50))

    attrs = dict(
        type="range",
        id=slider_id,
        min=str(min_val),
        max=str(max_val),
        step=str(step_val),
        value=str(current_val),
        cls=combine_classes(range_dui, range_sizes.sm, w.full),
        oninput=oninput,
    )
    if disabled:
        attrs['disabled'] = 'disabled'

    return Div(
        Div(
            Span(low_label, cls=label_cls),
            Span(high_label, cls=label_cls),
            cls=combine_classes(flex_display, justify.between, p.x(0.5)),
        ),
        Input(**attrs),
        cls=w.full,
    )

# %% ../../nbs/components/settings_modal.ipynb #sm-card-count-section
def _render_card_count_section(
    config: CardStackConfig,   # card stack config with visible_count_options
    ids: CardStackHtmlIds,     # HTML IDs for this instance
    current_count: int = 1,    # currently selected card count
    is_auto_mode: bool = True, # whether auto-adjust mode is active
) -> Div:                      # card count section with auto toggle and slider
    """Render the card count section with auto toggle and discrete slider."""
    opts = config.visible_count_options
    min_count = opts[0]
    max_count = opts[-1]
    step_count = opts[1] - opts[0] if len(opts) > 1 else 1
    prefix = config.prefix

    # JS: slider oninput calls handleCountChange with the numeric value
    slider_oninput = f"window.cardStacks['{prefix}'].handleCountChange(this.value)"

    # JS: toggle onchange — when checked (auto), call handleCountChange('auto') and disable slider;
    # when unchecked, call handleCountChange with slider value and enable slider
    toggle_onchange = (
        f"var slider=document.getElementById('{ids.card_count_slider}');"
        f"if(this.checked){{window.cardStacks['{prefix}'].handleCountChange('auto');slider.disabled=true;}}"
        f"else{{slider.disabled=false;window.cardStacks['{prefix}'].handleCountChange(slider.value);}}"
    )

    # Tick marks for discrete values
    tick_marks = Div(
        *[Span("|") for _ in opts],
        cls=combine_classes(justify.between, flex_display, p.x(0.5), font_size.xs,
                           text_dui.base_content.opacity(30)),
    )
    tick_labels = Div(
        *[Span(str(v)) for v in opts],
        cls=combine_classes(justify.between, flex_display, p.x(0.5), font_size.xs,
                           text_dui.base_content.opacity(50)),
    )

    slider_attrs = dict(
        type="range",
        id=ids.card_count_slider,
        min=str(min_count),
        max=str(max_count),
        step=str(step_count),
        value=str(current_count if not is_auto_mode else min_count),
        cls=combine_classes(range_dui, range_sizes.sm, w.full),
        oninput=slider_oninput,
    )
    if is_auto_mode:
        slider_attrs['disabled'] = 'disabled'

    return Div(
        # Label row: "Cards" on left, "Auto" toggle on right
        Div(
            _render_section_label("Cards"),
            Label(
                Span("Auto", cls=combine_classes(font_size.xs, text_dui.base_content.opacity(70))),
                Input(
                    type="checkbox",
                    id=ids.card_count_auto_toggle,
                    cls=combine_classes(toggle, toggle_sizes.sm),
                    checked=is_auto_mode,
                    onchange=toggle_onchange,
                ),
                cls=combine_classes(flex_display, items.center, gap(2)),
            ),
            cls=combine_classes(flex_display, items.center, justify.between, m.b(1)),
        ),
        # Slider
        Input(**slider_attrs),
        # Tick marks and labels
        tick_marks,
        tick_labels,
        cls=w.full,
    )

# %% ../../nbs/components/settings_modal.ipynb #sm-trigger-button
def render_settings_trigger(
    modal_id: str,          # ID of the settings modal dialog to open
    icon_size: int = 4,     # lucide icon size
) -> Button:                # ghost button with sliders-horizontal icon
    """Render a settings icon button that opens the card stack settings modal."""
    return Button(
        lucide_icon("sliders-horizontal", size=icon_size),
        cls=combine_classes(btn, btn_sizes.sm, btn_styles.ghost, btn_modifiers.circle),
        title="Card stack settings",
        onclick=f"document.getElementById('{modal_id}').showModal();",
        type="button",
    )

# %% ../../nbs/components/settings_modal.ipynb #sm-full-modal
def render_card_stack_settings_modal(
    config: CardStackConfig,       # card stack configuration
    ids: CardStackHtmlIds,         # HTML IDs for this instance
    current_count: int = 1,        # currently selected card count
    is_auto_mode: bool = True,     # whether auto-adjust mode is active
    card_width: int = 80,          # current card width in rem
    show_scale: bool = False,      # whether to include the scale slider
    card_scale: int = 100,         # current scale percentage (if show_scale=True)
    title: str = "Display Settings",  # modal title text
) -> tuple[FT, FT]:               # (modal_dialog, trigger_button)
    """Render a modal-based card stack settings panel.

    Returns two components:
    - `modal_dialog`: The Dialog element (place anywhere in page)
    - `trigger_button`: Small settings icon button (place in toolbar)
    """
    prefix = config.prefix

    # --- Build sections ---
    sections = []

    # Card count section
    sections.append(_render_card_count_section(
        config, ids, current_count=current_count, is_auto_mode=is_auto_mode,
    ))

    # Width section
    width_oninput = f"window.cardStacks['{prefix}'].updateWidth(this.value)"
    sections.append(Div(
        _render_section_label("Width"),
        _render_slider_with_labels(
            slider_id=ids.width_slider,
            min_val=config.card_width_min,
            max_val=config.card_width_max,
            step_val=config.card_width_step,
            current_val=card_width,
            low_label="Narrow",
            high_label="Wide",
            oninput=width_oninput,
        ),
        cls=w.full,
    ))

    # Scale section (opt-in)
    if show_scale:
        scale_oninput = f"window.cardStacks['{prefix}'].updateScale(this.value)"
        sections.append(Div(
            _render_section_label("Scale"),
            _render_slider_with_labels(
                slider_id=ids.scale_slider,
                min_val=config.card_scale_min,
                max_val=config.card_scale_max,
                step_val=config.card_scale_step,
                current_val=card_scale,
                low_label="Smaller",
                high_label="Larger",
                oninput=scale_oninput,
            ),
            cls=w.full,
        ))

    # --- Build modal ---
    modal_dialog = Dialog(
        Div(
            # Close button (top-right corner)
            Form(
                Button(
                    "\u2715",
                    cls=combine_classes(
                        btn, btn_sizes.sm, btn_modifiers.circle, btn_styles.ghost,
                        position.absolute, right._2, top._2,
                    ),
                ),
                method="dialog",
            ),
            # Title
            H3(
                lucide_icon("sliders-horizontal", size=5, cls=str(m.r(2))),
                title,
                cls=combine_classes(
                    font_size.lg, font_weight.bold,
                    flex_display, items.center,
                ),
            ),
            # Settings sections
            Div(
                *sections,
                cls=combine_classes(
                    flex_display, flex_direction.col, gap(5), p.t(4),
                ),
            ),
            cls=combine_classes(modal_box, max_w.sm),
        ),
        # Backdrop (click outside to close)
        Form(Button("close"), method="dialog", cls=str(modal_backdrop)),
        id=ids.settings_modal,
        cls=str(modal),
    )

    trigger = render_settings_trigger(modal_id=ids.settings_modal)

    return modal_dialog, trigger
