{# app/modules/loyalty/templates/loyalty/admin/programs.html #}
{% extends "admin/base.html" %}
{% from 'shared/macros/pagination.html' import pagination %}
{% from 'shared/macros/headers.html' import page_header %}
{% from 'shared/macros/alerts.html' import loading_state, error_state %}
{% from 'shared/macros/tables.html' import table_wrapper, table_header %}
{% from 'shared/macros/modals.html' import modal, confirm_modal_dynamic %}

{% block title %}{{ _('loyalty.admin.programs.title') }}{% endblock %}

{% block i18n_modules %}['loyalty']{% endblock %}

{% block alpine_data %}adminLoyaltyPrograms(){% endblock %}

{% block content %}
{{ page_header(_('loyalty.admin.programs.title'), action_label=_('loyalty.admin.programs.create_program'), action_onclick="showCreateModal = true") }}

{{ loading_state(_('loyalty.admin.programs.loading')) }}

{{ error_state(_('loyalty.admin.programs.error_loading')) }}

<!-- Stats Cards -->
<div x-show="!loading" class="grid gap-6 mb-8 md:grid-cols-2 xl:grid-cols-4">
    <!-- Card: Total Programs -->
    <div class="flex items-center p-4 bg-white rounded-lg shadow-xs dark:bg-gray-800">
        <div class="p-3 mr-4 text-purple-500 bg-purple-100 rounded-full dark:text-purple-100 dark:bg-purple-500">
            <span x-html="$icon('gift', 'w-5 h-5')"></span>
        </div>
        <div>
            <p class="mb-2 text-sm font-medium text-gray-600 dark:text-gray-400">
                {{ _('loyalty.admin.programs.total_programs') }}
            </p>
            <p class="text-lg font-semibold text-gray-700 dark:text-gray-200" x-text="stats.total_programs || 0">
                0
            </p>
        </div>
    </div>

    <!-- Card: Active Programs -->
    <div class="flex items-center p-4 bg-white rounded-lg shadow-xs dark:bg-gray-800">
        <div class="p-3 mr-4 text-green-500 bg-green-100 rounded-full dark:text-green-100 dark:bg-green-500">
            <span x-html="$icon('check-circle', 'w-5 h-5')"></span>
        </div>
        <div>
            <p class="mb-2 text-sm font-medium text-gray-600 dark:text-gray-400">
                {{ _('loyalty.admin.programs.active') }}
            </p>
            <p class="text-lg font-semibold text-gray-700 dark:text-gray-200" x-text="stats.active_programs || 0">
                0
            </p>
        </div>
    </div>

    <!-- Card: Total Members -->
    <div class="flex items-center p-4 bg-white rounded-lg shadow-xs dark:bg-gray-800">
        <div class="p-3 mr-4 text-blue-500 bg-blue-100 rounded-full dark:text-blue-100 dark:bg-blue-500">
            <span x-html="$icon('users', 'w-5 h-5')"></span>
        </div>
        <div>
            <p class="mb-2 text-sm font-medium text-gray-600 dark:text-gray-400">
                {{ _('loyalty.admin.programs.total_members') }}
            </p>
            <p class="text-lg font-semibold text-gray-700 dark:text-gray-200" x-text="formatNumber(stats.total_cards) || 0">
                0
            </p>
        </div>
    </div>

    <!-- Card: Transactions (30d) -->
    <div class="flex items-center p-4 bg-white rounded-lg shadow-xs dark:bg-gray-800">
        <div class="p-3 mr-4 text-orange-500 bg-orange-100 rounded-full dark:text-orange-100 dark:bg-orange-500">
            <span x-html="$icon('chart-bar', 'w-5 h-5')"></span>
        </div>
        <div>
            <p class="mb-2 text-sm font-medium text-gray-600 dark:text-gray-400">
                {{ _('loyalty.admin.programs.transactions_30d') }}
            </p>
            <p class="text-lg font-semibold text-gray-700 dark:text-gray-200" x-text="formatNumber(stats.transactions_30d) || 0">
                0
            </p>
        </div>
    </div>
</div>

<!-- Search and Filters Bar -->
<div x-show="!loading" class="mb-6 p-4 bg-white rounded-lg shadow-xs dark:bg-gray-800">
    <div class="flex flex-col md:flex-row md:items-center md:justify-between gap-4">
        <!-- Search Input -->
        <div class="flex-1 max-w-md">
            <div class="relative">
                <span class="absolute inset-y-0 left-0 flex items-center pl-3">
                    <span x-html="$icon('search', 'w-5 h-5 text-gray-400')"></span>
                </span>
                <input
                    type="text"
                    x-model="filters.search"
                    @input="debouncedSearch()"
                    placeholder="{{ _('loyalty.admin.programs.search_placeholder') }}"
                    class="w-full pl-10 pr-4 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-lg focus:border-purple-400 focus:outline-none dark:bg-gray-700 dark:text-gray-300"
                >
            </div>
        </div>

        <!-- Filters -->
        <div class="flex flex-wrap gap-3">
            <!-- Status Filter -->
            <select
                x-model="filters.is_active"
                @change="pagination.page = 1; loadPrograms()"
                class="px-4 py-2 text-sm text-gray-700 dark:text-gray-300 bg-white dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded-lg focus:border-purple-400 focus:outline-none"
            >
                <option value="">{{ _('loyalty.admin.programs.all_status') }}</option>
                <option value="true">{{ _('loyalty.common.active') }}</option>
                <option value="false">{{ _('loyalty.common.inactive') }}</option>
            </select>

            <!-- Refresh Button -->
            <button
                @click="loadPrograms(); loadStats()"
                class="flex items-center px-4 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 border border-gray-300 dark:border-gray-600 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-700 focus:outline-none transition-colors"
                title="{{ _('loyalty.common.refresh') }}"
            >
                <span x-html="$icon('refresh', 'w-4 h-4 mr-2')"></span>
                {{ _('loyalty.common.refresh') }}
            </button>
        </div>
    </div>
</div>

<!-- Programs Table -->
<div x-show="!loading">
    {% call table_wrapper() %}
            {{ table_header([_('loyalty.admin.programs.table_merchant'), _('loyalty.admin.programs.table_program_type'), _('loyalty.admin.programs.table_members'), _('loyalty.admin.programs.table_points_issued'), _('loyalty.admin.programs.table_status'), _('loyalty.admin.programs.table_created'), _('loyalty.admin.programs.table_actions')]) }}
            <tbody class="bg-white divide-y dark:divide-gray-700 dark:bg-gray-800">
                <!-- Empty State -->
                <template x-if="programs.length === 0">
                    <tr>
                        <td colspan="7" class="px-4 py-8 text-center text-gray-600 dark:text-gray-400">
                            <div class="flex flex-col items-center">
                                <span x-html="$icon('gift', 'w-12 h-12 mb-2 text-gray-300')"></span>
                                <p class="font-medium">{{ _('loyalty.admin.programs.no_programs') }}</p>
                                <p class="text-xs mt-1" x-text="filters.search || filters.is_active ? '{{ _('loyalty.admin.programs.adjust_filters')|replace("'", "\\'") }}' : '{{ _('loyalty.admin.programs.no_merchants_yet')|replace("'", "\\'") }}'"></p>
                            </div>
                        </td>
                    </tr>
                </template>

                <!-- Program Rows -->
                <template x-for="program in programs" :key="program.id">
                    <tr class="text-gray-700 dark:text-gray-400 hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors">
                        <!-- Merchant Info -->
                        <td class="px-4 py-3">
                            <div class="flex items-center text-sm">
                                <div class="relative hidden w-8 h-8 mr-3 rounded-full md:block">
                                    <div class="absolute inset-0 rounded-full flex items-center justify-center"
                                         :style="'background-color: ' + (program.card_color || '#4F46E5') + '20'">
                                        <span class="text-xs font-semibold"
                                              :style="'color: ' + (program.card_color || '#4F46E5')"
                                              x-text="program.merchant_name?.charAt(0).toUpperCase() || '?'"></span>
                                    </div>
                                </div>
                                <div>
                                    <p class="font-semibold" x-text="program.merchant_name || 'Unknown Merchant'"></p>
                                    <p class="text-xs text-gray-600 dark:text-gray-400" x-text="program.display_name || program.card_name || 'Loyalty Program'"></p>
                                </div>
                            </div>
                        </td>

                        <!-- Program Type -->
                        <td class="px-4 py-3 text-sm">
                            <span class="inline-flex items-center px-2 py-1 font-semibold leading-tight rounded-full"
                                  :class="{
                                      'text-purple-700 bg-purple-100 dark:bg-purple-700 dark:text-purple-100': program.loyalty_type === 'points',
                                      'text-blue-700 bg-blue-100 dark:bg-blue-700 dark:text-blue-100': program.loyalty_type === 'stamps',
                                      'text-green-700 bg-green-100 dark:bg-green-700 dark:text-green-100': program.loyalty_type === 'hybrid'
                                  }">
                                <span x-text="program.loyalty_type?.charAt(0).toUpperCase() + program.loyalty_type?.slice(1) || 'Unknown'"></span>
                            </span>
                            <p class="text-xs text-gray-500 mt-1" x-show="program.is_points_enabled">
                                <span x-text="program.points_per_euro"></span> {{ _('loyalty.admin.programs.pt_per_eur') }}
                            </p>
                        </td>

                        <!-- Members -->
                        <td class="px-4 py-3 text-sm">
                            <span class="font-semibold" x-text="formatNumber(program.total_cards) || 0"></span>
                            <span class="text-xs text-gray-500" x-show="program.active_cards"
                                  x-text="$t('loyalty.admin.programs.x_active', {count: program.active_cards})">
                            </span>
                        </td>

                        <!-- Points Issued -->
                        <td class="px-4 py-3 text-sm">
                            <span x-text="formatNumber(program.total_points_issued) || 0"></span>
                            <p class="text-xs text-gray-500" x-show="program.total_points_redeemed"
                               x-text="$t('loyalty.admin.programs.x_redeemed', {count: formatNumber(program.total_points_redeemed)})">
                            </p>
                        </td>

                        <!-- Status -->
                        <td class="px-4 py-3 text-xs">
                            <span class="inline-flex items-center px-2 py-1 font-semibold leading-tight rounded-full"
                                  :class="program.is_active ? 'text-green-700 bg-green-100 dark:bg-green-700 dark:text-green-100' : 'text-gray-700 bg-gray-100 dark:text-gray-100 dark:bg-gray-700'">
                                <span x-text="program.is_active ? '{{ _('loyalty.common.active')|replace("'", "\\'") }}' : '{{ _('loyalty.common.inactive')|replace("'", "\\'") }}'"></span>
                            </span>
                        </td>

                        <!-- Created Date -->
                        <td class="px-4 py-3 text-sm" x-text="formatDate(program.created_at)"></td>

                        <!-- Actions -->
                        <td class="px-4 py-3">
                            <div class="flex items-center space-x-2 text-sm">
                                <!-- View Button -->
                                <a
                                    :href="'/admin/loyalty/merchants/' + program.merchant_id"
                                    class="flex items-center justify-center p-2 text-blue-600 rounded-lg hover:bg-blue-50 dark:text-blue-400 dark:hover:bg-gray-700 focus:outline-none transition-colors"
                                    aria-label="{{ _('loyalty.common.view') }}"
                                >
                                    <span x-html="$icon('eye', 'w-5 h-5')"></span>
                                </a>

                                <!-- Edit Button -->
                                <a
                                    :href="'/admin/loyalty/merchants/' + program.merchant_id + '/program'"
                                    class="flex items-center justify-center p-2 text-purple-600 rounded-lg hover:bg-purple-50 dark:text-purple-400 dark:hover:bg-gray-700 focus:outline-none transition-colors"
                                    aria-label="{{ _('loyalty.common.edit') }}"
                                >
                                    <span x-html="$icon('edit', 'w-5 h-5')"></span>
                                </a>

                                <!-- Delete Button -->
                                <button type="button"
                                    @click="confirmDeleteProgram(program)"
                                    class="flex items-center justify-center p-2 text-red-600 rounded-lg hover:bg-red-50 dark:text-red-400 dark:hover:bg-gray-700 focus:outline-none transition-colors"
                                    aria-label="{{ _('loyalty.common.delete') }}"
                                >
                                    <span x-html="$icon('delete', 'w-5 h-5')"></span>
                                </button>

                                <!-- Activate/Deactivate Toggle -->
                                <button type="button"
                                    @click="toggleProgramActive(program)"
                                    class="flex items-center justify-center p-2 rounded-lg focus:outline-none transition-colors"
                                    :class="program.is_active ? 'text-orange-600 hover:bg-orange-50 dark:text-orange-400 dark:hover:bg-gray-700' : 'text-green-600 hover:bg-green-50 dark:text-green-400 dark:hover:bg-gray-700'"
                                    :aria-label="program.is_active ? '{{ _('loyalty.common.deactivate') }}' : '{{ _('loyalty.common.activate') }}'"
                                >
                                    <span x-html="$icon(program.is_active ? 'ban' : 'play', 'w-5 h-5')"></span>
                                </button>
                            </div>
                        </td>
                    </tr>
                </template>
            </tbody>
    {% endcall %}

    {{ pagination() }}
</div>

<!-- Delete Confirmation Modal -->
{{ confirm_modal_dynamic(
    'deleteProgramModal',
    _('loyalty.admin.programs.delete_title'),
    "$t('loyalty.admin.programs.delete_message', {name: deletingProgram?.merchant_name || ''})",
    'deleteProgram()',
    'showDeleteModal',
    _('loyalty.admin.programs.delete_confirm'),
    _('loyalty.common.cancel'),
    'danger'
) }}

<!-- Create Program Modal -->
{% call modal('createProgramModal', _('loyalty.admin.programs.create_title'), 'showCreateModal', show_footer=false) %}
    <p class="text-sm text-gray-600 dark:text-gray-400 mb-4">
        {{ _('loyalty.admin.programs.create_description') }}
    </p>

    <!-- Merchant Search -->
    <div class="mb-4">
        <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">{{ _('loyalty.admin.programs.search_merchant') }}</label>
        <div class="relative">
            <span class="absolute inset-y-0 left-0 flex items-center pl-3">
                <span x-html="$icon('search', 'w-4 h-4 text-gray-400')"></span>
            </span>
            <input type="text"
                   x-model="merchantSearch"
                   @input="searchMerchants()"
                   placeholder="{{ _('loyalty.admin.programs.type_merchant_name') }}"
                   class="w-full pl-10 pr-4 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-lg focus:border-purple-400 focus:outline-none dark:bg-gray-700 dark:text-gray-300">
        </div>
    </div>

    <!-- Search Results -->
    <div class="mb-4 max-h-48 overflow-y-auto border border-gray-200 dark:border-gray-600 rounded-lg" x-show="merchantResults.length > 0">
        <template x-for="m in merchantResults" :key="m.id">
            <button @click="selectedMerchant = m; merchantSearch = m.name"
                    class="w-full px-4 py-3 text-left text-sm hover:bg-gray-50 dark:hover:bg-gray-700 border-b border-gray-100 dark:border-gray-700 last:border-b-0 flex items-center justify-between"
                    :class="selectedMerchant?.id === m.id ? 'bg-purple-50 dark:bg-purple-900/20' : ''">
                <div>
                    <p class="font-medium text-gray-700 dark:text-gray-300" x-text="m.name"></p>
                    <p class="text-xs text-gray-500" x-text="m.contact_email"></p>
                </div>
                <span x-show="selectedMerchant?.id === m.id" x-html="$icon('check', 'w-5 h-5 text-purple-600')"></span>
            </button>
        </template>
    </div>

    <div x-show="merchantSearch && merchantResults.length === 0 && !searchingMerchants" class="mb-4 text-sm text-gray-500 text-center py-4">
        {{ _('loyalty.admin.programs.no_merchants_found') }}
    </div>

    <!-- Existing program warning -->
    <div x-show="selectedMerchant && existingProgramForMerchant(selectedMerchant.id)"
         class="mb-4 px-4 py-3 bg-yellow-50 border border-yellow-200 rounded-lg dark:bg-yellow-900/20 dark:border-yellow-800">
        <div class="flex items-start">
            <span x-html="$icon('exclamation-triangle', 'w-5 h-5 text-yellow-500 mr-3 mt-0.5 flex-shrink-0')"></span>
            <div>
                <p class="text-sm font-medium text-yellow-800 dark:text-yellow-200">{{ _('loyalty.admin.programs.existing_program_warning') }}</p>
                <a :href="'/admin/loyalty/merchants/' + selectedMerchant.id + '/program'"
                   class="inline-flex items-center mt-1 text-sm text-purple-600 hover:text-purple-700 dark:text-purple-400">
                    <span x-html="$icon('eye', 'w-4 h-4 mr-1')"></span>
                    {{ _('loyalty.admin.programs.view_edit_existing') }}
                </a>
            </div>
        </div>
    </div>

    <!-- Actions -->
    <div class="flex justify-end gap-3">
        <button @click="showCreateModal = false; merchantSearch = ''; merchantResults = []; selectedMerchant = null"
                class="px-4 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 border border-gray-300 dark:border-gray-600 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-700">
            {{ _('loyalty.common.cancel') }}
        </button>
        <button @click="goToCreateProgram()"
                :disabled="!selectedMerchant || existingProgramForMerchant(selectedMerchant?.id)"
                class="px-4 py-2 text-sm font-medium text-white bg-purple-600 rounded-lg hover:bg-purple-700 disabled:opacity-50 disabled:cursor-not-allowed">
            {{ _('loyalty.common.continue') }}
        </button>
    </div>
{% endcall %}
{% endblock %}

{% block extra_scripts %}
<script defer src="{{ url_for('loyalty_static', path='admin/js/loyalty-programs.js') }}"></script>
{% endblock %}
