{% extends "admin/base.html" %}
{% from 'shared/macros/headers.html' import section_header, tab_header %}
{% from 'shared/macros/alerts.html' import loading_state, error_state %}
{% from 'shared/macros/modals.html' import modal %}
{% from 'shared/macros/inputs.html' import number_stepper %}

{% block title %}Site Detail{% endblock %}

{% block alpine_data %}hostingSiteDetail({{ site_id }}){% endblock %}

{% block content %}
{{ loading_state('Loading site...') }}
{{ error_state('Error loading site') }}

<template x-if="!loading && !error && site">
<div class="space-y-6">
    <!-- Header -->
    <div class="flex flex-col sm:flex-row sm:items-center justify-between my-6 gap-4">
        <div class="flex items-center space-x-4">
            <a href="/admin/hosting/sites"
               class="flex items-center justify-center p-2 text-gray-500 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors"
               title="Back to sites">
                <span x-html="$icon('arrow-left', 'w-5 h-5')"></span>
            </a>
            <div class="relative hidden w-10 h-10 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-sm font-semibold text-teal-600 dark:text-teal-100"
                          x-text="site.business_name?.charAt(0).toUpperCase() || '?'"></span>
                </div>
            </div>
            <div>
                <h2 class="text-2xl font-semibold text-gray-700 dark:text-gray-200"
                    x-text="site.business_name"></h2>
                <p class="text-sm text-gray-500 dark:text-gray-400" x-show="site.live_domain" x-text="site.live_domain"></p>
            </div>
            <span class="px-2.5 py-0.5 text-xs font-medium rounded-full"
                  :class="statusBadgeClass(site.status)"
                  x-text="site.status.replace('_', ' ')"></span>
        </div>
    </div>

    <!-- Build POC (draft sites only) -->
    <div x-show="site.status === 'draft' && site.prospect_id" class="p-4 bg-white rounded-lg shadow-xs dark:bg-gray-800">
        <h3 class="text-sm font-semibold text-gray-700 dark:text-gray-300 mb-3">Build POC from Template</h3>
        <div class="flex flex-wrap items-end gap-3">
            <div class="flex-1 min-w-[200px]">
                <select x-model="selectedTemplate"
                        class="w-full px-3 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">
                    <option value="">Select a template...</option>
                    <template x-for="t in templates" :key="t.id">
                        <option :value="t.id" x-text="t.name + ' — ' + t.description"></option>
                    </template>
                </select>
            </div>
            <button type="button" @click="buildPoc()" :disabled="!selectedTemplate || buildingPoc"
                    class="inline-flex items-center px-4 py-2 text-sm font-medium leading-5 text-white transition-colors duration-150 bg-purple-600 border border-transparent rounded-lg hover:bg-purple-700 focus:outline-none disabled:opacity-50">
                <span x-text="buildingPoc ? 'Building...' : 'Build POC'"></span>
            </button>
        </div>
        <p x-show="pocResult" class="mt-2 text-sm text-green-600" x-text="pocResult"></p>
    </div>

    <!-- Lifecycle Actions -->
    <div class="flex flex-wrap gap-3 p-4 bg-white rounded-lg shadow-xs dark:bg-gray-800">
        <button type="button" x-show="site.status === 'draft'" @click="doAction('mark-poc-ready')"
                class="inline-flex items-center px-3 py-2 text-sm font-medium leading-5 text-white transition-colors duration-150 bg-blue-600 border border-transparent rounded-lg hover:bg-blue-700 focus:outline-none">
            Mark POC Ready
        </button>
        <button type="button" x-show="site.status === 'poc_ready'" @click="showProposalModal = true"
                class="inline-flex items-center px-3 py-2 text-sm font-medium leading-5 text-white transition-colors duration-150 bg-yellow-600 border border-transparent rounded-lg hover:bg-yellow-700 focus:outline-none">
            Send Proposal
        </button>
        <button type="button" x-show="site.status === 'proposal_sent'" @click="showAcceptModal = true"
                class="inline-flex items-center px-3 py-2 text-sm font-medium leading-5 text-white transition-colors duration-150 bg-purple-600 border border-transparent rounded-lg hover:bg-purple-700 focus:outline-none">
            Accept Proposal
        </button>
        <button type="button" x-show="site.status === 'accepted'" @click="showGoLiveModal = true"
                class="inline-flex items-center px-3 py-2 text-sm font-medium leading-5 text-white transition-colors duration-150 bg-green-600 border border-transparent rounded-lg hover:bg-green-700 focus:outline-none">
            Go Live
        </button>
        <button type="button" x-show="site.status === 'live'" @click="doAction('suspend')"
                class="inline-flex items-center px-3 py-2 text-sm font-medium leading-5 text-white transition-colors duration-150 bg-red-600 border border-transparent rounded-lg hover:bg-red-700 focus:outline-none">
            Suspend
        </button>
        <button type="button" x-show="site.status === 'suspended'" @click="doAction('go-live', {domain: site.live_domain})"
                class="inline-flex items-center px-3 py-2 text-sm font-medium leading-5 text-white transition-colors duration-150 bg-green-600 border border-transparent rounded-lg hover:bg-green-700 focus:outline-none">
            Reactivate
        </button>
        <button type="button" x-show="site.status !== 'cancelled' && site.status !== 'live'"
                @click="doAction('cancel')"
                class="inline-flex items-center px-3 py-2 text-sm font-medium leading-5 text-gray-700 dark:text-gray-300 transition-colors duration-150 bg-white dark:bg-gray-800 border border-gray-300 dark:border-gray-600 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-700 focus:outline-none">
            Cancel
        </button>
        <a x-show="['poc_ready', 'proposal_sent'].includes(site.status)"
           :href="'/hosting/sites/' + site.id + '/preview'" target="_blank"
           class="sm:ml-auto inline-flex items-center px-3 py-2 text-sm font-medium leading-5 text-teal-700 dark:text-teal-300 transition-colors duration-150 bg-teal-100 dark:bg-teal-900 border border-transparent rounded-lg hover:bg-teal-200 dark:hover:bg-teal-800 focus:outline-none">
            <span x-html="$icon('eye', 'w-4 h-4 mr-1')"></span>
            Preview POC
        </a>
    </div>

    <!-- Tabs -->
    {{ tab_header([
        {'id': 'overview', 'label': 'Overview', 'icon': 'eye'},
        {'id': 'services', 'label': 'Services', 'icon': 'cube'},
        {'id': 'store', 'label': 'Store', 'icon': 'shopping-bag'},
    ], active_var='activeTab') }}

    <!-- Tab: Overview -->
    <div x-show="activeTab === 'overview'" class="grid gap-6 md:grid-cols-2">
        <div class="p-4 bg-white rounded-lg shadow-xs dark:bg-gray-800">
            {{ section_header('Contact Info', icon='phone') }}
            <div class="space-y-2 text-sm">
                <div class="flex justify-between">
                    <span class="text-gray-600 dark:text-gray-400">Name</span>
                    <span class="font-medium text-gray-700 dark:text-gray-300" x-text="site.contact_name || '—'"></span>
                </div>
                <div class="flex justify-between">
                    <span class="text-gray-600 dark:text-gray-400">Email</span>
                    <span class="font-medium text-gray-700 dark:text-gray-300" x-text="site.contact_email || '—'"></span>
                </div>
                <div class="flex justify-between">
                    <span class="text-gray-600 dark:text-gray-400">Phone</span>
                    <span class="font-medium text-gray-700 dark:text-gray-300" x-text="site.contact_phone || '—'"></span>
                </div>
            </div>
        </div>
        <div class="p-4 bg-white rounded-lg shadow-xs dark:bg-gray-800">
            {{ section_header('Timeline', icon='clock') }}
            <div class="space-y-2 text-sm">
                <div class="flex justify-between">
                    <span class="text-gray-600 dark:text-gray-400">Created</span>
                    <span class="font-medium text-gray-700 dark:text-gray-300" x-text="site.created_at ? new Date(site.created_at).toLocaleDateString() : '—'"></span>
                </div>
                <div class="flex justify-between">
                    <span class="text-gray-600 dark:text-gray-400">Proposal Sent</span>
                    <span class="font-medium text-gray-700 dark:text-gray-300" x-text="site.proposal_sent_at ? new Date(site.proposal_sent_at).toLocaleDateString() : '—'"></span>
                </div>
                <div class="flex justify-between">
                    <span class="text-gray-600 dark:text-gray-400">Accepted</span>
                    <span class="font-medium text-gray-700 dark:text-gray-300" x-text="site.proposal_accepted_at ? new Date(site.proposal_accepted_at).toLocaleDateString() : '—'"></span>
                </div>
                <div class="flex justify-between">
                    <span class="text-gray-600 dark:text-gray-400">Went Live</span>
                    <span class="font-medium text-gray-700 dark:text-gray-300" x-text="site.went_live_at ? new Date(site.went_live_at).toLocaleDateString() : '—'"></span>
                </div>
            </div>
        </div>
        <div class="p-4 bg-white rounded-lg shadow-xs dark:bg-gray-800 md:col-span-2" x-show="site.proposal_notes || site.internal_notes">
            {{ section_header('Notes', icon='document-text') }}
            <div x-show="site.proposal_notes" class="mb-3">
                <p class="text-xs font-medium text-gray-500 dark:text-gray-400 uppercase mb-1">Proposal Notes</p>
                <p class="text-sm text-gray-700 dark:text-gray-300" x-text="site.proposal_notes"></p>
            </div>
            <div x-show="site.internal_notes">
                <p class="text-xs font-medium text-gray-500 dark:text-gray-400 uppercase mb-1">Internal Notes</p>
                <p class="text-sm text-gray-700 dark:text-gray-300" x-text="site.internal_notes"></p>
            </div>
        </div>
    </div>

    <!-- Tab: Services -->
    <div x-show="activeTab === 'services'" class="space-y-4">
        <div class="flex justify-end">
            <button type="button" @click="showServiceModal = true"
                    class="inline-flex items-center px-4 py-2 text-sm font-medium leading-5 text-white transition-colors duration-150 bg-teal-600 border border-transparent rounded-lg hover:bg-teal-700 focus:outline-none">
                <span x-html="$icon('plus', 'w-4 h-4 mr-2')"></span>
                Add Service
            </button>
        </div>
        <template x-for="svc in site.client_services || []" :key="svc.id">
            <div class="p-4 bg-white rounded-lg shadow-xs dark:bg-gray-800 border border-gray-200 dark:border-gray-700 hover:shadow-md transition-shadow">
                <div class="flex items-center justify-between">
                    <div>
                        <span class="text-sm font-semibold text-gray-700 dark:text-gray-200" x-text="svc.name"></span>
                        <span class="ml-2 px-2 py-0.5 text-xs font-medium rounded-full bg-gray-100 text-gray-600 dark:bg-gray-700 dark:text-gray-400"
                              x-text="svc.service_type.replace('_', ' ')"></span>
                    </div>
                    <span class="px-2.5 py-0.5 text-xs font-medium rounded-full"
                          :class="svc.status === 'active' ? 'bg-green-100 text-green-700 dark:bg-green-700 dark:text-green-100' : svc.status === 'expired' ? 'bg-red-100 text-red-700 dark:bg-red-700 dark:text-red-100' : 'bg-gray-100 text-gray-600 dark:bg-gray-700 dark:text-gray-400'"
                          x-text="svc.status"></span>
                </div>
                <div class="mt-2 flex flex-wrap gap-4 text-xs text-gray-500 dark:text-gray-400">
                    <span x-show="svc.price_cents" x-text="'€' + (svc.price_cents / 100).toFixed(2) + '/' + (svc.billing_period || 'month')"></span>
                    <span x-show="svc.domain_name" x-text="svc.domain_name"></span>
                    <span x-show="svc.expires_at" x-text="'Expires: ' + new Date(svc.expires_at).toLocaleDateString()"></span>
                    <span x-show="svc.mailbox_count" x-text="svc.mailbox_count + ' mailboxes'"></span>
                </div>
            </div>
        </template>
        <p x-show="!site.client_services?.length" class="text-sm text-gray-400 text-center py-8">No services yet</p>
    </div>

    <!-- Tab: Store -->
    <div x-show="activeTab === 'store'" class="p-4 bg-white rounded-lg shadow-xs dark:bg-gray-800">
        {{ section_header('Store Info', icon='shopping-bag') }}
        <div class="space-y-2 text-sm">
            <div class="flex justify-between">
                <span class="text-gray-600 dark:text-gray-400">Store ID</span>
                <span class="font-medium text-gray-700 dark:text-gray-300" x-text="site.store_id"></span>
            </div>
        </div>
        <div class="mt-4">
            <a :href="'/admin/stores/' + site.store_id"
               class="inline-flex items-center px-4 py-2 text-sm font-medium leading-5 text-teal-700 dark:text-teal-300 transition-colors duration-150 bg-teal-100 dark:bg-teal-900 border border-transparent rounded-lg hover:bg-teal-200 dark:hover:bg-teal-800 focus:outline-none">
                <span x-html="$icon('external-link', 'w-4 h-4 mr-2')"></span>
                Open in Store Admin
            </a>
        </div>
    </div>
</div>
</template>

<!-- Send Proposal Modal -->
{% call modal('proposalModal', 'Send Proposal', show_var='showProposalModal', size='md', show_footer=false) %}
    <div>
        <label class="block text-sm font-medium text-gray-700 dark:text-gray-400 mb-1">Proposal Notes</label>
        <textarea x-model="proposalNotes" rows="4"
                  class="w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-lg focus:border-purple-400 focus:outline-none focus:shadow-outline-purple dark:focus:shadow-outline-gray dark:bg-gray-700 dark:text-gray-300"></textarea>
    </div>
    <div class="flex justify-end mt-6 pt-4 border-t border-gray-200 dark:border-gray-700 space-x-3">
        <button type="button" @click="showProposalModal = false"
                class="px-4 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 bg-white dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-600 transition-colors">Cancel</button>
        <button type="button" @click="sendProposal()"
                class="inline-flex items-center px-4 py-2 text-sm font-medium text-white bg-yellow-600 border border-transparent rounded-lg hover:bg-yellow-700 focus:outline-none transition-colors duration-150">
            <span x-html="$icon('mail', 'w-4 h-4 mr-2')"></span> Send
        </button>
    </div>
{% endcall %}

<!-- Accept Proposal Modal -->
{% call modal('acceptModal', 'Accept Proposal', show_var='showAcceptModal', size='md', show_footer=false) %}
    <div>
        <label class="block text-sm font-medium text-gray-700 dark:text-gray-400 mb-1">Existing Merchant ID (leave empty to create new)</label>
        <input type="number" x-model="acceptMerchantId" placeholder="Optional" {# noqa: FE008 - merchant ID input #}
               class="w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-lg focus:border-purple-400 focus:outline-none focus:shadow-outline-purple dark:focus:shadow-outline-gray dark:bg-gray-700 dark:text-gray-300">
    </div>
    <div class="flex justify-end mt-6 pt-4 border-t border-gray-200 dark:border-gray-700 space-x-3">
        <button type="button" @click="showAcceptModal = false"
                class="px-4 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 bg-white dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-600 transition-colors">Cancel</button>
        <button type="button" @click="acceptProposal()"
                class="inline-flex items-center px-4 py-2 text-sm font-medium text-white bg-purple-600 border border-transparent rounded-lg hover:bg-purple-700 focus:outline-none transition-colors duration-150">
            <span x-html="$icon('check', 'w-4 h-4 mr-2')"></span> Accept
        </button>
    </div>
{% endcall %}

<!-- Go Live Modal -->
{% call modal('goLiveModal', 'Go Live', show_var='showGoLiveModal', size='md', show_footer=false) %}
    <div>
        <label class="block text-sm font-medium text-gray-700 dark:text-gray-400 mb-1">
            Domain <span class="text-red-500">*</span>
        </label>
        <input type="text" x-model="goLiveDomain" placeholder="example.lu"
               class="w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-lg focus:border-purple-400 focus:outline-none focus:shadow-outline-purple dark:focus:shadow-outline-gray dark:bg-gray-700 dark:text-gray-300">
    </div>
    <div class="flex justify-end mt-6 pt-4 border-t border-gray-200 dark:border-gray-700 space-x-3">
        <button type="button" @click="showGoLiveModal = false"
                class="px-4 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 bg-white dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-600 transition-colors">Cancel</button>
        <button type="button" @click="goLive()"
                class="inline-flex items-center px-4 py-2 text-sm font-medium text-white bg-green-600 border border-transparent rounded-lg hover:bg-green-700 focus:outline-none transition-colors duration-150">
            <span x-html="$icon('check', 'w-4 h-4 mr-2')"></span> Go Live
        </button>
    </div>
{% endcall %}

<!-- Add Service Modal -->
{% call modal('serviceModal', 'Add Service', show_var='showServiceModal', size='md', show_footer=false) %}
    <div class="space-y-4">
        <div>
            <label class="block text-sm font-medium text-gray-700 dark:text-gray-400 mb-1">Type</label>
            <select x-model="newService.service_type"
                    class="w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-lg focus:border-purple-400 focus:outline-none focus:shadow-outline-purple dark:focus:shadow-outline-gray dark:bg-gray-700 dark:text-gray-300">
                <option value="domain">Domain</option>
                <option value="email">Email</option>
                <option value="ssl">SSL</option>
                <option value="hosting">Hosting</option>
                <option value="website_maintenance">Website Maintenance</option>
            </select>
        </div>
        <div>
            <label class="block text-sm font-medium text-gray-700 dark:text-gray-400 mb-1">Name</label>
            <input type="text" x-model="newService.name" placeholder="e.g., acme.lu domain"
                   class="w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-lg focus:border-purple-400 focus:outline-none focus:shadow-outline-purple dark:focus:shadow-outline-gray dark:bg-gray-700 dark:text-gray-300">
        </div>
        <div class="grid grid-cols-2 gap-4">
            <div>
                <label class="block text-sm font-medium text-gray-700 dark:text-gray-400 mb-1">Price (cents)</label>
                {{ number_stepper(model='newService.price_cents', min=0, step=100, size='sm', label='Price (cents)') }}
            </div>
            <div>
                <label class="block text-sm font-medium text-gray-700 dark:text-gray-400 mb-1">Billing</label>
                <select x-model="newService.billing_period"
                        class="w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-lg focus:border-purple-400 focus:outline-none focus:shadow-outline-purple dark:focus:shadow-outline-gray dark:bg-gray-700 dark:text-gray-300">
                    <option value="monthly">Monthly</option>
                    <option value="annual">Annual</option>
                    <option value="one_time">One-time</option>
                </select>
            </div>
        </div>
    </div>
    <div class="flex justify-end mt-6 pt-4 border-t border-gray-200 dark:border-gray-700 space-x-3">
        <button type="button" @click="showServiceModal = false"
                class="px-4 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 bg-white dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-600 transition-colors">Cancel</button>
        <button type="button" @click="addService()"
                class="inline-flex items-center px-4 py-2 text-sm font-medium text-white bg-teal-600 border border-transparent rounded-lg hover:bg-teal-700 focus:outline-none transition-colors duration-150">
            <span x-html="$icon('plus', 'w-4 h-4 mr-2')"></span> Add
        </button>
    </div>
{% endcall %}
{% endblock %}

{% block extra_scripts %}
<script>
function hostingSiteDetail(siteId) {
    return {
        ...data(),
        currentPage: 'hosting-sites',
        loading: true,
        error: null,
        site: null,
        activeTab: 'overview',
        showProposalModal: false,
        showAcceptModal: false,
        showGoLiveModal: false,
        showServiceModal: false,
        proposalNotes: '',
        acceptMerchantId: '',
        goLiveDomain: '',
        newService: { service_type: 'domain', name: '', price_cents: null, billing_period: 'monthly' },
        // POC builder
        templates: [],
        selectedTemplate: '',
        buildingPoc: false,
        pocResult: '',
        async init() {
            await this.loadSite();
            await this.loadTemplates();
        },
        async loadTemplates() {
            try {
                var resp = await apiClient.get('/admin/hosting/sites/templates');
                this.templates = resp.templates || [];
            } catch (e) { /* ignore */ }
        },
        async buildPoc() {
            if (!this.selectedTemplate || !this.site.prospect_id) return;
            this.buildingPoc = true;
            this.pocResult = '';
            try {
                var result = await apiClient.post('/admin/hosting/sites/poc/build', {
                    prospect_id: this.site.prospect_id,
                    template_id: this.selectedTemplate,
                    site_id: this.site.id,
                });
                this.pocResult = 'POC built! ' + result.pages_created + ' pages created.';
                Utils.showToast('POC built successfully', 'success');
                await this.loadSite();
            } catch (e) {
                Utils.showToast('Build failed: ' + e.message, 'error');
            } finally {
                this.buildingPoc = false;
            }
        },
        async loadSite() {
            this.loading = true;
            this.error = null;
            try {
                this.site = await apiClient.get('/admin/hosting/sites/' + siteId);
            } catch (e) {
                this.error = e.message;
            } finally {
                this.loading = false;
            }
        },
        async doAction(action, body = {}) {
            try {
                await apiClient.post('/admin/hosting/sites/' + siteId + '/' + action, body);
                Utils.showToast('Action completed', 'success');
                await this.loadSite();
            } catch (e) {
                Utils.showToast(e.message || 'Action failed', 'error');
            }
        },
        async sendProposal() {
            await this.doAction('send-proposal', { notes: this.proposalNotes });
            this.showProposalModal = false;
        },
        async acceptProposal() {
            const body = {};
            if (this.acceptMerchantId) body.merchant_id = parseInt(this.acceptMerchantId);
            await this.doAction('accept', body);
            this.showAcceptModal = false;
        },
        async goLive() {
            await this.doAction('go-live', { domain: this.goLiveDomain });
            this.showGoLiveModal = false;
        },
        async addService() {
            try {
                await apiClient.post('/admin/hosting/sites/' + siteId + '/services', this.newService);
                Utils.showToast('Service added', 'success');
                this.showServiceModal = false;
                this.newService = { service_type: 'domain', name: '', price_cents: null, billing_period: 'monthly' };
                await this.loadSite();
            } catch (e) {
                Utils.showToast(e.message || 'Failed to add service', 'error');
            }
        },
        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 %}
