class AvisionLevels {
    constructor() {
        this.levels = {
            1: { status: 'active', completed: false },
            2: { status: 'locked', completed: false, unlockedAt: null },
            3: { status: 'premium-locked', completed: false, purchased: false },
            4: { status: 'locked', completed: false }
        };
        this.countdownInterval = null;
        this.countdownDuration = 72 * 60 * 60 * 1000;
    }

    init() {
        this.loadProgress();
        this.renderAllLevels();
        this.setupEventListeners();
        this.checkCountdown();
    }

    loadProgress() {
        const saved = localStorage.getItem('avision_levels');
        if (saved) {
            try {
                const parsed = JSON.parse(saved);
                this.levels = { ...this.levels, ...parsed };
            } catch (e) {
                console.error('Failed to parse saved levels:', e);
            }
        }
    }

    saveProgress() {
        localStorage.setItem('avision_levels', JSON.stringify(this.levels));
    }

    renderAllLevels() {
        Object.keys(this.levels).forEach(levelNum => {
            this.updateLevelUI(parseInt(levelNum));
        });
    }

    updateLevelUI(levelNum) {
        const levelCard = document.querySelector(`[data-level="${levelNum}"]`);
        if (!levelCard) return;

        const level = this.levels[levelNum];
        
        levelCard.classList.remove('active', 'locked', 'done', 'premium-locked');
        
        if (level.completed) {
            levelCard.classList.add('done');
        } else {
            levelCard.classList.add(level.status);
        }

        const statusEl = levelCard.querySelector('.level-status');
        if (statusEl) {
            statusEl.classList.remove('active', 'locked', 'done', 'premium');
            
            if (level.completed) {
                statusEl.classList.add('done');
                statusEl.textContent = '✓ ' + window.avisionI18n.get(`level_${levelNum}_done`, 'Completed');
            } else if (level.status === 'premium-locked') {
                statusEl.classList.add('premium');
                statusEl.textContent = window.avisionI18n.get('level_3_premium');
            } else if (level.status === 'locked') {
                statusEl.classList.add('locked');
                statusEl.textContent = window.avisionI18n.get(`level_${levelNum}_locked`, 'Locked');
            } else {
                statusEl.classList.add('active');
                statusEl.textContent = window.avisionI18n.get('dashboard_status_improving', 'In Progress');
            }
        }

        const actionBtns = levelCard.querySelectorAll('.btn');
        actionBtns.forEach(btn => {
            btn.disabled = level.status === 'locked' || (level.status === 'premium-locked' && !level.purchased);
        });
    }

    setupEventListeners() {
        document.querySelectorAll('[data-action="verify-level"]').forEach(btn => {
            btn.addEventListener('click', (e) => this.handleVerify(e));
        });

        document.querySelectorAll('[data-action="unlock-premium"]').forEach(btn => {
            btn.addEventListener('click', (e) => this.handlePremiumUnlock(e));
        });

        const bonusHeader = document.querySelector('.bonus-header');
        if (bonusHeader) {
            bonusHeader.addEventListener('click', () => this.toggleBonus());
        }

        document.querySelectorAll('[data-action="copy-email"]').forEach(btn => {
            btn.addEventListener('click', (e) => this.handleCopyEmail(e));
        });

        document.querySelectorAll('[data-action="email-sent"]').forEach(btn => {
            btn.addEventListener('click', (e) => this.handleEmailSent(e));
        });

        document.querySelectorAll('[data-action="skip-level4"]').forEach(btn => {
            btn.addEventListener('click', () => this.handleSkipLevel4());
        });
    }

    async handleVerify(e) {
        const btn = e.currentTarget;
        const levelCard = btn.closest('[data-level]');
        const levelNum = parseInt(levelCard.dataset.level);

        if (this.levels[levelNum].status === 'locked') return;

        const originalText = btn.textContent;
        btn.innerHTML = '<span class="loading-spinner"></span>';
        btn.disabled = true;

        await this.simulateDelay(2500);

        this.completeLevel(levelNum);
        
        btn.textContent = '✓ ' + window.avisionI18n.get(`level_${levelNum}_done`, 'Completed');
        btn.disabled = true;
        btn.classList.remove('btn-primary');
        btn.classList.add('btn-secondary');

        window.triggerConfetti?.();

        if (levelNum === 1) {
            this.unlockLevel(2);
        }
    }

    completeLevel(levelNum) {
        this.levels[levelNum].completed = true;
        this.levels[levelNum].status = 'done';
        this.saveProgress();
        this.updateLevelUI(levelNum);

        const scoreMap = { 1: 55, 2: 70, 3: 85, 4: 100 };
        window.avisionScore?.updateScore(scoreMap[levelNum] || 55);

        window.avisionUtils?.sendWebhookToWordPress(levelNum, 'completed');
    }

    unlockLevel(levelNum) {
        if (levelNum === 3) return;
        
        this.levels[levelNum].status = 'active';
        this.levels[levelNum].unlockedAt = Date.now();
        this.saveProgress();
        this.updateLevelUI(levelNum);

        if (levelNum === 2) {
            this.startCountdown();
        }
    }

    startCountdown() {
        const countdownContainer = document.querySelector('.countdown-container');
        if (!countdownContainer) return;

        const unlockedAt = this.levels[2].unlockedAt;
        if (!unlockedAt) return;

        const endTime = unlockedAt + this.countdownDuration;
        
        this.countdownInterval = setInterval(() => {
            const remaining = endTime - Date.now();
            
            if (remaining <= 0) {
                clearInterval(this.countdownInterval);
                countdownContainer.style.display = 'none';
                this.levels[2].status = 'active';
                this.saveProgress();
                this.updateLevelUI(2);
                return;
            }

            const hours = Math.floor(remaining / (1000 * 60 * 60));
            const minutes = Math.floor((remaining % (1000 * 60 * 60)) / (1000 * 60));
            const seconds = Math.floor((remaining % (1000 * 60)) / 1000);

            const timerEl = countdownContainer.querySelector('.countdown-timer');
            if (timerEl) {
                timerEl.textContent = `${String(hours).padStart(2, '0')}h ${String(minutes).padStart(2, '0')}m ${String(seconds).padStart(2, '0')}s`;
            }
        }, 1000);
    }

    checkCountdown() {
        if (this.levels[2].unlockedAt && !this.levels[2].completed) {
            this.startCountdown();
        }
    }

    handlePremiumUnlock(e) {
        window.location.href = '/payment?type=dashboard&level=3';
    }

    toggleBonus() {
        const bonusSection = document.querySelector('.bonus-section');
        if (bonusSection) {
            bonusSection.classList.toggle('open');
        }
    }

    handleCopyEmail(e) {
        const btn = e.currentTarget;
        const textarea = document.querySelector('.email-template');
        if (textarea) {
            navigator.clipboard.writeText(textarea.value).then(() => {
                const originalText = btn.textContent;
                btn.textContent = window.avisionI18n.get('level_4_copied');
                setTimeout(() => {
                    btn.textContent = originalText;
                }, 2000);
            });
        }
    }

    handleEmailSent(e) {
        this.completeLevel(4);
        window.avisionChatbot?.addBotMessage(
            window.avisionI18n.get('chatbot_welcome', "Great job! Your webmaster kit email has been sent. Your SEO optimization is nearly complete!")
        );
    }

    handleSkipLevel4() {
        const bonusSection = document.querySelector('.bonus-section');
        if (bonusSection) {
            bonusSection.classList.remove('open');
        }
        
        window.avisionChatbot?.addBotMessage(
            "No problem! You can always come back to complete Level 4 later when you're ready."
        );
    }

    simulateDelay(ms) {
        return new Promise(resolve => setTimeout(resolve, ms));
    }
}

document.addEventListener('DOMContentLoaded', () => {
    window.avisionLevels = new AvisionLevels();
    if (document.querySelector('[data-level]')) {
        window.avisionLevels.init();
    }
});
