/**
 * ============================================================================
 * ARTICLE BUILDER - MAIN APPLICATION
 * ============================================================================
 *
 * Handles all application logic including:
 * - Tab navigation
 * - Prompt loading and rendering
 * - User input management
 * - Placeholder replacement
 * - Clipboard operations
 *
 * @author    @maurosicard
 * @version   2.0
 * ============================================================================
 */

class ArticleBuilderApp {
    constructor() {
        // Application state
        this.state = {
            currentStep: 0,
            userInputs: {},
            loadedPrompts: {},
            promptCache: {},
            completedSteps: new Set(),  // Track which steps are completed
            promptResults: {}  // Store prompt results for each step
        };

        // DOM element references
        this.elements = {
            tabs: document.querySelectorAll('.tab'),
            stepContents: document.querySelectorAll('.step-content'),
            promptDisplays: document.querySelectorAll('.prompt-display')
        };

        // Initialize the application
        this.init();
    }

    /**
     * Initialize application
     * Sets up event listeners and loads initial state
     */
    init() {
        console.log('🚀 Article Builder initializing...');

        // Setup event listeners
        this.setupTabNavigation();
        this.setupInputHandlers();
        this.setupCopyButtons();
        this.setupClearDataButton();

        // Load user inputs from localStorage if available
        this.loadFromStorage();

        // Render initial step
        this.renderCurrentStep();

        console.log('✅ Article Builder ready');
    }

    /**
     * Setup tab navigation event listeners
     */
    setupTabNavigation() {
        this.elements.tabs.forEach((tab, index) => {
            tab.addEventListener('click', () => {
                this.navigateToStep(index);
            });
        });

        // Navigation buttons (Previous/Next)
        document.querySelectorAll('[data-action="next-step"]').forEach(btn => {
            btn.addEventListener('click', () => this.nextStep());
        });

        document.querySelectorAll('[data-action="prev-step"]').forEach(btn => {
            btn.addEventListener('click', () => this.previousStep());
        });
    }

    /**
     * Setup input field change handlers
     */
    setupInputHandlers() {
        // Article title input
        const titleInput = document.getElementById('article-title');
        if (titleInput) {
            titleInput.addEventListener('input', (e) => {
                this.updateUserInput('articleTitle', e.target.value);
                this.checkStepCompletion(0);  // Check if Step 0 is completed
            });
        }

        // Article context textarea
        const contextInput = document.getElementById('article-context');
        if (contextInput) {
            contextInput.addEventListener('input', (e) => {
                this.updateUserInput('articleContext', e.target.value);
            });
        }

        // Prompt result inputs (Steps 1-9)
        for (let i = 1; i <= 9; i++) {
            const resultInput = document.getElementById(`prompt-result-${i}`);
            if (resultInput) {
                resultInput.addEventListener('input', (e) => {
                    this.updatePromptResult(i, e.target.value);
                });
            }
        }
    }

    /**
     * Setup copy to clipboard buttons
     */
    setupCopyButtons() {
        document.querySelectorAll('[data-action="copy-prompt"]').forEach(btn => {
            btn.addEventListener('click', (e) => {
                const stepElement = e.target.closest('.step-content');
                const stepNumber = parseInt(stepElement.dataset.step);
                const button = e.currentTarget;
                const promptIndex = button.getAttribute('data-prompt-index');
                this.copyPromptToClipboard(stepNumber, promptIndex);
            });
        });

        // Setup paste from clipboard buttons
        document.querySelectorAll('[data-action="paste-prompt"]').forEach(btn => {
            btn.addEventListener('click', async (e) => {
                e.preventDefault();
                const button = e.currentTarget;
                const targetId = button.getAttribute('data-target');
                console.log('Paste button clicked, target:', targetId);
                await this.pasteFromClipboard(targetId);
            });
        });
    }

    /**
     * Setup clear all data button
     */
    setupClearDataButton() {
        const clearBtn = document.querySelector('[data-action="clear-all-data"]');
        const modal = document.getElementById('clearDataModal');
        const cancelBtn = document.getElementById('modalCancelBtn');
        const confirmBtn = document.getElementById('modalConfirmBtn');

        if (clearBtn && modal) {
            // Show modal when clear button is clicked
            clearBtn.addEventListener('click', () => {
                this.showModal();
            });

            // Hide modal when cancel is clicked
            if (cancelBtn) {
                cancelBtn.addEventListener('click', () => {
                    this.hideModal();
                });
            }

            // Clear data and hide modal when confirm is clicked
            if (confirmBtn) {
                confirmBtn.addEventListener('click', () => {
                    this.clearAllData();
                    this.hideModal();
                });
            }

            // Close modal when clicking outside the modal content
            modal.addEventListener('click', (e) => {
                if (e.target === modal) {
                    this.hideModal();
                }
            });
        }
    }

    /**
     * Navigate to a specific step
     * @param {number} stepNumber - Step to navigate to (0-7)
     */
    navigateToStep(stepNumber) {
        if (stepNumber === this.state.currentStep) return;

        // Update state
        this.state.currentStep = stepNumber;

        // Update UI
        this.updateTabStates();
        this.updateStepContent();
        this.renderCurrentStep();

        // Scroll the active tab into view (for mobile carousel)
        this.scrollActiveTabIntoView(stepNumber);

        // Smooth scroll to top
        window.scrollTo({ top: 0, behavior: 'smooth' });
    }

    /**
     * Scroll the active tab into view on mobile
     * @param {number} stepNumber - Step number to scroll to
     */
    scrollActiveTabIntoView(stepNumber) {
        const activeTab = document.querySelector(`.tab[data-step="${stepNumber}"]`);
        const tabsContainer = document.querySelector('.tabs');

        if (activeTab && tabsContainer) {
            // Calculate scroll position to center the tab
            const containerWidth = tabsContainer.offsetWidth;
            const tabLeft = activeTab.offsetLeft;
            const tabWidth = activeTab.offsetWidth;
            const scrollPosition = tabLeft - (containerWidth / 2) + (tabWidth / 2);

            // Smooth scroll to the calculated position
            tabsContainer.scrollTo({
                left: scrollPosition,
                behavior: 'smooth'
            });
        }
    }

    /**
     * Navigate to next step
     */
    nextStep() {
        if (this.state.currentStep < 9) {
            this.navigateToStep(this.state.currentStep + 1);
        }
    }

    /**
     * Navigate to previous step
     */
    previousStep() {
        if (this.state.currentStep > 0) {
            this.navigateToStep(this.state.currentStep - 1);
        }
    }

    /**
     * Update tab active states
     */
    updateTabStates() {
        this.elements.tabs.forEach((tab, index) => {
            if (index === this.state.currentStep) {
                tab.classList.add('active');
            } else {
                tab.classList.remove('active');
            }
        });
    }

    /**
     * Update step content visibility
     */
    updateStepContent() {
        this.elements.stepContents.forEach((content, index) => {
            if (index === this.state.currentStep) {
                content.classList.add('active');
            } else {
                content.classList.remove('active');
            }
        });
    }

    /**
     * Update user input and save to storage
     * @param {string} key - Input identifier
     * @param {string} value - Input value
     */
    updateUserInput(key, value) {
        this.state.userInputs[key] = value;
        this.saveToStorage();

        // Re-render prompts that depend on this input
        this.rerenderDependentPrompts(key);
    }

    /**
     * Update prompt result and check completion
     * @param {number} stepNumber - Step number
     * @param {string} value - Result value
     */
    updatePromptResult(stepNumber, value) {
        this.state.promptResults[stepNumber] = value;
        this.checkStepCompletion(stepNumber);
        this.saveToStorage();
    }

    /**
     * Check if a step is completed and update check icon
     * @param {number} stepNumber - Step to check
     */
    checkStepCompletion(stepNumber) {
        let isCompleted = false;

        if (stepNumber === 0) {
            // Step 0 is completed if article title is filled
            isCompleted = this.state.userInputs.articleTitle?.trim().length > 0;
        } else {
            // Steps 1-9 are completed if prompt result is filled
            isCompleted = this.state.promptResults[stepNumber]?.trim().length > 0;
        }

        // Update completion state
        if (isCompleted) {
            this.state.completedSteps.add(stepNumber);
        } else {
            this.state.completedSteps.delete(stepNumber);
        }

        // Update check icon visibility
        this.updateCheckIcon(stepNumber, isCompleted);
        this.saveToStorage();
    }

    /**
     * Update check icon visibility for a step
     * @param {number} stepNumber - Step number
     * @param {boolean} show - Whether to show the icon
     */
    updateCheckIcon(stepNumber, show) {
        const tab = document.querySelector(`.tab[data-step="${stepNumber}"]`);
        if (tab) {
            const checkIcon = tab.querySelector('.tab-check-icon');
            if (checkIcon) {
                checkIcon.style.display = show ? 'inline' : 'none';
            }
        }
    }

    /**
     * Check if a step's dependencies are met
     * @param {number} stepNumber - Step to check
     * @returns {boolean} Whether dependencies are met
     */
    isStepUnlocked(stepNumber) {
        const stepConfig = PROMPT_CONFIG.getStep(stepNumber);
        if (!stepConfig || !stepConfig.requiredSteps) return true;

        // Check if all required steps are completed
        return stepConfig.requiredSteps.every(reqStep =>
            this.state.completedSteps.has(reqStep)
        );
    }

    /**
     * Re-render prompts that use a specific input
     * @param {string} inputKey - The input that changed
     */
    rerenderDependentPrompts(inputKey) {
        PROMPT_CONFIG.getPromptSteps().forEach(step => {
            if (step.dependencies && step.dependencies.includes(inputKey)) {
                this.renderPrompt(parseInt(step.number));
            }
        });
    }

    /**
     * Render current step
     * Loads and displays prompt if applicable
     */
    async renderCurrentStep() {
        const stepConfig = PROMPT_CONFIG.getStep(this.state.currentStep);

        if (!stepConfig) {
            console.error('Invalid step:', this.state.currentStep);
            return;
        }

        // If step has a prompt, load and render it
        if (stepConfig.hasPrompt) {
            await this.renderPrompt(this.state.currentStep);
        }
    }

    /**
     * Load prompt from .md file
     * @param {string} promptFile - Path to prompt file
     * @returns {Promise<string>} Prompt content
     */
    async loadPromptFile(promptFile) {
        // Return cached version if available
        if (this.state.promptCache[promptFile]) {
            return this.state.promptCache[promptFile];
        }

        try {
            const response = await fetch(promptFile);

            if (!response.ok) {
                throw new Error(`HTTP ${response.status}: ${response.statusText}`);
            }

            const content = await response.text();

            // Cache the prompt
            this.state.promptCache[promptFile] = content;

            return content;
        } catch (error) {
            console.error(`Failed to load prompt file ${promptFile}:`, error);
            return `Error loading prompt file: ${promptFile}\n\nPlease ensure the file exists and the application is running on a web server.`;
        }
    }

    /**
     * Replace placeholders in prompt with user inputs
     * @param {string} template - Prompt template with placeholders
     * @param {object} placeholders - Mapping of placeholders to input keys
     * @returns {string} Rendered prompt
     */
    replacePlaceholders(template, placeholders) {
        let result = template;

        // Replace each placeholder with actual user input
        for (const [placeholder, inputKey] of Object.entries(placeholders)) {
            let value;

            // Special handling for prompt results - pull from promptResults
            if (inputKey === 'articleFocus') {
                value = this.state.promptResults[1] || placeholder;
            }
            else if (inputKey === 'researchTopic') {
                value = this.state.promptResults[2] || placeholder;
            }
            else if (inputKey === 'communityIntel') {
                value = this.state.promptResults[3] || placeholder;
            }
            else if (inputKey === 'seoQuestions') {
                value = this.state.promptResults[4] || placeholder;
            }
            else if (inputKey === 'articleContent') {
                value = this.state.promptResults[6] || placeholder;
            }
            // Special handling for articleContext - conditional formatting
            else if (inputKey === 'articleContext') {
                const contextValue = this.state.userInputs[inputKey] || '';
                if (contextValue.trim()) {
                    value = ` with the following context: "${contextValue}"`;
                } else {
                    value = '';
                }
            }
            // Default handling for other inputs
            else {
                value = this.state.userInputs[inputKey] || placeholder;
            }

            // Use global regex to replace all occurrences
            const regex = new RegExp(placeholder.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'g');
            result = result.replace(regex, value);
        }

        return result;
    }

    /**
     * Render prompt for a specific step
     * @param {number} stepNumber - Step number to render
     */
    async renderPrompt(stepNumber) {
        const stepConfig = PROMPT_CONFIG.getStep(stepNumber);

        if (!stepConfig || !stepConfig.hasPrompt) return;

        // Check if this step has dual prompts (e.g., Step 7)
        if (stepConfig.hasDualPrompts) {
            await this.renderDualPrompts(stepNumber);
            return;
        }

        // Find the prompt display element for this step
        const promptDisplay = document.querySelector(
            `.step-content[data-step="${stepNumber}"] .prompt-display`
        );

        if (!promptDisplay) {
            console.warn(`No prompt display found for step ${stepNumber}`);
            return;
        }

        // Check if dependencies are met
        const missingRequirements = this.getMissingRequirements(stepNumber);

        if (missingRequirements.length > 0) {
            // Show error message if requirements not met
            this.showRequirementsError(promptDisplay, missingRequirements);
            return;
        }

        // Show loading state
        promptDisplay.textContent = 'Loading prompt...';
        promptDisplay.classList.add('loading');
        promptDisplay.classList.remove('error');

        // Load the prompt file
        const promptTemplate = await this.loadPromptFile(stepConfig.promptFile);

        // Replace placeholders with user inputs
        let renderedPrompt = this.replacePlaceholders(
            promptTemplate,
            stepConfig.placeholders || {}
        );

        // Special handling for Step 6 (Generate Article): append Article Structure if provided
        if (stepNumber === 6 && this.state.promptResults[5] && this.state.promptResults[5].trim().length > 0) {
            renderedPrompt += '\n\n[SPECIAL USER REQUEST]\nThe user is requesting to follow this specific article structure, so please adhere to that:\n\n' + this.state.promptResults[5];
        }

        // Update the display
        promptDisplay.textContent = renderedPrompt;
        promptDisplay.classList.remove('loading');

        // Store rendered prompt for clipboard
        this.state.loadedPrompts[stepNumber] = renderedPrompt;
    }

    /**
     * Render dual prompts for steps with two prompt displays
     * @param {number} stepNumber - Step number to render
     */
    async renderDualPrompts(stepNumber) {
        const stepConfig = PROMPT_CONFIG.getStep(stepNumber);

        // Find both prompt display elements
        const promptDisplay1 = document.querySelector(
            `.step-content[data-step="${stepNumber}"] .prompt-display[data-prompt-index="0"]`
        );
        const promptDisplay2 = document.querySelector(
            `.step-content[data-step="${stepNumber}"] .prompt-display[data-prompt-index="1"]`
        );

        if (!promptDisplay1 || !promptDisplay2) {
            console.warn(`Dual prompt displays not found for step ${stepNumber}`);
            return;
        }

        // Check if dependencies are met
        const missingRequirements = this.getMissingRequirements(stepNumber);

        if (missingRequirements.length > 0) {
            // Show error message in both displays
            this.showRequirementsError(promptDisplay1, missingRequirements);
            this.showRequirementsError(promptDisplay2, missingRequirements);
            return;
        }

        // Show loading state for both
        promptDisplay1.textContent = 'Loading prompt...';
        promptDisplay1.classList.add('loading');
        promptDisplay1.classList.remove('error');

        promptDisplay2.textContent = 'Loading prompt...';
        promptDisplay2.classList.add('loading');
        promptDisplay2.classList.remove('error');

        // Load both prompt files
        const promptTemplate1 = await this.loadPromptFile(stepConfig.promptFile);
        const promptTemplate2 = await this.loadPromptFile(stepConfig.promptFile2);

        // Replace placeholders with user inputs for both prompts
        const renderedPrompt1 = this.replacePlaceholders(
            promptTemplate1,
            stepConfig.placeholders || {}
        );
        const renderedPrompt2 = this.replacePlaceholders(
            promptTemplate2,
            stepConfig.placeholders || {}
        );

        // Update both displays
        promptDisplay1.textContent = renderedPrompt1;
        promptDisplay1.classList.remove('loading');

        promptDisplay2.textContent = renderedPrompt2;
        promptDisplay2.classList.remove('loading');

        // Store both rendered prompts for clipboard
        if (!this.state.loadedPrompts[stepNumber]) {
            this.state.loadedPrompts[stepNumber] = {};
        }
        this.state.loadedPrompts[stepNumber][0] = renderedPrompt1;
        this.state.loadedPrompts[stepNumber][1] = renderedPrompt2;
    }

    /**
     * Get missing requirements for a step
     * @param {number} stepNumber - Step to check
     * @returns {array} Array of missing requirement descriptions
     */
    getMissingRequirements(stepNumber) {
        const stepConfig = PROMPT_CONFIG.getStep(stepNumber);
        const missing = [];

        if (!stepConfig || !stepConfig.requiredSteps) return missing;

        // Check each required step
        stepConfig.requiredSteps.forEach(reqStep => {
            if (!this.state.completedSteps.has(reqStep)) {
                const reqConfig = PROMPT_CONFIG.getStep(reqStep);
                if (reqStep === 0) {
                    missing.push('User Input (Article Title)');
                } else if (reqConfig) {
                    missing.push(`Step ${reqStep}: ${reqConfig.title} (Prompt Result)`);
                }
            }
        });

        return missing;
    }

    /**
     * Show requirements error in prompt display
     * @param {HTMLElement} promptDisplay - The prompt display element
     * @param {array} missingRequirements - Array of missing requirement descriptions
     */
    showRequirementsError(promptDisplay, missingRequirements) {
        promptDisplay.classList.add('error');
        promptDisplay.classList.remove('loading');

        const errorHTML = `
            <div class="error-content">
                <i class="bi bi-exclamation-circle-fill error-icon"></i>
                <strong>Missing Requirements</strong>
                To show this prompt, you must first complete:
                <ul>
                    ${missingRequirements.map(req => `<li>${req}</li>`).join('')}
                </ul>
            </div>
        `;

        promptDisplay.innerHTML = errorHTML;
    }

    /**
     * Update dependency text for current step
     */
    updateDependencyText() {
        const dependencyElement = document.querySelector(
            `.step-content[data-step="${this.state.currentStep}"] [data-dependencies]`
        );

        if (dependencyElement) {
            const depText = PROMPT_CONFIG.getDependencyText(this.state.currentStep);
            dependencyElement.innerHTML = depText;
        }
    }

    /**
     * Copy prompt to clipboard
     * @param {number} stepNumber - Step whose prompt to copy
     */
    async copyPromptToClipboard(stepNumber, promptIndex = null) {
        let prompt;

        // Check if this is a dual prompt step
        if (promptIndex !== null) {
            const prompts = this.state.loadedPrompts[stepNumber];
            prompt = prompts ? prompts[promptIndex] : null;
        } else {
            prompt = this.state.loadedPrompts[stepNumber];
        }

        if (!prompt) {
            console.error('No prompt available to copy');
            return;
        }

        try {
            await navigator.clipboard.writeText(prompt);

            // Visual feedback
            this.showCopyFeedback(stepNumber, promptIndex);
        } catch (error) {
            console.error('Failed to copy to clipboard:', error);

            // Fallback: select text
            this.fallbackCopy(stepNumber, promptIndex);
        }
    }

    /**
     * Paste from clipboard to prompt result textarea
     * @param {string} targetId - ID of the textarea to paste into
     */
    async pasteFromClipboard(targetId) {
        console.log('pasteFromClipboard called with targetId:', targetId);

        const textarea = document.getElementById(targetId);
        if (!textarea) {
            console.error('Target textarea not found:', targetId);
            return;
        }

        console.log('Textarea found:', textarea);

        try {
            console.log('Attempting to read from clipboard...');
            const text = await navigator.clipboard.readText();
            console.log('Clipboard text read successfully, length:', text.length);

            textarea.value = text;
            console.log('Text set to textarea');

            // Trigger the input event to update state and check completion
            const stepNumber = parseInt(targetId.split('-')[2]);
            console.log('Updating prompt result for step:', stepNumber);
            this.updatePromptResult(stepNumber, text);

            // Visual feedback
            this.showPasteFeedback(targetId);
            console.log('Paste complete!');
        } catch (error) {
            console.error('Failed to paste from clipboard:', error);
            alert('Unable to paste from clipboard. Please grant clipboard permissions or paste manually using Cmd/Ctrl+V');
        }
    }

    /**
     * Show visual feedback when text is pasted
     * @param {string} targetId - ID of the target textarea
     */
    showPasteFeedback(targetId) {
        const btn = document.querySelector(`[data-target="${targetId}"]`);
        if (!btn) return;

        const originalText = btn.innerHTML;
        btn.innerHTML = '<i class="bi bi-check-circle"></i> Pasted!';
        btn.classList.add('success');

        setTimeout(() => {
            btn.innerHTML = originalText;
            btn.classList.remove('success');
        }, 2000);
    }

    /**
     * Show visual feedback when prompt is copied
     * @param {number} stepNumber - Step number
     * @param {string|null} promptIndex - Prompt index for dual prompts
     */
    showCopyFeedback(stepNumber, promptIndex = null) {
        let selector = `.step-content[data-step="${stepNumber}"] [data-action="copy-prompt"]`;

        // If promptIndex is specified, target the specific button
        if (promptIndex !== null) {
            selector += `[data-prompt-index="${promptIndex}"]`;
        }

        const btn = document.querySelector(selector);

        if (!btn) return;

        const originalText = btn.innerHTML;
        btn.innerHTML = '<i class="bi bi-check-circle"></i> Copied!';
        btn.classList.add('success');

        setTimeout(() => {
            btn.innerHTML = originalText;
            btn.classList.remove('success');
        }, 2000);
    }

    /**
     * Fallback copy method using text selection
     * @param {number} stepNumber - Step number
     * @param {string|null} promptIndex - Prompt index for dual prompts
     */
    fallbackCopy(stepNumber, promptIndex = null) {
        let selector = `.step-content[data-step="${stepNumber}"] .prompt-display`;

        // If promptIndex is specified, target the specific display
        if (promptIndex !== null) {
            selector += `[data-prompt-index="${promptIndex}"]`;
        }

        const promptDisplay = document.querySelector(selector);

        if (!promptDisplay) return;

        const range = document.createRange();
        range.selectNodeContents(promptDisplay);

        const selection = window.getSelection();
        selection.removeAllRanges();
        selection.addRange(range);

        try {
            document.execCommand('copy');
            this.showCopyFeedback(stepNumber, promptIndex);
        } catch (error) {
            console.error('Fallback copy failed:', error);
        }

        selection.removeAllRanges();
    }

    /**
     * Save state to localStorage
     */
    saveToStorage() {
        try {
            // Save user inputs
            localStorage.setItem('articleBuilder_userInputs',
                JSON.stringify(this.state.userInputs)
            );

            // Save prompt results
            localStorage.setItem('articleBuilder_promptResults',
                JSON.stringify(this.state.promptResults)
            );

            // Save completed steps (convert Set to Array for JSON)
            localStorage.setItem('articleBuilder_completedSteps',
                JSON.stringify(Array.from(this.state.completedSteps))
            );
        } catch (error) {
            console.warn('Failed to save to localStorage:', error);
        }
    }

    /**
     * Load state from localStorage
     */
    loadFromStorage() {
        try {
            // Load user inputs
            const savedInputs = localStorage.getItem('articleBuilder_userInputs');
            if (savedInputs) {
                this.state.userInputs = JSON.parse(savedInputs);

                // Populate form fields
                const titleInput = document.getElementById('article-title');
                const contextInput = document.getElementById('article-context');

                if (titleInput && this.state.userInputs.articleTitle) {
                    titleInput.value = this.state.userInputs.articleTitle;
                }

                if (contextInput && this.state.userInputs.articleContext) {
                    contextInput.value = this.state.userInputs.articleContext;
                }

                // Check Step 0 completion
                this.checkStepCompletion(0);
            }

            // Load prompt results
            const savedResults = localStorage.getItem('articleBuilder_promptResults');
            if (savedResults) {
                this.state.promptResults = JSON.parse(savedResults);

                // Populate prompt result textareas
                for (let i = 1; i <= 9; i++) {
                    const resultInput = document.getElementById(`prompt-result-${i}`);
                    if (resultInput && this.state.promptResults[i]) {
                        resultInput.value = this.state.promptResults[i];
                        this.checkStepCompletion(i);
                    }
                }
            }

            // Load completed steps (convert Array back to Set)
            const savedCompleted = localStorage.getItem('articleBuilder_completedSteps');
            if (savedCompleted) {
                this.state.completedSteps = new Set(JSON.parse(savedCompleted));

                // Update all check icons
                this.state.completedSteps.forEach(stepNum => {
                    this.updateCheckIcon(stepNum, true);
                });
            }
        } catch (error) {
            console.warn('Failed to load from localStorage:', error);
        }
    }

    /**
     * Clear all builder data from localStorage and reset application state
     */
    clearAllData() {
        try {
            // Clear all localStorage items
            localStorage.removeItem('articleBuilder_userInputs');
            localStorage.removeItem('articleBuilder_promptResults');
            localStorage.removeItem('articleBuilder_completedSteps');

            // Reset application state
            this.state.userInputs = {};
            this.state.promptResults = {};
            this.state.completedSteps = new Set();

            // Clear all input fields
            const titleInput = document.getElementById('article-title');
            const contextInput = document.getElementById('article-context');

            if (titleInput) titleInput.value = '';
            if (contextInput) contextInput.value = '';

            // Clear all prompt result textareas
            for (let i = 1; i <= 9; i++) {
                const resultInput = document.getElementById(`prompt-result-${i}`);
                if (resultInput) resultInput.value = '';
            }

            // Hide all check icons
            document.querySelectorAll('.tab-check-icon').forEach(icon => {
                icon.style.display = 'none';
            });

            // Navigate back to first step
            this.navigateToStep(0);

            console.log('✅ All builder data cleared successfully');
        } catch (error) {
            console.error('Failed to clear data:', error);
        }
    }

    /**
     * Show the clear data modal
     */
    showModal() {
        const modal = document.getElementById('clearDataModal');
        if (modal) {
            modal.style.display = 'flex';
        }
    }

    /**
     * Hide the clear data modal with animation
     */
    hideModal() {
        const modal = document.getElementById('clearDataModal');
        const modalContent = modal?.querySelector('.modal-content');

        if (modal && modalContent) {
            // Add fade-out animation
            modalContent.style.animation = 'modalSlideOut 0.2s ease';
            modal.style.opacity = '0';

            // Wait for animation to complete before hiding
            setTimeout(() => {
                modal.style.display = 'none';
                modal.style.opacity = '1';
                modalContent.style.animation = '';
            }, 200);
        }
    }
}

// Initialize app when DOM is ready
if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', () => {
        window.articleBuilder = new ArticleBuilderApp();
    });
} else {
    window.articleBuilder = new ArticleBuilderApp();
}
