<template>
    <section class="container py-4">
        <h1 class="mb-4">⚙️ App Settings</h1>
        <!-- Notifications Section -->
        <div class="card mb-4">
            <div class="card-header fw-bold d-flex justify-content-between align-items-center">
                🔔 Notifications
                <InfoTooltip text="Enable or disable app-wide push notifications for this device." />
            </div>
            <div class="card-body">
                <p class="mb-3">Notifications are enabled per device. Manage them for <strong>this device and browser</strong> specifically.</p>
                <div v-if="isSubscribed">
                    <p class="text-success">✅ You are subscribed to notifications.</p>
                    <button class="btn btn-danger me-2" @click="unsubscribeFromPush">Unsubscribe</button>
                    <button class="btn btn-secondary" @click="sendTestNotification">Send Test Notification</button>
                </div>
                <div v-else>
                    <p class="text-muted">🔕 You are not subscribed to notifications yet.</p>
                    <button class="btn btn-primary me-2" @click="subscribeToPush">Enable Notifications</button>
                </div>
            </div>
        </div>
        <!-- Personalization -->
        <div class="card mb-4">
            <div class="card-header fw-bold d-flex justify-content-between align-items-center">
                🎨 Personalization
                <InfoTooltip text="Customize the app's appearance and language preferences." />
            </div>
            <div class="card-body">
                <div class="mb-3">
                    <label class="form-label">Theme</label>
                    <select class="form-select">
                        <option>Light</option>
                        <option>Dark</option>
                        <option>System Default</option>
                    </select>
                </div>
                <div>
                    <label class="form-label">App Language</label>
                    <select class="form-select">
                        <option>English</option>
                        <option>Spanish</option>
                        <option>French</option>
                        <option>German</option>
                    </select>
                </div>
            </div>
        </div>
        <!-- Privacy -->
        <div class="card mb-4">
            <div class="card-header fw-bold d-flex justify-content-between align-items-center">
                🔐 Privacy & Security
                <InfoTooltip text="Control how your data is handled and secure your sessions." />
            </div>
            <div class="card-body">
                <div class="form-check mb-2">
                    <input class="form-check-input" type="checkbox" id="dataTracking" />
                    <label class="form-check-label" for="dataTracking">
                        Allow anonymous usage data collection
                    </label>
                </div>
                <div class="form-check">
                    <input class="form-check-input" type="checkbox" id="autoLogout" />
                    <label class="form-check-label" for="autoLogout">
                        Auto-logout after 15 minutes of inactivity
                    </label>
                </div>
            </div>
        </div>
        <!-- Integrations -->
        <div class="card mb-4">
            <div class="card-header fw-bold d-flex justify-content-between align-items-center">
                🔌 Integrations
                <InfoTooltip text="Connect third-party services to expand app capabilities." />
            </div>
            <div class="card-body">
                <p>Manage connected services and API keys.</p>
                <button class="btn btn-outline-secondary">Connect Google Calendar</button>
            </div>
        </div>
        <!-- Experimental Features -->
        <div class="card mb-4">
            <div class="card-header fw-bold d-flex justify-content-between align-items-center">
                🧪 Experimental Features
                <InfoTooltip text="Try out beta or in-development features before official release." />
            </div>
            <div class="card-body">
                <div class="form-check mb-2">
                    <input class="form-check-input" type="checkbox" id="betaFeatures" />
                    <label class="form-check-label" for="betaFeatures">
                        Enable beta features
                    </label>
                </div>
            </div>
        </div>
    </section>
</template>
<script>
import InfoTooltip from "@/components/InfoTooltip.vue"
import { popupStore } from '@/stores/popupStore.js';

export default {
    name: "SettingsView",
    components: {
        InfoTooltip
    },
    data() {
        return {
            isSubscribed: false
        };
    },
    methods: {
        async checkSubscription() {
            try {
                const registration = await navigator.serviceWorker.ready;
                const subscription = await registration.pushManager.getSubscription();

                if (subscription) {
                    const res = await fetch("https://192.168.70.11:8000/api/check-subscription", {
                        method: "POST",
                        headers: { "Content-Type": "application/json" },
                        body: JSON.stringify(subscription)
                    });

                    const data = await res.json();
                    this.isSubscribed = data.exists;
                } else {
                    this.isSubscribed = false;
                }
            } catch (error) {
                popupStore.addPopupMessage(`❌ Subscription check failed: ${error.message}`);
                this.isSubscribed = false;
            }
        },
        async subscribeToPush() {
            try {
                const registration = await navigator.serviceWorker.ready;
                const permission = await Notification.requestPermission();

                if (permission !== "granted") {
                    popupStore.addPopupMessage(`❌ Permission denied for notifications.`);
                    return;
                }

                const vapidKey = "BNf7z00erjRX3kUBfGZK-TE1Tz6Zypb1I4aDVZkaWO1113xV_L6hDMbe_Evv8ruUiu-E88xPhRNIEL4ayjqcL5o";
                const convertedKey = this.urlBase64ToUint8Array(vapidKey);

                const subscription = await registration.pushManager.subscribe({
                    userVisibleOnly: true,
                    applicationServerKey: convertedKey,
                });

                await fetch("https://192.168.70.11:8000/api/subscribe", {
                    method: "POST",
                    headers: { "Content-Type": "application/json" },
                    body: JSON.stringify(subscription),
                });

                popupStore.addPopupMessage(`✅ Subscribed successfully.`);
            } catch (error) {
                popupStore.addPopupMessage(`❌ Subscription failed: ${error.message}`);
            }
            setTimeout(() => this.checkSubscription(), 1000);
        },
        async unsubscribeFromPush() {
            try {
                const registration = await navigator.serviceWorker.ready;
                const subscription = await registration.pushManager.getSubscription();

                if (subscription) {
                    // Send full subscription to backend
                    await fetch("https://192.168.70.11:8000/api/unsubscribe", {
                        method: "POST",
                        headers: { "Content-Type": "application/json" },
                        body: JSON.stringify(subscription),
                    });

                    // Unsubscribe on client too
                    await subscription.unsubscribe();

                    popupStore.addPopupMessage(`✅ Unsubscribed successfully.`);
                }
            } catch (error) {
                popupStore.addPopupMessage(`❌ Unsubscribe failed: ${error.message}`);
            }
            setTimeout(() => this.checkSubscription(), 1000);
        },
        async sendTestNotification() {
            try {
                const registration = await navigator.serviceWorker.ready;
                const subscription = await registration.pushManager.getSubscription();

                if (!subscription) {
                    popupStore.addPopupMessage(`❌ No push subscription found.`);
                    return;
                }

                const response = await fetch("https://192.168.70.11:8000/api/send-test", {
                    method: "POST",
                    headers: { "Content-Type": "application/json" },
                    body: JSON.stringify(subscription),
                });

                if (!response.ok) {
                    popupStore.addPopupMessage(`❌ Failed to send test notification.`);
                } else {
                    popupStore.addPopupMessage(`✅ Test notification send successfully.`);
                }
            } catch (error) {
                popupStore.addPopupMessage(`❌ Error sending test notification: ${error.message}`);
            }
        },
        urlBase64ToUint8Array(base64String) {
            const padding = '='.repeat((4 - base64String.length % 4) % 4);
            const base64 = (base64String + padding).replace(/-/g, '+').replace(/_/g, '/');
            const rawData = window.atob(base64);
            return Uint8Array.from([...rawData].map(char => char.charCodeAt(0)));
        }
    },
    mounted() {
        this.checkSubscription();
    }
};
</script>
<style scoped>
.help-icon {
    width: 1rem;
    height: 1rem;
    cursor: pointer;
    color: #6c757d;
    /* Bootstrap muted color */
}

.help-icon:hover {
    color: #000;
}

.card {
    border-radius: 0.75rem;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.card-header {
    background-color: #f8f9fa;
}
</style>