<x-guest-layout>
    <div class="flex items-center justify-center min-h-screen bg-gray-100 dark:bg-gray-900">
        <div class="px-8 py-6 mt-4 text-left bg-white dark:bg-gray-800 shadow-lg rounded-lg sm:w-2/3 lg:w-1/2">
            <h3 class="text-2xl font-bold text-center text-gray-800 dark:text-gray-200">Step 1: Activate License</h3>
            <p class="text-sm text-center text-gray-600 dark:text-gray-400 mt-1 mb-6">
                Please enter your license key or purchase code to activate the application for your domain.
            </p>

            @if (session('success'))
                <div class="mt-4 p-4 mb-4 text-sm text-green-700 bg-green-100 rounded-lg dark:bg-green-200 dark:text-green-800" role="alert">
                    {{ session('success') }}
                </div>
            @endif
            @if (session('error'))
                <div class="mt-4 p-4 mb-4 text-sm text-red-700 bg-red-100 rounded-lg dark:bg-red-200 dark:text-red-800" role="alert">
                    {{ session('error') }}
                </div>
            @endif
            @if (session()->has('info'))
                <div class="mt-4 p-4 mb-4 text-sm text-blue-700 bg-blue-100 rounded-lg dark:bg-blue-200 dark:text-blue-800" role="alert">
                    {{ session('info') }}
                </div>
            @endif

            <form method="POST" action="{{ route('install.activate.process') }}" class="mt-6 space-y-6">
                @csrf

                <div>
                    <label for="domain" class="block text-sm font-medium text-gray-700 dark:text-gray-300">Domain <span class="text-red-500">*</span></label>
                    <input type="url" name="domain" id="domain" value="{{ old('domain', request()->getSchemeAndHttpHost()) }}" required class="input-field" placeholder="https://yourdomain.com">
                    <p class="mt-1 text-xs text-gray-500 dark:text-gray-400">Enter the full domain URL (including http/https) where this boilerplate will be used.</p>
                    @error('domain') <p class="error-message">{{ $message }}</p> @enderror
                </div>

                <div>
                    <label for="license_key" class="block text-sm font-medium text-gray-700 dark:text-gray-300">License Key</label>
                    <input type="text" name="license_key" id="license_key" value="{{ old('license_key') }}" class="input-field">
                    @error('license_key') <p class="error-message">{{ $message }}</p> @enderror
                </div>

                <div class="text-center my-2 text-sm text-gray-500 dark:text-gray-400">OR</div>

                <div>
                    <label for="purchase_code" class="block text-sm font-medium text-gray-700 dark:text-gray-300">Purchase Code</label>
                    <input type="text" name="purchase_code" id="purchase_code" value="{{ old('purchase_code') }}" class="input-field">
                    @error('purchase_code') <p class="error-message">{{ $message }}</p> @enderror
                </div>

                <!-- Placeholder for license status -->
                <div id="license-status-info" class="mt-4 text-sm">
                    {{-- Status will be dynamically inserted here --}}
                </div>

                <div class="mt-8">
                    <button type="submit" class="w-full flex justify-center py-3 px-4 border border-transparent rounded-md shadow-sm text-base font-medium text-white bg-purple-600 hover:bg-purple-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-purple-500">
                        Activate License
                    </button>
                </div>
            </form>
        </div>
    </div>
    <style>
        .input-field { margin-top: 0.25rem; display: block; width: 100%; box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.05); font-size: 0.875rem; line-height: 1.25rem; border-color: #D1D5DB; border-radius: 0.375rem; }
        .dark .input-field { border-color: #4B5563; background-color: #374151; color: #F3F4F6; }
        .input-field:focus { ring-color: #A78BFA; border-color: #A78BFA; }
        .error-message { margin-top: 0.25rem; font-size: 0.875rem; line-height: 1.25rem; color: #EF4444; }
    </style>

    {{-- Add JavaScript directly here if x-guest-layout doesn't have a scripts stack --}}
    <script>
        document.addEventListener('DOMContentLoaded', function () {
            const licenseKeyInput = document.getElementById('license_key');
            const purchaseCodeInput = document.getElementById('purchase_code');
            const domainInput = document.getElementById('domain');
            const statusInfoDiv = document.getElementById('license-status-info');
            const form = licenseKeyInput.closest('form');
            const csrfToken = form.querySelector('input[name="_token"]').value;

            let debounceTimer;

            function displayStatus(data) {
                let html = '';
                if (data.message) { // Always show a message if provided
                    let bgColor = 'bg-yellow-50 dark:bg-gray-700';
                    let borderColor = 'border-yellow-300 dark:border-gray-600';
                    let textColor = 'text-yellow-700 dark:text-yellow-300';

                    if (data.valid === true) {
                        bgColor = 'bg-green-50 dark:bg-green-900';
                        borderColor = 'border-green-300 dark:border-green-700';
                        textColor = 'text-green-700 dark:text-green-300';
                    } else if (data.valid === false) {
                        bgColor = 'bg-red-50 dark:bg-red-900';
                        borderColor = 'border-red-300 dark:border-red-700';
                        textColor = 'text-red-700 dark:text-red-300';
                    }

                    html = `<div class="p-3 rounded-md ${bgColor} ${borderColor} ${textColor}">`;
                    if (data.status) {
                        html += `<p><strong>Status:</strong> <span class="capitalize">${data.status}</span></p>`;
                    }
                    if (data.type) {
                        html += `<p><strong>Type:</strong> <span class="capitalize">${data.type}</span></p>`;
                    }
                    html += `<p>${data.message}</p></div>`;
                }
                statusInfoDiv.innerHTML = html;
            }

            function clearStatus() {
                statusInfoDiv.innerHTML = '<p class="text-gray-500 dark:text-gray-400">Enter a code and domain to check its status.</p>';
            }
            clearStatus(); // Initial state

            async function validateCode(codeValue, codeType) {
                const domainValue = domainInput.value;

                if (!codeValue.trim() || !domainValue.trim()) {
                    clearStatus();
                    return;
                }

                statusInfoDiv.innerHTML = '<p class="text-gray-500 dark:text-gray-400">Validating code...</p>';

                try {
                    const response = await fetch('{{ route("install.validate-code.ajax") }}', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                            'X-CSRF-TOKEN': csrfToken,
                            'Accept': 'application/json',
                        },
                        body: JSON.stringify({
                            [codeType]: codeValue,
                            domain: domainValue,
                            code_type: codeType
                        })
                    });
                    const data = await response.json();
                    displayStatus(data);
                } catch (error) {
                    console.error('Validation request failed:', error);
                    displayStatus({ valid: null, message: 'An error occurred while trying to validate. Check console.' });
                }
            }

            function handleDebouncedInput(event) {
                clearTimeout(debounceTimer);
                const inputElement = event.target;
                debounceTimer = setTimeout(() => validateCode(inputElement.value, inputElement.id), 750);
            }

            [licenseKeyInput, purchaseCodeInput, domainInput].forEach(input => {
                if (input) input.addEventListener('input', handleDebouncedInput);
            });
        });
    </script>
</x-guest-layout>