{# app/modules/tenancy/templates/tenancy/merchant/store-detail.html #}
{% extends "merchant/base.html" %}

{% block title %}Store Details{% endblock %}

{% block content %}
<div x-data="merchantStoreDetail({{ store_id }})">

    <!-- Page Header -->
    <div class="mb-8">
        <a href="/merchants/account/stores" class="inline-flex items-center text-sm text-indigo-600 hover:text-indigo-800 mb-4">
            <svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7"/>
            </svg>
            Back to Stores
        </a>
        <div class="flex items-center justify-between">
            <div>
                <h2 class="text-2xl font-bold text-gray-900" x-text="store?.name || 'Store Details'"></h2>
                <p class="mt-1 text-sm text-gray-400 font-mono" x-text="store?.store_code"></p>
            </div>
            <div class="flex items-center gap-3">
                <!-- Status Badges -->
                <span class="px-2.5 py-1 text-xs font-semibold rounded-full"
                      :class="{
                          'bg-green-100 text-green-800': store?.is_active,
                          'bg-gray-100 text-gray-600': !store?.is_active
                      }"
                      x-text="store?.is_active ? 'Active' : 'Inactive'"></span>
                <template x-if="store?.is_verified">
                    <span class="px-2.5 py-1 text-xs font-semibold rounded-full bg-blue-100 text-blue-800">Verified</span>
                </template>
                <template x-if="store && !store.is_verified">
                    <span class="px-2.5 py-1 text-xs font-semibold rounded-full bg-yellow-100 text-yellow-800">Pending Verification</span>
                </template>
            </div>
        </div>
    </div>

    <!-- Error -->
    <div x-show="error" x-cloak class="mb-6 p-4 bg-red-50 border border-red-200 rounded-lg">
        <p class="text-sm text-red-800" x-text="error"></p>
    </div>

    <!-- Success -->
    <div x-show="successMessage" x-cloak class="mb-6 p-4 bg-green-50 border border-green-200 rounded-lg">
        <p class="text-sm text-green-800" x-text="successMessage"></p>
    </div>

    <!-- Loading -->
    <div x-show="loading" class="text-center py-12 text-gray-500">
        <svg class="inline w-6 h-6 animate-spin mr-2" fill="none" viewBox="0 0 24 24">
            <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
            <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"></path>
        </svg>
        Loading store details...
    </div>

    <div x-show="!loading && store" class="space-y-6">

        <!-- Store Information (read-only) -->
        <div class="bg-white rounded-lg shadow-sm border border-gray-200">
            <div class="px-6 py-4 border-b border-gray-200">
                <h3 class="text-lg font-semibold text-gray-900">Store Information</h3>
            </div>
            <div class="p-6">
                <dl class="grid grid-cols-1 gap-4 sm:grid-cols-2">
                    <div>
                        <dt class="text-sm font-medium text-gray-500">Store Code</dt>
                        <dd class="mt-1 text-sm text-gray-900 font-mono" x-text="store.store_code"></dd>
                    </div>
                    <div>
                        <dt class="text-sm font-medium text-gray-500">Subdomain</dt>
                        <dd class="mt-1 text-sm text-gray-900" x-text="store.subdomain"></dd>
                    </div>
                    <div>
                        <dt class="text-sm font-medium text-gray-500">Default Language</dt>
                        <dd class="mt-1 text-sm text-gray-900" x-text="store.default_language || 'Not set'"></dd>
                    </div>
                    <div>
                        <dt class="text-sm font-medium text-gray-500">Created</dt>
                        <dd class="mt-1 text-sm text-gray-900" x-text="formatDate(store.created_at)"></dd>
                    </div>
                </dl>
            </div>
        </div>

        <!-- Platform Assignments -->
        <div x-show="store.platforms && store.platforms.length > 0" class="bg-white rounded-lg shadow-sm border border-gray-200">
            <div class="px-6 py-4 border-b border-gray-200">
                <h3 class="text-lg font-semibold text-gray-900">Platforms</h3>
            </div>
            <div class="p-6">
                <div class="flex flex-wrap gap-2">
                    <template x-for="platform in store.platforms" :key="platform.id">
                        <span class="inline-flex items-center px-3 py-1.5 text-sm rounded-lg border"
                              :class="{
                                  'bg-green-50 border-green-200 text-green-800': platform.is_active,
                                  'bg-gray-50 border-gray-200 text-gray-600': !platform.is_active
                              }">
                            <span x-text="platform.name"></span>
                            <span class="ml-1.5 text-xs font-mono opacity-60" x-text="platform.code"></span>
                        </span>
                    </template>
                </div>
            </div>
        </div>

        <!-- Editable Fields -->
        <div class="bg-white rounded-lg shadow-sm border border-gray-200">
            <div class="px-6 py-4 border-b border-gray-200 flex items-center justify-between">
                <h3 class="text-lg font-semibold text-gray-900">Store Details</h3>
                <template x-if="!editing">
                    <button @click="startEditing()" class="text-sm text-indigo-600 hover:text-indigo-800 font-medium">Edit</button>
                </template>
            </div>

            <!-- View Mode -->
            <div x-show="!editing" class="p-6">
                <dl class="grid grid-cols-1 gap-4 sm:grid-cols-2">
                    <div class="sm:col-span-2">
                        <dt class="text-sm font-medium text-gray-500">Name</dt>
                        <dd class="mt-1 text-sm text-gray-900" x-text="store.name"></dd>
                    </div>
                    <div class="sm:col-span-2">
                        <dt class="text-sm font-medium text-gray-500">Description</dt>
                        <dd class="mt-1 text-sm text-gray-900" x-text="store.description || 'No description'"></dd>
                    </div>
                    <div>
                        <dt class="text-sm font-medium text-gray-500">Contact Email</dt>
                        <dd class="mt-1 text-sm text-gray-900" x-text="store.contact_email || '-'"></dd>
                    </div>
                    <div>
                        <dt class="text-sm font-medium text-gray-500">Contact Phone</dt>
                        <dd class="mt-1 text-sm text-gray-900" x-text="store.contact_phone || '-'"></dd>
                    </div>
                    <div>
                        <dt class="text-sm font-medium text-gray-500">Website</dt>
                        <dd class="mt-1 text-sm text-gray-900" x-text="store.website || '-'"></dd>
                    </div>
                    <div>
                        <dt class="text-sm font-medium text-gray-500">Tax Number</dt>
                        <dd class="mt-1 text-sm text-gray-900" x-text="store.tax_number || '-'"></dd>
                    </div>
                    <div class="sm:col-span-2">
                        <dt class="text-sm font-medium text-gray-500">Business Address</dt>
                        <dd class="mt-1 text-sm text-gray-900" x-text="store.business_address || '-'"></dd>
                    </div>
                </dl>
            </div>

            <!-- Edit Mode -->
            <form x-show="editing" @submit.prevent="saveStore()" class="p-6 space-y-4">
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">Name</label>
                    <input type="text" x-model="editForm.name" required minlength="2" maxlength="255"
                           class="w-full px-4 py-2.5 border border-gray-300 rounded-lg text-gray-900 focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 transition-colors" />
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">Description</label>
                    <textarea x-model="editForm.description" rows="2"
                              class="w-full px-4 py-2.5 border border-gray-300 rounded-lg text-gray-900 focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 transition-colors"></textarea>
                </div>
                <div class="grid grid-cols-1 gap-4 sm:grid-cols-2">
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">Contact Email</label>
                        <input type="email" x-model="editForm.contact_email"
                               class="w-full px-4 py-2.5 border border-gray-300 rounded-lg text-gray-900 focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 transition-colors" />
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">Contact Phone</label>
                        <input type="tel" x-model="editForm.contact_phone"
                               class="w-full px-4 py-2.5 border border-gray-300 rounded-lg text-gray-900 focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 transition-colors" />
                    </div>
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">Website</label>
                    <input type="url" x-model="editForm.website" placeholder="https://example.com"
                           class="w-full px-4 py-2.5 border border-gray-300 rounded-lg text-gray-900 placeholder-gray-400 focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 transition-colors" />
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">Business Address</label>
                    <textarea x-model="editForm.business_address" rows="2"
                              class="w-full px-4 py-2.5 border border-gray-300 rounded-lg text-gray-900 focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 transition-colors"></textarea>
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">Tax Number (VAT ID)</label>
                    <input type="text" x-model="editForm.tax_number" placeholder="LU12345678"
                           class="w-full px-4 py-2.5 border border-gray-300 rounded-lg text-gray-900 placeholder-gray-400 focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 transition-colors" />
                </div>
                <div class="flex justify-end gap-3 pt-4 border-t border-gray-200">
                    <button type="button" @click="editing = false"
                            class="px-4 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-lg hover:bg-gray-50 transition-colors">
                        Cancel
                    </button>
                    <button type="submit" :disabled="saving"
                            class="inline-flex items-center px-5 py-2.5 text-sm font-semibold text-white bg-indigo-600 rounded-lg hover:bg-indigo-700 transition-colors disabled:opacity-50">
                        <span x-show="!saving">Save Changes</span>
                        <span x-show="saving" class="inline-flex items-center">
                            <svg class="w-4 h-4 animate-spin mr-2" fill="none" viewBox="0 0 24 24">
                                <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                                <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"></path>
                            </svg>
                            Saving...
                        </span>
                    </button>
                </div>
            </form>
        </div>

    </div>

    <!-- Not Found -->
    <div x-show="!loading && !store && notFound" class="text-center py-16">
        <svg class="w-16 h-16 mx-auto mb-4 text-gray-300" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9.172 16.172a4 4 0 015.656 0M9 10h.01M15 10h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/>
        </svg>
        <h3 class="text-lg font-semibold text-gray-700">Store not found</h3>
        <p class="mt-1 text-gray-500">This store doesn't exist or you don't have access to it.</p>
        <a href="/merchants/account/stores" class="mt-4 inline-flex items-center text-sm text-indigo-600 hover:text-indigo-800">
            &larr; Back to Stores
        </a>
    </div>

</div>
{% endblock %}

{% block extra_scripts %}
<script>
function merchantStoreDetail(storeId) {
    return {
        storeId,
        loading: true,
        store: null,
        error: null,
        successMessage: null,
        notFound: false,
        editing: false,
        saving: false,
        editForm: {},

        init() {
            this.loadStore();
        },

        async loadStore() {
            try {
                this.store = await apiClient.get(`/merchants/account/stores/${this.storeId}`);
            } catch (err) {
                if (err.status === 404) {
                    this.notFound = true;
                } else {
                    this.error = 'Failed to load store details.';
                }
            } finally {
                this.loading = false;
            }
        },

        startEditing() {
            this.editForm = {
                name: this.store.name || '',
                description: this.store.description || '',
                contact_email: this.store.contact_email || '',
                contact_phone: this.store.contact_phone || '',
                website: this.store.website || '',
                business_address: this.store.business_address || '',
                tax_number: this.store.tax_number || '',
            };
            this.editing = true;
        },

        async saveStore() {
            this.saving = true;
            this.error = null;
            this.successMessage = null;

            // Only send fields that changed
            const payload = {};
            for (const [key, value] of Object.entries(this.editForm)) {
                const original = this.store[key] || '';
                if (value !== original) {
                    payload[key] = value || null;
                }
            }

            if (Object.keys(payload).length === 0) {
                this.editing = false;
                this.saving = false;
                return;
            }

            try {
                this.store = await apiClient.put(
                    `/merchants/account/stores/${this.storeId}`,
                    payload
                );
                this.editing = false;
                this.successMessage = 'Store updated successfully.';
                setTimeout(() => { this.successMessage = null; }, 3000);
            } catch (err) {
                this.error = err.message || 'Failed to update store.';
            } finally {
                this.saving = false;
            }
        },

        formatDate(dateStr) {
            if (!dateStr) return '-';
            return new Date(dateStr).toLocaleDateString('en-GB', { day: 'numeric', month: 'short', year: 'numeric' });
        }
    };
}
</script>
{% endblock %}
