<template>
    <header class="topbar">
        <div class="topbar-left">
            <button class="topbar-toggle" @click="$emit('toggle-sidebar')" aria-label="Toggle navigation" title="Toggle sidebar">
                <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor">
                    <path stroke-linecap="round" stroke-linejoin="round" d="M3.75 6.75h16.5M3.75 12h16.5m-16.5 5.25h16.5" />
                </svg>
            </button>
        </div>

        <div class="topbar-search" @focusin="open = true" @focusout="handleFocusOut">
            <div class="topbar-search-icon">
                <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.8" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" d="M21 21l-5.197-5.197m0 0A7.5 7.5 0 105.196 5.196a7.5 7.5 0 0010.607 10.607z"/></svg>
            </div>
            <input
                type="search"
                class="topbar-search-input"
                placeholder="Search..."
                v-model="query"
                @keydown.down.prevent="moveActive(1)"
                @keydown.up.prevent="moveActive(-1)"
                @keydown.enter.prevent="goActive"
                @keydown.esc="closeSearch"
                ref="searchInput"
            >
            <span class="topbar-search-kbd" v-if="!query">Ctrl+K</span>
            <button v-else class="topbar-search-clear" @mousedown.prevent="clearSearch" aria-label="Clear search">
                <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" d="M6 18L18 6M6 6l12 12"/></svg>
            </button>

            <div v-if="open" class="topbar-search-panel">
                <div v-if="loading" class="topbar-search-status">Searching…</div>

                <template v-else-if="groups.length">
                    <div v-for="group in groups" :key="group.key" class="topbar-search-group">
                        <div class="topbar-search-group-label">{{ group.label }}</div>
                        <button
                            v-for="item in group.items"
                            :key="group.key + '-' + item.id"
                            class="topbar-search-item"
                            :class="{ 'is-active': item.flatIndex === activeIndex }"
                            @mousedown.prevent="go(item)"
                            @mouseenter="activeIndex = item.flatIndex"
                        >
                            <span class="topbar-search-item-label">{{ item.label }}</span>
                            <span v-if="item.sublabel" class="topbar-search-item-sub">{{ item.sublabel }}</span>
                        </button>
                    </div>
                </template>

                <div v-else class="topbar-search-status">No results for "{{ query }}"</div>
            </div>
        </div>

        <div class="topbar-actions">
            <a href="#" class="topbar-icon-btn topbar-help-btn" title="Help">
                <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.8" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" d="M9.879 7.519c1.171-1.025 3.071-1.025 4.242 0 1.172 1.025 1.172 2.687 0 3.712-.203.179-.43.326-.67.442-.745.361-1.45.999-1.45 1.827v.75M21 12a9 9 0 11-18 0 9 9 0 0118 0zm-9 5.25h.008v.008H12v-.008z"/></svg>
            </a>
            <button class="topbar-icon-btn" title="Toggle dark mode" @click="toggleTheme">
                <svg v-if="theme === 'dark'" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.8" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" d="M12 3v2.25m6.364.386l-1.591 1.591M21 12h-2.25m-.386 6.364l-1.591-1.591M12 18.75V21m-4.773-4.227l-1.591 1.591M5.25 12H3m4.227-4.773L5.636 5.636M15.75 12a3.75 3.75 0 11-7.5 0 3.75 3.75 0 017.5 0z"/></svg>
                <svg v-else xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.8" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" d="M21.752 15.002A9.72 9.72 0 0118 15.75c-5.385 0-9.75-4.365-9.75-9.75 0-1.33.266-2.597.748-3.752A9.753 9.753 0 003 11.25C3 16.635 7.365 21 12.75 21a9.753 9.753 0 009.002-5.998z"/></svg>
            </button>

            <div class="topbar-divider"></div>

            <!-- Notifications Wrapper -->
            <div class="topbar-notifications" ref="notificationsRef">
                <button class="topbar-icon-btn" title="Notifications" @click="toggleNotifications">
                    <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.8" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" d="M14.857 17.082a23.848 23.848 0 005.454-1.31A8.967 8.967 0 0118 9.75v-.7V9A6 6 0 006 9v.75a8.967 8.967 0 01-2.312 6.022c1.733.64 3.56 1.085 5.455 1.31m5.714 0a24.255 24.255 0 01-5.714 0m5.714 0a3 3 0 11-5.714 0"></path></svg>
                    <span class="topbar-badge" v-if="unreadCount > 0"></span>
                </button>

                <div v-if="showNotifications" class="notifications-panel">
                    <div class="notifications-header">
                        <span class="notifications-title">Notifications ({{ unreadCount }})</span>
                        <div class="notifications-actions">
                            <button class="btn-text-link" v-if="unreadCount > 0" @click="markAllRead">Mark all read</button>
                            <button class="btn-text-link text-danger" v-if="notifications.length > 0" @click="clearNotifications">Clear</button>
                        </div>
                    </div>

                    <div class="notifications-list" v-if="notifications.length > 0">
                        <div
                            v-for="notif in notifications"
                            :key="notif.id"
                            class="notification-item"
                            :class="{ 'is-unread': !notif.read_at }"
                            @click="handleNotificationClick(notif)"
                        >
                            <div class="notification-icon" :class="`is-${notif.type}`">
                                <svg v-if="notif.type === 'success'" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" width="14" height="14">
                                    <path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.857-9.809a.75.75 0 00-1.214-.882l-3.483 4.79-1.88-1.88a.75.75 0 10-1.06 1.061l2.5 2.5a.75.75 0 001.137-.089l4-5.5z" clip-rule="evenodd" />
                                </svg>
                                <svg v-else-if="notif.type === 'error'" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" width="14" height="14">
                                    <path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.28 7.22a.75.75 0 00-1.06 1.06L8.94 10l-1.72 1.72a.75.75 0 101.06 1.06L10 11.06l1.72 1.72a.75.75 0 101.06-1.06L11.06 10l1.72-1.72a.75.75 0 00-1.06-1.06L10 8.94 8.28 7.22z" clip-rule="evenodd" />
                                </svg>
                                <svg v-else-if="notif.type === 'warning'" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" width="14" height="14">
                                    <path fill-rule="evenodd" d="M8.485 2.495c.673-1.167 2.357-1.167 3.03 0l6.28 10.875c.673 1.167-.17 2.53-1.515 2.53H3.72c-1.34 0-2.2-1.363-1.515-2.53l6.28-10.875zM10 5a.75.75 0 01.75.75v3.5a.75.75 0 01-1.5 0v-3.5A.75.75 0 0110 5zm0 9a1 1 0 100-2 1 1 0 000 2z" clip-rule="evenodd" />
                                </svg>
                                <svg v-else xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" width="14" height="14">
                                    <path fill-rule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a.75.75 0 000 1.5h.253a.25.25 0 01.244.304l-.459 2.066A1.75 1.75 0 0010.747 15H11a.75.75 0 000-1.5h-.253a.25.25 0 01-.244-.304l.459-2.066A1.75 1.75 0 009.253 9H9z" clip-rule="evenodd" />
                                </svg>
                            </div>
                            <div class="notification-content">
                                <div class="notification-item-title">{{ notif.title }}</div>
                                <div class="notification-item-message">{{ notif.message }}</div>
                                <div class="notification-item-time">{{ formatTime(notif.created_at) }}</div>
                            </div>
                        </div>
                    </div>
                    <div class="notifications-empty" v-else>
                        No notifications
                    </div>
                </div>
            </div>

            <button class="topbar-lang">
                <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.8" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" d="M12 21a9.004 9.004 0 008.716-6.747M12 21a9.004 9.004 0 01-8.716-6.747M12 21c2.485 0 4.5-4.03 4.5-9S14.485 3 12 3m0 18c-2.485 0-4.5-4.03-4.5-9S9.515 3 12 3m0 0a8.997 8.997 0 017.843 4.582M12 3a8.997 8.997 0 00-7.843 4.582m15.686 0A11.953 11.953 0 0112 10.5c-2.998 0-5.74-1.1-7.843-2.918m15.686 0A8.959 8.959 0 0121 12c0 .778-.099 1.533-.284 2.253m0 0A17.919 17.919 0 0112 16.5c-3.162 0-6.133-.815-8.716-2.247m0 0A9.015 9.015 0 013 12c0-1.605.42-3.113 1.157-4.418"/></svg>
                <span class="topbar-lang-label">English</span>
                <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" d="M19.5 8.25l-7.5 7.5-7.5-7.5"/></svg>
            </button>

            <div class="topbar-divider"></div>

            <button class="topbar-icon-btn" title="Log out" @click="logout">
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-log-out-icon lucide-log-out"><path d="m16 17 5-5-5-5"/><path d="M21 12H9"/><path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"/></svg>            </button>
        </div>
    </header>
</template>

<script setup>
import { ref, computed, watch, onMounted, onUnmounted } from 'vue';
import { router } from '@inertiajs/vue3';
import axios from 'axios';
import { useTheme } from '@/Composables/useTheme';

defineEmits(['toggle-sidebar']);

const searchInput = ref(null);
const { theme, toggleTheme } = useTheme();

function logout() {
    router.post(route('logout'));
}

const focusSearch = () => {
    searchInput.value?.focus();
    open.value = true;
};

// ── Command palette ──
const PAGES = [
    { label: 'Home',              path: '/dashboard',      keywords: 'dashboard overview' },
    { label: 'Email Campaigns',   path: '/campaigns',       keywords: 'email campaign broadcast newsletter' },
    { label: 'Audience Overview', path: '/audience',        keywords: 'audience stats' },
    { label: 'Contacts',          path: '/contacts',        keywords: 'people subscribers audience' },
    { label: 'Import Contacts',   path: '/contacts/import', keywords: 'csv upload import' },
    { label: 'Lists',             path: '/lists',           keywords: 'segment group' },
    { label: 'Tags',              path: '/tags',            keywords: 'label' },
    { label: 'Webhooks',          path: '/webhooks',        keywords: 'integration api form' },
    { label: 'SMTP Config',       path: '/sending/smtp',    keywords: 'sending mail server provider' },
];

const query = ref('');
const open = ref(false);
const loading = ref(false);
const activeIndex = ref(0);
const remote = ref({ campaigns: [], contacts: [], lists: [], tags: [] });

let debounceTimer = null;

watch(query, (value) => {
    const q = value.trim();

    if (debounceTimer) clearTimeout(debounceTimer);

    if (q.length < 2) {
        remote.value = { campaigns: [], contacts: [], lists: [], tags: [] };
        loading.value = false;
        activeIndex.value = 0;
        return;
    }

    loading.value = true;
    debounceTimer = setTimeout(async () => {
        try {
            const { data } = await axios.get('/search', { params: { q } });
            remote.value = data;
        } catch {
            remote.value = { campaigns: [], contacts: [], lists: [], tags: [] };
        } finally {
            loading.value = false;
            activeIndex.value = 0;
        }
    }, 250);
});

const filteredPages = computed(() => {
    const q = query.value.trim().toLowerCase();
    if (!q) return PAGES;
    return PAGES.filter((p) => p.label.toLowerCase().includes(q) || p.keywords.includes(q));
});

// Flattens every visible section into one indexable list so arrow keys /
// Enter can move through pages, campaigns, contacts, lists and tags as if
// they were a single results list.
const groups = computed(() => {
    let flatIndex = 0;
    const sections = [];

    const pages = filteredPages.value.slice(0, 6).map((p) => ({
        id: p.path,
        label: p.label,
        sublabel: null,
        url: p.path,
        flatIndex: flatIndex++,
    }));
    if (pages.length) sections.push({ key: 'pages', label: 'Pages', items: pages });

    if (query.value.trim().length >= 2) {
        const campaigns = remote.value.campaigns.map((c) => ({
            id: c.id,
            label: c.title,
            sublabel: c.status,
            url: c.type === 'recurring' ? `/recurring-email/${c.id}/edit` : `/campaigns/${c.id}`,
            flatIndex: flatIndex++,
        }));
        if (campaigns.length) sections.push({ key: 'campaigns', label: 'Campaigns', items: campaigns });

        const contacts = remote.value.contacts.map((c) => ({
            id: c.id,
            label: c.name || c.email,
            sublabel: c.name ? c.email : null,
            url: `/contacts/${c.id}`,
            flatIndex: flatIndex++,
        }));
        if (contacts.length) sections.push({ key: 'contacts', label: 'Contacts', items: contacts });

        const lists = remote.value.lists.map((l) => ({
            id: l.id,
            label: l.title,
            sublabel: 'List',
            url: '/lists',
            flatIndex: flatIndex++,
        }));
        if (lists.length) sections.push({ key: 'lists', label: 'Lists', items: lists });

        const tags = remote.value.tags.map((t) => ({
            id: t.id,
            label: t.title,
            sublabel: 'Tag',
            url: '/tags',
            flatIndex: flatIndex++,
        }));
        if (tags.length) sections.push({ key: 'tags', label: 'Tags', items: tags });
    }

    return sections;
});

const flatCount = computed(() => groups.value.reduce((n, g) => n + g.items.length, 0));

function moveActive(delta) {
    if (!flatCount.value) return;
    activeIndex.value = (activeIndex.value + delta + flatCount.value) % flatCount.value;
}

function go(item) {
    open.value = false;
    query.value = '';
    router.visit(item.url);
}

function goActive() {
    for (const group of groups.value) {
        const item = group.items.find((i) => i.flatIndex === activeIndex.value);
        if (item) return go(item);
    }
}

function clearSearch() {
    query.value = '';
    searchInput.value?.focus();
}

function closeSearch() {
    open.value = false;
    searchInput.value?.blur();
}

function handleFocusOut(e) {
    if (!e.currentTarget.contains(e.relatedTarget)) {
        open.value = false;
    }
}

// Global Ctrl+K / Cmd+K - works from anywhere in the app, not just while
// the search input already has focus.
function handleGlobalShortcut(e) {
    if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === 'k') {
        e.preventDefault();
        focusSearch();
    }
}

// ── Notifications ──
const notifications = ref([]);
const unreadCount = ref(0);
const showNotifications = ref(false);
const notificationsRef = ref(null);

const fetchNotifications = async () => {
    try {
        const { data } = await axios.get('/notifications');
        notifications.value = data.notifications;
        unreadCount.value = data.unreadCount;
    } catch (e) {
        console.error('Failed to fetch notifications', e);
    }
};

const toggleNotifications = () => {
    showNotifications.value = !showNotifications.value;
    if (showNotifications.value) {
        fetchNotifications();
    }
};

const markAllRead = async () => {
    try {
        await axios.post('/notifications/read-all');
        notifications.value.forEach(n => {
            n.read_at = new Date().toISOString();
        });
        unreadCount.value = 0;
    } catch (e) {
        console.error(e);
    }
};

const clearNotifications = async () => {
    try {
        await axios.delete('/notifications/clear');
        notifications.value = [];
        unreadCount.value = 0;
    } catch (e) {
        console.error(e);
    }
};

const handleNotificationClick = async (notif) => {
    if (!notif.read_at) {
        try {
            await axios.post(`/notifications/${notif.id}/read`);
            notif.read_at = new Date().toISOString();
            if (unreadCount.value > 0) unreadCount.value--;
        } catch (e) {
            console.error(e);
        }
    }
    showNotifications.value = false;
    if (notif.link) {
        router.visit(notif.link);
    }
};

const formatTime = (timeStr) => {
    if (!timeStr) return '';
    const date = new Date(timeStr);
    const now = new Date();
    const diffMs = now - date;
    const diffMins = Math.floor(diffMs / 60000);
    const diffHrs = Math.floor(diffMins / 60);

    if (diffMins < 1) return 'Just now';
    if (diffMins < 60) return `${diffMins}m ago`;
    if (diffHrs < 24) return `${diffHrs}h ago`;
    return date.toLocaleDateString(undefined, { month: 'short', day: 'numeric' });
};

// Click outside handler for notifications
const handleClickOutsideNotifications = (e) => {
    if (notificationsRef.value && !notificationsRef.value.contains(e.target)) {
        showNotifications.value = false;
    }
};

let pollInterval = null;

onMounted(() => {
    window.addEventListener('keydown', handleGlobalShortcut);
    document.addEventListener('click', handleClickOutsideNotifications);
    fetchNotifications();
    // Poll every 15s
    pollInterval = setInterval(fetchNotifications, 15000);
});

onUnmounted(() => {
    window.removeEventListener('keydown', handleGlobalShortcut);
    document.removeEventListener('click', handleClickOutsideNotifications);
    if (pollInterval) clearInterval(pollInterval);
});
</script>

<style scoped>
.topbar-notifications {
  position: relative;
  display: inline-block;
}

/* Logout icon hover animation */
.topbar-icon-btn .lucide-log-out {
  overflow: visible;
  transition: color 0.2s ease;
}

.topbar-icon-btn .lucide-log-out path {
  transition: transform 0.25s cubic-bezier(0.34, 1.4, 0.64, 1);
}

.topbar-icon-btn:hover .lucide-log-out {
  color: #ef4444;
}

.topbar-icon-btn:hover .lucide-log-out path:nth-child(1),
.topbar-icon-btn:hover .lucide-log-out path:nth-child(2) {
  transform: translateX(2px);
}

.notifications-panel {
  position: absolute;
  top: calc(100% + 8px);
  right: 0;
  width: 320px;
  background: var(--bg-surface);
  border: 1px solid var(--border-color);
  border-radius: 8px;
  box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.1), 0 8px 10px -6px rgba(0, 0, 0, 0.05);
  z-index: 1000;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  animation: slideDown 0.15s ease-out;

  @media (max-width: 640px) {
    position: fixed;
    top: 58px;
    left: 12px;
    right: 12px;
    width: auto;
    max-width: calc(100vw - 24px);
    z-index: 20000;
  }
}

@keyframes slideDown {
  from {
    opacity: 0;
    transform: translateY(-8px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.notifications-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px 12px;
  border-bottom: 1px solid var(--border-color);
  background: var(--bg-page);
}

.notifications-title {
  font-size: 13px;
  font-weight: 600;
  color: var(--text-primary);
}

.notifications-actions {
  display: flex;
  gap: 8px;
}

.btn-text-link {
  background: none;
  border: none;
  font-size: 11px;
  color: #2563eb;
  cursor: pointer;
  padding: 0;
  font-weight: 500;
  transition: opacity 0.15s;
}

.btn-text-link:hover {
  text-decoration: underline;
  opacity: 0.8;
}

.btn-text-link.text-danger {
  color: #ef4444;
}

.notifications-list {
  max-height: 280px;
  overflow-y: auto;
}

.notification-item {
  display: flex;
  gap: 10px;
  padding: 10px 12px;
  border-bottom: 1px solid var(--border-color);
  cursor: pointer;
  transition: background 0.15s;
}

.notification-item:last-child {
  border-bottom: none;
}

.notification-item:hover {
  background: var(--bg-hover);
}

.notification-item.is-unread {
  background: var(--active-bg, rgba(37, 99, 235, 0.04));
}

.notification-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 28px;
  height: 28px;
  border-radius: 50%;
  flex-shrink: 0;
}

.notification-icon.is-success {
  background: #def7ec;
  color: #03543f;
}

.notification-icon.is-error {
  background: #fde8e8;
  color: #9b1c1c;
}

.notification-icon.is-warning {
  background: #fef3c7;
  color: #92400e;
}

.notification-icon.is-info {
  background: #e1effe;
  color: #1e429f;
}

.notification-content {
  display: flex;
  flex-direction: column;
  gap: 2px;
  min-width: 0;
}

.notification-item-title {
  font-size: 12px;
  font-weight: 600;
  color: var(--text-primary);
}

.notification-item-message {
  font-size: 11px;
  color: var(--text-secondary);
  line-height: 1.3;
  word-break: break-word;
}

.notification-item-time {
  font-size: 10px;
  color: var(--text-muted);
  margin-top: 2px;
}

.notifications-empty {
  padding: 20px;
  text-align: center;
  font-size: 12px;
  color: var(--text-muted);
}
</style>
