<?php
// components/Ui/FilterPills.php
namespace Components\Ui;

use Components\Button;

class FilterPills
{
    /**
     * Render a set of filter pills consisting of an optional "ALL" pill and one pill per provided filter value.
     *
     * Expects Alpine helpers to be present in the surrounding scope by default:
     *   - setFilter(v)
     *   - isFilter(v)
     * You can change the function names using opts: isFilterFn, setFilterFn.
     *
     * @param array $filters List of filter values (strings) to render as pills
     * @param array $opts Options:
     *  - include_all: bool (default true)
     *  - all_label: string (default 'ALL') — overridden by labels_map[all_value] when present
     *  - all_value: string (default 'ALL') — value used for the "All" pill
     *  - labels_map: array<string, string> Mapping from filter value to display label (supports all_value key)
     *  - isFilterFn: string (default 'isFilter')
     *  - setFilterFn: string (default 'setFilter')
     *  - active_class: string (default 'bg-brand/50! text-white!') // applied conditionally via :class
     *  - filter_key: string (optional) — if provided, passed as the second argument to setFilter/isFilter
     *  - button_opts: array // forwarded to Button::render (variant/size/rounded/class/attrs merged)
     */
    public static function render(array $filters, array $opts = []): string
    {
        $includeAll  = $opts['include_all'] ?? true;
        $filterKey   = (string)($opts['filter_key'] ?? '');
        $allValue    = (string)($opts['all_value'] ?? 'ALL');
        $labelsMap   = is_array($opts['labels_map'] ?? null) ? $opts['labels_map'] : [];
        $allLabel    = (string)($labelsMap[$allValue] ?? ($opts['all_label'] ?? mh_lng('MAILBEEZ_UI_FILTER_ALL_LABEL', 'All')));
        $isFilterFn  = (string)($opts['isFilterFn'] ?? 'isFilter');
        $setFilterFn = (string)($opts['setFilterFn'] ?? 'setFilter');
        $activeClass = (string)($opts['active_class'] ?? 'bg-brand/70! text-white/90!');
        $buttonOpts  = is_array($opts['button_opts'] ?? null) ? $opts['button_opts'] : [];

        // Defaults aligned with existing usage
        $defaultBtn = [
            'variant' => 'secondary',
            'size'    => 'md',
            'rounded' => 'full',
            'class'   => 'aria-pressed:bg-gray-100 aria-pressed:text-secondary px-3!',
            'attrs'   => [],
        ];

        // Merge provided overrides shallowly
        $btnBase = array_merge($defaultBtn, $buttonOpts);
        $btnBase['attrs'] = array_merge($defaultBtn['attrs'], $buttonOpts['attrs'] ?? []);

        ob_start();
        $keyJs = $filterKey !== '' ? ', ' . json_encode($filterKey, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) : '';
        if ($includeAll) {
            $jsAll = json_encode($allValue, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
            $attrs = array_merge($btnBase['attrs'], [
                '@click'       => $setFilterFn . "(" . $jsAll . $keyJs . ")",
                ':class'       => $isFilterFn . "(" . $jsAll . $keyJs . ") ? '" . $activeClass . "' : ''",
                'aria-pressed' => $isFilterFn . "(" . $jsAll . $keyJs . ") ? 'true' : 'false'",
            ]);
            echo Button::render($allLabel, array_merge($btnBase, ['attrs' => $attrs]));
        }

        foreach ($filters as $f) {
            // Ensure proper JSON encoding for JavaScript literal
            $js = json_encode($f, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
            $attrs = array_merge($btnBase['attrs'], [
                '@click'       => $setFilterFn . '(' . $js . $keyJs . ')',
                ':class'       => $isFilterFn . '(' . $js . $keyJs . ") ? '" . $activeClass . "' : ''",
                'aria-pressed' => $isFilterFn . '(' . $js . $keyJs . ") ? 'true' : 'false'",
            ]);
            $label = (string)($labelsMap[(string)$f] ?? (string)$f);
            echo Button::render($label, array_merge($btnBase, ['attrs' => $attrs]));
        }

        return ob_get_clean();
    }
}
