(function () {
    'use strict';

    const STORAGE_KEY = 'melon_lite_home_sections_v27';
    const KNOWN_KEYS = [
        'today_recommend',
        'auto_mix',
        'recent_played',
        'recommendations',
        'recent_added',
        'popular',
        'liked',
        'playlists',
        'genre_tags',
        'auto_playlists',
        'listening_summary',
        'recent_frequent',
        'hidden_gems',
        'old_liked'
    ];

    function storageGet(key) {
        try { return window.localStorage.getItem(key); } catch (err) { return null; }
    }

    function storageSet(key, value) {
        try {
            window.localStorage.setItem(key, value);
            return true;
        } catch (err) {
            return false;
        }
    }

    function storageRemove(key) {
        try { window.localStorage.removeItem(key); } catch (err) {}
    }

    function parseConfig() {
        const raw = storageGet(STORAGE_KEY);
        if (!raw) return { order: [], hidden: [] };
        try {
            const parsed = JSON.parse(raw);
            if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) throw new Error('invalid');
            return {
                order: Array.isArray(parsed.order) ? parsed.order.filter(isKnownKey) : [],
                hidden: Array.isArray(parsed.hidden) ? parsed.hidden.filter(isKnownKey) : []
            };
        } catch (err) {
            storageRemove(STORAGE_KEY);
            return { order: [], hidden: [] };
        }
    }

    function saveConfig(config) {
        const clean = normalizeConfig(config, currentKeys());
        storageSet(STORAGE_KEY, JSON.stringify(clean));
        return clean;
    }

    function isKnownKey(key) {
        return KNOWN_KEYS.indexOf(String(key || '')) !== -1;
    }

    function currentRoot() {
        return document.querySelector('[data-home-customize-root]');
    }

    function currentList() {
        const root = currentRoot();
        return root ? root.querySelector('[data-home-section-list]') : null;
    }

    function sectionNodes() {
        const root = currentRoot();
        if (!root) return [];
        return Array.from(root.querySelectorAll('[data-home-section]')).filter(function (node) {
            return isKnownKey(node.getAttribute('data-home-section'));
        });
    }

    function currentKeys() {
        return sectionNodes().map(function (node) { return node.getAttribute('data-home-section'); });
    }

    function normalizeConfig(config, keys) {
        const available = keys.filter(isKnownKey);
        const seen = new Set();
        const order = [];
        (config.order || []).forEach(function (key) {
            if (available.indexOf(key) === -1 || seen.has(key)) return;
            seen.add(key);
            order.push(key);
        });
        available.forEach(function (key) {
            if (!seen.has(key)) order.push(key);
        });
        const hidden = Array.from(new Set((config.hidden || []).filter(function (key) {
            return available.indexOf(key) !== -1;
        })));
        return { order: order, hidden: hidden };
    }

    function sectionLabel(node) {
        const label = String(node.getAttribute('data-home-label') || '').trim();
        if (label) return label;
        const title = node.querySelector('.section-title');
        return title ? title.textContent.trim() : node.getAttribute('data-home-section');
    }

    function sectionMap() {
        const map = {};
        sectionNodes().forEach(function (node) {
            map[node.getAttribute('data-home-section')] = node;
        });
        return map;
    }

    function announce(message, type) {
        if (window.showToast) {
            window.showToast(message, type || 'info');
            return;
        }
        const status = document.querySelector('[data-home-editor-status]');
        if (status) status.textContent = message;
    }

    function applyHomeConfig() {
        const list = currentList();
        if (!list) return;
        const keys = currentKeys();
        const config = normalizeConfig(parseConfig(), keys);
        const map = sectionMap();
        config.order.forEach(function (key) {
            if (map[key]) list.appendChild(map[key]);
        });
        let visibleCount = 0;
        sectionNodes().forEach(function (node) {
            const key = node.getAttribute('data-home-section');
            const hidden = config.hidden.indexOf(key) !== -1;
            node.hidden = hidden;
            node.classList.toggle('is-home-section-hidden', hidden);
            if (!hidden) visibleCount += 1;
        });
        const empty = currentRoot().querySelector('[data-home-empty]');
        if (empty) empty.hidden = visibleCount > 0;
        renderEditor(config);
    }

    function itemTemplate(key, node, config, index, total) {
        const checked = config.hidden.indexOf(key) === -1 ? 'checked' : '';
        const upDisabled = index === 0 ? 'disabled' : '';
        const downDisabled = index >= total - 1 ? 'disabled' : '';
        return '' +
            '<article class="home-editor-item" data-home-editor-item="' + escapeHtml(key) + '">' +
                '<label class="home-editor-toggle">' +
                    '<input type="checkbox" data-home-section-toggle="' + escapeHtml(key) + '" ' + checked + '>' +
                    '<span>' + escapeHtml(sectionLabel(node)) + '</span>' +
                '</label>' +
                '<div class="home-editor-move">' +
                    '<button type="button" class="btn btn-secondary btn-sm" data-home-move="up" data-home-section-key="' + escapeHtml(key) + '" ' + upDisabled + ' aria-label="위로 이동"><i class="fa-solid fa-arrow-up"></i></button>' +
                    '<button type="button" class="btn btn-secondary btn-sm" data-home-move="down" data-home-section-key="' + escapeHtml(key) + '" ' + downDisabled + ' aria-label="아래로 이동"><i class="fa-solid fa-arrow-down"></i></button>' +
                '</div>' +
            '</article>';
    }

    function renderEditor(config) {
        const panel = document.querySelector('[data-home-customizer]');
        const list = document.querySelector('[data-home-editor-list]');
        if (!panel || !list) return;
        const map = sectionMap();
        const clean = normalizeConfig(config || parseConfig(), currentKeys());
        list.innerHTML = clean.order.map(function (key, index) {
            return map[key] ? itemTemplate(key, map[key], clean, index, clean.order.length) : '';
        }).join('');
    }

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

    function togglePanel(forceOpen) {
        const panel = document.querySelector('[data-home-customizer]');
        if (!panel) return;
        panel.hidden = typeof forceOpen === 'boolean' ? !forceOpen : !panel.hidden;
        if (!panel.hidden) {
            renderEditor(parseConfig());
            panel.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
        }
    }

    function moveSection(key, direction) {
        const config = normalizeConfig(parseConfig(), currentKeys());
        const index = config.order.indexOf(key);
        if (index === -1) return;
        const next = direction === 'up' ? index - 1 : index + 1;
        if (next < 0 || next >= config.order.length) return;
        const tmp = config.order[index];
        config.order[index] = config.order[next];
        config.order[next] = tmp;
        saveConfig(config);
        applyHomeConfig();
        announce('홈 섹션 순서를 저장했습니다.', 'success');
    }

    function setSectionVisible(key, visible) {
        const config = normalizeConfig(parseConfig(), currentKeys());
        const hidden = new Set(config.hidden);
        if (visible) hidden.delete(key);
        else hidden.add(key);
        config.hidden = Array.from(hidden);
        saveConfig(config);
        applyHomeConfig();
        announce('홈 섹션 표시 설정을 저장했습니다.', 'success');
    }

    function resetHomeConfig() {
        storageRemove(STORAGE_KEY);
        applyHomeConfig();
        announce('기본 홈 구성으로 복구했습니다.', 'success');
    }

    function bindHomeCustomizer() {
        const root = currentRoot();
        if (!root || root.dataset.homeCustomizerBound === '1') {
            if (root) applyHomeConfig();
            return;
        }
        root.dataset.homeCustomizerBound = '1';
        root.addEventListener('click', function (event) {
            const open = event.target.closest('[data-home-edit-open]');
            if (open) {
                event.preventDefault();
                togglePanel(true);
                return;
            }
            const close = event.target.closest('[data-home-edit-close]');
            if (close) {
                event.preventDefault();
                togglePanel(false);
                return;
            }
            const reset = event.target.closest('[data-home-reset]');
            if (reset) {
                event.preventDefault();
                resetHomeConfig();
                return;
            }
            const move = event.target.closest('[data-home-move]');
            if (move) {
                event.preventDefault();
                moveSection(move.getAttribute('data-home-section-key'), move.getAttribute('data-home-move'));
            }
        });
        root.addEventListener('change', function (event) {
            const control = event.target.closest('[data-home-section-toggle]');
            if (!control) return;
            setSectionVisible(control.getAttribute('data-home-section-toggle'), control.checked);
        });
        applyHomeConfig();
    }

    window.MelonLiteInitHomeCustomizer = bindHomeCustomizer;
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', bindHomeCustomizer);
    } else {
        bindHomeCustomizer();
    }
    document.addEventListener('melonlite:page-ready', bindHomeCustomizer);
})();
