(function () {
    'use strict';

    if (window.__melonOnboardingInitialized) return;
    window.__melonOnboardingInitialized = true;

    const STORAGE_KEY = 'melonlite:onboarding:v1';
    const SNOOZE_MS = 1000 * 60 * 60 * 24;

    const steps = [
        {
            icon: 'fa-solid fa-play',
            title: '음악은 어디서든 계속 재생됩니다',
            body: '곡 목록의 재생 버튼을 누르면 하단 플레이어에서 재생됩니다. 페이지를 이동해도 PJAX 구조 안에서는 재생 상태가 유지됩니다.',
            href: 'index.php?view=all',
            action: '전체 음악 보기'
        },
        {
            icon: 'fa-solid fa-magnifying-glass',
            title: '검색과 필터로 빠르게 찾기',
            body: '곡명, 아티스트, 앨범, 가사를 검색하고 장르, 연도, 태그 필터로 원하는 곡을 좁힐 수 있습니다.',
            href: 'search.php',
            action: '검색 열기'
        },
        {
            icon: 'fa-solid fa-list',
            title: '플레이리스트와 좋아요',
            body: '좋아요로 자주 듣는 곡을 모으고, 플레이리스트로 상황에 맞는 음악 목록을 만들 수 있습니다.',
            href: 'playlists.php',
            action: '플레이리스트 보기'
        },
        {
            icon: 'fa-solid fa-music',
            title: '가사 보기와 직접 등록',
            body: '전체화면 플레이어와 곡 상세에서 가사를 확인할 수 있습니다. 가사가 없는 곡은 직접 등록하거나 수정할 수 있습니다.',
            href: 'help.php',
            action: '도움말 보기'
        },
        {
            icon: 'fa-solid fa-sliders',
            title: '설정, 피드백, 서비스 상태',
            body: '사용자 설정에서 화면과 플레이어 동작을 조정하고, 문제가 있으면 피드백 또는 서비스 상태 페이지를 확인하세요.',
            href: 'user_settings.php',
            action: '설정 열기'
        }
    ];

    let currentStep = 0;

    function basePath() {
        return window.APP_BASE_PATH || window.APP_ROOT_PATH || './';
    }

    function readState() {
        try {
            const raw = localStorage.getItem(STORAGE_KEY);
            return raw ? JSON.parse(raw) : {};
        } catch (error) {
            return {};
        }
    }

    function writeState(next) {
        try {
            localStorage.setItem(STORAGE_KEY, JSON.stringify(next || {}));
        } catch (error) {
            /* localStorage may be blocked. The modal still works for this session. */
        }
    }

    function shouldSkipAutoOpen() {
        const path = window.location.pathname || '';
        if (/\/admin\//i.test(path) || /\/(login|logout|setup_admin)\.php$/i.test(path)) return true;
        if (document.body.classList.contains('modal-open') || document.body.classList.contains('guest-preview-ended')) return true;

        const state = readState();
        if (state.dismissed) return true;
        if (state.snoozeUntil && Date.now() < Number(state.snoozeUntil)) return true;
        return false;
    }

    function ensureModal() {
        let modal = document.getElementById('onboarding-modal');
        if (modal) return modal;

        modal = document.createElement('div');
        modal.id = 'onboarding-modal';
        modal.className = 'onboarding-modal-overlay modal-overlay';
        modal.hidden = true;
        modal.setAttribute('aria-hidden', 'true');
        modal.innerHTML = [
            '<section class="onboarding-card" role="dialog" aria-modal="true" aria-labelledby="onboarding-title">',
            '  <button type="button" class="modal-close-btn onboarding-close" data-onboarding-close aria-label="온보딩 닫기"><i class="fas fa-times"></i></button>',
            '  <div class="onboarding-step-icon" id="onboarding-step-icon" aria-hidden="true"></div>',
            '  <div class="onboarding-step-count" id="onboarding-step-count"></div>',
            '  <h2 id="onboarding-title"></h2>',
            '  <p id="onboarding-body"></p>',
            '  <div class="onboarding-progress" aria-hidden="true" id="onboarding-progress"></div>',
            '  <div class="onboarding-actions">',
            '    <button type="button" class="btn btn-secondary" data-onboarding-prev>이전</button>',
            '    <a class="btn btn-secondary" id="onboarding-action-link" href="help.php">관련 기능 열기</a>',
            '    <button type="button" class="btn btn-primary" data-onboarding-next>다음</button>',
            '  </div>',
            '  <div class="onboarding-secondary-actions">',
            '    <button type="button" class="btn btn-secondary btn-sm" data-onboarding-later>나중에 보기</button>',
            '    <button type="button" class="btn btn-secondary btn-sm" data-onboarding-never>다시 보지 않기</button>',
            '  </div>',
            '</section>'
        ].join('');
        document.body.appendChild(modal);
        return modal;
    }

    function renderStep() {
        const step = steps[currentStep] || steps[0];
        const modal = ensureModal();
        const icon = modal.querySelector('#onboarding-step-icon');
        const count = modal.querySelector('#onboarding-step-count');
        const title = modal.querySelector('#onboarding-title');
        const body = modal.querySelector('#onboarding-body');
        const action = modal.querySelector('#onboarding-action-link');
        const progress = modal.querySelector('#onboarding-progress');
        const prev = modal.querySelector('[data-onboarding-prev]');
        const next = modal.querySelector('[data-onboarding-next]');

        if (icon) icon.innerHTML = `<i class="${step.icon}" aria-hidden="true"></i>`;
        if (count) count.textContent = `${currentStep + 1} / ${steps.length}`;
        if (title) title.textContent = step.title;
        if (body) body.textContent = step.body;
        if (action) {
            action.textContent = step.action;
            const linkBase = new URL(basePath(), window.location.origin).href;
            action.href = new URL(step.href, linkBase).toString();
        }
        if (prev) prev.disabled = currentStep === 0;
        if (next) next.textContent = currentStep === steps.length - 1 ? '시작하기' : '다음';
        if (progress) {
            progress.innerHTML = steps.map(function (_, index) {
                return `<span class="${index <= currentStep ? 'is-active' : ''}"></span>`;
            }).join('');
        }
    }

    function openOnboarding(stepIndex) {
        currentStep = Number.isFinite(stepIndex) ? Math.max(0, Math.min(steps.length - 1, stepIndex)) : 0;
        const modal = ensureModal();
        renderStep();
        modal.hidden = false;
        modal.style.display = 'flex';
        modal.setAttribute('aria-hidden', 'false');
        document.body.classList.add('modal-open', 'onboarding-modal-open');
    }

    function closeOnboarding() {
        const modal = document.getElementById('onboarding-modal');
        if (!modal) return;
        modal.hidden = true;
        modal.style.display = 'none';
        modal.setAttribute('aria-hidden', 'true');
        document.body.classList.remove('modal-open', 'onboarding-modal-open');
    }

    function finishOnboarding() {
        writeState({ dismissed: true, dismissedAt: Date.now() });
        closeOnboarding();
    }

    function snoozeOnboarding() {
        writeState({ snoozeUntil: Date.now() + SNOOZE_MS });
        closeOnboarding();
    }

    function maybeAutoOpen() {
        if (shouldSkipAutoOpen()) return;
        window.setTimeout(function () {
            if (!shouldSkipAutoOpen()) openOnboarding(0);
        }, 800);
    }

    document.addEventListener('click', function (event) {
        const openButton = event.target.closest('[data-onboarding-open], #help-open-onboarding');
        if (openButton) {
            event.preventDefault();
            openOnboarding(0);
            return;
        }

        if (event.target.closest('[data-onboarding-close]')) {
            event.preventDefault();
            snoozeOnboarding();
            return;
        }

        if (event.target.closest('[data-onboarding-later]')) {
            event.preventDefault();
            snoozeOnboarding();
            return;
        }

        if (event.target.closest('[data-onboarding-never]')) {
            event.preventDefault();
            finishOnboarding();
            return;
        }

        if (event.target.closest('[data-onboarding-prev]')) {
            event.preventDefault();
            currentStep = Math.max(0, currentStep - 1);
            renderStep();
            return;
        }

        if (event.target.closest('[data-onboarding-next]')) {
            event.preventDefault();
            if (currentStep >= steps.length - 1) {
                finishOnboarding();
                return;
            }
            currentStep += 1;
            renderStep();
            return;
        }

        const modal = document.getElementById('onboarding-modal');
        if (modal && event.target === modal) snoozeOnboarding();
    });

    document.addEventListener('keydown', function (event) {
        if (event.key === 'Escape' && document.body.classList.contains('onboarding-modal-open')) {
            snoozeOnboarding();
        }
    });

    document.addEventListener('DOMContentLoaded', maybeAutoOpen);
    document.addEventListener('melonlite:page-ready', function () {
        if (!document.getElementById('onboarding-modal')) maybeAutoOpen();
    });
})();
