<template>
    <header id="page-topbar" class="gw-topbar-header">
        <div class="layout-width">
            <div class="navbar-header d-flex justify-content-between align-items-center py-2 px-3">
                
                <!-- Left: Hamburger & Account Title -->
                <div class="d-flex align-items-center gap-3">
                    <button type="button" class="btn gw-hamburger-btn" id="topnav-hamburger-icon" @click="toggleAppMenu()" title="Toggle Navigation">
                        <i v-if="httpRequest" class="fa fa-spin fa-spinner text-info"></i>
                        <i v-else class="fa fa-bars"></i>
                    </button>

                    <!-- Account / App Name Pill -->
                    <div class="d-none d-md-flex align-items-center gap-2 gw-header-badge">
                        <span class="gw-app-pill">
                            <i class="fa-solid fa-tower-broadcast text-primary me-1"></i>
                            <strong>{{ showData(Config.config, 'name') || 'SMS Gateway' }}</strong>
                        </span>
                        <span class="gw-divider-slash">/</span>
                        <span class="gw-company-pill">
                            <i class="fa-regular fa-building text-info me-1"></i>
                            {{ showData(Config.user, 'company_name') || showData(Config.user, 'name') || 'Administrator' }}
                        </span>
                    </div>
                </div>

                <!-- Right: Status, Theme Toggle, Website, Tickets, Notifications, User Profile -->
                <div class="d-flex align-items-center gap-2">

                    <!-- Live Real-Time Gateway Node Pulse Badge -->
                    <div class="d-none d-lg-flex align-items-center gw-node-status me-2">
                        <span class="gw-node-dot"></span>
                        <span>Gateway: <strong>Active</strong></span>
                    </div>

                    <!-- Dark / Light Theme Mode Switcher -->
                    <div class="header-item">
                        <button 
                            type="button" 
                            class="btn gw-icon-btn rounded-circle" 
                            id="header-theme-toggle"
                            :title="currentThemeMode === 'dark' ? 'Switch to White / Light Mode' : 'Switch to Dark Mode'"
                            @click="toggleThemeMode()"
                        >
                            <i v-if="currentThemeMode === 'dark'" class="fa-regular fa-sun fs-16 text-warning"></i>
                            <i v-else class="fa-regular fa-moon fs-16"></i>
                        </button>
                    </div>

                    <!-- Visit Website Link -->
                    <a target="_blank" :href="baseUrl" class="btn btn-sm d-none d-sm-inline-flex align-items-center gap-1 gw-topbar-btn gw-btn-outline-dark">
                        <i class="fa fa-arrow-up-right-from-square"></i>
                        <span>Website</span>
                    </a>

                    <!-- Ticket Button -->
                    <router-link class="btn btn-sm d-inline-flex align-items-center gap-1 gw-topbar-btn gw-btn-ticket" to="/admin/ticket">
                        <i class="fa-solid fa-ticket"></i>
                        <span class="d-none d-md-inline">Tickets</span>
                    </router-link>

                    <!-- Notifications Dropdown -->
                    <div class="dropdown topbar-head-dropdown ms-1 header-item">
                        <button type="button" class="btn gw-icon-btn rounded-circle position-relative" id="page-header-notifications-dropdown" data-bs-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                            <i class="fa-regular fa-bell fs-16"></i>
                            <span v-if="CountNotification > 0" class="position-absolute top-0 start-100 translate-middle badge rounded-pill bg-danger gw-notif-badge-pill">
                                {{ CountNotification }}
                            </span>
                        </button>

                        <div class="dropdown-menu dropdown-menu-end shadow-lg gw-notif-dropdown p-0" aria-labelledby="page-header-notifications-dropdown">
                            <div class="gw-notif-header p-3 border-bottom d-flex align-items-center justify-content-between">
                                <h6 class="m-0 fw-bold"><i class="fa fa-bell text-primary me-2"></i> Notifications</h6>
                                <span class="badge bg-primary-subtle text-primary rounded-pill">{{ CountNotification }} New</span>
                            </div>

                            <div class="gw-notif-body">
                                <template v-if="$store.state.Notifications.length > 0">
                                    <a v-for="(notification, index) in $store.state.Notifications" :key="index" class="dropdown-item p-3 border-bottom d-flex align-items-start gap-3 gw-notif-item" @click="updateNotificationAsViewed(notification)">
                                        <div class="gw-notif-icon bg-info-subtle text-info">
                                            <i class="fa-regular fa-comment-dots"></i>
                                        </div>
                                        <div class="flex-grow-1">
                                            <div class="d-flex justify-content-between align-items-center mb-1">
                                                <strong class="gw-notif-title" :class="{ 'text-muted fw-normal': notification.is_notified == 1 }">{{ notification.title }}</strong>
                                                <small class="text-muted gw-notif-time">{{ notification.created_at }}</small>
                                            </div>
                                            <p class="text-muted mb-0 small text-truncate gw-notif-text">{{ notification.notification }}</p>
                                        </div>
                                    </a>
                                </template>
                                <template v-else>
                                    <div class="p-4 text-center text-muted">
                                        <i class="fa-regular fa-bell-slash fa-2x mb-2 text-secondary"></i>
                                        <p class="mb-0 small">No new notifications</p>
                                    </div>
                                </template>
                            </div>

                            <div class="p-2 text-center border-top">
                                <router-link class="btn btn-sm btn-link text-primary w-100 text-decoration-none fw-bold" to="/admin/notification">
                                    View All Notifications <i class="fa fa-arrow-right ms-1"></i>
                                </router-link>
                            </div>
                        </div>
                    </div>

                    <!-- User Profile Dropdown -->
                    <div class="dropdown ms-2 header-item topbar-user">
                        <button type="button" class="btn p-1 gw-user-btn" id="page-header-user-dropdown" data-bs-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                            <span class="d-flex align-items-center gap-2">
                                <img class="rounded-circle gw-avatar" :src="getImage('uploads/avater.png')" alt="User Avatar">
                                <span class="d-none d-xl-inline-block text-start">
                                    <span class="d-block fw-bold fs-13 text-white">{{ showData(Config.user, 'name') || 'User' }}</span>
                                    <small class="d-block gw-user-role-text">Administrator</small>
                                </span>
                                <i class="fa fa-chevron-down ms-1 d-none d-xl-inline-block gw-user-chevron"></i>
                            </span>
                        </button>

                        <div class="dropdown-menu dropdown-menu-end shadow-lg gw-user-dropdown p-2">
                            <div class="px-3 py-2 border-bottom mb-2">
                                <span class="d-block fw-bold text-dark">{{ showData(Config.user, 'name') }}</span>
                                <small class="text-muted">{{ showData(Config.user, 'email') }}</small>
                            </div>
                            <router-link class="dropdown-item py-2 rounded-2" to="editUser">
                                <i class="fa-regular fa-user text-primary me-2"></i> Account Profile
                            </router-link>
                            <a class="dropdown-item py-2 rounded-2 text-danger" :href="`${baseUrl}/logout`">
                                <i class="fa-solid fa-arrow-right-from-bracket me-2"></i> Sign Out
                            </a>
                        </div>
                    </div>

                </div>

            </div>
        </div>
    </header>
</template>

<script>
import axios from 'axios';
import { applyThemeMode } from '../../helpers/general';

export default {
    name: "topNavBar",
    data() {
        return {
            currentThemeMode: 'light',
            currentNotifications: [],
            updateNotification: [],
            desktop_notifyeds: [],
            notificationPage: 1,
            Notifications: [],
            NotificationIds: [],
        };
    },
    methods: {
        toggleThemeMode() {
            const nextMode = this.currentThemeMode === 'dark' ? 'light' : 'dark';
            this.currentThemeMode = nextMode;
            localStorage.setItem('theme_mode', nextMode);
            applyThemeMode(nextMode);

            axios.post('/api/user/theme_mode', { theme_mode: nextMode }).catch(() => {});
        },
        toggleAppMenu: function() {
            $('body').toggleClass('vertical-sidebar-enable');
        },
        checkNotification: function() {
            const _this = this;
            _this.axios({
                method: "post",
                url: _this.urlGenerate(`api/notification?page=${_this.notificationPage}`),
                data: {
                    tickets: _this.updateNotification,
                },
            })
            .then(function(response) {
                if (response && response.data) {
                    _this.notificationPage = _this.notificationPage + 1;
                    _this.updateNotification = [];

                    var retData = response.data;
                    if (retData && parseInt(retData.status) === 2000) {
                        const newNotifications = retData.result.notification;

                        Object.keys(newNotifications).forEach((key) => {
                            if (_this.$store.state.NotificationIds.indexOf(key) == -1) {
                                _this.currentNotifications.push(newNotifications[key]);
                                _this.$store.commit('NotificationIds', key);
                                _this.$store.commit('Notifications', newNotifications[key]);
                            }
                        });
                    }
                }
            })
            .catch(function(error) {
                console.error('Notification check error:', error);
            });
        },
        updateNotificationAsViewed(notification) {
            const _this = this;
            _this.axios.post('/api/notification/update', {
                desktop_notifyeds: [notification.id],
                type: 'update',
            })
            .then(response => {
                if (response.status === 200) {
                    notification.status = 0;
                    notification.is_notified = 1;
                    _this.desktop_notifyeds = [];
                    _this.$router.push(notification.link);
                }
            })
            .catch(error => {
                console.error('Update notification error:', error);
            });
        }
    },
    computed: {
        CountNotification() {
            let count = 0;
            this.$store.state.Notifications.forEach(element => {
                if (element.is_notified == 0) {
                    count++;
                }
            });
            return count;
        }
    },
    mounted() {
        const _this = this;
        const savedMode = localStorage.getItem('theme_mode') || 'light';
        _this.currentThemeMode = savedMode;
        applyThemeMode(savedMode);

        setInterval(function() {
            if (_this.$store.state.NotificationIds.length < 8) {
                if (_this.notificationPage > 5) {
                    _this.notificationPage = 1;
                }
                _this.checkNotification();
            }
        }, 5000);
    }
};
</script>
