<!-- PWA Push Notification Subscription Component -->
<div x-data="pushNotification()" x-init="init()" class="inline-block">
    <!-- Notification Button -->
    <button
        x-show="!isSubscribed && canSubscribe"
        @click="subscribe()"
        :disabled="isLoading"
        class="inline-flex items-center px-4 py-2 text-sm font-medium text-white transition-colors bg-indigo-600 border border-transparent rounded-lg shadow-sm hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 disabled:opacity-50 disabled:cursor-not-allowed dark:focus:ring-offset-gray-900"
    >
        <svg x-show="!isLoading" class="w-5 h-5 mr-2 -ml-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 17h5l-1.405-1.405A2.032 2.032 0 0118 14.158V11a6.002 6.002 0 00-4-5.659V5a2 2 0 10-4 0v.341C7.67 6.165 6 8.388 6 11v3.159c0 .538-.214 1.055-.595 1.436L4 17h5m6 0v1a3 3 0 11-6 0v-1m6 0H9"/>
        </svg>
        <svg x-show="isLoading" class="w-5 h-5 mr-2 -ml-1 animate-spin" 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 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
        </svg>
        <span x-text="isLoading ? 'Enabling...' : 'Enable Notifications'"></span>
    </button>

    <!-- Already Subscribed Badge -->
    <div
        x-show="isSubscribed"
        class="inline-flex items-center px-4 py-2 text-sm font-medium text-green-800 bg-green-100 border border-green-200 rounded-lg dark:bg-green-900 dark:text-green-200 dark:border-green-800"
    >
        <svg class="w-5 h-5 mr-2 -ml-1" fill="currentColor" viewBox="0 0 20 20">
            <path d="M10 2a6 6 0 00-6 6v3.586l-.707.707A1 1 0 004 14h12a1 1 0 00.707-1.707L16 11.586V8a6 6 0 00-6-6zM10 18a3 3 0 01-3-3h6a3 3 0 01-3 3z"/>
        </svg>
        <span>Notifications Enabled</span>
    </div>

    <!-- Not Supported Message -->
    <div
        x-show="!canSubscribe && !isSubscribed"
        class="inline-flex items-center px-4 py-2 text-sm font-medium text-yellow-800 bg-yellow-100 border border-yellow-200 rounded-lg dark:bg-yellow-900 dark:text-yellow-200 dark:border-yellow-800"
        x-cloak
    >
        <svg class="w-5 h-5 mr-2 -ml-1" fill="currentColor" viewBox="0 0 20 20">
            <path fill-rule="evenodd" d="M8.257 3.099c.765-1.36 2.722-1.36 3.486 0l5.58 9.92c.75 1.334-.213 2.98-1.742 2.98H4.42c-1.53 0-2.493-1.646-1.743-2.98l5.58-9.92zM11 13a1 1 0 11-2 0 1 1 0 012 0zm-1-8a1 1 0 00-1 1v3a1 1 0 002 0V6a1 1 0 00-1-1z" clip-rule="evenodd"/>
        </svg>
        <span>Push notifications not supported</span>
    </div>
</div>

<script>
function pushNotification() {
    return {
        isSubscribed: false,
        isLoading: false,
        canSubscribe: false,

        init() {
            // Check if Push API is supported
            this.canSubscribe = ('serviceWorker' in navigator) &&
                               ('PushManager' in window) &&
                               ('Notification' in window);

            if (this.canSubscribe) {
                this.checkSubscription();
            }
        },

        async checkSubscription() {
            try {
                const registration = await navigator.serviceWorker.ready;
                const subscription = await registration.pushManager.getSubscription();
                this.isSubscribed = subscription !== null;

                console.log('[PWA] Subscription status:', this.isSubscribed);
            } catch (error) {
                console.error('[PWA] Error checking subscription:', error);
            }
        },

        async subscribe() {
            this.isLoading = true;

            try {
                // Request notification permission
                const permission = await Notification.requestPermission();

                if (permission !== 'granted') {
                    alert('Please allow notifications to receive order updates');
                    this.isLoading = false;
                    return;
                }

                // Get service worker registration
                const registration = await navigator.serviceWorker.ready;

                // Get VAPID public key
                const response = await fetch('/api/vapid-public-key');
                const data = await response.json();

                // Subscribe to push notifications
                const subscription = await registration.pushManager.subscribe({
                    userVisibleOnly: true,
                    applicationServerKey: this.urlBase64ToUint8Array(data.publicKey)
                });

                // Send subscription to server
                const saveResponse = await fetch('/push-subscription', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content
                    },
                    body: JSON.stringify(subscription)
                });

                const result = await saveResponse.json();

                if (result.success) {
                    this.isSubscribed = true;
                    console.log('[PWA] Subscription successful');

                    // Show success message
                    this.showNotification('Notifications Enabled!',
                        'You will now receive order notifications');
                } else {
                    throw new Error(result.message || 'Failed to save subscription');
                }

            } catch (error) {
                console.error('[PWA] Subscription error:', error);
                alert('Failed to enable notifications: ' + error.message);
            } finally {
                this.isLoading = false;
            }
        },

        urlBase64ToUint8Array(base64String) {
            const padding = '='.repeat((4 - base64String.length % 4) % 4);
            const base64 = (base64String + padding)
                .replace(/\-/g, '+')
                .replace(/_/g, '/');

            const rawData = window.atob(base64);
            const outputArray = new Uint8Array(rawData.length);

            for (let i = 0; i < rawData.length; ++i) {
                outputArray[i] = rawData.charCodeAt(i);
            }

            return outputArray;
        },

        showNotification(title, body) {
            if ('Notification' in window && Notification.permission === 'granted') {
                new Notification(title, {
                    body: body,
                    icon: '/icons/icon-192.png',
                    badge: '/icons/icon-72.png'
                });
            }
        }
    }
}
</script>

<style>
[x-cloak] {
    display: none !important;
}
</style>
