@extends('site.layout')

@section('title', 'Dewemoji - Discover')
@section('meta_description', 'Search emojis by keyword, meaning, and category. Explore Dewemoji with fast API-powered results.')

@push('head')
<style>
    #grid {
        --card-min: 104px;
        --emoji-size: 2rem;
        grid-template-columns: repeat(auto-fill, minmax(var(--card-min), 1fr));
    }
    @media (max-width: 640px) {
        #grid {
            --card-min: 0px;
            grid-template-columns: repeat(3, minmax(0, 1fr));
        }
    }
</style>
@endpush

@section('content')
<div class="flex h-screen w-full">
    <aside class="hidden lg:flex w-20 lg:w-64 h-full glass-panel flex-col justify-between p-4 z-50 shrink-0">
        <div>
            <div class="flex items-center gap-3 px-2 mb-8 mt-2">
                <div class="w-10 h-10 rounded-xl bg-gradient-to-br from-white to-gray-300 flex items-center justify-center shadow-lg shadow-white/20 shrink-0">
                    <img src="/assets/logo/logo-mark.svg" alt="Dewemoji logo" class="w-7 h-7 object-contain" />
                </div>
                <h1 class="font-display font-bold text-lg tracking-tight hidden lg:block">Dewemoji</h1>
            </div>
            <nav class="space-y-1">
                <a href="{{ route('home') }}" class="flex items-center gap-4 px-3 py-3 rounded-xl bg-white/10 text-brand-sun border border-white/5 transition-all group">
                    <i data-lucide="layout-grid" class="w-5 h-5"></i>
                    <span class="text-sm font-medium hidden lg:block">Discover</span>
                </a>
                <a href="{{ route('api-docs') }}" class="flex items-center gap-4 px-3 py-3 rounded-xl text-gray-400 hover:text-white hover:bg-white/5 transition-all group">
                    <i data-lucide="book-open" class="w-5 h-5 group-hover:scale-110 transition-transform"></i>
                    <span class="text-sm font-medium hidden lg:block">API Docs</span>
                </a>
                <a href="{{ route('pricing') }}" class="flex items-center gap-4 px-3 py-3 rounded-xl text-gray-400 hover:text-white hover:bg-white/5 transition-all group">
                    <i data-lucide="badge-dollar-sign" class="w-5 h-5 group-hover:scale-110 transition-transform"></i>
                    <span class="text-sm font-medium hidden lg:block">Pricing</span>
                </a>
                <a href="{{ route('support') }}" class="flex items-center gap-4 px-3 py-3 rounded-xl text-gray-400 hover:text-white hover:bg-white/5 transition-all group">
                    <i data-lucide="life-buoy" class="w-5 h-5 group-hover:scale-110 transition-transform"></i>
                    <span class="text-sm font-medium hidden lg:block">Support</span>
                </a>
            </nav>
        </div>
        <div class="space-y-1">
            @auth
                <a href="{{ route('dashboard.overview') }}" class="flex items-center gap-4 px-3 py-3 rounded-xl text-gray-400 hover:text-white hover:bg-white/5 transition-all">
                    <i data-lucide="layout-dashboard" class="w-5 h-5"></i>
                    <span class="text-sm font-medium hidden lg:block">Dashboard</span>
                </a>
            @endauth
            @guest
                <a href="{{ route('login') }}" class="flex items-center gap-4 px-3 py-3 rounded-xl text-gray-400 hover:text-white hover:bg-white/5 transition-all">
                    <i data-lucide="log-in" class="w-5 h-5"></i>
                    <span class="text-sm font-medium hidden lg:block">Login</span>
                </a>
            @endguest
            <a href="{{ route('privacy') }}" class="flex items-center gap-4 px-3 py-3 rounded-xl text-gray-400 hover:text-white hover:bg-white/5 transition-all">
                <i data-lucide="shield-check" class="w-5 h-5"></i>
                <span class="text-sm font-medium hidden lg:block">Privacy</span>
            </a>
            <a href="{{ route('terms') }}" class="flex items-center gap-4 px-3 py-3 rounded-xl text-gray-400 hover:text-white hover:bg-white/5 transition-all">
                <i data-lucide="file-text" class="w-5 h-5"></i>
                <span class="text-sm font-medium hidden lg:block">Terms</span>
            </a>
        </div>
    </aside>

    <main class="flex-1 flex flex-col h-full min-w-0 relative z-10">
        <header class="glass-header px-6 py-5 shrink-0 sticky top-0 z-40">
            <div class="w-full flex flex-col gap-4">
                <div class="flex flex-col md:flex-row gap-4 md:items-center justify-between">
                    <div class="relative group grow max-w-3xl">
                        <div class="absolute -inset-0.5 bg-gradient-to-r from-brand-ocean to-brand-sun rounded-xl blur opacity-20 group-hover:opacity-40 transition duration-500"></div>
                        <div class="relative flex items-center bg-[#151518] border border-white/10 rounded-xl shadow-2xl h-11 theme-surface">
                            <div class="pl-4 pr-3 text-gray-400">
                                <i data-lucide="search" class="w-5 h-5"></i>
                            </div>
                            <input id="q" type="text" placeholder="Search emojis by keyword, mood, meaning..." class="w-full bg-transparent text-white placeholder-gray-500 focus:outline-none font-medium h-full text-sm sm:text-base">
                            <div class="flex md:hidden items-center gap-2 pr-2">
                                <button id="tone-toggle-mobile" class="w-8 h-8 rounded-full theme-surface border border-white/10 flex items-center justify-center text-gray-300 hover:text-white transition-colors shrink-0" title="Tone: Default">
                                    <span id="tone-dot-mobile" class="w-3 h-3 rounded-full bg-white/80 border border-white/30"></span>
                                </button>
                                <button id="theme-toggle-mobile" class="w-8 h-8 rounded-full theme-surface border border-white/10 flex items-center justify-center text-gray-300 hover:text-white transition-colors shrink-0">
                                    <span class="sr-only">Toggle theme</span>
                                    <i data-lucide="sun-moon" class="w-4 h-4"></i>
                                </button>
                            </div>
                        </div>
                    </div>

                    <div class="flex items-center gap-3 shrink-0">
                        <select id="category" class="bg-[#151518] border border-white/10 rounded-xl px-4 text-sm text-gray-300 focus:outline-none focus:border-brand-ocean hover:bg-white/5 transition-colors h-11 cursor-pointer appearance-none theme-surface">
                            <option value="">All Categories</option>
                        </select>
                        <select id="subcategory" class="bg-[#151518] border border-white/10 rounded-xl px-4 text-sm text-gray-300 focus:outline-none focus:border-brand-ocean hover:bg-white/5 transition-colors h-11 cursor-pointer appearance-none theme-surface" disabled>
                            <option value="">All Subcategories</option>
                        </select>
                        <button id="tone-toggle" class="hidden md:flex w-10 h-10 rounded-full theme-surface border border-white/10 shadow-lg items-center justify-center text-gray-300 hover:text-white transition-colors" title="Tone: Default">
                            <span id="tone-dot-desktop" class="w-4 h-4 rounded-full bg-white/80 border border-white/30"></span>
                        </button>
                        <button id="theme-toggle" class="hidden md:flex w-10 h-10 rounded-full theme-surface border border-white/10 shadow-lg items-center justify-center text-gray-300 hover:text-white transition-colors">
                            <span class="sr-only">Toggle theme</span>
                            <i data-lucide="moon" class="w-4 h-4" data-theme-icon="dark"></i>
                            <i data-lucide="sun" class="w-4 h-4 hidden" data-theme-icon="light"></i>
                        </button>
                        <div class="w-px h-8 bg-white/10 mx-1 hidden lg:block"></div>
                    </div>
                </div>

                <div class="flex flex-wrap items-center gap-2 justify-between">
                    <div class="flex flex-wrap gap-2">
                        <button data-tag="happy" class="quick-tag px-2 py-1 bg-white/5 hover:bg-brand-ocean/20 hover:text-brand-oceanSoft border border-white/5 rounded text-[11px] transition-colors">#happy</button>
                        <button data-tag="love" class="quick-tag px-2 py-1 bg-white/5 hover:bg-brand-ocean/20 hover:text-brand-oceanSoft border border-white/5 rounded text-[11px] transition-colors">#love</button>
                        <button data-tag="party" class="quick-tag px-2 py-1 bg-white/5 hover:bg-brand-ocean/20 hover:text-brand-oceanSoft border border-white/5 rounded text-[11px] transition-colors">#party</button>
                        <button data-tag="thumbs" class="quick-tag px-2 py-1 bg-white/5 hover:bg-brand-ocean/20 hover:text-brand-oceanSoft border border-white/5 rounded text-[11px] transition-colors">#thumbs</button>
                        <button data-tag="animal" class="quick-tag px-2 py-1 bg-white/5 hover:bg-brand-ocean/20 hover:text-brand-oceanSoft border border-white/5 rounded text-[11px] transition-colors">#animal</button>
                    </div>
                    <div class="text-xs text-gray-400" id="result-count">Showing 0</div>
                </div>
            </div>
        </header>

        <div class="flex-1 overflow-y-auto p-4 sm:p-6 pb-24 lg:pb-6">
            <div class="w-full">
                <div id="hero-cards" class="grid grid-cols-1 md:grid-cols-3 lg:grid-cols-4 gap-4 mb-6 transition-all duration-300">
                    <section id="hero-main" class="md:col-span-2 glass-card rounded-2xl p-6 relative overflow-hidden min-h-[180px] flex flex-col justify-end transition-all duration-300">
                        <div class="absolute top-0 right-0 p-5 opacity-50">
                            <i data-lucide="sparkles" class="w-5 h-5 text-brand-sun"></i>
                        </div>
                        <div class="relative z-10">
                            <span class="inline-block px-2 py-0.5 rounded bg-brand-sun/20 text-brand-sun text-[10px] font-bold mb-2 border border-brand-sun/30">NEW ENGINE</span>
                            <h3 class="font-display text-2xl font-bold mb-1">Semantic Discovery</h3>
                            <p class="text-gray-400 text-xs max-w-sm">Search the meaning, not just emoji names. EN + ID keywords supported.</p>
                        </div>
                        <div class="absolute -top-10 -right-10 w-48 h-48 bg-gradient-to-br from-brand-ocean/25 to-brand-sun/20 rounded-full blur-3xl"></div>
                    </section>

                    <section id="hero-optional-1" class="glass-card rounded-2xl p-5 flex flex-col relative">
                        <div class="flex justify-between items-center mb-4">
                            <h4 class="font-bold text-gray-200 text-sm">Trending Now</h4>
                            <i data-lucide="trending-up" class="w-4 h-4 text-brand-sun"></i>
                        </div>
                        <div id="trending-list" class="flex flex-wrap gap-2"></div>
                    </section>

                    <section id="hero-optional-2" class="glass-card rounded-2xl p-5 flex flex-col justify-between">
                        <div class="flex justify-between items-start">
                            <div class="w-8 h-8 rounded-lg bg-purple-500/20 flex items-center justify-center text-purple-400">
                                <i data-lucide="history" class="w-4 h-4"></i>
                            </div>
                            <span id="dataset-count" class="text-[10px] text-gray-500 font-mono">0 items</span>
                        </div>
                        <div>
                            <h4 class="font-bold text-sm">Recent</h4>
                            <div id="recent-list" class="flex gap-2 mt-2"></div>
                        </div>
                    </section>
                </div>

                <div class="flex items-center gap-2 mb-4 px-1">
                    <h4 class="font-bold text-gray-200">All Emojis</h4>
                    <div class="h-px bg-white/10 flex-1"></div>
                    <div class="hidden sm:flex items-center gap-2 text-[11px] text-gray-400">
                        <button id="grid-smaller" class="w-7 h-7 rounded-md bg-white/5 hover:bg-white/10 border border-white/10">-</button>
                        <input id="grid-size" type="range" min="0" max="2" step="1" value="1" class="w-20 accent-[#2053ff]">
                        <button id="grid-bigger" class="w-7 h-7 rounded-md bg-white/5 hover:bg-white/10 border border-white/10">+</button>
                    </div>
                    <span id="count" class="text-xs text-gray-500">0 / 0</span>
                </div>

                <div id="grid" class="grid gap-2 pb-8"></div>

                <div class="py-8 flex justify-center">
                    <button id="more" class="hidden px-4 py-2 rounded-xl bg-white/10 hover:bg-white/20 border border-white/10 text-sm text-gray-200 transition-colors">Load more</button>
                </div>
            </div>
        </div>
    </main>
</div>

<div id="toast" class="fixed bottom-8 left-1/2 -translate-x-1/2 translate-y-24 opacity-0 transition-all duration-300 z-50">
    <div class="bg-brand-ocean text-white px-4 py-2 rounded-full font-bold shadow-[0_0_20px_rgba(32,83,255,0.45)] flex items-center gap-2 text-sm">
        <i data-lucide="check" class="w-4 h-4"></i>
        <span id="toast-msg">Copied!</span>
    </div>
</div>

<div id="keyword-edit-modal" class="hidden fixed inset-0 z-50 items-center justify-center">
    <div class="absolute inset-0 bg-black/70 backdrop-blur-sm"></div>
    <div class="relative z-10 w-full max-w-lg rounded-3xl glass-card p-6">
        <div class="flex items-center justify-between">
            <h3 class="text-lg font-semibold text-white">Edit keyword</h3>
            <button id="keyword-edit-close" class="w-8 h-8 rounded-full bg-white/10 hover:bg-white/20 flex items-center justify-center text-gray-200">
                <i data-lucide="x" class="w-4 h-4"></i>
            </button>
        </div>
        <form id="keyword-edit-form" class="mt-4 grid gap-4">
            <input type="hidden" id="keyword-edit-id">
            <input type="hidden" id="keyword-edit-slug">
            <div>
                <label class="text-xs uppercase tracking-[0.2em] text-gray-400">Keyword</label>
                <input type="text" id="keyword-edit-text" class="mt-2 w-full rounded-xl bg-black/40 border border-white/10 px-4 py-3 text-sm text-gray-200 focus:outline-none focus:border-brand-ocean" required>
            </div>
            <div>
                <label class="text-xs uppercase tracking-[0.2em] text-gray-400">Language</label>
                <input type="text" id="keyword-edit-lang" class="mt-2 w-full rounded-xl bg-black/40 border border-white/10 px-4 py-3 text-sm text-gray-200 focus:outline-none focus:border-brand-ocean">
            </div>
            <div class="flex items-center justify-end gap-2">
                <button type="button" id="keyword-edit-cancel" class="rounded-full border border-white/10 px-4 py-2 text-sm text-gray-200 hover:bg-white/5">Cancel</button>
                <button type="submit" class="rounded-full bg-brand-ocean text-white font-semibold px-5 py-2 text-sm">Save</button>
            </div>
        </form>
    </div>
</div>
@endsection

@push('scripts')
<script>
(() => {
    const state = { page: 1, limit: 32, total: 0, items: [], categories: {} };
    const userTier = @json($userTier ?? null);
    const isPersonal = userTier === 'personal';
    const isSignedIn = @json(auth()->check());
    const initialQuery = @json($initialQuery ?? '');
    const initialCategory = @json($initialCategory ?? '');
    const initialSubcategory = @json($initialSubcategory ?? '');
    const initialPath = @json($canonicalPath ?? '/');
    const qEl = document.getElementById('q');
    const catEl = document.getElementById('category');
    const subEl = document.getElementById('subcategory');
    const toneDesktopBtn = document.getElementById('tone-toggle');
    const toneMobileBtn = document.getElementById('tone-toggle-mobile');
    const toneDotDesktop = document.getElementById('tone-dot-desktop');
    const toneDotMobile = document.getElementById('tone-dot-mobile');
    const themeMobileBtn = document.getElementById('theme-toggle-mobile');
    const themeDesktopBtn = document.getElementById('theme-toggle');
    const grid = document.getElementById('grid');
    const count = document.getElementById('count');
    const more = document.getElementById('more');
    const resultCount = document.getElementById('result-count');
    const datasetCount = document.getElementById('dataset-count');
    const trendingList = document.getElementById('trending-list');
    const recentList = document.getElementById('recent-list');
    const heroCards = document.getElementById('hero-cards');
    const heroMain = document.getElementById('hero-main');
    const heroOptional1 = document.getElementById('hero-optional-1');
    const heroOptional2 = document.getElementById('hero-optional-2');
    const gridSizeEl = document.getElementById('grid-size');
    const gridSmallerEl = document.getElementById('grid-smaller');
    const gridBiggerEl = document.getElementById('grid-bigger');
    const densityStorageKey = 'dewemoji_grid_density';
    const csrf = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content');
    const keywordEditModal = document.getElementById('keyword-edit-modal');
    const keywordEditClose = document.getElementById('keyword-edit-close');
    const keywordEditCancel = document.getElementById('keyword-edit-cancel');
    const keywordEditForm = document.getElementById('keyword-edit-form');
    const keywordEditId = document.getElementById('keyword-edit-id');
    const keywordEditSlug = document.getElementById('keyword-edit-slug');
    const keywordEditText = document.getElementById('keyword-edit-text');
    const keywordEditLang = document.getElementById('keyword-edit-lang');
    const toneStorageKey = 'dewemoji_skin_tone';
    const toneOrder = ['off', 'light', 'medium-light', 'medium', 'medium-dark', 'dark'];
    const toneLabelMap = {
        off: 'Default',
        light: 'Light',
        'medium-light': 'Medium light',
        medium: 'Medium',
        'medium-dark': 'Medium dark',
        dark: 'Dark',
    };
    const toneColorMap = {
        off: '#ffd155',
        light: '#f6d7c3',
        'medium-light': '#e8bc95',
        medium: '#c68a62',
        'medium-dark': '#8f5f45',
        dark: '#5b3b2f',
    };
    let currentTone = 'off';
    const toneIndexMap = {
        light: 0,
        'medium-light': 1,
        medium: 2,
        'medium-dark': 3,
        dark: 4,
    };

    if (initialQuery) qEl.value = initialQuery;

    function slugify(text) {
        return String(text || '')
            .toLowerCase()
            .replaceAll('&', 'and')
            .replace(/[^a-z0-9]+/g, '-')
            .replace(/^-+|-+$/g, '');
    }

    function categoryLabelToSlug(label) {
        const map = {
            'Smileys & Emotion': 'smileys',
            'People & Body': 'people',
            'Animals & Nature': 'animals',
            'Food & Drink': 'food',
            'Travel & Places': 'travel',
            'Activities': 'activities',
            'Objects': 'objects',
            'Symbols': 'symbols',
            'Flags': 'flags',
        };
        return map[String(label || '')] || '';
    }

    function syncUrl() {
        const q = qEl.value.trim();
        const cat = catEl.value;
        const sub = subEl.value;
        const params = new URLSearchParams();
        let path = '/';

        if (q !== '') {
            params.set('q', q);
            if (cat) params.set('category', cat);
            if (sub) params.set('subcategory', sub);
            path = '/';
        } else if (cat) {
            const catSlug = categoryLabelToSlug(cat);
            if (catSlug) {
                path = '/' + catSlug;
                if (sub) path += '/' + slugify(sub);
            } else {
                params.set('category', cat);
                if (sub) params.set('subcategory', sub);
            }
        } else {
            path = initialPath === '/browse' ? '/browse' : '/';
        }

        const query = params.toString();
        const target = query ? `${path}?${query}` : path;
        window.history.replaceState({}, '', target);
    }

    function esc(s) {
        return String(s || '').replace(/[&<>"']/g, (c) => ({ '&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;' }[c]));
    }

    function selectedTone() {
        return currentTone;
    }

    function setToneControlValue(value) {
        const normalized = toneOrder.includes(String(value)) ? String(value) : 'off';
        currentTone = normalized;
        const bg = toneColorMap[normalized] || toneColorMap.off;
        const title = `Tone: ${toneLabelMap[normalized] || 'Default'}`;
        [toneDotDesktop, toneDotMobile].forEach((dot) => {
            if (!dot) return;
            dot.style.backgroundColor = bg;
        });
        [toneDesktopBtn, toneMobileBtn].forEach((btn) => {
            if (!btn) return;
            btn.title = title;
            btn.setAttribute('aria-label', title);
        });
    }

    function emojiWithTone(item) {
        const tone = selectedTone();
        if (tone === 'off') return item.emoji;
        if (!item?.supports_skin_tone) return item.emoji;
        const variants = Array.isArray(item?.variants) ? item.variants : [];
        const idx = toneIndexMap[tone];
        if (typeof idx === 'number' && variants[idx]) return variants[idx];
        return item.emoji_base || item.emoji;
    }

    function applyGridDensity(level) {
        const sizes = [
            { min: 90, emoji: '2.2rem' },
            { min: 108, emoji: '2.45rem' },
            { min: 132, emoji: '2.8rem' },
        ];
        const safe = Math.max(0, Math.min(2, Number(level) || 0));
        const conf = sizes[safe];
        grid.style.setProperty('--card-min', `${conf.min}px`);
        grid.style.setProperty('--emoji-size', conf.emoji);
        if (gridSizeEl) gridSizeEl.value = String(safe);
        localStorage.setItem(densityStorageKey, String(safe));
    }


    function hasActiveFilters() {
        return qEl.value.trim() !== '' || catEl.value !== '' || subEl.value !== '';
    }

    function updateHeroMode() {
        const compact = hasActiveFilters();
        heroCards.classList.toggle('mb-6', !compact);
        heroCards.classList.toggle('mb-3', compact);
        heroMain.classList.toggle('min-h-[180px]', !compact);
        heroMain.classList.toggle('min-h-[120px]', compact);
    }

    async function loadCategories() {
        const res = await fetch('/v1/categories');
        const data = await res.json();
        state.categories = data || {};
        Object.keys(state.categories).forEach((name) => {
            const opt = document.createElement('option');
            opt.value = name;
            opt.textContent = name;
            catEl.appendChild(opt);
        });
    }

    function renderSubcategories() {
        const subs = state.categories[catEl.value] || [];
        subEl.innerHTML = '<option value="">All subcategories</option>';
        subs.forEach((s) => {
            const opt = document.createElement('option');
            opt.value = s;
            opt.textContent = s;
            subEl.appendChild(opt);
        });
        subEl.disabled = subs.length === 0;
    }

    function showToast(message) {
        const toast = document.getElementById('toast');
        const msg = document.getElementById('toast-msg');
        msg.textContent = message;
        toast.classList.remove('translate-y-24', 'opacity-0');
        setTimeout(() => toast.classList.add('translate-y-24', 'opacity-0'), 1400);
    }

    function loadRecent() {
        try {
            return JSON.parse(localStorage.getItem('dewemoji_recent') || '[]');
        } catch {
            return [];
        }
    }

    function saveRecent(items) {
        localStorage.setItem('dewemoji_recent', JSON.stringify(items.slice(0, 8)));
    }

    function addRecent(emoji) {
        const curr = loadRecent().filter((e) => e !== emoji);
        curr.unshift(emoji);
        saveRecent(curr);
        renderRecent();
    }

    function renderRecent() {
        const recent = loadRecent();
        recentList.innerHTML = '';
        const fallback = ['🚀', '💀', '✨'];
        const source = recent.length ? recent : fallback;
        source.forEach((emoji) => {
            const btn = document.createElement('button');
            btn.className = 'w-8 h-8 rounded bg-white/5 hover:bg-white/10 flex items-center justify-center text-lg';
            btn.textContent = emoji;
            btn.addEventListener('click', () => window.copyEmoji(emoji));
            recentList.appendChild(btn);
        });
    }

    function renderTrendingFromItems(items) {
        const score = new Map();
        items.forEach((item) => {
            const tags = []
                .concat(item.keywords_en || [])
                .concat(item.intent_tags || []);
            tags.forEach((tag) => {
                const t = String(tag || '').trim().toLowerCase();
                if (!t || t.length < 3) return;
                score.set(t, (score.get(t) || 0) + 1);
            });
        });

        const top = Array.from(score.entries())
            .sort((a, b) => b[1] - a[1])
            .slice(0, 6)
            .map(([tag]) => tag);

        const fallback = ['happy', 'love', 'party', 'thumbs', 'animal', 'food'];
        const tags = top.length ? top : fallback;

        trendingList.innerHTML = '';
        tags.forEach((tag) => {
            const btn = document.createElement('button');
            btn.className = 'px-2 py-1 bg-white/5 hover:bg-brand-ocean/20 hover:text-brand-oceanSoft border border-white/5 rounded text-[11px] transition-colors';
            btn.textContent = '#' + tag;
            btn.addEventListener('click', () => {
                qEl.value = tag;
                fetchEmojis(true);
            });
            trendingList.appendChild(btn);
        });
    }

    window.copyEmoji = function (emoji) {
        navigator.clipboard.writeText(emoji).then(() => {
            showToast('Copied ' + emoji);
            addRecent(emoji);
        });
    }

    async function fetchEmojis(reset = false) {
        if (reset) {
            state.page = 1;
            state.items = [];
            grid.innerHTML = '';
        }

        updateHeroMode();

        const params = new URLSearchParams({ page: String(state.page), limit: String(state.limit) });
        if (qEl.value.trim()) params.set('q', qEl.value.trim());
        if (catEl.value) params.set('category', catEl.value);
        if (subEl.value) params.set('subcategory', subEl.value);

        const endpoint = isSignedIn ? '/dashboard/keywords/search' : '/v1/emojis';
        const res = await fetch(endpoint + '?' + params.toString());
        const data = await res.json();
        if (!res.ok) {
            const msg = data.message || data.error || `API error (${res.status})`;
            grid.innerHTML = `<p class="text-xs text-amber-300 col-span-full">${esc(msg)}</p>`;
            state.total = 0;
            state.items = [];
            updateStats();
            return;
        }
        state.total = data.total || 0;

        const incoming = data.items || [];
        incoming.forEach((item) => state.items.push(item));
        renderGrid(incoming, reset);
        updateStats();
        syncUrl();
    }

    function renderGrid(items, reset) {
        if (reset && state.items.length === 0) {
            grid.innerHTML = '<p class="text-xs text-gray-500 col-span-full">No emojis found.</p>';
            return;
        }

        items.forEach((item) => {
            const renderedEmoji = emojiWithTone(item);
            const card = document.createElement('div');
            card.className = 'emoji-card relative aspect-square rounded-lg bg-white/5 hover:bg-white/10 transition-transform hover:scale-[1.02] border border-transparent hover:border-white/20 overflow-hidden group';
            card.innerHTML = `
                <a href="/emoji/${encodeURIComponent(item.slug)}" class="absolute inset-0 flex items-center justify-center pb-10">
                    <span class="leading-none" style="font-size:var(--emoji-size)">${esc(renderedEmoji)}</span>
                </a>
                <div class="emoji-card-bar absolute bottom-0 left-0 right-0 border-t border-white/10 bg-black/20 px-2 py-1.5 flex items-start gap-1">
                    <span class="emoji-name-clamp text-[10px] text-gray-300 text-left flex-1">${esc(item.name)}</span>
                    <button type="button" class="copy-btn shrink-0 w-6 h-6 rounded bg-white/10 hover:bg-brand-ocean/30 text-[11px] text-gray-200 hover:text-white transition-colors" title="Copy emoji">⧉</button>
                </div>
            `;
            const copyBtn = card.querySelector('.copy-btn');
            if (copyBtn) {
                copyBtn.addEventListener('click', (e) => {
                    e.preventDefault();
                    e.stopPropagation();
                    navigator.clipboard.writeText(renderedEmoji).then(() => {
                        showToast('Copied ' + renderedEmoji);
                        addRecent(renderedEmoji);
                    });
                });
            }
            card.addEventListener('contextmenu', (e) => {
                e.preventDefault();
                navigator.clipboard.writeText(renderedEmoji).then(() => {
                    showToast('Copied ' + renderedEmoji);
                    addRecent(renderedEmoji);
                });
            });
            grid.appendChild(card);
        });
    }

    function updateStats() {
        count.textContent = `${state.items.length} / ${state.total}`;
        resultCount.textContent = `Showing ${state.items.length}`;
        datasetCount.textContent = `${state.total} matches`;
        more.classList.toggle('hidden', state.items.length >= state.total);
    }

    let timer = null;
    qEl.addEventListener('input', () => {
        clearTimeout(timer);
        timer = setTimeout(() => fetchEmojis(true), 220);
    });

    catEl.addEventListener('change', async () => {
        renderSubcategories();
        await fetchEmojis(true);
    });

    subEl.addEventListener('change', () => fetchEmojis(true));
    const onToneChange = (nextTone = null) => {
        const tone = nextTone || selectedTone();
        setToneControlValue(tone);
        localStorage.setItem(toneStorageKey, tone);
        fetchEmojis(true);
    };
    const cycleTone = () => {
        const idx = toneOrder.indexOf(selectedTone());
        const next = toneOrder[(idx + 1) % toneOrder.length];
        onToneChange(next);
    };
    toneDesktopBtn?.addEventListener('click', cycleTone);
    toneMobileBtn?.addEventListener('click', cycleTone);

    themeMobileBtn?.addEventListener('click', () => {
        themeDesktopBtn?.click();
    });

    // keep mobile icon synced when desktop toggle flips theme
    themeDesktopBtn?.addEventListener('click', () => {
        setTimeout(() => lucide.createIcons(), 0);
    });

    more.addEventListener('click', async () => {
        state.page += 1;
        await fetchEmojis(false);
    });

    document.querySelectorAll('.quick-tag').forEach((btn) => {
        btn.addEventListener('click', () => {
            qEl.value = btn.dataset.tag || '';
            fetchEmojis(true);
        });
    });

    function openKeywordEdit(item) {
        if (!isPersonal || !item.matched_keyword_id) return;
        keywordEditId.value = item.matched_keyword_id;
        keywordEditSlug.value = item.slug;
        keywordEditText.value = item.matched_keyword || '';
        keywordEditLang.value = item.matched_lang || '';
        keywordEditModal.classList.remove('hidden');
        keywordEditModal.classList.add('flex');
        keywordEditText.focus();
    }

    function closeKeywordEdit() {
        keywordEditModal.classList.add('hidden');
        keywordEditModal.classList.remove('flex');
    }

    keywordEditClose?.addEventListener('click', closeKeywordEdit);
    keywordEditCancel?.addEventListener('click', closeKeywordEdit);
    keywordEditModal?.addEventListener('click', (e) => {
        if (e.target === keywordEditModal) closeKeywordEdit();
    });

    keywordEditForm?.addEventListener('submit', async (e) => {
        e.preventDefault();
        const id = keywordEditId.value;
        const payload = {
            emoji_slug: keywordEditSlug.value,
            keyword: keywordEditText.value.trim(),
            lang: keywordEditLang.value.trim() || 'und',
        };
        if (!id || !payload.keyword) return;
        const res = await fetch(`/dashboard/keywords/${id}`, {
            method: 'PUT',
            headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/json',
                ...(csrf ? { 'X-CSRF-TOKEN': csrf } : {}),
            },
            body: JSON.stringify(payload),
        });
        const data = await res.json().catch(() => null);
        if (!res.ok || !data?.ok) {
            showToast('Could not update keyword');
            return;
        }
        closeKeywordEdit();
        fetchEmojis(true);
    });

    if (gridSizeEl && gridSmallerEl && gridBiggerEl) {
        const initialDensity = localStorage.getItem(densityStorageKey) ?? '1';
        applyGridDensity(Number(initialDensity));

        gridSizeEl.addEventListener('input', () => applyGridDensity(Number(gridSizeEl.value)));
        gridSmallerEl.addEventListener('click', () => applyGridDensity(Number(gridSizeEl.value) - 1));
        gridBiggerEl.addEventListener('click', () => applyGridDensity(Number(gridSizeEl.value) + 1));
    }

    (async () => {
        setToneControlValue(localStorage.getItem(toneStorageKey) || 'off');
        await loadCategories();
        if (initialCategory && state.categories[initialCategory]) {
            catEl.value = initialCategory;
            renderSubcategories();
            if (initialSubcategory) {
                const hasInitialSub = Array.from(subEl.options).some((opt) => opt.value === initialSubcategory);
                if (hasInitialSub) subEl.value = initialSubcategory;
            }
        }
        await fetchEmojis(true);
        renderTrendingFromItems(state.items);
        renderRecent();
        updateHeroMode();
        lucide.createIcons();
    })();
})();
</script>
@endpush
