<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Vocab Master Pro+</title>
    <style>
        :root {
            --primary-blue: #4255ff;
            --secondary-blue: #303f9f;
            --success-green: #4CAF50;
            --danger-red: #ff5252;
            --learn-purple: #9c27b0;
            --background-gray: #f6f7fb;
        }

        body {
            font-family: 'Segoe UI', system-ui, sans-serif;
            margin: 0;
            padding: 0;
            background-color: var(--background-gray);
            min-height: 100vh;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
        }

        .header {
            background-color: var(--primary-blue);
            color: white;
            padding: 1rem 2rem;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }

        .nav-bar {
            display: flex;
            align-items: center;
            justify-content: space-between;
        }

        .primary-btn {
            background-color: var(--primary-blue);
            color: white;
            border: none;
            padding: 12px 24px;
            border-radius: 8px;
            cursor: pointer;
            font-weight: 600;
            transition: all 0.2s;
        }

        .primary-btn.learn {
            background-color: var(--learn-purple);
        }

        .primary-btn:hover {
            filter: brightness(1.1);
            transform: translateY(-1px);
        }

        .section {
            display: none;
            animation: fadeIn 0.3s ease-in;
        }

        .section.active {
            display: block;
        }

        .term-management {
            background: white;
            padding: 2rem;
            border-radius: 12px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        }

        .input-group {
            display: grid;
            gap: 1rem;
            margin-bottom: 2rem;
        }

        .styled-input {
            padding: 14px;
            border: 2px solid #ddd;
            border-radius: 8px;
            font-size: 16px;
            width: 100%;
        }

        .term-list {
            margin: 2rem 0;
            max-height: 400px;
            overflow-y: auto;
        }

        .term-card {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 1rem;
            margin: 0.5rem 0;
            background: var(--background-gray);
            border-radius: 8px;
        }

        .delete-btn {
            background: none;
            border: none;
            color: var(--danger-red);
            cursor: pointer;
            font-size: 1.5rem;
            padding: 0 8px;
        }

        .learning-container {
            background: white;
            padding: 2rem;
            border-radius: 16px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.1);
            margin: 2rem auto;
            max-width: 800px;
        }

        .progress-container {
            margin-bottom: 2rem;
        }

        .progress-header {
            display: flex;
            justify-content: space-between;
            margin-bottom: 1rem;
        }

        .progress-bar {
            width: 100%;
            height: 12px;
            background: #eee;
            border-radius: 6px;
        }

        .progress {
            height: 100%;
            border-radius: 6px;
            transition: width 0.3s ease;
        }

        .learn-progress {
            background: var(--learn-purple);
        }

        .question-display {
            font-size: 1.5rem;
            margin-bottom: 2rem;
            text-align: center;
            line-height: 1.5;
            min-height: 80px;
        }

        .options-grid {
            display: grid;
            grid-template-columns: 1fr;
            gap: 1rem;
        }

        .option-btn {
            padding: 1.5rem;
            border: 2px solid #eee;
            border-radius: 12px;
            cursor: pointer;
            transition: all 0.2s;
            font-size: 1.1rem;
            background: white;
        }

        .option-btn:hover:not(.disabled) {
            border-color: var(--primary-blue);
            transform: translateY(-2px);
        }

        .correct {
            border-color: var(--success-green) !important;
            background: #e8f5e9 !important;
        }

        .incorrect {
            border-color: var(--danger-red) !important;
            background: #ffebee !important;
        }

        .disabled {
            pointer-events: none;
            opacity: 0.7;
        }

        .results-screen {
            text-align: center;
            padding: 2rem;
        }

        .score-display {
            font-size: 2.5rem;
            color: var(--learn-purple);
            margin: 1rem 0;
            font-weight: bold;
        }

        .flashcard-container {
            display: flex;
            flex-direction: column;
            align-items: center;
            gap: 2rem;
            margin-top: 2rem;
        }

        .flashcard {
            width: 600px;
            max-width: 90%;
            height: 400px;
            min-height: 300px;
            max-height: 60vh;
            perspective: 1000px;
        }

        .flashcard-inner {
            width: 100%;
            height: 100%;
            position: relative;
            transform-style: preserve-3d;
            transition: transform 0.6s;
            cursor: pointer;
            border-radius: 16px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.1);
        }

        .flashcard.flipped .flashcard-inner {
            transform: rotateY(180deg);
        }

        .flashcard-face {
            position: absolute;
            width: 100%;
            height: 100%;
            backface-visibility: hidden;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 2rem;
            background: white;
            border-radius: 16px;
            font-size: 2rem;
            text-align: center;
            line-height: 1.4;
        }

        .flashcard-back {
            transform: rotateY(180deg);
            background: var(--primary-blue);
            color: white;
        }

        .flashcard-nav {
            display: flex;
            gap: 2rem;
            align-items: center;
            margin-top: 1rem;
        }

        .nav-button {
            background: var(--primary-blue);
            color: white;
            border: none;
            padding: 12px;
            border-radius: 50%;
            cursor: pointer;
            font-size: 1.5rem;
            width: 60px;
            height: 60px;
            display: flex;
            align-items: center;
            justify-content: center;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            transition: all 0.2s;
        }

        .nav-button:hover:not(:disabled) {
            transform: scale(1.1);
            background: var(--secondary-blue);
        }

        .nav-button:disabled {
            background: #ccc;
            cursor: not-allowed;
            opacity: 0.7;
        }

        .card-counter {
            font-size: 1.2rem;
            color: #666;
            font-weight: 500;
        }

        .import-box {
            border: 2px dashed #ddd;
            border-radius: 8px;
            padding: 1.5rem;
            text-align: center;
            margin: 1rem 0;
            cursor: pointer;
            transition: all 0.2s;
        }

        .import-box:hover {
            border-color: var(--primary-blue);
            background: #f8f9ff;
        }

        .notification {
            position: fixed;
            top: 20px;
            right: 20px;
            padding: 1rem 2rem;
            border-radius: 8px;
            background: white;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            animation: slideIn 0.3s ease-out;
        }

        .loading {
            position: relative;
            pointer-events: none;
            opacity: 0.7;
        }

        .loading::after {
            content: "";
            position: absolute;
            width: 16px;
            height: 16px;
            border: 2px solid #fff;
            border-radius: 50%;
            border-top-color: transparent;
            animation: spin 0.8s linear infinite;
            right: 10px;
            top: 50%;
            transform: translateY(-50%);
        }

        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(10px); }
            to { opacity: 1; transform: translateY(0); }
        }

        @keyframes slideIn {
            from { transform: translateX(100%); }
            to { transform: translateX(0); }
        }

        @keyframes spin {
            to { transform: translateY(-50%) rotate(360deg); }
        }

        @media (max-width: 768px) {
            .nav-bar {
                flex-direction: column;
                gap: 1rem;
            }
            
            .primary-btn {
                padding: 10px 18px;
            }

            .flashcard {
                height: 400px;
            }
            
            .flashcard-face {
                font-size: 1.5rem;
                padding: 1rem;
            }

            .nav-button {
                width: 50px;
                height: 50px;
                font-size: 1.2rem;
            }
        }
    </style>
</head>
<body>
    <div class="header">
        <div class="container nav-bar">
            <h1>Vocab Master Pro+</h1>
            <div>
                <button class="primary-btn" onclick="showSection('manage')">Manage</button>
                <button class="primary-btn" onclick="showSection('flashcards')">Flashcards</button>
                <button class="primary-btn learn" onclick="startLearn()">Learn</button>
                <button class="primary-btn" onclick="startQuiz()">Quiz</button>
            </div>
        </div>
    </div>

    <div class="container">
        <!-- Manage Terms Section -->
        <div id="manage" class="section active">
            <div class="term-management">
                <h2>Manage Vocabulary</h2>
                <div class="input-group">
                    <input type="text" class="styled-input" id="termInput" placeholder="Enter term">
                    <input type="text" class="styled-input" id="definitionInput" placeholder="Enter definition">
                    <button class="primary-btn" onclick="addTerm()">Add Term</button>
                </div>
                
                <div class="import-box" onclick="document.getElementById('fileInput').click()">
                    📥 Drag and drop or click to import Quizlet CSV
                </div>
                <input type="file" id="fileInput" hidden accept=".csv,.txt" onchange="handleQuizletImport(event)">
                
                <div class="term-list" id="termsContainer"></div>
                <div style="display: flex; gap: 1rem; margin-top: 2rem;">
                    <button class="primary-btn" onclick="exportTerms()">Export</button>
                    <button class="primary-btn" onclick="importTerms()">Import</button>
                </div>
            </div>
        </div>

        <!-- Flashcards Section -->
        <div id="flashcards" class="section">
            <div class="flashcard-container">
                <div class="flashcard" id="currentFlashcard" onclick="toggleFlashcard()">
                    <div class="flashcard-inner">
                        <div class="flashcard-face" id="flashcardFront"></div>
                        <div class="flashcard-face flashcard-back" id="flashcardBack"></div>
                    </div>
                </div>
                <div class="flashcard-nav">
                    <button class="nav-button" onclick="changeFlashcard(-1)" id="prevCard">←</button>
                    <span class="card-counter" id="cardCount">1/1</span>
                    <button class="nav-button" onclick="changeFlashcard(1)" id="nextCard">→</button>
                </div>
            </div>
        </div>

        <!-- Learn Section -->
        <div id="learn" class="section">
            <div class="learning-container">
                <div class="progress-container">
                    <div class="progress-header">
                        <span id="learnProgressText">Initial Round</span>
                        <span id="learnProgressCount">0/0</span>
                    </div>
                    <div class="progress-bar">
                        <div class="progress learn-progress" id="learnProgress"></div>
                    </div>
                </div>
                <div class="question-display" id="learnQuestion"></div>
                <div class="options-grid" id="learnOptions"></div>
                <div class="results-screen" id="learnResults"></div>
            </div>
        </div>

        <!-- Quiz Section -->
        <div id="quiz" class="section">
            <div class="learning-container">
                <div class="progress-container">
                    <div class="progress-header">
                        <span>Quiz Progress</span>
                        <span id="quizProgressCount">0/0</span>
                    </div>
                    <div class="progress-bar">
                        <div class="progress" id="quizProgressBar"></div>
                    </div>
                </div>
                <div class="question-display" id="quizQuestion"></div>
                <div class="options-grid" id="quizOptions"></div>
                <div class="results-screen" id="quizResults"></div>
            </div>
        </div>
    </div>

    <script>
        const VocabApp = {
            terms: JSON.parse(localStorage.getItem('terms')) || [],
            
            init() {
                document.addEventListener('DOMContentLoaded', () => {
                    this.updateTermList();
                    if (this.terms.length > 0) this.updateFlashcardDisplay();
                });
            },

            saveTerms() {
                localStorage.setItem('terms', JSON.stringify(this.terms));
                this.showNotification('Changes saved!', 'success');
            },

            showNotification(message, type = 'info') {
                const notification = document.createElement('div');
                notification.className = `notification ${type}`;
                notification.textContent = message;
                document.body.appendChild(notification);
                setTimeout(() => notification.remove(), 3000);
            },

            async handleQuizletImport(event) {
                const file = event.target.files[0];
                if (!file) return;

                const reader = new FileReader();
                reader.onload = (e) => {
                    try {
                        const content = e.target.result;
                        const newTerms = content.split('\n')
                            .map(line => {
                                const [term, definition] = line.split(/,(?=(?:(?:[^"]*"){2})*[^"]*$)/);
                                return {
                                    term: term?.trim().replace(/^"|"$/g, ''),
                                    definition: definition?.trim().replace(/^"|"$/g, '')
                                };
                            })
                            .filter(t => t.term && t.definition);

                        this.terms = [...this.terms, ...newTerms];
                        this.updateTermList();
                        this.saveTerms();
                        this.showNotification(`Imported ${newTerms.length} terms from Quizlet!`, 'success');
                    } catch (error) {
                        this.showNotification('Error importing file. Ensure CSV format is "term,definition"', 'error');
                    }
                    event.target.value = '';
                };
                reader.readAsText(file);
            },

            handleAnswer(selected, correct, callback) {
                const options = document.querySelectorAll('.option-btn');
                let isCorrect = false;

                options.forEach(opt => {
                    opt.classList.add('disabled');
                    if(opt.textContent === correct) {
                        opt.classList.add('correct');
                        if(selected === correct) isCorrect = true;
                    }
                    if(opt.textContent === selected && selected !== correct) {
                        opt.classList.add('incorrect');
                    }
                });

                setTimeout(() => callback(isCorrect), 1500);
            },

            shuffle(array) {
                const shuffled = [...array];
                for (let i = shuffled.length - 1; i > 0; i--) {
                    const j = Math.floor(Math.random() * (i + 1));
                    [shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];
                }
                return shuffled;
            },

            addTerm(term, definition) {
                if (!term || !definition) return false;
                
                const existing = this.terms.find(t => t.term.toLowerCase() === term.toLowerCase());
                if (existing) {
                    this.showNotification('Term already exists! Updating definition...', 'warning');
                    existing.definition = definition;
                } else {
                    this.terms.push({ term: term.trim(), definition: definition.trim() });
                }
                return true;
            },

            updateTermList() {
                const container = document.getElementById('termsContainer');
                container.innerHTML = this.terms.map((term, index) => `
                    <div class="term-card">
                        <div>
                            <strong>${term.term}</strong>
                            <p style="color: #666; margin-top: 4px;">${term.definition}</p>
                        </div>
                        <button class="delete-btn" onclick="VocabApp.deleteTerm(${index})">×</button>
                    </div>
                `).join('');
            },

            deleteTerm(index) {
                this.terms.splice(index, 1);
                this.updateTermList();
                this.saveTerms();
                if(currentCardIndex >= this.terms.length) currentCardIndex = Math.max(0, this.terms.length - 1);
                if(document.getElementById('flashcards').classList.contains('active')) this.updateFlashcardDisplay();
            },

            updateFlashcardDisplay() {
                const front = document.getElementById('flashcardFront');
                const back = document.getElementById('flashcardBack');
                const counter = document.getElementById('cardCount');
                
                if(this.terms.length > 0) {
                    front.textContent = this.terms[currentCardIndex].term;
                    back.textContent = this.terms[currentCardIndex].definition;
                    counter.textContent = `${currentCardIndex + 1}/${this.terms.length}`;
                    document.getElementById('currentFlashcard').classList.remove('flipped');
                } else {
                    front.textContent = 'No terms available';
                    back.textContent = 'Add terms in the manage section';
                    counter.textContent = '0/0';
                }
                
                document.getElementById('prevCard').disabled = currentCardIndex === 0;
                document.getElementById('nextCard').disabled = currentCardIndex === this.terms.length - 1;
            }
        };

        // Global variables
        let currentCardIndex = 0;
        let currentLearnState = {
            termsQueue: [],
            incorrectTerms: [],
            currentIndex: 0,
            isReviewRound: false,
            totalQuestions: 0
        };
        let quizCurrentQuestion = 0;
        let quizScore = 0;

        // UI Functions
        function showSection(sectionId) {
            document.querySelectorAll('.section').forEach(s => s.classList.remove('active'));
            document.getElementById(sectionId).classList.add('active');
            if(sectionId === 'flashcards') VocabApp.updateFlashcardDisplay();
        }

        function addTerm() {
            const termInput = document.getElementById('termInput');
            const definitionInput = document.getElementById('definitionInput');
            
            if (VocabApp.addTerm(termInput.value, definitionInput.value)) {
                termInput.value = '';
                definitionInput.value = '';
                VocabApp.updateTermList();
                VocabApp.saveTerms();
            }
        }

        function changeFlashcard(delta) {
            currentCardIndex = Math.max(0, Math.min(VocabApp.terms.length - 1, currentCardIndex + delta));
            VocabApp.updateFlashcardDisplay();
        }

        function toggleFlashcard() {
            document.getElementById('currentFlashcard').classList.toggle('flipped');
        }

        // Learn Mode
        function startLearn() {
            if(VocabApp.terms.length < 1) {
                VocabApp.showNotification('Please add terms first!', 'error');
                return;
            }

            showSection('learn');
            currentLearnState = {
                termsQueue: VocabApp.shuffle([...VocabApp.terms]),
                incorrectTerms: [],
                currentIndex: 0,
                isReviewRound: false,
                totalQuestions: VocabApp.terms.length
            };
            document.getElementById('learnResults').innerHTML = '';
            updateLearnProgress();
            showNextLearnQuestion();
        }

        function showNextLearnQuestion() {
            const container = document.getElementById('learnOptions');
            container.innerHTML = '';
            
            if(currentLearnState.currentIndex >= currentLearnState.termsQueue.length) {
                if(currentLearnState.incorrectTerms.length > 0 && !currentLearnState.isReviewRound) {
                    currentLearnState.termsQueue = VocabApp.shuffle([...currentLearnState.incorrectTerms]);
                    currentLearnState.incorrectTerms = [];
                    currentLearnState.currentIndex = 0;
                    currentLearnState.isReviewRound = true;
                    currentLearnState.totalQuestions += currentLearnState.termsQueue.length;
                    document.getElementById('learnProgressText').textContent = 'Review Round';
                } else {
                    showLearnResults();
                    return;
                }
            }

            const currentTerm = currentLearnState.termsQueue[currentLearnState.currentIndex];
            const options = VocabApp.shuffle([
                currentTerm.definition,
                ...getRandomDefinitions(currentTerm.definition, 3)
            ]);

            document.getElementById('learnQuestion').textContent = 
                `What is the definition of "${currentTerm.term}"?`;

            container.innerHTML = options.map(opt => `
                <button class="option-btn" onclick="handleLearnAnswer('${opt}', '${currentTerm.definition}')">
                    ${opt}
                </button>
            `).join('');

            updateLearnProgress();
        }

        function handleLearnAnswer(selected, correct) {
            VocabApp.handleAnswer(selected, correct, (isCorrect) => {
                if (!isCorrect) {
                    currentLearnState.incorrectTerms.push(
                        currentLearnState.termsQueue[currentLearnState.currentIndex]
                    );
                }
                currentLearnState.currentIndex++;
                showNextLearnQuestion();
            });
        }

        function updateLearnProgress() {
            const totalAnswered = currentLearnState.currentIndex + 
                                (currentLearnState.isReviewRound ? currentLearnState.totalQuestions - currentLearnState.termsQueue.length : 0);
            const progress = (totalAnswered / currentLearnState.totalQuestions) * 100;
            
            document.getElementById('learnProgress').style.width = `${progress}%`;
            document.getElementById('learnProgressCount').textContent = 
                `${totalAnswered}/${currentLearnState.totalQuestions}`;
        }

        function showLearnResults() {
            const container = document.getElementById('learnResults');
            const score = currentLearnState.totalQuestions - currentLearnState.incorrectTerms.length;
            
            container.innerHTML = `
                <h2>Learning Complete! 🎉</h2>
                <div class="score-display">${score}/${currentLearnState.totalQuestions}</div>
                <p>Accuracy: ${Math.round((score/currentLearnState.totalQuestions)*100)}%</p>
                ${currentLearnState.incorrectTerms.length > 0 ? `
                    <button class="primary-btn learn" onclick="startLearn()">
                        Practice Mistakes Again
                    </button>
                ` : ''}
                <button class="primary-btn" onclick="showSection('manage')">
                    Return to Terms
                </button>
            `;
        }

        // Quiz Mode
        function startQuiz() {
            if(VocabApp.terms.length < 1) {
                VocabApp.showNotification('Please add terms first!', 'error');
                return;
            }

            showSection('quiz');
            quizCurrentQuestion = 0;
            quizScore = 0;
            document.getElementById('quizResults').innerHTML = '';
            document.getElementById('quizQuestion').style.display = 'block';
            document.getElementById('quizOptions').style.display = 'grid';
            showNextQuizQuestion();
        }

        function showNextQuizQuestion() {
            if(quizCurrentQuestion >= VocabApp.terms.length) {
                showQuizResults();
                return;
            }

            const currentTerm = VocabApp.terms[quizCurrentQuestion];
            const options = VocabApp.shuffle([
                currentTerm.definition,
                ...getRandomDefinitions(currentTerm.definition, 3)
            ]);

            document.getElementById('quizQuestion').textContent = 
                `What is the definition of "${currentTerm.term}"?`;

            document.getElementById('quizOptions').innerHTML = options.map(opt => `
                <button class="option-btn" onclick="handleQuizAnswer('${opt}', '${currentTerm.definition}')">
                    ${opt}
                </button>
            `).join('');

            updateQuizProgress();
        }

        function handleQuizAnswer(selected, correct) {
            VocabApp.handleAnswer(selected, correct, (isCorrect) => {
                if (isCorrect) quizScore++;
                quizCurrentQuestion++;
                quizCurrentQuestion < VocabApp.terms.length ? showNextQuizQuestion() : showQuizResults();
            });
        }

        function updateQuizProgress() {
            document.getElementById('quizProgressCount').textContent = 
                `${quizCurrentQuestion + 1}/${VocabApp.terms.length}`;
            document.getElementById('quizProgressBar').style.width = 
                `${((quizCurrentQuestion + 1) / VocabApp.terms.length) * 100}%`;
        }

        function showQuizResults() {
            document.getElementById('quizQuestion').style.display = 'none';
            document.getElementById('quizOptions').style.display = 'none';
            document.getElementById('quizResults').innerHTML = `
                <h2>Quiz Complete!</h2>
                <div class="score-display">${quizScore}/${VocabApp.terms.length}</div>
                <p>${Math.round((quizScore/VocabApp.terms.length)*100)}% Correct Answers</p>
                <button class="primary-btn" onclick="startQuiz()">Retry Quiz</button>
            `;
        }

        // Utilities
        function getRandomDefinitions(exclude, count) {
            const filtered = VocabApp.terms.filter(t => t.definition !== exclude);
            return VocabApp.shuffle(filtered).slice(0, count).map(t => t.definition);
        }

        function handleQuizletImport(event) {
            VocabApp.handleQuizletImport(event);
        }

        // Event Listeners
        document.querySelectorAll('button').forEach(btn => {
            btn.addEventListener('click', function() {
                if (this.classList.contains('primary-btn')) {
                    this.classList.add('loading');
                    setTimeout(() => this.classList.remove('loading'), 1000);
                }
            });
        });

        // Initialize the app
        VocabApp.init();
    </script>
</body>
</html>