@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: 54px;
        --emoji-size: 1.9rem;
        grid-template-columns: repeat(auto-fill, minmax(var(--card-min), 1fr));
    }
    #grid[data-hide-labels="1"] .emoji-card {
        border-color: rgba(255, 255, 255, 0.06);
    }
    #grid[data-hide-labels="1"] .emoji-card-copy {
        opacity: 0;
        transform: translateY(-2px);
        transition: all 150ms ease;
    }
    #grid[data-hide-labels="1"] .emoji-card:hover .emoji-card-copy,
    #grid[data-hide-labels="1"] .emoji-card:focus-within .emoji-card-copy {
        opacity: 1;
        transform: translateY(0);
    }
    @media (max-width: 640px) {
        #grid {
            --card-min: 44px;
        }
    }
</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('download') }}" 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="download" class="w-5 h-5 group-hover:scale-110 transition-transform"></i>
                    <span class="text-sm font-medium hidden lg:block">Download</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="mobile-filters-open" type="button" class="h-8 rounded-lg bg-white/5 border border-white/10 px-2 text-xs text-gray-300 hover:bg-white/10 transition-colors inline-flex items-center gap-1.5 shrink-0">
                                    <i data-lucide="sliders-horizontal" class="w-3.5 h-3.5"></i>
                                    <span>Filter</span>
                                </button>
                                <button id="favorites-only-toggle-mobile" type="button" 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="Show favorites only">
                                    <span class="text-sm leading-none">☆</span>
                                </button>
                                <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="hidden md:block 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="hidden md:block 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="favorites-only-toggle" type="button" 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="Show favorites only">
                            <span class="text-sm leading-none">☆</span>
                        </button>
                        <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="hidden sm: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 id="catalog-scroll" 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="hidden md:flex md:col-span-2 glass-card rounded-2xl p-6 relative overflow-hidden min-h-[180px] 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 class="mt-4">
                            <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>
                    <button id="labels-toggle" class="h-8 rounded-md bg-white/5 hover:bg-white/10 border border-white/10 px-2 text-[11px] text-gray-300">
                        Labels: Off
                    </button>
                    <div class="flex sm:hidden items-center gap-1 text-[11px] text-gray-400">
                        <button id="grid-smaller-mobile" class="w-8 h-8 rounded-md bg-white/5 hover:bg-white/10 border border-white/10">-</button>
                        <button id="grid-bigger-mobile" class="w-8 h-8 rounded-md bg-white/5 hover:bg-white/10 border border-white/10">+</button>
                    </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 id="grid-sentinel" class="h-2 w-full"></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 left-1/2 -translate-x-1/2 translate-y-24 opacity-0 transition-all duration-300 z-50" style="bottom: calc(env(safe-area-inset-bottom, 0px) + 6rem);">
    <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>

<div id="mobile-filters-sheet" class="hidden md:hidden fixed inset-0 z-50 items-end">
    <div id="mobile-filters-backdrop" class="absolute inset-0 bg-black/70 backdrop-blur-sm"></div>
    <div class="relative z-10 w-full rounded-t-3xl glass-card theme-surface p-5 pb-6 border-t border-white/10" style="padding-bottom: calc(env(safe-area-inset-bottom, 0px) + 6rem);">
        <div class="flex items-center justify-between mb-4">
            <h3 class="text-sm font-semibold text-gray-100">Filters</h3>
            <button id="mobile-filters-close" type="button" class="w-9 h-9 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>
        <div class="grid gap-3">
            <select id="category-mobile" class="bg-[#151518] border border-white/10 rounded-xl px-4 text-sm text-gray-300 focus:outline-none focus:border-brand-ocean h-12 cursor-pointer appearance-none theme-surface">
                <option value="">All Categories</option>
            </select>
            <select id="subcategory-mobile" class="bg-[#151518] border border-white/10 rounded-xl px-4 text-sm text-gray-300 focus:outline-none focus:border-brand-ocean h-12 cursor-pointer appearance-none theme-surface" disabled>
                <option value="">All Subcategories</option>
            </select>
            <div class="grid grid-cols-2 gap-3 pt-1">
                <button id="mobile-filters-reset" type="button" class="h-11 rounded-xl border border-white/10 text-sm text-gray-200 hover:bg-white/5">Reset</button>
                <button id="mobile-filters-apply" type="button" class="h-11 rounded-xl bg-brand-ocean text-white force-white text-sm font-semibold">Apply</button>
            </div>
        </div>
    </div>
</div>
@endsection

@push('scripts')
<script>
(() => {
    const state = { page: 1, limit: 48, 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 mobileFiltersOpenEl = document.getElementById('mobile-filters-open');
    const mobileFiltersSheetEl = document.getElementById('mobile-filters-sheet');
    const mobileFiltersBackdropEl = document.getElementById('mobile-filters-backdrop');
    const mobileFiltersCloseEl = document.getElementById('mobile-filters-close');
    const mobileFiltersApplyEl = document.getElementById('mobile-filters-apply');
    const mobileFiltersResetEl = document.getElementById('mobile-filters-reset');
    const catMobileEl = document.getElementById('category-mobile');
    const subMobileEl = document.getElementById('subcategory-mobile');
    const favoritesOnlyDesktopBtn = document.getElementById('favorites-only-toggle');
    const favoritesOnlyMobileBtn = document.getElementById('favorites-only-toggle-mobile');
    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 catalogScrollEl = document.getElementById('catalog-scroll');
    const count = document.getElementById('count');
    const more = document.getElementById('more');
    const gridSentinel = document.getElementById('grid-sentinel');
    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 favoritesList = document.getElementById('favorites-list');
    const favoritesClearEl = document.getElementById('favorites-clear');
    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 gridSmallerMobileEl = document.getElementById('grid-smaller-mobile');
    const gridBiggerMobileEl = document.getElementById('grid-bigger-mobile');
    const labelsToggleEl = document.getElementById('labels-toggle');
    const densityStorageKey = 'dewemoji_grid_density';
    const labelsStorageKey = 'dewemoji_grid_show_labels';
    const recentStorageKey = 'dewemoji_recent';
    const favoritesStorageKey = 'dewemoji_favorites';
    const favoritesOnlyStorageKey = 'dewemoji_favorites_only';
    let isFetching = false;
    let autoLoadObserver = null;
    const AUTOLOAD_THRESHOLD_PX = 420;

    function initialLimitByViewport() {
        const w = window.innerWidth || 1280;
        if (w >= 1536) return 120;
        if (w >= 1280) return 96;
        if (w >= 1024) return 80;
        if (w >= 768) return 64;
        return 48;
    }
    state.limit = initialLimitByViewport();
    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,
    };
    const toneCharBySlug = {
        light: '\u{1F3FB}',
        'medium-light': '\u{1F3FC}',
        medium: '\u{1F3FD}',
        'medium-dark': '\u{1F3FE}',
        dark: '\u{1F3FF}',
    };
    const TONE_CPS = new Set([0x1F3FB, 0x1F3FC, 0x1F3FD, 0x1F3FE, 0x1F3FF]);
    const MODIFIABLE_BASES = new Set([
        0x1F9D1, 0x1F468, 0x1F469, 0x1F466, 0x1F467, 0x1F476,
        0x1F575, 0x1F93C, 0x26F9, 0x1F3CB, 0x1F93D, 0x1F93E, 0x1F926,
    ]);
    const NOT_TONEABLE_BASES = new Set([
        0x1F9BE, 0x1F9BF, 0x1FAC0, 0x1F9E0, 0x1FAC1, 0x1F9B7, 0x1F9B4,
        0x1F440, 0x1F441, 0x1F445, 0x1F444, 0x1FAE6,
        0x1F9DE, 0x1F9DF, 0x1F9CC, 0x26F7, 0x1F3C2,
    ]);
    const NON_TONEABLE_NAME_PATTERNS = [
        /\bspeaking head\b/i,
        /\bbust in silhouette\b/i,
        /\bbusts in silhouette\b/i,
        /\bfootprints?\b/i,
        /\bfingerprint\b/i,
        /\bfamily\b/i,
        /\bpeople hugging\b/i,
        /\bpeople with bunny ears\b/i,
        /\bpeople wrestling\b/i,
        /\bpeople fencing\b/i,
        /\bperson fencing\b/i,
        /\bmen wrestling\b/i,
        /\bwomen wrestling\b/i,
        /\bmerman\b/i,
        /\bmermaid\b/i,
        /\bdeaf man\b/i,
        /\bdeaf woman\b/i,
        /\bman: beard\b/i,
        /\bwoman: beard\b/i,
        /\bperson running facing right\b/i,
        /\bperson walking facing right\b/i,
        /\bperson kneeling facing right\b/i,
    ];
    const ROLE_TONEABLE_NAME_PATTERNS = [
        /\btechnologist\b/i,
        /\bscientist\b/i,
        /\boffice worker\b/i,
        /\bfactory worker\b/i,
        /\bmechanic\b/i,
        /\bcook\b/i,
        /\bfarmer\b/i,
        /\bjudge\b/i,
        /\bteacher\b/i,
        /\bstudent\b/i,
        /\bhealth worker\b/i,
        /\bsinger\b/i,
        /\bastronaut\b/i,
        /\bfirefighter\b/i,
        /\bfacepalming\b/i,
        /\bdancing\b/i,
        /\bdetective\b/i,
        /\bfencing\b/i,
        /\bbouncing ball\b/i,
        /\blifting weights\b/i,
        /\bwrestling\b/i,
    ];
    const TONE_CATEGORY_ALLOWLIST = new Set(['people & body', 'activities']);
    const ANDROID_TONE_RENDER_BLOCKLIST_PATTERNS = [
        /\bperson fencing\b/i,
        /\bmen wrestling\b/i,
        /\bwomen wrestling\b/i,
    ];
    const ANDROID_TONE_RENDER_BLOCKLIST_SLUGS = new Set([
        'person-fencing',
        'men-wrestling',
        'women-wrestling',
    ]);
    const ANDROID_TONE_IMAGE_FALLBACK_SLUGS = new Set([
        'person-fencing',
        'men-wrestling',
        'women-wrestling',
    ]);
    const IS_ANDROID_RENDERER = (() => {
        try {
            if (/Android/i.test(navigator.userAgent || '')) return true;
            const platform = window.Capacitor?.getPlatform?.();
            return platform === 'android';
        } catch (_) {
            return /Android/i.test(navigator.userAgent || '');
        }
    })();

    function twemojiSvgUrlFromCodepoints(cp) {
        return `https://twemoji.maxcdn.com/v/latest/svg/${cp}.svg`;
    }

    function notoEmojiSvgUrlFromCodepoints(cp) {
        return `https://cdn.jsdelivr.net/gh/googlefonts/noto-emoji@main/svg/emoji_u${String(cp || '').replace(/-/g, '_')}.svg`;
    }

    function shouldUseToneImageFallback(item, emojiStr) {
        if (!IS_ANDROID_RENDERER) return false;
        const glyph = String(emojiStr || '');
        if (!glyph) return false;
        const hasToneModifier = /[\u{1F3FB}-\u{1F3FF}]/u.test(glyph);
        if (!hasToneModifier) return false;
        if (selectedTone() === 'off' && item) return false;
        const slug = String(item?.slug || '').toLowerCase();
        if (slug) {
            if (!ANDROID_TONE_IMAGE_FALLBACK_SLUGS.has(slug)) return false;
        }
        return /\u200D/.test(glyph);
    }

    function renderEmojiGlyph(container, emojiStr, { item = null } = {}) {
        if (!container) return;
        const glyph = String(emojiStr || '');
        if (!glyph) {
            container.textContent = '';
            return;
        }
        if (!shouldUseToneImageFallback(item, glyph) || !window.twemoji?.convert?.toCodePoint) {
            container.textContent = glyph;
            return;
        }
        let cp = '';
        try {
            cp = window.twemoji.convert.toCodePoint(glyph);
        } catch (_) {
            container.textContent = glyph;
            return;
        }
        if (!cp) {
            container.textContent = glyph;
            return;
        }
        const img = new Image();
        img.alt = glyph;
        img.draggable = false;
        img.decoding = 'async';
        img.loading = 'lazy';
        img.className = 'inline-block align-middle select-none';
        img.style.width = '1em';
        img.style.height = '1em';
        img.style.objectFit = 'contain';
        img.onerror = () => {
            img.onerror = () => {
                container.textContent = glyph;
            };
            img.src = twemojiSvgUrlFromCodepoints(cp);
        };
        img.src = notoEmojiSvgUrlFromCodepoints(cp);
        container.replaceChildren(img);
    }

    function isLabelsEnabled() {
        return localStorage.getItem(labelsStorageKey) === '1';
    }

    function applyLabelsToggleUI() {
        const enabled = isLabelsEnabled();
        grid.dataset.hideLabels = enabled ? '0' : '1';
        if (labelsToggleEl) labelsToggleEl.textContent = `Labels: ${enabled ? 'On' : 'Off'}`;
    }

    function isFavoritesOnlyEnabled() {
        return localStorage.getItem(favoritesOnlyStorageKey) === '1';
    }

    function setFavoritesOnlyEnabled(enabled) {
        localStorage.setItem(favoritesOnlyStorageKey, enabled ? '1' : '0');
        applyFavoritesOnlyUI();
    }

    function applyFavoritesOnlyUI() {
        const active = isFavoritesOnlyEnabled();
        [favoritesOnlyDesktopBtn, favoritesOnlyMobileBtn].forEach((btn) => {
            if (!btn) return;
            btn.classList.toggle('text-yellow-300', active);
            btn.classList.toggle('border-yellow-400/30', active);
            btn.classList.toggle('bg-yellow-400/10', active);
            btn.classList.toggle('text-gray-300', !active);
            btn.title = active ? 'Showing favorites only' : 'Show favorites only';
            btn.setAttribute('aria-pressed', active ? 'true' : 'false');
            const icon = btn.querySelector('span');
            if (icon) icon.textContent = active ? '★' : '☆';
        });
    }

    function isMobileFiltersOpen() {
        return mobileFiltersSheetEl?.classList.contains('flex');
    }

    function openMobileFilters() {
        if (!mobileFiltersSheetEl) return;
        syncMobileFiltersFromDesktop();
        mobileFiltersSheetEl.classList.remove('hidden');
        mobileFiltersSheetEl.classList.add('flex');
        setTimeout(() => lucide.createIcons(), 0);
    }

    function closeMobileFilters() {
        if (!mobileFiltersSheetEl) return false;
        if (!isMobileFiltersOpen()) return false;
        mobileFiltersSheetEl.classList.add('hidden');
        mobileFiltersSheetEl.classList.remove('flex');
        return true;
    }

    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 (!isToneAllowedForItem(item)) return item.emoji_base || item.emoji;
        const toneChar = toneCharBySlug[tone];
        if (!toneChar) return item.emoji;
        const base = stripSkinTone(item?.emoji_base || item?.emoji || '');
        if (!base) return item.emoji;
        const toned = applyToneSmart(base, toneChar);
        return toned || base;
    }

    function isNameNonToneable(item) {
        const name = String(item?.name || '').toLowerCase();
        return NON_TONEABLE_NAME_PATTERNS.some((rx) => rx.test(name));
    }

    function isRoleToneable(item) {
        const name = String(item?.name || '').toLowerCase();
        return ROLE_TONEABLE_NAME_PATTERNS.some((rx) => rx.test(name));
    }

    function isToneAllowedForItem(item) {
        if (!item?.supports_skin_tone) return false;
        const category = String(item?.category || '').toLowerCase();
        if (!TONE_CATEGORY_ALLOWLIST.has(category)) return false;
        if (isNameNonToneable(item)) return false;
        if (IS_ANDROID_RENDERER) {
            const name = String(item?.name || '').toLowerCase();
            const slug = String(item?.slug || '').toLowerCase();
            const usesImageFallback = ANDROID_TONE_IMAGE_FALLBACK_SLUGS.has(slug);
            if (!usesImageFallback && ANDROID_TONE_RENDER_BLOCKLIST_SLUGS.has(slug)) return false;
            if (!usesImageFallback && ANDROID_TONE_RENDER_BLOCKLIST_PATTERNS.some((rx) => rx.test(name))) return false;
        }

        const base = stripSkinTone(item?.emoji_base || item?.emoji || '');
        if (!base || !canApplyToneTo(base)) return false;

        const name = String(item?.name || '').toLowerCase();
        const looksGenderedRole =
            category === 'people & body' &&
            (name.startsWith('man ') || name.startsWith('woman ') || /[:\-,]\s*(man|woman)\b/.test(name));
        if (looksGenderedRole && !isRoleToneable(item)) return false;

        return true;
    }

    function stripSkinTone(emojiChar) {
        return String(emojiChar || '').replace(/[\u{1F3FB}-\u{1F3FF}]/gu, '');
    }

    function containsZWJ(s) {
        return /\u200D/.test(String(s || ''));
    }

    function countHumans(s) {
        let n = 0;
        for (const ch of Array.from(String(s || ''))) {
            const cp = ch.codePointAt(0);
            if (cp === 0x1F468 || cp === 0x1F469 || cp === 0x1F9D1) n++;
        }
        return n;
    }

    function canApplyToneTo(s) {
        if (!s) return false;
        try {
            const cp0 = String(s).codePointAt(0);
            if (NOT_TONEABLE_BASES.has(cp0)) return false;
        } catch (_) {}
        if (!containsZWJ(s)) return true;
        return countHumans(s) <= 2;
    }

    function toCodePoints(str) {
        const out = [];
        for (const ch of String(str || '')) out.push(ch.codePointAt(0));
        return out;
    }

    function fromCodePoints(arr) {
        return String.fromCodePoint(...arr);
    }

    function applyToneSmart(emojiChar, toneChar) {
        if (!emojiChar || !toneChar) return emojiChar;
        const toneCp = String(toneChar).codePointAt(0);
        if (!TONE_CPS.has(toneCp)) return emojiChar;

        const cps = toCodePoints(emojiChar);
        for (const cp of cps) {
            if (TONE_CPS.has(cp)) return emojiChar;
        }

        const VS16 = 0xFE0F;
        const ZWJ = 0x200D;

        const idxs = [];
        for (let i = 0; i < cps.length; i += 1) {
            if (MODIFIABLE_BASES.has(cps[i])) idxs.push(i);
        }

        if (idxs.length === 0) {
            if (cps.includes(ZWJ)) return emojiChar;
            let pos = 1;
            let rightStart = pos;
            if (cps[1] === VS16) {
                // Android renders a tone swatch on some sequences when VS16 stays before the modifier.
                // Build modifier sequence as base + tone (+ rest), dropping the immediate VS16.
                rightStart = 2;
            }
            const left = cps.slice(0, pos);
            left.push(toneCp);
            return fromCodePoints(left.concat(cps.slice(rightStart)));
        }

        if (idxs.length === 2) {
            const out = cps.slice();
            const insertAfter = (baseIdx) => {
                let pos = baseIdx + 1;
                if (out[pos] === VS16) out.splice(pos, 1);
                out.splice(pos, 0, toneCp);
            };
            insertAfter(idxs[1]);
            insertAfter(idxs[0]);
            return fromCodePoints(out);
        }

        let pos = idxs[0] + 1;
        let rightStart = pos;
        if (cps[pos] === VS16) {
            rightStart = pos + 1;
        }
        const left = cps.slice(0, pos);
        left.push(toneCp);
        return fromCodePoints(left.concat(cps.slice(rightStart)));
    }

    function applyGridDensity(level) {
        const safe = Math.max(0, Math.min(6, Number(level) || 0));
        const min = 34 + (safe * 10);
        const emoji = 1.45 + (safe * 0.17);
        grid.style.setProperty('--card-min', `${min}px`);
        grid.style.setProperty('--emoji-size', `${emoji.toFixed(2)}rem`);
        if (gridSizeEl) gridSizeEl.value = String(safe);
        localStorage.setItem(densityStorageKey, String(safe));
    }


    function hasActiveFilters() {
        return isFavoritesOnlyEnabled() || 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 || {};
        const fillCategorySelect = (selectEl) => {
            if (!selectEl) return;
            selectEl.innerHTML = '<option value="">All Categories</option>';
            Object.keys(state.categories).forEach((name) => {
                const opt = document.createElement('option');
                opt.value = name;
                opt.textContent = name;
                selectEl.appendChild(opt);
            });
        };
        fillCategorySelect(catEl);
        fillCategorySelect(catMobileEl);
    }

    function fillSubcategories(selectEl, categoryValue, selectedValue = '') {
        if (!selectEl) return;
        const subs = state.categories[categoryValue] || [];
        selectEl.innerHTML = '<option value="">All Subcategories</option>';
        subs.forEach((s) => {
            const opt = document.createElement('option');
            opt.value = s;
            opt.textContent = s;
            selectEl.appendChild(opt);
        });
        const hasSelected = Array.from(selectEl.options).some((opt) => opt.value === selectedValue);
        selectEl.value = hasSelected ? selectedValue : '';
        selectEl.disabled = subs.length === 0;
    }

    function renderSubcategories() {
        fillSubcategories(subEl, catEl.value, subEl.value);
        fillSubcategories(subMobileEl, catEl.value, subEl.value);
    }

    function syncMobileFiltersFromDesktop() {
        if (!catMobileEl || !subMobileEl) return;
        catMobileEl.value = catEl.value;
        fillSubcategories(subMobileEl, catMobileEl.value, subEl.value);
    }

    function syncDesktopFiltersFromMobile() {
        if (!catMobileEl || !subMobileEl) return;
        catEl.value = catMobileEl.value;
        fillSubcategories(subEl, catEl.value, subMobileEl.value);
    }

    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 {
            const parsed = JSON.parse(localStorage.getItem(recentStorageKey) || '[]');
            return Array.isArray(parsed) ? parsed.filter(isRecentEmojiToken) : [];
        } catch {
            return [];
        }
    }

    function isRecentEmojiToken(value) {
        const s = String(value || '').trim();
        if (!s) return false;
        if (s.length > 24) return false;
        if (/[:;&<#\\]/.test(s)) return false;
        try {
            return /\p{Extended_Pictographic}/u.test(s);
        } catch {
            return /[\u{1F300}-\u{1FAFF}\u{2600}-\u{27BF}]/u.test(s);
        }
    }

    function saveRecent(items) {
        const clean = items.filter(isRecentEmojiToken);
        localStorage.setItem(recentStorageKey, JSON.stringify(clean.slice(0, 8)));
    }

    function addRecent(emoji) {
        if (!isRecentEmojiToken(emoji)) return;
        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';
            renderEmojiGlyph(btn, emoji);
            btn.addEventListener('click', () => window.copyEmoji(emoji));
            recentList.appendChild(btn);
        });
    }

    function loadFavorites() {
        try {
            const parsed = JSON.parse(localStorage.getItem(favoritesStorageKey) || '[]');
            if (!Array.isArray(parsed)) return [];
            return parsed
                .filter((item) => item && typeof item === 'object')
                .map((item) => ({
                    slug: String(item.slug || '').trim(),
                    emoji: String(item.emoji || '').trim(),
                    name: String(item.name || '').trim(),
                    category: String(item.category || '').trim(),
                    subcategory: String(item.subcategory || '').trim(),
                    supports_skin_tone: Boolean(item.supports_skin_tone),
                    variants: Array.isArray(item.variants) ? item.variants : [],
                }))
                .filter((item) => item.slug !== '' && isRecentEmojiToken(item.emoji));
        } catch {
            return [];
        }
    }

    function saveFavorites(items) {
        localStorage.setItem(favoritesStorageKey, JSON.stringify(items.slice(0, 24)));
    }

    function isFavoriteSlug(slug) {
        const key = String(slug || '');
        return loadFavorites().some((item) => item.slug === key);
    }

    function toggleFavorite(item) {
        const slug = String(item?.slug || '');
        if (!slug) return false;
        const current = loadFavorites();
        const all = current.filter((row) => row.slug !== slug);
        const exists = all.length !== current.length;
        if (!exists) {
            all.unshift({
                slug,
                emoji: emojiWithTone(item),
                name: String(item?.name || ''),
                category: String(item?.category || ''),
                subcategory: String(item?.subcategory || ''),
                supports_skin_tone: Boolean(item?.supports_skin_tone),
                variants: Array.isArray(item?.variants) ? item.variants : [],
            });
        }
        saveFavorites(all);
        renderFavorites();
        return !exists;
    }

    function renderFavorites() {
        if (!favoritesList) return;
        const favorites = loadFavorites();
        favoritesList.innerHTML = '';
        if (favorites.length === 0) {
            const empty = document.createElement('span');
            empty.className = 'text-xs text-gray-500';
            empty.textContent = 'No favorites yet';
            favoritesList.appendChild(empty);
            return;
        }
        favorites.slice(0, 8).forEach((fav) => {
            const a = document.createElement('a');
            a.href = `/emoji/${encodeURIComponent(fav.slug)}`;
            a.className = 'w-8 h-8 rounded bg-white/5 hover:bg-white/10 flex items-center justify-center text-lg';
            a.title = fav.name || fav.slug;
            renderEmojiGlyph(a, fav.emoji);
            favoritesList.appendChild(a);
        });
    }

    function favoriteItemsForCatalog() {
        const q = qEl.value.trim().toLowerCase();
        const cat = String(catEl.value || '').trim().toLowerCase();
        const sub = String(subEl.value || '').trim().toLowerCase();

        return loadFavorites().filter((item) => {
            const name = String(item.name || '').toLowerCase();
            const slug = String(item.slug || '').toLowerCase();
            const emoji = String(item.emoji || '');
            const itemCat = String(item.category || '').toLowerCase();
            const itemSub = String(item.subcategory || '').toLowerCase();

            if (q && !(name.includes(q) || slug.includes(q) || emoji.includes(q))) {
                return false;
            }
            if (cat && itemCat !== cat) {
                return false;
            }
            if (sub && itemSub !== sub) {
                return false;
            }
            return true;
        }).map((item) => ({
            emoji: item.emoji,
            emoji_base: item.emoji,
            name: item.name || item.slug,
            slug: item.slug,
            category: item.category || '',
            subcategory: item.subcategory || '',
            supports_skin_tone: Boolean(item.supports_skin_tone),
            variants: Array.isArray(item.variants) ? item.variants : [],
        }));
    }

    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 (isFetching) return;
        isFetching = true;
        if (reset) {
            state.page = 1;
            state.items = [];
            grid.innerHTML = '';
        }

        updateHeroMode();

        if (isFavoritesOnlyEnabled()) {
            try {
                const allFavorites = favoriteItemsForCatalog();
                state.total = allFavorites.length;
                const start = (state.page - 1) * state.limit;
                const incoming = allFavorites.slice(start, start + state.limit);
                if (reset) state.items = [];
                incoming.forEach((item) => state.items.push(item));
                renderGrid(incoming, reset);
                updateStats();
                syncUrl();
                return;
            } finally {
                isFetching = false;
            }
        }

        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';
        try {
            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();
        } finally {
            isFetching = false;
        }
    }

    async function maybeAutoLoadNextPage() {
        if (isFetching) return;
        if (state.items.length >= state.total) return;
        state.page += 1;
        await fetchEmojis(false);
    }

    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;
        }

        const showLabels = isLabelsEnabled();
        items.forEach((item) => {
            const renderedEmoji = emojiWithTone(item);
            const favoriteActive = isFavoriteSlug(item.slug);
            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 = showLabels
                ? `
                    ${favoriteActive ? '<span class="absolute top-1.5 left-1.5 z-10 text-yellow-300 text-sm leading-none select-none pointer-events-none" title="Favorited">★</span>' : ''}
                    <a href="/emoji/${encodeURIComponent(item.slug)}" class="absolute inset-0 flex items-center justify-center pb-10">
                        <span class="emoji-glyph 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>
                `
                : `
                    ${favoriteActive ? '<span class="absolute top-1.5 left-1.5 z-10 text-yellow-300 text-sm leading-none select-none pointer-events-none" title="Favorited">★</span>' : ''}
                    <a href="/emoji/${encodeURIComponent(item.slug)}" class="absolute inset-0 flex items-center justify-center">
                        <span class="emoji-glyph leading-none" style="font-size:var(--emoji-size)">${esc(renderedEmoji)}</span>
                    </a>
                    <button type="button" class="copy-btn emoji-card-copy absolute top-1.5 right-1.5 w-7 h-7 rounded bg-black/35 hover:bg-brand-ocean/40 border border-white/20 text-[11px] text-gray-100 hover:text-white transition-colors" title="Copy emoji">⧉</button>
                `;
            renderEmojiGlyph(card.querySelector('.emoji-glyph'), renderedEmoji, { item });
            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}${isFavoritesOnlyEnabled() ? ' • Favorites' : ''}`;
        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));
    catMobileEl?.addEventListener('change', () => {
        fillSubcategories(subMobileEl, catMobileEl.value, '');
    });
    subMobileEl?.addEventListener('change', () => {
        // no-op; applied explicitly via button for better mobile UX
    });
    mobileFiltersOpenEl?.addEventListener('click', openMobileFilters);
    mobileFiltersCloseEl?.addEventListener('click', closeMobileFilters);
    mobileFiltersBackdropEl?.addEventListener('click', closeMobileFilters);
    mobileFiltersResetEl?.addEventListener('click', () => {
        if (catMobileEl) catMobileEl.value = '';
        fillSubcategories(subMobileEl, '', '');
    });
    mobileFiltersApplyEl?.addEventListener('click', async () => {
        syncDesktopFiltersFromMobile();
        closeMobileFilters();
        await 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 () => {
        await maybeAutoLoadNextPage();
    });

    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) {
        gridSizeEl.max = '6';
        const initialDensity = localStorage.getItem(densityStorageKey) ?? '2';
        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));
    }
    gridSmallerMobileEl?.addEventListener('click', () => {
        const base = Number(localStorage.getItem(densityStorageKey) ?? gridSizeEl?.value ?? 2);
        applyGridDensity(base - 1);
    });
    gridBiggerMobileEl?.addEventListener('click', () => {
        const base = Number(localStorage.getItem(densityStorageKey) ?? gridSizeEl?.value ?? 2);
        applyGridDensity(base + 1);
    });
    labelsToggleEl?.addEventListener('click', () => {
        localStorage.setItem(labelsStorageKey, isLabelsEnabled() ? '0' : '1');
        applyLabelsToggleUI();
        fetchEmojis(true);
    });
    const onFavoritesOnlyToggle = async () => {
        const next = !isFavoritesOnlyEnabled();
        if (next && loadFavorites().length === 0) {
            showToast('No favorites yet');
            return;
        }
        setFavoritesOnlyEnabled(next);
        await fetchEmojis(true);
    };
    favoritesOnlyDesktopBtn?.addEventListener('click', onFavoritesOnlyToggle);
    favoritesOnlyMobileBtn?.addEventListener('click', onFavoritesOnlyToggle);
    favoritesClearEl?.addEventListener('click', () => {
        saveFavorites([]);
        renderFavorites();
        if (isFavoritesOnlyEnabled()) {
            setFavoritesOnlyEnabled(false);
            fetchEmojis(true);
        }
        showToast('Favorites cleared');
    });

    window.dewemojiHandleAndroidBack = () => {
        if (closeMobileFilters()) return true;
        if (keywordEditModal?.classList.contains('flex')) {
            closeKeywordEdit();
            return true;
        }
        return false;
    };
    window.addEventListener('keydown', (e) => {
        if (e.key === 'Escape') {
            if (closeMobileFilters()) return;
        }
    });

    (async () => {
        applyLabelsToggleUI();
        applyFavoritesOnlyUI();
        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();
        renderFavorites();
        updateHeroMode();
        if (catalogScrollEl) {
            catalogScrollEl.addEventListener('scroll', () => {
                const remaining = catalogScrollEl.scrollHeight - catalogScrollEl.scrollTop - catalogScrollEl.clientHeight;
                if (remaining <= AUTOLOAD_THRESHOLD_PX) {
                    maybeAutoLoadNextPage();
                }
            }, { passive: true });
        }

        if (gridSentinel && 'IntersectionObserver' in window) {
            autoLoadObserver = new IntersectionObserver(async (entries) => {
                const first = entries[0];
                if (!first?.isIntersecting) return;
                await maybeAutoLoadNextPage();
            }, { root: catalogScrollEl || null, rootMargin: '500px 0px' });
            autoLoadObserver.observe(gridSentinel);
        }
        lucide.createIcons();
    })();
})();
</script>
@endpush
