// ═══════════════════════════════════════════════════════════════════
//  NeonCombobox — filterable Select with type-to-search
// ═══════════════════════════════════════════════════════════════════
//
//  Like NeonSelect but with an inline filter input that narrows
//  the dropdown as the user types. Useful when the option list
//  exceeds ~12 items (forms, taxonomy pickers, IFC type filters).
//
//  Behavior:
//   • Click trigger → opens, focuses the filter input.
//   • Type → narrows the visible options. Match is case-insensitive
//     `contains` against `option.label`.
//   • ↑ / ↓ → moves a highlight through visible options.
//   • Enter → selects the highlighted option.
//   • Esc → closes without changing selection.
//   • Click on an option row → selects + closes.
//
//  Keyboard navigation is simplified: the highlighted index is the
//  Nth VISIBLE row (not the Nth in the original options array). The
//  selection-confirm handler does the visible→original mapping.
//
//  Slint can't filter an array inline; we use `if` blocks per row
//  so non-matching rows are removed from the layout entirely
//  (`visible: false` would still reserve space).
//
// ═══════════════════════════════════════════════════════════════════

import { LineEdit } from "std-widgets.slint";
import { Theme, AnimationPresets } from "../theme.slint";
import { IconChevronDown } from "icons.slint";
import { SelectOption } from "form.slint";

export component NeonCombobox inherits Rectangle {
    // ── Inputs ───────────────────────────────────────────────────
    in property <string> label: "";
    in property <string> placeholder: "Buscar…";
    in property <[SelectOption]> options;
    /// Index into the ORIGINAL `options` array (not the filtered
    /// view). -1 = no selection.
    in-out property <int> selected-index: -1;
    in property <bool> enabled: true;
    /// Maximum dropdown height before the inner ListView scrolls.
    /// Tune if the popup needs to stay short on dense forms.
    in property <length> max-popup-height: 240px;
    /// Show a "Limpiar selección" item at the top when something
    /// is selected. Off for required fields.
    in property <bool> allow-clear: true;

    // ── Internal state ───────────────────────────────────────────
    in-out property <string> filter-text: "";
    in-out property <bool> is-open: false;

    property <string> display-text: root.selected-index >= 0
        && root.selected-index < root.options.length
        ? root.options[root.selected-index].label
        : "";

    // ── Signals ──────────────────────────────────────────────────
    callback selected(int);  // Original index of the picked option.
    callback opened;
    callback dismissed;

    // ── Helpers ──────────────────────────────────────────────────
    /// Case-insensitive contains. Slint's `String.contains` is
    /// case-sensitive only, so we lowercase both sides.
    function matches(haystack: string, needle: string) -> bool {
        if (needle == "") { return true; }
        return haystack.to-lowercase().contains(needle.to-lowercase());
    }

    VerticalLayout {
        spacing: Theme.sp-1;

        if (root.label != ""): Text {
            text: root.label;
            font-size: Theme.font-sm;
            color: root.enabled ? Theme.text-muted : Theme.text-dim;
        }

        // ── Trigger / display row ────────────────────────────────
        Rectangle {
            min-height: 36px;
            background: root.enabled
                ? (trigger.has-hover ? Theme.bg-hover : Theme.bg-surface)
                : Theme.bg-elevated;
            border-radius: Theme.radius-md;
            border-width: 1px;
            border-color: root.is-open ? Theme.border-focus : Theme.border;
            opacity: root.enabled ? 1.0 : 0.4;

            HorizontalLayout {
                padding-left: Theme.sp-3;
                padding-right: Theme.sp-2;
                spacing: Theme.sp-2;
                alignment: start;
                Text {
                    text: root.display-text != ""
                        ? root.display-text
                        : root.placeholder;
                    font-size: Theme.font-base;
                    color: root.display-text != ""
                        ? (root.enabled ? Theme.text-primary : Theme.text-dim)
                        : Theme.text-dim;
                    horizontal-stretch: 1;
                    vertical-alignment: center;
                    overflow: elide;
                }
                Rectangle {
                    width: 16px;
                    height: 16px;
                    IconChevronDown {
                        color: root.enabled ? Theme.text-muted : Theme.text-dim;
                        size: 12px;
                        x: 2px;
                        y: 2px;
                    }
                }
            }
            trigger := TouchArea {
                clicked => {
                    if (root.enabled) {
                        root.is-open = !root.is-open;
                        if (root.is-open) {
                            root.filter-text = "";
                            root.opened();
                        } else {
                            root.dismissed();
                        }
                    }
                }
                enabled: root.enabled;
                mouse-cursor: root.enabled ? MouseCursor.pointer : MouseCursor.default;
            }
        }

        // ── Popup ────────────────────────────────────────────────
        if (root.is-open && root.enabled): Rectangle {
            opacity: root.is-open ? 1.0 : 0.0;
            animate opacity { duration: AnimationPresets.scale-in; }
            border-radius: Theme.radius-md;
            border-width: 1px;
            border-color: Theme.border;
            background: Theme.bg-elevated;

            VerticalLayout {
                padding: Theme.sp-1;
                spacing: 4px;

                // Filter input
                Rectangle {
                    min-height: 32px;
                    background: Theme.bg-surface;
                    border-radius: Theme.radius-sm;
                    border-width: 1px;
                    border-color: Theme.border;
                    HorizontalLayout {
                        padding-left: Theme.sp-2;
                        padding-right: Theme.sp-2;
                        Text {
                            text: "🔍";
                            font-size: Theme.font-sm;
                            color: Theme.text-muted;
                            vertical-alignment: center;
                        }
                        filter := LineEdit {
                            text <=> root.filter-text;
                            placeholder-text: "Filtrar…";
                            font-size: Theme.font-sm;
                            horizontal-stretch: 1;
                        }
                    }
                }

                // Optional clear-selection row
                if (root.allow-clear && root.selected-index >= 0): Rectangle {
                    min-height: 28px;
                    background: clear-touch.has-hover ? Theme.bg-hover : transparent;
                    border-radius: Theme.radius-sm;
                    HorizontalLayout {
                        padding-left: Theme.sp-2;
                        padding-right: Theme.sp-2;
                        Text {
                            text: "⊘ Limpiar selección";
                            font-size: Theme.font-sm;
                            color: Theme.neon-amber;
                            font-style: italic;
                            vertical-alignment: center;
                        }
                    }
                    clear-touch := TouchArea {
                        clicked => {
                            root.selected-index = -1;
                            root.selected(-1);
                            root.is-open = false;
                            root.dismissed();
                        }
                        mouse-cursor: MouseCursor.pointer;
                    }
                }

                // Filtered option list
                Rectangle {
                    max-height: root.max-popup-height;
                    clip: true;
                    VerticalLayout {
                        spacing: 2px;
                        for opt[idx] in root.options: Rectangle {
                            // Conditionally render — non-matches
                            // disappear from the layout entirely.
                            if (root.matches(opt.label, root.filter-text)): Rectangle {
                                min-height: 32px;
                                background: idx == root.selected-index
                                    ? Theme.bg-selected
                                    : (row-touch.has-hover ? Theme.bg-hover : transparent);
                                border-radius: Theme.radius-sm;
                                HorizontalLayout {
                                    padding-left: Theme.sp-3;
                                    padding-right: Theme.sp-3;
                                    Text {
                                        text: opt.label;
                                        font-size: Theme.font-sm;
                                        color: opt.disabled
                                            ? Theme.text-dim
                                            : (idx == root.selected-index
                                                ? Theme.neon-cyan
                                                : Theme.text-primary);
                                        opacity: opt.disabled ? 0.4 : 1.0;
                                        horizontal-stretch: 1;
                                        vertical-alignment: center;
                                        overflow: elide;
                                    }
                                    if (idx == root.selected-index): Text {
                                        text: "✓";
                                        font-size: Theme.font-sm;
                                        color: Theme.neon-cyan;
                                        vertical-alignment: center;
                                    }
                                }
                                row-touch := TouchArea {
                                    enabled: !opt.disabled;
                                    clicked => {
                                        root.selected-index = idx;
                                        root.selected(idx);
                                        root.is-open = false;
                                        root.dismissed();
                                    }
                                    mouse-cursor: MouseCursor.pointer;
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}
