<!-- Time Filter Component
     Required context variables:
       - current_url:     API endpoint URL (e.g. '/api/tokens')
       - target_id:       HTMX target element ID (e.g. 'tokens-content')
     Optional context variables:
       - show_realtime:   bool — include 15m option (default: false)
       - storage_key:     localStorage key for per-page persistence (default: no persistence)
       - default_period:  server-rendered default period value (default: 'today')
-->
{% set api_url = current_url|default('/api/dashboard') %}
{% set content_target = target_id|default('dashboard-content') %}
{% set _show_15m = show_realtime|default(false) %}
{% set _storage_key = storage_key|default('') %}
{% set _default_period = default_period|default('today') %}

<div
    x-data="{
        selectedPeriod: '{{ _default_period }}',
        showCustom: false,
        customStart: '',
        customEnd: '',
        init() {
            {% if _storage_key %}
            const legacyMap = { week: '7days', month: 'this_month', '1hour': '15min' };
            const raw = localStorage.getItem('{{ _storage_key }}');
            const stored = raw && legacyMap[raw] ? legacyMap[raw] : raw;
            const valid = ['15min','today','this_week','7days','this_month','3months','all','custom'];
            {% if not _show_15m %}valid.splice(valid.indexOf('15min'), 1);{% endif %}
            if (stored && valid.includes(stored)) {
                this.selectedPeriod = stored;
                if (stored === 'custom') {
                    this.customStart = localStorage.getItem('{{ _storage_key }}_start') || '';
                    this.customEnd   = localStorage.getItem('{{ _storage_key }}_end')   || '';
                    if (this.customStart && this.customEnd) {
                        this.showCustom = true;
                    } else {
                        this.selectedPeriod = '{{ _default_period }}';
                    }
                }
                if (stored !== '{{ _default_period }}' && stored !== 'custom') {
                    this.$nextTick(() => this._fire(stored));
                } else if (stored === 'custom' && this.customStart && this.customEnd) {
                    this.$nextTick(() => this._fire('custom'));
                }
            }
            {% endif %}
        },
        _fire(period) {
            if (period === 'custom' && (!this.customStart || !this.customEnd)) return;
            let url = '{{ api_url }}?period=' + period;
            if (period === 'custom' && this.customStart && this.customEnd) {
                url += '&start=' + this.customStart + '&end=' + this.customEnd;
            }
            htmx.ajax('GET', url, {target: '#{{ content_target }}', swap: 'innerHTML'});
        },
        select(period) {
            this.selectedPeriod = period;
            this.showCustom = (period === 'custom');
            {% if _storage_key %}localStorage.setItem('{{ _storage_key }}', period);{% endif %}
            if (period !== 'custom') { this._fire(period); }
        },
        applyCustom() {
            if (!this.customStart || !this.customEnd) return;
            {% if _storage_key %}
            localStorage.setItem('{{ _storage_key }}_start', this.customStart);
            localStorage.setItem('{{ _storage_key }}_end',   this.customEnd);
            {% endif %}
            this._fire('custom');
        }
    }"
    class="flex flex-wrap items-center gap-2"
>
    <!-- Period select -->
    <select
        @change="select($event.target.value)"
        :value="selectedPeriod"
        aria-label="Time period"
        class="px-3 py-2 text-sm border border-gray-300 rounded-lg bg-white focus:outline-none focus:ring-2 focus:ring-[#0770E3] focus:border-[#0770E3] cursor-pointer"
    >
        {% if _show_15m %}<option value="15min">Last 15 min</option>{% endif %}
        <option value="today">Today</option>
        <option value="this_week">This week</option>
        <option value="7days">Last 7 days</option>
        <option value="this_month">This month</option>
        <option value="3months">Last 3 months</option>
        <option value="all">All time</option>
        <option value="custom">Custom range…</option>
    </select>

    <!-- Custom date range inputs -->
    <div x-show="showCustom" x-transition class="flex items-center gap-2">
        <input
            type="date"
            x-model="customStart"
            :max="customEnd || undefined"
            aria-label="Custom range start date"
            class="px-2 py-2 text-sm border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[#0770E3] focus:border-[#0770E3]"
        />
        <span class="text-gray-400 text-sm">–</span>
        <input
            type="date"
            x-model="customEnd"
            :min="customStart || undefined"
            @change="applyCustom()"
            aria-label="Custom range end date"
            class="px-2 py-2 text-sm border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[#0770E3] focus:border-[#0770E3]"
        />
        <button
            @click="applyCustom()"
            :disabled="!customStart || !customEnd"
            class="px-3 py-2 text-sm font-medium rounded-lg bg-[#0770E3] text-white disabled:opacity-40 disabled:cursor-not-allowed transition-colors"
        >Apply</button>
    </div>

    <!-- Loading indicator -->
    <span class="htmx-indicator text-[#0770E3]">
        <svg class="w-5 h-5 spinner" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
            <circle cx="12" cy="12" r="10" stroke-opacity="0.25"/>
            <path d="M12 2a10 10 0 0 1 10 10" stroke-linecap="round"/>
        </svg>
    </span>
</div>
