{# app/modules/tenancy/templates/tenancy/merchant/stores.html #}
{% extends "merchant/base.html" %}

{% block title %}My Stores{% endblock %}

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

    <!-- Page Header -->
    <div class="mb-8 flex items-center justify-between">
        <div>
            <h2 class="text-2xl font-bold text-gray-900">My Stores</h2>
            <p class="mt-1 text-gray-500">View and manage your connected stores.</p>
        </div>
        <button
            x-show="canCreateStore"
            @click="showCreateModal = true"
            class="inline-flex items-center px-4 py-2.5 text-sm font-semibold text-white bg-indigo-600 rounded-lg hover:bg-indigo-700 transition-colors"
        >
            <svg class="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"/>
            </svg>
            Add Store
        </button>
    </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 stores...
    </div>

    <!-- Empty State -->
    <div x-show="!loading && stores.length === 0" 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="M19 21V5a2 2 0 00-2-2H7a2 2 0 00-2 2v16m14 0h2m-2 0h-5m-9 0H3m2 0h5M9 7h1m-1 4h1m4-4h1m-1 4h1m-5 10v-5a1 1 0 011-1h2a1 1 0 011 1v5m-4 0h4"/>
        </svg>
        <h3 class="text-lg font-semibold text-gray-700">No stores yet</h3>
        <p class="mt-1 text-gray-500">Create your first store to get started.</p>
        <button
            x-show="canCreateStore"
            @click="showCreateModal = true"
            class="mt-4 inline-flex items-center px-4 py-2 text-sm font-semibold text-indigo-600 border border-indigo-300 rounded-lg hover:bg-indigo-50 transition-colors"
        >
            <svg class="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"/>
            </svg>
            Add Store
        </button>
    </div>

    <!-- Store Cards Grid -->
    <div x-show="!loading && stores.length > 0" class="grid gap-6 md:grid-cols-2 lg:grid-cols-3">
        <template x-for="store in stores" :key="store.id">
            <a :href="'/merchants/account/stores/' + store.id"
               class="block bg-white rounded-lg shadow-sm border border-gray-200 overflow-hidden hover:shadow-md hover:border-indigo-200 transition-all cursor-pointer group">
                <div class="p-6">
                    <!-- Store Name and Status -->
                    <div class="flex items-start justify-between mb-4">
                        <div>
                            <h3 class="text-lg font-semibold text-gray-900 group-hover:text-indigo-600 transition-colors" x-text="store.name"></h3>
                            <p class="text-sm text-gray-400 font-mono" x-text="store.store_code"></p>
                        </div>
                        <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>
                    </div>

                    <!-- Details -->
                    <dl class="space-y-2 text-sm">
                        <div class="flex justify-between">
                            <dt class="text-gray-500">Subdomain</dt>
                            <dd class="font-medium text-gray-900" x-text="store.subdomain || '-'"></dd>
                        </div>
                        <div class="flex justify-between">
                            <dt class="text-gray-500">Created</dt>
                            <dd class="font-medium text-gray-900" x-text="formatDate(store.created_at)"></dd>
                        </div>
                    </dl>

                    <!-- Verification Badge -->
                    <div class="mt-4 flex items-center gap-2">
                        <template x-if="store.is_verified">
                            <span class="inline-flex items-center px-2 py-0.5 text-xs font-medium rounded bg-blue-100 text-blue-800">
                                <svg class="w-3 h-3 mr-1" fill="currentColor" viewBox="0 0 20 20">
                                    <path fill-rule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clip-rule="evenodd"/>
                                </svg>
                                Verified
                            </span>
                        </template>
                        <template x-if="!store.is_verified">
                            <span class="inline-flex items-center px-2 py-0.5 text-xs font-medium rounded bg-yellow-100 text-yellow-800">
                                Pending Verification
                            </span>
                        </template>
                    </div>
                </div>
                <!-- Card Footer -->
                <div class="px-6 py-3 bg-gray-50 border-t border-gray-100 text-right">
                    <span class="text-xs text-indigo-600 font-medium group-hover:underline">View Details &rarr;</span>
                </div>
            </a>
        </template>
    </div>

    <!-- Create Store Modal -->
    <div x-show="showCreateModal" x-cloak class="fixed inset-0 z-50 flex items-center justify-center">
        <div class="fixed inset-0 bg-black bg-opacity-50" @click="showCreateModal = false"></div>
        <div class="relative bg-white rounded-lg shadow-xl w-full max-w-lg mx-4" @click.stop>
            <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">Create New Store</h3>
                <button @click="showCreateModal = false" class="text-gray-400 hover:text-gray-600">
                    <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/>
                    </svg>
                </button>
            </div>

            <form @submit.prevent="createStore()" class="p-6 space-y-4">
                <!-- Store Name -->
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">Store Name</label>
                    <input
                        type="text"
                        x-model="createForm.name"
                        @input="autoGenerateCode()"
                        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"
                        placeholder="My Awesome Store"
                    />
                </div>

                <!-- Store Code & Subdomain -->
                <div class="grid grid-cols-2 gap-4">
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">Store Code</label>
                        <input
                            type="text"
                            x-model="createForm.store_code"
                            required
                            minlength="2"
                            maxlength="50"
                            class="w-full px-4 py-2.5 border border-gray-300 rounded-lg text-gray-900 font-mono uppercase focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 transition-colors"
                            placeholder="MYSTORE"
                        />
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">Subdomain</label>
                        <input
                            type="text"
                            x-model="createForm.subdomain"
                            required
                            minlength="2"
                            maxlength="100"
                            pattern="[a-z0-9][a-z0-9-]*[a-z0-9]"
                            class="w-full px-4 py-2.5 border border-gray-300 rounded-lg text-gray-900 lowercase focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 transition-colors"
                            placeholder="my-store"
                        />
                    </div>
                </div>

                <!-- Description -->
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">Description</label>
                    <textarea
                        x-model="createForm.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"
                        placeholder="Brief description of the store"
                    ></textarea>
                </div>

                <!-- Platform Selection -->
                <div x-show="availablePlatforms.length > 0">
                    <label class="block text-sm font-medium text-gray-700 mb-2">Platforms</label>
                    <div class="space-y-2">
                        <template x-for="platform in availablePlatforms" :key="platform.id">
                            <label class="flex items-center gap-2 cursor-pointer">
                                <input
                                    type="checkbox"
                                    :value="platform.id"
                                    x-model.number="createForm.platform_ids"
                                    class="rounded border-gray-300 text-indigo-600 focus:ring-indigo-500"
                                />
                                <span class="text-sm text-gray-700" x-text="platform.name"></span>
                                <span class="text-xs text-gray-400 font-mono" x-text="platform.code"></span>
                            </label>
                        </template>
                    </div>
                </div>

                <!-- Create Error -->
                <div x-show="createError" class="p-3 bg-red-50 border border-red-200 rounded-lg">
                    <p class="text-sm text-red-800" x-text="createError"></p>
                </div>

                <!-- Actions -->
                <div class="flex justify-end gap-3 pt-4 border-t border-gray-200">
                    <button
                        type="button"
                        @click="showCreateModal = 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="creating"
                        class="inline-flex items-center px-5 py-2 text-sm font-semibold text-white bg-indigo-600 rounded-lg hover:bg-indigo-700 transition-colors disabled:opacity-50"
                    >
                        <span x-show="!creating">Create Store</span>
                        <span x-show="creating" 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>
                            Creating...
                        </span>
                    </button>
                </div>
            </form>
        </div>
    </div>

</div>
{% endblock %}

{% block extra_scripts %}
<script>
function merchantStores() {
    return {
        loading: true,
        error: null,
        successMessage: null,
        stores: [],
        canCreateStore: false,
        showCreateModal: false,
        creating: false,
        createError: null,
        availablePlatforms: [],
        createForm: {
            name: '',
            store_code: '',
            subdomain: '',
            description: '',
            platform_ids: [],
        },

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

        async loadStores() {
            try {
                const data = await apiClient.get('/merchants/account/stores');
                this.stores = data.stores || data.items || [];
                this.canCreateStore = data.can_create_store !== false;
            } catch (err) {
                console.error('Error loading stores:', err);
                this.error = 'Failed to load stores. Please try again.';
            } finally {
                this.loading = false;
            }
        },

        autoGenerateCode() {
            const name = this.createForm.name;
            this.createForm.store_code = name
                .toUpperCase()
                .replace(/[^A-Z0-9]+/g, '-')
                .replace(/^-|-$/g, '')
                .substring(0, 20);
            this.createForm.subdomain = name
                .toLowerCase()
                .replace(/[^a-z0-9]+/g, '-')
                .replace(/^-|-$/g, '')
                .substring(0, 50);
        },

        async createStore() {
            this.creating = true;
            this.createError = null;

            // Load platforms if not yet loaded
            if (this.availablePlatforms.length === 0) {
                try {
                    this.availablePlatforms = await apiClient.get('/merchants/account/platforms');
                } catch (e) { /* ignore */ }
            }

            try {
                await apiClient.post('/merchants/account/stores', this.createForm);
                this.showCreateModal = false;
                this.createForm = { name: '', store_code: '', subdomain: '', description: '', platform_ids: [] };
                this.successMessage = 'Store created successfully! It is pending admin verification.';
                setTimeout(() => { this.successMessage = null; }, 5000);
                await this.loadStores();
            } catch (err) {
                this.createError = err.message || 'Failed to create store.';
            } finally {
                this.creating = false;
            }
        },

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