(function () {
    if (window.__MELON_LITE_SEARCH_INITED) return;
    window.__MELON_LITE_SEARCH_INITED = true;

    const RECENT_KEY = 'melon_lite_recent_searches_v20';
    const MAX_RECENT = 10;

    function safeJsonParse(value, fallback) {
        try {
            const parsed = JSON.parse(value);
            return parsed || fallback;
        } catch (err) {
            return fallback;
        }
    }

    function getRecentSearches() {
        const items = safeJsonParse(localStorage.getItem(RECENT_KEY) || '[]', []);
        return Array.isArray(items) ? items : [];
    }

    function saveRecentSearch(query) {
        query = String(query || '').trim().slice(0, 120);
        if (!query) return;
        const now = Date.now();
        const map = new Map();
        getRecentSearches().forEach(function (item) {
            if (!item || !item.q) return;
            map.set(item.q, {
                q: item.q,
                count: Math.max(1, parseInt(item.count, 10) || 1),
                at: parseInt(item.at, 10) || 0
            });
        });
        const existing = map.get(query) || { q: query, count: 0, at: 0 };
        existing.count += 1;
        existing.at = now;
        map.set(query, existing);
        const next = Array.from(map.values())
            .sort(function (a, b) { return b.at - a.at; })
            .slice(0, MAX_RECENT);
        try {
            localStorage.setItem(RECENT_KEY, JSON.stringify(next));
        } catch (err) {}
    }

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

    function makeAbsoluteUrl(url) {
        return new URL(url, window.location.origin + (window.APP_BASE_PATH || './')).href;
    }

    function ensureSuggestBox(form) {
        let box = form.querySelector('.quick-suggest-box');
        if (!box) {
            box = document.createElement('div');
            box.className = 'quick-suggest-box';
            box.hidden = true;
            form.appendChild(box);
        }
        return box;
    }

    function renderSuggestions(form, items) {
        const box = ensureSuggestBox(form);
        if (!items || items.length === 0) {
            box.hidden = true;
            box.innerHTML = '';
            return;
        }
        box.innerHTML = items.map(function (item) {
            const typeMap = { song: '곡', artist: '아티스트', album: '앨범', tag: '태그', playlist: '플레이리스트' };
            const playData = item.type === 'song' ? [
                'data-play-id="' + escapeHtml(item.play_id) + '"',
                'data-title="' + escapeHtml(item.title) + '"',
                'data-artist="' + escapeHtml(item.artist) + '"',
                'data-album="' + escapeHtml(item.album) + '"',
                'data-duration="' + escapeHtml(item.duration || 0) + '"'
            ].join(' ') : '';
            return '<div class="quick-suggest-item" data-url="' + escapeHtml(item.url) + '" ' + playData + '>' +
                '<span class="suggest-type">' + escapeHtml(typeMap[item.type] || item.type) + '</span>' +
                '<strong>' + escapeHtml(item.label) + '</strong>' +
                '<small>' + escapeHtml(item.sub || '') + '</small>' +
                (item.type === 'song' ? '<button type="button" class="suggest-play-btn" title="바로 재생"><i class="fas fa-play"></i></button>' : '') +
                '</div>';
        }).join('');
        box.hidden = false;
    }

    function bindQuickSearchForm(form) {
        if (!form || form.dataset.searchBound === '1') return;
        form.dataset.searchBound = '1';
        const input = form.querySelector('input[type="search"], input[name="q"], input[name="search"]');
        if (!input) return;
        let timer = null;
        let controller = null;

        input.addEventListener('input', function () {
            const q = input.value.trim();
            clearTimeout(timer);
            if (controller) controller.abort();
            if (q.length < 2) {
                renderSuggestions(form, []);
                return;
            }
            timer = setTimeout(function () {
                controller = new AbortController();
                fetch((window.APP_BASE_PATH || './') + 'api/search_suggest.php?q=' + encodeURIComponent(q), {
                    credentials: 'same-origin',
                    signal: controller.signal,
                    headers: { 'Accept': 'application/json' }
                })
                    .then(function (res) { return res.json(); })
                    .then(function (data) {
                        if (!data.success) throw new Error(data.message || 'suggest failed');
                        renderSuggestions(form, data.items || []);
                    })
                    .catch(function (err) {
                        if (err.name !== 'AbortError') renderSuggestions(form, []);
                    });
            }, 220);
        });

        form.addEventListener('submit', function () {
            saveRecentSearch(input.value);
        });

        form.addEventListener('click', function (event) {
            const play = event.target.closest('.suggest-play-btn');
            const item = event.target.closest('.quick-suggest-item');
            if (!item) return;
            event.preventDefault();
            event.stopPropagation();
            if (play && item.dataset.playId && window.AppPlayer && window.AppPlayer.playTrackObject) {
                saveRecentSearch(input.value);
                window.AppPlayer.playTrackObject({
                    id: item.dataset.playId,
                    title: item.dataset.title || '',
                    artist: item.dataset.artist || '',
                    album: item.dataset.album || '',
                    duration: parseInt(item.dataset.duration, 10) || 0
                });
                ensureSuggestBox(form).hidden = true;
                return;
            }
            const url = item.dataset.url;
            if (url) {
                saveRecentSearch(input.value);
                if (window.MelonLiteNavigate) window.MelonLiteNavigate(new URL(makeAbsoluteUrl(url)), { push: true });
                else window.location.href = makeAbsoluteUrl(url);
            }
        });

        document.addEventListener('click', function (event) {
            if (!form.contains(event.target)) ensureSuggestBox(form).hidden = true;
        });
    }

    function renderRecentPanel() {
        const panel = document.querySelector('[data-recent-search-panel]');
        const list = document.querySelector('[data-recent-search-list]');
        if (!panel || !list) return;
        const items = getRecentSearches();
        if (items.length === 0) {
            panel.hidden = true;
            list.innerHTML = '';
            return;
        }
        panel.hidden = false;
        list.innerHTML = items.map(function (item) {
            return '<a class="recent-search-chip" href="search.php?q=' + encodeURIComponent(item.q) + '">' +
                escapeHtml(item.q) + '<small>' + escapeHtml(item.count || 1) + '</small></a>';
        }).join('');
    }

    function initSearchPage() {
        document.querySelectorAll('.sidebar-search-form, .quick-search-form, .enhanced-search-form').forEach(bindQuickSearchForm);
        renderRecentPanel();
        const pageForm = document.querySelector('[data-search-form]');
        if (pageForm && pageForm.dataset.submitRecentBound !== '1') {
            pageForm.dataset.submitRecentBound = '1';
            pageForm.addEventListener('submit', function () {
                const input = pageForm.querySelector('input[name="q"]');
                if (input) saveRecentSearch(input.value);
            });
        }
        const clear = document.querySelector('[data-clear-recent-searches]');
        if (clear && clear.dataset.bound !== '1') {
            clear.dataset.bound = '1';
            clear.addEventListener('click', function () {
                try { localStorage.removeItem(RECENT_KEY); } catch (err) {}
                renderRecentPanel();
            });
        }
    }

    window.MelonLiteInitSearchPage = initSearchPage;
    document.addEventListener('DOMContentLoaded', initSearchPage);
    document.addEventListener('melonlite:page-ready', initSearchPage);
})();

