/**
 * FacetDropdown Component
 *
 * A dropdown component that displays facet values from a specific field
 * and allows users to filter search results by selecting values.
 *
 * Can be used standalone (fetches its own data) or integrated with SearchProvider.
 *
 * @cssVariables
 * Customize the dropdown appearance using CSS variables:
 *
 * Button:
 * - `--facet-dropdown-button-bg`: Button background color
 * - `--facet-dropdown-text`: Button text color
 * - `--facet-dropdown-border`: Button and panel border color
 * - `--facet-dropdown-font-size`: Button font size (default: 0.875rem)
 * - `--facet-dropdown-font-weight`: Button font weight (default: 500)
 *
 * Dropdown Panel:
 * - `--facet-dropdown-bg`: Panel background color
 * - `--facet-dropdown-shadow`: Panel box shadow
 *
 * Options:
 * - `--facet-dropdown-option-text`: Option text color
 * - `--facet-dropdown-option-font-size`: Option font size (default: 0.875rem)
 * - `--facet-dropdown-option-font-weight-active`: Active option font weight (default: 500)
 * - `--facet-dropdown-option-active-bg`: Active option background color
 *
 * Count Badge:
 * - `--facet-dropdown-count-text`: Count text color
 * - `--facet-dropdown-count-font-size`: Count font size (default: 0.75rem)
 *
 * Scrollbar:
 * - `--facet-dropdown-scrollbar-thumb`: Scrollbar thumb color
 * - `--facet-dropdown-scrollbar-thumb-hover`: Scrollbar thumb hover color
 *
 * @example
 * ```tsx
 * <FacetDropdown
 *   field="category"
 *   placeholder="All Categories"
 *   applyFilter={true}
 *   showCounts={true}
 * />
 * ```
 */
import React, { useState, useEffect, useRef, useCallback } from "react";
import { createPortal } from "react-dom";
import { useSearchContext } from "./SearchProvider";
import { useSearchState } from "../hooks/useSearchState";
import { log } from "@seekora-ai/ui-sdk-core";
import { ensureSeekoraStyles } from "../styles/inject";
// Z-index scale for consistent layering
// SearchOverlay uses z-100, so dropdown must be higher
const Z_INDEX = {
    dropdown: 150, // Higher than SearchOverlay (100)
    modal: 200,
    overlay: 300,
    tooltip: 50,
};
// ---------------------------------------------------------------------------
// Component
// ---------------------------------------------------------------------------
export const FacetDropdown = ({ field, placeholder = "All Categories", className, theme: customTheme = {}, onChange, value: controlledValue, maxOptions = 10, showCounts = true, options: providedOptions, client: providedClient, applyFilter = true, navigateOnSelect = false, searchPageUrl = "/search", useFiltersApi = false, }) => {
    const { client: contextClient, theme, stateManager } = useSearchContext();
    const { addRefinement, removeRefinement, refinements, search } = useSearchState();
    const client = providedClient || contextClient;
    useEffect(() => {
        ensureSeekoraStyles();
    }, []);
    const [open, setOpen] = useState(false);
    const [facetOptions, setFacetOptions] = useState(providedOptions || []);
    const [internalValue, setInternalValue] = useState(controlledValue || "");
    const [dropdownPosition, setDropdownPosition] = useState(null);
    const dropdownRef = useRef(null);
    const buttonRef = useRef(null);
    // Determine the current value (controlled or uncontrolled)
    const currentValue = controlledValue !== undefined ? controlledValue : internalValue;
    // ---------------------------------------------------------------------------
    // Fetch facet values
    // ---------------------------------------------------------------------------
    const fetchFacetValues = useCallback(async () => {
        if (providedOptions || !client)
            return;
        try {
            log.verbose("FacetDropdown: Fetching facet values", {
                field,
                useFiltersApi,
            });
            if (useFiltersApi) {
                // Use dedicated Filters API via state manager
                const response = await stateManager.fetchFilters({
                    facetBy: field,
                    maxFacetValues: 100,
                });
                const targetFilter = (response?.filters || []).find((f) => f.field === field);
                if (targetFilter && targetFilter.values) {
                    const options = targetFilter.values.map((v) => ({
                        value: v.value || "",
                        count: v.count || 0,
                        label: v.value || "",
                    }));
                    setFacetOptions(options);
                    log.verbose("FacetDropdown: Facet options loaded via Filters API", {
                        field,
                        count: options.length,
                    });
                }
                else {
                    log.verbose("FacetDropdown: No filter data found", { field });
                    setFacetOptions([]);
                }
            }
            else {
                // Fallback: use search API with per_page=0
                const response = await client.search("*", {
                    facet_by: field,
                    max_facet_values: 100,
                    per_page: 0,
                });
                log.verbose("FacetDropdown: Search response", { response });
                const facetsData = response?.data?.facets || response?.facets;
                const facets = Array.isArray(facetsData) ? facetsData : [];
                const targetFacet = facets.find((f) => f.field_name === field || f.field === field);
                if (targetFacet && targetFacet.counts) {
                    const options = targetFacet.counts.map((count) => ({
                        value: count.value,
                        count: count.count,
                        label: count.value,
                    }));
                    setFacetOptions(options);
                    log.verbose("FacetDropdown: Facet options loaded", {
                        field,
                        count: options.length,
                    });
                }
                else {
                    log.verbose("FacetDropdown: No facet data found", { field, facets });
                    setFacetOptions([]);
                }
            }
        }
        catch (error) {
            const err = error instanceof Error ? error : new Error(String(error));
            log.error("FacetDropdown: Error fetching facet values", {
                field,
                error: err.message,
            });
            setFacetOptions([]);
        }
    }, [field, client, providedOptions, useFiltersApi]);
    useEffect(() => {
        if (!providedOptions && client) {
            fetchFacetValues();
        }
    }, [fetchFacetValues, providedOptions, client]);
    // ---------------------------------------------------------------------------
    // Calculate dropdown position when opened
    // ---------------------------------------------------------------------------
    useEffect(() => {
        if (!open || !buttonRef.current)
            return;
        const updatePosition = () => {
            if (!buttonRef.current)
                return;
            const rect = buttonRef.current.getBoundingClientRect();
            setDropdownPosition({
                top: rect.bottom + window.scrollY + 4,
                left: rect.left + window.scrollX,
                width: rect.width,
            });
        };
        updatePosition();
        window.addEventListener("scroll", updatePosition, true);
        window.addEventListener("resize", updatePosition);
        return () => {
            window.removeEventListener("scroll", updatePosition, true);
            window.removeEventListener("resize", updatePosition);
        };
    }, [open]);
    // ---------------------------------------------------------------------------
    // Click outside handler
    // ---------------------------------------------------------------------------
    useEffect(() => {
        if (!open)
            return;
        const handleClickOutside = (e) => {
            if (dropdownRef.current &&
                !dropdownRef.current.contains(e.target) &&
                buttonRef.current &&
                !buttonRef.current.contains(e.target)) {
                setOpen(false);
            }
        };
        const handleEscape = (e) => {
            if (e.key === "Escape") {
                setOpen(false);
            }
        };
        document.addEventListener("mousedown", handleClickOutside);
        document.addEventListener("keydown", handleEscape);
        return () => {
            document.removeEventListener("mousedown", handleClickOutside);
            document.removeEventListener("keydown", handleEscape);
        };
    }, [open]);
    // ---------------------------------------------------------------------------
    // Selection handler
    // ---------------------------------------------------------------------------
    const handleSelect = useCallback((value) => {
        log.verbose("FacetDropdown: Value selected", { field, value });
        // Update internal state
        setInternalValue(value);
        setOpen(false);
        // Call onChange callback
        if (onChange) {
            onChange(value);
        }
        // Apply filter if enabled and we have search state
        if (applyFilter && addRefinement && removeRefinement) {
            // Remove any existing refinement for this field
            const existingRefinement = refinements.find((r) => r.field === field);
            if (existingRefinement) {
                removeRefinement(field, existingRefinement.value, false);
            }
            // Add new refinement if value is not empty
            if (value) {
                addRefinement(field, value, true); // true = trigger search
            }
            else if (search) {
                // If clearing the filter, trigger search manually
                search();
            }
        }
        // Navigate to search page if enabled
        if (navigateOnSelect && value && typeof window !== "undefined") {
            const url = new URL(window.location.origin + searchPageUrl);
            url.searchParams.set(field, value);
            window.location.href = url.toString();
        }
    }, [
        field,
        onChange,
        applyFilter,
        addRefinement,
        removeRefinement,
        refinements,
        search,
        navigateOnSelect,
        searchPageUrl,
    ]);
    // ---------------------------------------------------------------------------
    // Render
    // ---------------------------------------------------------------------------
    const displayLabel = currentValue || placeholder;
    const hasOptions = facetOptions.length > 0;
    const buttonClass = [
        "facet-dropdown-button",
        customTheme.button,
        className,
        open && customTheme.buttonOpen,
    ]
        .filter(Boolean)
        .join(" ");
    // Render dropdown panel via portal
    const renderDropdown = () => {
        if (!open ||
            !hasOptions ||
            !dropdownPosition ||
            typeof document === "undefined") {
            return null;
        }
        // Runtime-derived positioning values — must stay inline
        const panelPositionStyle = {
            top: `${dropdownPosition.top}px`,
            left: `${dropdownPosition.left}px`,
            minWidth: `${dropdownPosition.width}px`,
        };
        // Runtime-derived border radius from theme prop — must stay inline when present
        const optionRadiusStyle = theme?.borderRadius && typeof theme.borderRadius !== "string"
            ? { borderRadius: theme.borderRadius.small }
            : undefined;
        const panelRadiusStyle = theme?.borderRadius && typeof theme.borderRadius !== "string"
            ? {
                "--facet-dropdown-panel-radius": theme.borderRadius.medium,
            }
            : undefined;
        const dropdown = (React.createElement("div", { ref: dropdownRef, className: customTheme.panel || "facet-dropdown-panel", role: "listbox", "aria-label": `${field} options`, style: panelRadiusStyle
                ? { ...panelPositionStyle, ...panelRadiusStyle }
                : panelPositionStyle },
            React.createElement("button", { type: "button", role: "option", "aria-selected": !currentValue, "data-active": !currentValue ? "true" : undefined, onClick: (e) => {
                    e.preventDefault();
                    e.stopPropagation();
                    handleSelect("");
                }, className: [
                    "facet-dropdown-option",
                    customTheme.option,
                    !currentValue && customTheme.optionActive,
                ]
                    .filter(Boolean)
                    .join(" "), style: optionRadiusStyle },
                React.createElement("span", { className: "facet-dropdown-option__label" }, placeholder)),
            facetOptions.map((option) => {
                const isActive = currentValue === option.value;
                return (React.createElement("button", { key: option.value, type: "button", role: "option", "aria-selected": isActive, "data-active": isActive ? "true" : undefined, onClick: (e) => {
                        e.preventDefault();
                        e.stopPropagation();
                        handleSelect(option.value);
                    }, className: [
                        "facet-dropdown-option",
                        customTheme.option,
                        isActive && customTheme.optionActive,
                    ]
                        .filter(Boolean)
                        .join(" "), style: optionRadiusStyle },
                    React.createElement("span", { className: "facet-dropdown-option__label" }, option.label || option.value),
                    showCounts && (React.createElement("span", { className: "facet-dropdown-option__count" },
                        "(",
                        option.count,
                        ")"))));
            })));
        return createPortal(dropdown, document.body);
    };
    // Runtime-derived border radius for the trigger button
    const buttonRadiusStyle = theme?.borderRadius && typeof theme.borderRadius !== "string"
        ? {
            "--facet-dropdown-button-radius": theme.borderRadius.medium,
        }
        : undefined;
    return (React.createElement("div", { className: "facet-dropdown-container" },
        React.createElement("button", { ref: buttonRef, type: "button", onClick: (e) => {
                e.preventDefault();
                e.stopPropagation();
                setOpen((prev) => !prev);
            }, className: buttonClass, "aria-label": `Filter by ${field}`, "aria-expanded": open, "aria-haspopup": "listbox", style: buttonRadiusStyle, disabled: !hasOptions },
            React.createElement("span", { className: "facet-dropdown-button__label" }, displayLabel),
            React.createElement("svg", { className: ["facet-dropdown-button__caret", customTheme.caretIcon]
                    .filter(Boolean)
                    .join(" "), width: "16", height: "16", viewBox: "0 0 16 16", fill: "none", xmlns: "http://www.w3.org/2000/svg", "aria-hidden": "true" },
                React.createElement("path", { d: "M4 6L8 10L12 6", stroke: "currentColor", strokeWidth: "1.5", strokeLinecap: "round", strokeLinejoin: "round" }))),
        renderDropdown()));
};
