{% extends "admin/base.html" %}
{% 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, table_empty_state %}
{% from 'shared/macros/pagination.html' import pagination %}

{% block title %}Hosted Sites{% endblock %}

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

{% block content %}
{{ page_header('Hosted Sites', action_label='New Site', action_url='/admin/hosting/sites/new', action_icon='plus') }}

<!-- Filters -->
<div x-show="!loading && !error" 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 -->
        <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="search" @input.debounce.300ms="pagination.page = 1; loadSites()"
                       placeholder="Business name, email, domain..."
                       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">
            <select x-model="filterStatus" @change="pagination.page = 1; loadSites()"
                    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="">All Status</option>
                <option value="draft">Draft</option>
                <option value="poc_ready">POC Ready</option>
                <option value="proposal_sent">Proposal Sent</option>
                <option value="accepted">Accepted</option>
                <option value="live">Live</option>
                <option value="suspended">Suspended</option>
                <option value="cancelled">Cancelled</option>
            </select>

        </div>
    </div>
</div>

{{ loading_state('Loading sites...') }}
{{ error_state('Error loading sites') }}

<!-- Sites Table -->
<div x-show="!loading && !error">
    {% call table_wrapper() %}
        {{ table_header(['Business', 'Status', 'Contact', 'Domain', 'Created', 'Actions']) }}
        <tbody class="bg-white divide-y dark:divide-gray-700 dark:bg-gray-800">
            {{ table_empty_state(6, title='No hosted sites found', x_message="search || filterStatus ? 'Try adjusting your search or filters' : 'Create your first hosted site to get started'", show_condition='sites.length === 0', icon='globe') }}
            <template x-for="s in sites" :key="s.id">
                <tr class="text-gray-700 dark:text-gray-400 hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors">
                    <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 bg-teal-100 dark:bg-teal-600 flex items-center justify-center">
                                    <span class="text-xs font-semibold text-teal-600 dark:text-teal-100"
                                          x-text="s.business_name?.charAt(0).toUpperCase() || '?'"></span>
                                </div>
                            </div>
                            <div>
                                <p class="font-semibold" x-text="s.business_name"></p>
                                <p class="text-xs text-gray-600 dark:text-gray-400" x-text="s.contact_name || ''"></p>
                            </div>
                        </div>
                    </td>
                    <td class="px-4 py-3 text-sm">
                        <span class="px-2.5 py-0.5 text-xs font-medium rounded-full"
                              :class="statusBadgeClass(s.status)"
                              x-text="s.status.replace('_', ' ')"></span>
                    </td>
                    <td class="px-4 py-3 text-sm">
                        <span x-text="s.contact_email || '—'" class="text-xs"></span>
                    </td>
                    <td class="px-4 py-3 text-sm">
                        <span x-text="s.live_domain || '—'" class="text-xs"></span>
                    </td>
                    <td class="px-4 py-3 text-sm">
                        <span x-text="new Date(s.created_at).toLocaleDateString()" class="text-xs"></span>
                    </td>
                    <td class="px-4 py-3">
                        <div class="flex items-center space-x-2 text-sm">
                            <a :href="'/admin/hosting/sites/' + s.id"
                               class="flex items-center justify-center p-2 text-teal-600 rounded-lg hover:bg-teal-50 dark:text-teal-400 dark:hover:bg-gray-700 focus:outline-none transition-colors"
                               title="View details">
                                <span x-html="$icon('eye', 'w-5 h-5')"></span>
                            </a>
                            <button type="button" @click="deleteSite(s)"
                                    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"
                                    title="Delete">
                                <span x-html="$icon('trash', 'w-5 h-5')"></span>
                            </button>
                        </div>
                    </td>
                </tr>
            </template>
        </tbody>
    {% endcall %}

    {{ pagination() }}
</div>
{% endblock %}

{% block extra_scripts %}
<script>
function hostingSitesList() {
    return {
        ...data(),
        currentPage: 'hosting-sites',
        loading: true,
        error: null,
        sites: [],
        search: '',
        filterStatus: '',
        pagination: { page: 1, per_page: 20, total: 0, pages: 0 },
        async init() {
            if (window.PlatformSettings) {
                this.pagination.per_page = await window.PlatformSettings.getRowsPerPage();
            }
            await this.loadSites();
        },
        async loadSites() {
            this.loading = true;
            this.error = null;
            try {
                const params = new URLSearchParams({
                    page: this.pagination.page,
                    per_page: this.pagination.per_page,
                });
                if (this.search) params.set('search', this.search);
                if (this.filterStatus) params.set('status', this.filterStatus);
                const response = await apiClient.get('/admin/hosting/sites?' + params);
                this.sites = response.items || [];
                this.pagination.total = response.total || 0;
                this.pagination.pages = response.pages || 0;
            } catch (e) {
                this.error = e.message;
            } finally {
                this.loading = false;
            }
        },
        async deleteSite(site) {
            if (!confirm('Delete "' + site.business_name + '"? This will also delete the associated store.')) return;
            try {
                await apiClient.delete('/admin/hosting/sites/' + site.id);
                Utils.showToast('Site deleted', 'success');
                await this.loadSites();
            } catch (e) {
                Utils.showToast('Failed: ' + e.message, 'error');
            }
        },
        get startIndex() {
            if (this.pagination.total === 0) return 0;
            return (this.pagination.page - 1) * this.pagination.per_page + 1;
        },
        get endIndex() {
            const end = this.pagination.page * this.pagination.per_page;
            return end > this.pagination.total ? this.pagination.total : end;
        },
        get totalPages() { return this.pagination.pages; },
        get pageNumbers() {
            const pages = [];
            const total = this.totalPages;
            const current = this.pagination.page;
            if (total <= 7) { for (let i = 1; i <= total; i++) pages.push(i); return pages; }
            pages.push(1);
            if (current > 3) pages.push('...');
            for (let i = Math.max(2, current - 1); i <= Math.min(total - 1, current + 1); i++) pages.push(i);
            if (current < total - 2) pages.push('...');
            pages.push(total);
            return pages;
        },
        goToPage(page) {
            if (page === '...' || page < 1 || page > this.totalPages) return;
            this.pagination.page = page;
            this.loadSites();
        },
        nextPage() { if (this.pagination.page < this.totalPages) { this.pagination.page++; this.loadSites(); } },
        previousPage() { if (this.pagination.page > 1) { this.pagination.page--; this.loadSites(); } },
        statusBadgeClass(status) {
            const classes = {
                draft: 'text-gray-700 bg-gray-100 dark:text-gray-300 dark:bg-gray-700',
                poc_ready: 'text-blue-700 bg-blue-100 dark:text-blue-100 dark:bg-blue-700',
                proposal_sent: 'text-yellow-700 bg-yellow-100 dark:text-yellow-100 dark:bg-yellow-700',
                accepted: 'text-purple-700 bg-purple-100 dark:text-purple-100 dark:bg-purple-700',
                live: 'text-green-700 bg-green-100 dark:text-green-100 dark:bg-green-700',
                suspended: 'text-red-700 bg-red-100 dark:text-red-100 dark:bg-red-700',
                cancelled: 'text-gray-500 bg-gray-200 dark:text-gray-400 dark:bg-gray-600',
            };
            return classes[status] || 'text-gray-700 bg-gray-100';
        },
    };
}
</script>
{% endblock %}
