/* ========================================
   Azure Certification Portal - Main App
   ======================================== */

window.ExamData = window.ExamData || {};

const App = {
  state: {
    view: 'dashboard',
    currentExam: null,
    mode: null,
    quiz: null,
    currentQuestion: 0,
    showAnswer: false,
    filter: { domain: 'all', difficulty: 'all', status: 'all' },
    timerInterval: null,
    studyAnswers: {},
    studySubmitted: {}
  },

  examOrder: [
    'az-900','ai-900','ai-901','sc-900','dp-900',
    'az-104','az-204','az-700',
    'az-305',
    'sc-100','sc-200','sc-300','sc-400','az-500',
    'az-400',
    'ai-102','ai-103','ai-200',
    'dp-100','dp-203','dp-300','dp-700',
    'az-120','az-140'
  ],

  init() {
    const savedTheme = localStorage.getItem('certportal-theme') || 'light';
    document.documentElement.setAttribute('data-theme', savedTheme);
    this.updateThemeIcon(savedTheme);
    this.bindEvents();
    this.updateNavProgress();
    this.render();
  },

  bindEvents() {
    // Nav items
    document.querySelectorAll('.nav-item').forEach(btn => {
      btn.addEventListener('click', () => {
        this.navigate(btn.dataset.view, btn.dataset.exam);
      });
    });
    // Language
    document.getElementById('lang-de').addEventListener('click', () => setLanguage('de'));
    document.getElementById('lang-en').addEventListener('click', () => setLanguage('en'));
    // Theme
    document.getElementById('theme-toggle').addEventListener('click', () => this.toggleTheme());
    // Sidebar toggle
    document.getElementById('menu-toggle').addEventListener('click', () => this.toggleSidebar());
    const sidebarClose = document.getElementById('sidebar-close');
    if (sidebarClose) sidebarClose.addEventListener('click', () => this.toggleSidebar());
    // Modal close
    document.getElementById('modal-overlay').addEventListener('click', (e) => {
      if (e.target === e.currentTarget) this.closeModal();
    });
    // Content delegation
    document.getElementById('content').addEventListener('click', (e) => this.handleContentClick(e));
    document.getElementById('content').addEventListener('change', (e) => this.handleContentChange(e));
    document.getElementById('modal-content')?.addEventListener('click', (e) => this.handleContentClick(e));
  },

  handleContentClick(e) {
    const btn = e.target.closest('[data-action]');
    if (!btn) return;
    const action = btn.dataset.action;
    switch (action) {
      case 'open-exam': this.navigate('exam', btn.dataset.exam); break;
      case 'start-study': this.startStudy(); break;
      case 'start-quiz-config': this.showQuizConfig(); break;
      case 'start-quiz': this.startQuiz(); break;
      case 'select-option': this.selectOption(btn.dataset.question, btn.dataset.option); break;
      case 'submit-answer': this.submitAnswer(); break;
      case 'show-answer': this.showStudyAnswer(); break;
      case 'next-question': this.nextQuestion(); break;
      case 'prev-question': this.prevQuestion(); break;
      case 'goto-question': this.goToQuestion(parseInt(btn.dataset.index)); break;
      case 'finish-quiz': this.finishQuiz(); break;
      case 'review-answers': this.reviewAnswers(); break;
      case 'retry-quiz': this.startStudy(); break;
      case 'back-to-exam': this.navigate('exam', this.state.currentExam); break;
      case 'back-to-dashboard': this.navigate('dashboard'); break;
      case 'reset-progress': this.resetProgress(); break;
      case 'close-modal': this.closeModal(); break;
      case 'open-mslearn': {
        const exam = window.ExamData[this.state.currentExam];
        if (exam?.meta?.msLearnUrl) window.open(exam.meta.msLearnUrl, '_blank');
        break;
      }
    }
  },

  handleContentChange(e) {
    const el = e.target;
    if (el.id === 'filter-domain') { this.state.filter.domain = el.value; this.state.currentQuestion = 0; this.render(); }
    if (el.id === 'filter-difficulty') { this.state.filter.difficulty = el.value; this.state.currentQuestion = 0; this.render(); }
    if (el.id === 'filter-status') { this.state.filter.status = el.value; this.state.currentQuestion = 0; this.render(); }
  },

  navigate(view, exam = null) {
    this.clearTimer();
    this.state.view = view;
    this.state.currentExam = exam;
    this.state.mode = null;
    this.state.quiz = null;
    this.state.showAnswer = false;
    this.state.currentQuestion = 0;
    this.state.filter = { domain: 'all', difficulty: 'all', status: 'all' };
    this.state.studyAnswers = {};
    this.state.studySubmitted = {};
    // Update active nav
    document.querySelectorAll('.nav-item').forEach(b => b.classList.remove('active'));
    const sel = exam
      ? document.querySelector(`.nav-item[data-exam="${exam}"]`)
      : document.querySelector('.nav-item[data-view="dashboard"]');
    if (sel) sel.classList.add('active');
    document.getElementById('sidebar').classList.remove('open');
    this.render();
    window.scrollTo(0, 0);
  },

  render() {
    const content = document.getElementById('content');
    const title = document.getElementById('page-title');
    const actions = document.getElementById('topbar-actions');
    actions.innerHTML = '';

    switch (this.state.view) {
      case 'dashboard':
        title.textContent = t('dashboard.title');
        content.innerHTML = this.renderDashboard();
        break;
      case 'exam':
        if (this.state.mode === 'study') {
          this.renderStudyMode(content, title, actions);
        } else if (this.state.mode === 'quiz') {
          this.renderQuizMode(content, title, actions);
        } else if (this.state.mode === 'results') {
          this.renderResultsView(content, title);
        } else if (this.state.mode === 'review') {
          this.renderReviewView(content, title);
        } else {
          this.renderExamDetail(content, title);
        }
        break;
      default:
        title.textContent = t('dashboard.title');
        content.innerHTML = this.renderDashboard();
    }
    this.updateNavProgress();
  },

  /* ====== DASHBOARD ====== */
  renderDashboard() {
    const exams = this.examOrder.filter(id => window.ExamData[id]);
    if (exams.length === 0) {
      return `<div class="empty-state"><div class="icon">📚</div><p>${t('loading')}</p></div>`;
    }

    // Global stats
    let totalQ = 0, totalA = 0, totalC = 0, started = 0;
    exams.forEach(id => {
      const exam = window.ExamData[id];
      const cnt = exam.questions.length;
      totalQ += cnt;
      const stats = ProgressManager.getStats(id, cnt);
      totalA += stats.answered;
      totalC += stats.correct;
      if (stats.answered > 0) started++;
    });

    let html = `
      <p class="mb-16" style="color:var(--text-secondary)">${t('dashboard.subtitle')}</p>
      <div class="stats-row mb-16">
        <div class="stat"><div class="stat-value">${exams.length}</div><div class="stat-label">${t('dashboard.examsStarted').replace('Gestartet','Gesamt').replace('Started','Total')}</div></div>
        <div class="stat"><div class="stat-value">${totalA}/${totalQ}</div><div class="stat-label">${t('dashboard.questionsAnswered')}</div></div>
        <div class="stat"><div class="stat-value">${totalA > 0 ? Math.round((totalC/totalA)*100) : 0}%</div><div class="stat-label">${t('dashboard.avgScore')}</div></div>
      </div>
      <div class="dashboard-grid">`;

    exams.forEach(id => {
      const exam = window.ExamData[id];
      const m = exam.meta;
      const stats = ProgressManager.getStats(id, exam.questions.length);
      const fillClass = stats.percentage >= 70 ? 'high' : stats.percentage < 30 && stats.percentage > 0 ? 'low' : '';
      const isMust = id === 'az-305';

      html += `
        <div class="card exam-card" data-action="open-exam" data-exam="${id}">
          ${isMust ? `<div class="must-badge">MUSS / MUST</div>` : ''}
          <div class="card-header">
            <div>
              <div style="display:flex;align-items:center;gap:8px">
                <span class="card-icon">${m.icon}</span>
                <span class="card-title">${id.toUpperCase()}</span>
              </div>
              <div class="card-subtitle">${m.title[currentLang]}</div>
            </div>
            <span class="level-badge level-${m.level}">${t('level.' + m.level)}</span>
          </div>
          <div class="card-body">
            <div class="progress-bar"><div class="progress-fill ${fillClass}" style="width:${stats.percentage}%"></div></div>
            <div class="progress-info">
              <span>${stats.answered}/${stats.total} ${t('dashboard.questionsAnswered')}</span>
              <span>${stats.percentage}%</span>
            </div>
            ${stats.bestScore > 0 ? `<div class="mt-8" style="font-size:0.8rem;color:var(--text-secondary)">🏆 ${t('exam.bestScore')}: ${stats.bestScore}/1000</div>` : ''}
          </div>
        </div>`;
    });

    html += '</div>';
    return html;
  },

  /* ====== EXAM DETAIL ====== */
  renderExamDetail(content, title) {
    const exam = window.ExamData[this.state.currentExam];
    if (!exam) { content.innerHTML = `<div class="empty-state"><div class="icon">❌</div><p>Exam not found</p></div>`; return; }
    const m = exam.meta;
    const stats = ProgressManager.getStats(this.state.currentExam, exam.questions.length);
    title.textContent = `${this.state.currentExam.toUpperCase()} - ${m.title[currentLang]}`;

    let html = `
      <div class="exam-header">
        <div class="exam-info">
          <h2>${m.icon} ${m.title[currentLang]}</h2>
          <p>${m.description[currentLang]}</p>
          <div class="exam-meta">
            <div class="exam-meta-item">📝 <strong>${m.questionCount}</strong> ${t('exam.questionCount')}</div>
            <div class="exam-meta-item">⏱️ <strong>${m.totalTime}</strong> ${t('exam.minutes')}</div>
            <div class="exam-meta-item">🎯 <strong>${m.passingScore}/1000</strong> ${t('exam.passingScore')}</div>
            <div class="exam-meta-item"><span class="level-badge level-${m.level}">${t('level.' + m.level)}</span></div>
          </div>
          <div class="exam-actions">
            <button class="btn btn-primary btn-lg" data-action="start-study">📖 ${t('exam.startStudy')}</button>
            <button class="btn btn-success btn-lg" data-action="start-quiz-config">📝 ${t('exam.startQuiz')}</button>
            ${m.msLearnUrl ? `<button class="btn btn-outline" data-action="open-mslearn">🔗 ${t('exam.mslearn')}</button>` : ''}
            <button class="btn btn-secondary btn-sm" data-action="reset-progress">🗑️ ${t('progress.reset')}</button>
          </div>
        </div>
      </div>

      <div class="stats-row mb-16">
        <div class="stat"><div class="stat-value">${exam.questions.length}</div><div class="stat-label">${t('exam.allQuestions')}</div></div>
        <div class="stat"><div class="stat-value">${stats.answered}</div><div class="stat-label">${t('filter.answered')}</div></div>
        <div class="stat"><div class="stat-value">${stats.correctPercentage}%</div><div class="stat-label">${t('filter.correct')}</div></div>
        <div class="stat"><div class="stat-value">${stats.bestScore}</div><div class="stat-label">${t('exam.bestScore')}</div></div>
        <div class="stat"><div class="stat-value">${stats.attempts}</div><div class="stat-label">${t('exam.attempts')}</div></div>
      </div>

      <div class="section-header"><h3>${t('exam.domains')}</h3></div>
      <div class="domains-grid">`;

    if (m.domains) {
      m.domains.forEach(d => {
        html += `
          <div class="domain-card">
            <h4>${d.name[currentLang]}</h4>
            <div class="weight">${d.weight}</div>
            ${d.objectives ? `<ul>${d.objectives.map(o => `<li>${o[currentLang]}</li>`).join('')}</ul>` : ''}
          </div>`;
      });
    }
    html += '</div>';

    // Company profiles section
    const companies = window.CompanyProfiles ? window.CompanyProfiles.getForExam(this.state.currentExam) : [];
    if (companies.length > 0) {
      html += `<div class="section-header mt-24"><h3>🏢 ${t('companies.title')}</h3></div>
        <p style="color:var(--text-secondary);margin-bottom:12px;font-size:0.9rem">${t('companies.subtitle')}</p>
        <div class="companies-grid">`;
      companies.forEach(c => {
        html += `
          <div class="company-card">
            <div class="company-header">
              <span class="company-logo">${c.logo}</span>
              <div>
                <div class="company-name">${c.name}</div>
                <div class="company-industry">${c.industry[currentLang]}</div>
              </div>
            </div>
            <div class="company-meta">
              <span>📍 ${c.hq[currentLang]}</span>
              <span>👥 ${c.employees.toLocaleString()}</span>
            </div>
            <p class="company-desc">${c.description[currentLang]}</p>
            <details class="company-details">
              <summary>${t('companies.infrastructure')}</summary>
              <ul>${c.infrastructure[currentLang].map(i => '<li>' + i + '</li>').join('')}</ul>
            </details>
            <details class="company-details">
              <summary>${t('companies.challenges')}</summary>
              <ul>${c.challenges[currentLang].map(ch => '<li>' + ch + '</li>').join('')}</ul>
            </details>
          </div>`;
      });
      html += '</div>';
    }

    content.innerHTML = html;
  },

  /* ====== STUDY MODE ====== */
  startStudy() {
    this.state.mode = 'study';
    this.state.currentQuestion = 0;
    this.state.showAnswer = false;
    this.state.studyAnswers = {};
    this.state.studySubmitted = {};
    this.render();
  },

  getFilteredQuestions() {
    const exam = window.ExamData[this.state.currentExam];
    if (!exam) return [];
    let questions = [...exam.questions];
    const f = this.state.filter;
    const progress = ProgressManager.getProgress(this.state.currentExam);

    if (f.domain !== 'all') {
      questions = questions.filter(q => q.domain[currentLang] === f.domain || q.domain['en'] === f.domain);
    }
    if (f.difficulty !== 'all') {
      questions = questions.filter(q => q.difficulty === f.difficulty);
    }
    if (f.status !== 'all') {
      questions = questions.filter(q => {
        const a = progress.answers[q.id];
        if (f.status === 'unanswered') return !a;
        if (f.status === 'answered') return !!a;
        if (f.status === 'correct') return a && a.correct;
        if (f.status === 'incorrect') return a && !a.correct;
        return true;
      });
    }
    return questions;
  },

  renderStudyMode(content, title, actions) {
    const exam = window.ExamData[this.state.currentExam];
    if (!exam) return;
    title.textContent = `${this.state.currentExam.toUpperCase()} - ${t('exam.study')}`;
    actions.innerHTML = `<button class="btn btn-secondary btn-sm" data-action="back-to-exam">← ${t('results.back')}</button>`;

    const questions = this.getFilteredQuestions();
    if (questions.length === 0) {
      content.innerHTML = `<div class="empty-state"><div class="icon">🔍</div><p>${t('noQuestions')}</p></div>` + this.renderFilters(exam);
      return;
    }
    if (this.state.currentQuestion >= questions.length) this.state.currentQuestion = 0;
    const q = questions[this.state.currentQuestion];
    const qId = q.id;
    const isSubmitted = this.state.studySubmitted[qId] !== undefined;

    let html = this.renderFilters(exam);
    html += `<div class="question-container">`;
    html += this.renderQuestionHeader(this.state.currentQuestion, questions.length);
    html += this.renderQuestionMeta(q);

    if (q.scenario) {
      html += `<div class="scenario-box"><h3>📋 ${t('quiz.scenario')}</h3><p>${q.scenario[currentLang]}</p></div>`;
    }

    html += `<div class="question-text">${q.question[currentLang]}</div>`;
    html += `<div class="select-hint">${q.type === 'multiple' ? t('quiz.selectMultiple') : t('quiz.selectOne')}</div>`;

    html += `<div class="options-list">`;
    q.options.forEach(opt => {
      let cls = 'option';
      const selected = (this.state.studyAnswers[qId] || []).includes(opt.id);
      if (selected) cls += ' selected';
      if (isSubmitted) {
        cls += ' disabled';
        if (q.correct.includes(opt.id)) cls += ' correct';
        else if (selected) cls += ' incorrect';
      }
      html += `<div class="${cls}" data-action="select-option" data-question="${qId}" data-option="${opt.id}">
        <span class="option-letter">${opt.id}</span>
        <span class="option-text">${opt.text[currentLang]}</span>
      </div>`;
    });
    html += `</div>`;

    if (!isSubmitted) {
      html += `<button class="btn btn-primary" data-action="show-answer" ${!(this.state.studyAnswers[qId]?.length) ? 'disabled' : ''}>${t('quiz.showAnswer')}</button>`;
    } else {
      const correct = this.state.studySubmitted[qId];
      html += `<div style="font-size:1.1rem;font-weight:600;margin-bottom:12px;color:${correct ? 'var(--success)' : 'var(--danger)'}">${correct ? t('quiz.correct') : t('quiz.incorrect')}</div>`;
      html += this.renderExplanation(q);
    }

    // Navigation
    html += `<div class="question-nav-btns mt-16">
      <button class="btn btn-secondary" data-action="prev-question" ${this.state.currentQuestion === 0 ? 'disabled' : ''}>← ${t('quiz.previous')}</button>
      <button class="btn btn-primary" data-action="next-question" ${this.state.currentQuestion >= questions.length - 1 ? 'disabled' : ''}>${t('quiz.next')} →</button>
    </div>`;

    // Question map
    html += `<div class="mt-16"><div class="section-header"><h3>${t('quiz.questionMap')}</h3></div><div class="question-map">`;
    questions.forEach((qq, i) => {
      let mc = 'qmap-item';
      if (i === this.state.currentQuestion) mc += ' current';
      if (this.state.studySubmitted[qq.id] !== undefined) {
        mc += this.state.studySubmitted[qq.id] ? ' correct-map' : ' incorrect-map';
      }
      html += `<div class="${mc}" data-action="goto-question" data-index="${i}">${i + 1}</div>`;
    });
    html += '</div></div></div>';

    content.innerHTML = html;
  },

  /* ====== QUIZ MODE ====== */
  showQuizConfig() {
    const exam = window.ExamData[this.state.currentExam];
    if (!exam) return;
    const totalQ = exam.questions.length;

    const overlay = document.getElementById('modal-overlay');
    document.getElementById('modal-title').textContent = t('exam.configQuiz');
    document.getElementById('modal-content').innerHTML = `
      <div class="quiz-config">
        <div class="form-group">
          <label>${t('quiz.numQuestions')}</label>
          <input type="number" id="quiz-num-q" min="5" max="${totalQ}" value="${Math.min(totalQ, 40)}">
        </div>
        <div class="form-group">
          <label>${t('quiz.timed')}</label>
          <select id="quiz-timed">
            <option value="yes">✓ ${t('quiz.timed')} (${exam.meta.totalTime} min)</option>
            <option value="no">✗ ${currentLang === 'de' ? 'Ohne Timer' : 'No Timer'}</option>
          </select>
        </div>
        <div class="form-group">
          <label>${t('quiz.shuffle')}</label>
          <select id="quiz-shuffle">
            <option value="yes">✓ ${t('quiz.shuffle')}</option>
            <option value="no">✗ ${currentLang === 'de' ? 'Reihenfolge beibehalten' : 'Keep Order'}</option>
          </select>
        </div>
        <button class="btn btn-success btn-lg" data-action="start-quiz" style="width:100%;margin-top:8px">🚀 ${t('quiz.start')}</button>
      </div>`;
    overlay.classList.remove('hidden');
  },

  startQuiz() {
    const exam = window.ExamData[this.state.currentExam];
    if (!exam) return;
    const numQ = parseInt(document.getElementById('quiz-num-q')?.value) || exam.questions.length;
    const timed = (document.getElementById('quiz-timed')?.value) !== 'no';
    const shuffle = (document.getElementById('quiz-shuffle')?.value) !== 'no';

    this.closeModal();
    this.state.mode = 'quiz';
    this.state.currentQuestion = 0;
    this.state.showAnswer = false;
    this.state.quiz = new QuizEngine(exam.questions, {
      shuffle,
      timeLimit: timed ? exam.meta.totalTime : null,
      mode: 'quiz',
      questionCount: numQ
    }).start();

    if (timed) {
      this.state.timerInterval = setInterval(() => {
        if (this.state.quiz && this.state.quiz.isTimeUp()) {
          this.finishQuiz();
        }
        this.updateTimerDisplay();
      }, 1000);
    }
    this.render();
  },

  renderQuizMode(content, title, actions) {
    const quiz = this.state.quiz;
    if (!quiz) return;
    const q = quiz.getCurrentQuestion();
    if (!q) return;
    const progress = quiz.getProgress();
    title.textContent = `${this.state.currentExam.toUpperCase()} - ${t('exam.quiz')}`;
    actions.innerHTML = `<button class="btn btn-danger btn-sm" data-action="finish-quiz">🏁 ${t('quiz.finish')}</button>`;

    let html = '';

    // Timer
    if (quiz.options.timeLimit) {
      const remaining = quiz.getTimeRemaining();
      const mins = Math.floor(remaining);
      const secs = Math.floor((remaining - mins) * 60);
      const timerClass = remaining < 5 ? 'danger' : remaining < 15 ? 'warning' : '';
      const pct = (remaining / quiz.options.timeLimit) * 100;
      html += `<div class="timer-bar">
        <span class="timer-icon">⏱️</span>
        <span class="timer-text ${timerClass}" id="timer-display">${String(mins).padStart(2,'0')}:${String(secs).padStart(2,'0')}</span>
        <div class="timer-progress"><div class="progress-bar"><div class="progress-fill" style="width:${pct}%"></div></div></div>
        <span class="question-counter">${progress.current}/${progress.total}</span>
      </div>`;
    }

    html += `<div class="question-container">`;
    html += this.renderQuestionHeader(quiz.currentIndex, quiz.questions.length);
    html += this.renderQuestionMeta(q);

    if (q.scenario) {
      html += `<div class="scenario-box"><h3>📋 ${t('quiz.scenario')}</h3><p>${q.scenario[currentLang]}</p></div>`;
    }

    html += `<div class="question-text">${q.question[currentLang]}</div>`;
    html += `<div class="select-hint">${q.type === 'multiple' ? t('quiz.selectMultiple') : t('quiz.selectOne')}</div>`;

    const isSubmitted = quiz.isSubmitted(q.id);
    html += `<div class="options-list">`;
    q.options.forEach(opt => {
      let cls = 'option';
      const selected = quiz.isSelected(q.id, opt.id);
      if (selected) cls += ' selected';
      if (isSubmitted) {
        cls += ' disabled';
        if (q.correct.includes(opt.id)) cls += ' correct';
        else if (selected) cls += ' incorrect';
      }
      html += `<div class="${cls}" data-action="select-option" data-question="${q.id}" data-option="${opt.id}">
        <span class="option-letter">${opt.id}</span>
        <span class="option-text">${opt.text[currentLang]}</span>
      </div>`;
    });
    html += `</div>`;

    if (!isSubmitted) {
      html += `<button class="btn btn-primary" data-action="submit-answer" ${!quiz.getSelectedOptions(q.id).length ? 'disabled' : ''}>${t('quiz.submit')}</button>`;
    } else {
      const result = quiz.submitted[q.id];
      html += `<div style="font-size:1.1rem;font-weight:600;margin-bottom:12px;color:${result.correct ? 'var(--success)' : 'var(--danger)'}">${result.correct ? t('quiz.correct') : t('quiz.incorrect')}</div>`;
      html += this.renderExplanation(q);
    }

    html += `<div class="question-nav-btns mt-16">
      <button class="btn btn-secondary" data-action="prev-question" ${quiz.currentIndex === 0 ? 'disabled' : ''}>← ${t('quiz.previous')}</button>
      ${quiz.currentIndex >= quiz.questions.length - 1
        ? `<button class="btn btn-success" data-action="finish-quiz">🏁 ${t('quiz.finish')}</button>`
        : `<button class="btn btn-primary" data-action="next-question">${t('quiz.next')} →</button>`}
    </div>`;

    // Question map
    html += `<div class="mt-16"><div class="section-header"><h3>${t('quiz.questionMap')}</h3></div><div class="question-map">`;
    quiz.questions.forEach((qq, i) => {
      let mc = 'qmap-item';
      if (i === quiz.currentIndex) mc += ' current';
      else if (quiz.isSubmitted(qq.id)) mc += ' answered';
      html += `<div class="${mc}" data-action="goto-question" data-index="${i}">${i + 1}</div>`;
    });
    html += '</div></div></div>';

    content.innerHTML = html;
  },

  /* ====== RESULTS ====== */
  finishQuiz() {
    this.clearTimer();
    if (!this.state.quiz) return;

    const unanswered = this.state.quiz.questions.length - Object.keys(this.state.quiz.submitted).length;
    if (unanswered > 0 && !confirm(t('quiz.endConfirm'))) return;

    const results = this.state.quiz.getResults();
    ProgressManager.saveQuizResult(this.state.currentExam, results);
    this.state.mode = 'results';
    this.state.lastResults = results;
    this.render();
  },

  renderResultsView(content, title) {
    const results = this.state.lastResults;
    if (!results) return;
    title.textContent = t('results.title');
    const passed = results.passed;
    const durMin = Math.floor(results.duration / 60000);
    const durSec = Math.floor((results.duration % 60000) / 1000);

    let html = `<div class="results-container">
      <div class="results-score ${passed ? '' : 'failed'}">${results.score}/1000</div>
      <div class="results-label ${passed ? 'passed' : 'failed'}">${passed ? t('results.passed') : t('results.failed')}</div>
      <p style="color:var(--text-secondary);margin-bottom:8px">${t('results.passingScore')}</p>
      <p style="color:var(--text-secondary);font-size:0.85rem">${t('results.duration')}: ${durMin}m ${durSec}s</p>
      <div class="results-stats">
        <div class="results-stat"><div class="value" style="color:var(--success)">${results.correct}</div><div class="label">${t('results.correct')}</div></div>
        <div class="results-stat"><div class="value" style="color:var(--danger)">${results.incorrect}</div><div class="label">${t('results.incorrect')}</div></div>
        <div class="results-stat"><div class="value" style="color:var(--text-tertiary)">${results.unanswered}</div><div class="label">${t('results.unanswered')}</div></div>
      </div>
      <div class="mt-24" style="display:flex;gap:12px;justify-content:center;flex-wrap:wrap">
        <button class="btn btn-primary btn-lg" data-action="review-answers">📝 ${t('results.review')}</button>
        <button class="btn btn-secondary btn-lg" data-action="retry-quiz">🔄 ${t('results.retry')}</button>
        <button class="btn btn-secondary" data-action="back-to-exam">← ${t('results.back')}</button>
      </div>
    </div>`;
    content.innerHTML = html;
  },

  /* ====== REVIEW ====== */
  reviewAnswers() {
    this.state.mode = 'review';
    this.render();
  },

  renderReviewView(content, title) {
    const results = this.state.lastResults;
    if (!results) return;
    title.textContent = `${t('results.review')} - ${this.state.currentExam.toUpperCase()}`;

    let html = `<button class="btn btn-secondary mb-16" data-action="back-to-exam">← ${t('results.back')}</button>`;
    results.questions.forEach((q, i) => {
      const answer = results.answers[q.id];
      const isCorrect = answer?.correct;
      const selected = answer?.selected || [];
      html += `<div class="review-item ${isCorrect ? 'review-correct' : 'review-incorrect'}">
        <div class="question-meta mb-8">
          <span class="badge badge-${q.difficulty}">${t('filter.' + q.difficulty)}</span>
          <span class="badge badge-domain">${q.domain[currentLang]}</span>
        </div>
        <div class="review-question">${i + 1}. ${q.question[currentLang]}</div>
        <div class="review-answer">
          ${selected.length > 0
            ? `${currentLang === 'de' ? 'Deine Antwort' : 'Your answer'}: <span class="${isCorrect ? 'correct-text' : 'incorrect-text'}">${selected.join(', ')}</span>`
            : `<span class="incorrect-text">${currentLang === 'de' ? 'Nicht beantwortet' : 'Not answered'}</span>`}
          ${!isCorrect ? ` — ${currentLang === 'de' ? 'Richtig' : 'Correct'}: <span class="correct-text">${q.correct.join(', ')}</span>` : ''}
        </div>
        ${this.renderExplanation(q)}
      </div>`;
    });
    content.innerHTML = html;
  },

  /* ====== HELPERS ====== */
  renderFilters(exam) {
    const domains = [...new Set(exam.questions.map(q => q.domain[currentLang]))];
    return `<div class="filter-bar">
      <label>${t('filter.domain')}:</label>
      <select id="filter-domain">
        <option value="all">${t('filter.all')}</option>
        ${domains.map(d => `<option value="${d}" ${this.state.filter.domain === d ? 'selected' : ''}>${d}</option>`).join('')}
      </select>
      <label>${t('filter.difficulty')}:</label>
      <select id="filter-difficulty">
        <option value="all">${t('filter.all')}</option>
        <option value="easy" ${this.state.filter.difficulty === 'easy' ? 'selected' : ''}>${t('filter.easy')}</option>
        <option value="medium" ${this.state.filter.difficulty === 'medium' ? 'selected' : ''}>${t('filter.medium')}</option>
        <option value="hard" ${this.state.filter.difficulty === 'hard' ? 'selected' : ''}>${t('filter.hard')}</option>
      </select>
      <label>${t('filter.status')}:</label>
      <select id="filter-status">
        <option value="all">${t('filter.all')}</option>
        <option value="unanswered" ${this.state.filter.status === 'unanswered' ? 'selected' : ''}>${t('filter.unanswered')}</option>
        <option value="correct" ${this.state.filter.status === 'correct' ? 'selected' : ''}>${t('filter.correct')}</option>
        <option value="incorrect" ${this.state.filter.status === 'incorrect' ? 'selected' : ''}>${t('filter.incorrect')}</option>
      </select>
    </div>`;
  },

  renderQuestionHeader(current, total) {
    return `<div class="question-header">
      <span class="question-counter">${t('quiz.question')} ${current + 1} ${t('quiz.of')} ${total}</span>
    </div>`;
  },

  renderQuestionMeta(q) {
    const typeLabel = q.type === 'multiple' ? (currentLang === 'de' ? 'Mehrfachauswahl' : 'Multiple Choice') :
                      q.type === 'scenario' ? (currentLang === 'de' ? 'Szenario' : 'Scenario') :
                      (currentLang === 'de' ? 'Einzelauswahl' : 'Single Choice');
    return `<div class="question-meta">
      <span class="badge badge-${q.difficulty}">${t('filter.' + q.difficulty)}</span>
      <span class="badge badge-domain">${q.domain[currentLang]}</span>
      <span class="badge badge-type">${typeLabel}</span>
    </div>`;
  },

  renderExplanation(q) {
    let html = `<div class="explanation-box">
      <h3>💡 ${t('quiz.explanation')}</h3>
      <p>${q.explanation[currentLang]}</p>`;
    if (q.hint) {
      html += `<div class="hint-box"><h4>💭 ${t('quiz.hint')}</h4><p>${q.hint[currentLang]}</p></div>`;
    }
    if (q.reference) {
      html += `<a href="${q.reference}" target="_blank" class="ref-link">📖 ${t('quiz.reference')}</a>`;
    }
    html += '</div>';
    return html;
  },

  selectOption(questionId, optionId) {
    if (this.state.mode === 'study') {
      if (this.state.studySubmitted[questionId] !== undefined) return;
      if (!this.state.studyAnswers[questionId]) this.state.studyAnswers[questionId] = [];
      const exam = window.ExamData[this.state.currentExam];
      const q = exam.questions.find(qq => qq.id === questionId);
      if (!q) return;
      if (q.type === 'multiple') {
        const idx = this.state.studyAnswers[questionId].indexOf(optionId);
        if (idx >= 0) this.state.studyAnswers[questionId].splice(idx, 1);
        else this.state.studyAnswers[questionId].push(optionId);
      } else {
        this.state.studyAnswers[questionId] = [optionId];
      }
    } else if (this.state.mode === 'quiz' && this.state.quiz) {
      if (this.state.quiz.isSubmitted(questionId)) return;
      this.state.quiz.selectOption(questionId, optionId);
    }
    this.render();
  },

  showStudyAnswer() {
    const questions = this.getFilteredQuestions();
    const q = questions[this.state.currentQuestion];
    if (!q) return;
    const selected = this.state.studyAnswers[q.id] || [];
    const sortedSel = [...selected].sort();
    const sortedCorr = [...q.correct].sort();
    const correct = sortedSel.length === sortedCorr.length && sortedSel.every((v, i) => v === sortedCorr[i]);
    this.state.studySubmitted[q.id] = correct;
    ProgressManager.saveAnswer(this.state.currentExam, q.id, selected, correct);
    this.render();
  },

  submitAnswer() {
    if (!this.state.quiz) return;
    const q = this.state.quiz.getCurrentQuestion();
    if (!q || this.state.quiz.isSubmitted(q.id)) return;
    this.state.quiz.submitAnswer(q.id);
    this.render();
  },

  nextQuestion() {
    if (this.state.mode === 'study') {
      const questions = this.getFilteredQuestions();
      if (this.state.currentQuestion < questions.length - 1) {
        this.state.currentQuestion++;
        this.state.showAnswer = false;
        this.render();
      }
    } else if (this.state.quiz) {
      this.state.quiz.next();
      this.render();
    }
  },

  prevQuestion() {
    if (this.state.mode === 'study') {
      if (this.state.currentQuestion > 0) {
        this.state.currentQuestion--;
        this.state.showAnswer = false;
        this.render();
      }
    } else if (this.state.quiz) {
      this.state.quiz.previous();
      this.render();
    }
  },

  goToQuestion(index) {
    if (this.state.mode === 'study') {
      this.state.currentQuestion = index;
      this.state.showAnswer = false;
    } else if (this.state.quiz) {
      this.state.quiz.goTo(index);
    }
    this.render();
  },

  resetProgress() {
    if (confirm(t('progress.resetConfirm'))) {
      ProgressManager.resetProgress(this.state.currentExam);
      this.state.studyAnswers = {};
      this.state.studySubmitted = {};
      this.render();
    }
  },

  /* ====== UI HELPERS ====== */
  toggleTheme() {
    const current = document.documentElement.getAttribute('data-theme');
    const next = current === 'dark' ? 'light' : 'dark';
    document.documentElement.setAttribute('data-theme', next);
    localStorage.setItem('certportal-theme', next);
    this.updateThemeIcon(next);
  },

  updateThemeIcon(theme) {
    const btn = document.getElementById('theme-toggle');
    if (btn) btn.textContent = theme === 'dark' ? '☀️' : '🌙';
  },

  toggleSidebar() {
    document.getElementById('sidebar').classList.toggle('open');
  },

  closeModal() {
    document.getElementById('modal-overlay').classList.add('hidden');
  },

  clearTimer() {
    if (this.state.timerInterval) {
      clearInterval(this.state.timerInterval);
      this.state.timerInterval = null;
    }
  },

  updateTimerDisplay() {
    if (!this.state.quiz) return;
    const el = document.getElementById('timer-display');
    if (!el) return;
    const remaining = this.state.quiz.getTimeRemaining();
    if (remaining === null) return;
    const mins = Math.floor(remaining);
    const secs = Math.floor((remaining - mins) * 60);
    el.textContent = `${String(mins).padStart(2,'0')}:${String(secs).padStart(2,'0')}`;
    el.className = 'timer-text' + (remaining < 5 ? ' danger' : remaining < 15 ? ' warning' : '');
  },

  updateNavProgress() {
    this.examOrder.forEach(id => {
      const el = document.getElementById(`nav-prog-${id}`);
      if (!el) return;
      const exam = window.ExamData[id];
      if (!exam) { el.textContent = ''; return; }
      const stats = ProgressManager.getStats(id, exam.questions.length);
      el.textContent = stats.percentage > 0 ? `${stats.percentage}%` : '';
    });
  }
};

// Init on DOM ready
document.addEventListener('DOMContentLoaded', () => App.init());
