{% extends "layouts/app.html" %}
{% from "components/card.html" import stat_card %}
{% from "components/table.html" import responsive_table %}

{% block title %}Token Usage - Claude Monitor{% endblock %}

{% block main_content %}
<div class="space-y-8" x-data="{
    selectedPeriod: '{{ period|default('today') }}',
    selectedModel: '{{ selected_model|default('') }}',
    showCustom: false,
    customStart: '',
    customEnd: '',
    init() {
        const legacyMap = { week: '7days', month: 'this_month', '1hour': '15min' };
        const raw = localStorage.getItem('cs_period_tokens');
        const stored = raw && legacyMap[raw] ? legacyMap[raw] : raw;
        const validPeriods = ['15min','today','this_week','7days','this_month','3months','all','custom'];
        if (stored && validPeriods.includes(stored)) {
            this.selectedPeriod = stored;
            if (stored === 'custom') {
                this.customStart = localStorage.getItem('cs_period_tokens_start') || '';
                this.customEnd   = localStorage.getItem('cs_period_tokens_end')   || '';
                if (this.customStart && this.customEnd) {
                    this.showCustom = true;
                } else {
                    this.selectedPeriod = '{{ period|default('today') }}';
                }
            }
            const canReload = stored !== 'custom' || (this.customStart && this.customEnd);
            if (canReload && stored !== '{{ period|default('today') }}') {
                this.$nextTick(() => this._reload(this.selectedPeriod));
            }
        }
    },
    _url(period) {
        let url = '/api/tokens?period=' + period + '&model=' + this.selectedModel;
        if (period === 'custom' && this.customStart && this.customEnd) {
            url += '&start=' + this.customStart + '&end=' + this.customEnd;
        }
        return url;
    },
    _reload(period) {
        htmx.ajax('GET', this._url(period), {target: '#tokens-content', swap: 'innerHTML'});
    },
    select(period) {
        this.selectedPeriod = period;
        this.showCustom = (period === 'custom');
        localStorage.setItem('cs_period_tokens', period);
        if (period !== 'custom') { this._reload(period); }
    },
    applyCustom() {
        if (!this.customStart || !this.customEnd) return;
        localStorage.setItem('cs_period_tokens_start', this.customStart);
        localStorage.setItem('cs_period_tokens_end',   this.customEnd);
        this._reload('custom');
    }
}">
    <!-- Page Title and Filters -->
    <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
        <div>
            <h1 class="text-3xl font-bold text-gray-900">Token Usage</h1>
            <p class="mt-2 text-gray-600">Detailed breakdown of your token consumption and costs</p>
        </div>

        <div class="flex flex-col sm:flex-row gap-4">
            <!-- Model Filter -->
            <div class="flex items-center gap-2">
                <label for="model-filter" class="text-sm font-medium text-gray-700">Model:</label>
                <select
                    id="model-filter"
                    name="model"
                    @change="selectedModel = $event.target.value; _reload(selectedPeriod)"
                    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]"
                >
                    <option value="">All Models</option>
                    {% for model in available_models|default([]) %}
                    <option value="{{ model.id }}" {% if selected_model == model.id %}selected{% endif %}>{{ model.name }}</option>
                    {% endfor %}
                </select>
            </div>

            <!-- Time Filter -->
            <div class="flex flex-wrap items-center gap-2">
                <select
                    @change="select($event.target.value)"
                    :value="selectedPeriod"
                    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"
                >
                    <option value="15min">Last 15 min</option>
                    <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 inputs -->
                <div x-show="showCustom" x-transition class="flex items-center gap-2">
                    <input type="date" x-model="customStart" :max="customEnd||undefined" class="px-2 py-2 text-sm border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[#0770E3]" />
                    <span class="text-gray-400 text-sm">–</span>
                    <input type="date" x-model="customEnd" :min="customStart||undefined" @change="applyCustom()" class="px-2 py-2 text-sm border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[#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">Apply</button>
                </div>

                <!-- Loading Spinner -->
                <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>
        </div>
    </div>

    <!-- Tokens Content (HTMX Target) -->
    <div id="tokens-content">
        {% include "partials/tokens_content.html" %}
    </div>
</div>
{% endblock %}
