// ═══════════════════════════════════════════════════════════════
// VERA Vault — Popup Controller
// View routing, chrome.storage integration, credential rendering,
// theme toggling, consent flow, legal modals, enhanced onboarding
// ═══════════════════════════════════════════════════════════════

document.addEventListener('DOMContentLoaded', () => {
  const I = window.VERA_ICONS;
  const icon = window.veraIcon;

  // ─── Legal Content ─────────────────────────────────────────
  const LEGAL = {
    terms: {
      title: 'Terms & Conditions',
      body: `
        <h4>1. Acceptance of Terms</h4>
        <p>By installing and using the VERA Vault browser extension, you agree to these Terms and Conditions. If you do not agree, please uninstall the extension.</p>
        <h4>2. Description of Service</h4>
        <p>VERA Vault is a privacy-preserving browser extension that stores digitally signed purchase credentials locally on your device and generates Zero-Knowledge Proofs for anonymous review verification.</p>
        <h4>3. Privacy-First Architecture</h4>
        <p>VERA does not operate central servers for storing user data. All credentials are stored exclusively in your browser's local storage. We do not collect, transmit, or process any personal information.</p>
        <h4>4. Acceptable Use</h4>
        <p>The cryptographic proofs generated by VERA are intended solely for verifying authentic purchases. Any attempt to forge, manipulate, or misuse credentials is strictly prohibited.</p>
        <h4>5. Data Ownership</h4>
        <p>You retain full ownership of all credentials stored in your Vault. You may delete individual credentials or reset the entire Vault at any time through the Settings page.</p>
        <h4>6. Limitation of Liability</h4>
        <p>VERA is provided as-is for research and educational purposes. The developers are not liable for any loss of data resulting from browser updates, extension removal, or device changes.</p>
      `
    },
    privacy: {
      title: 'Privacy Policy',
      body: `
        <h4>Your Data Stays Yours</h4>
        <p>VERA Vault is designed from the ground up to prevent data collection. We believe privacy is a fundamental right.</p>
        <h4>What We Collect</h4>
        <p><strong>Nothing.</strong> We do not collect analytics, telemetry, usage data, or any personal information. The extension does not make network requests to any VERA-operated server.</p>
        <h4>Local Storage Only</h4>
        <p>Your Verifiable Credentials are stored in Chrome's local storage API. This data exists only on your device and is never synchronized, uploaded, or shared.</p>
        <h4>Zero-Knowledge Proofs</h4>
        <p>When you verify a review, mathematical proofs are generated locally on your device and sent directly to the merchant's website. These proofs do not contain your name, email, IP address, or any information that could identify you.</p>
        <h4>What Merchants Receive</h4>
        <p>Merchants receive only: (1) the cryptographic proof that you purchased the product, and (2) your review text and rating. They cannot determine your identity from this information.</p>
        <h4>Data Deletion</h4>
        <p>You can delete any credential or reset the entire Vault at any time. Uninstalling the extension also removes all stored data.</p>
      `
    }
  };

  // ─── Inject Icons ───────────────────────────────────────────
  function injectIcons() {
    // Navigation
    document.getElementById('navDashIcon').innerHTML = icon('layoutDashboard');
    document.getElementById('navCredIcon').innerHTML = icon('vault');
    document.getElementById('navHistIcon').innerHTML = icon('clock');
    document.getElementById('navSettIcon').innerHTML = icon('settings');
    document.getElementById('navAboutIcon').innerHTML = icon('info');

    // Dashboard stats
    document.getElementById('statSecureIcon').innerHTML = icon('shieldCheck');
    document.getElementById('statVerifiedIcon').innerHTML = icon('checkCircle');

    // Explainer
    document.getElementById('explainerInfoIcon').innerHTML = icon('info');
    document.getElementById('explainerChevron').innerHTML = icon('chevronRight');
    document.getElementById('exp-store-icon').innerHTML = icon('store');
    document.getElementById('exp-shield-icon').innerHTML = icon('shield');
    document.getElementById('exp-check-icon').innerHTML = icon('checkCircle');

    // Settings
    document.getElementById('settingThemeIcon').innerHTML = icon('moon');
    document.getElementById('settingResetIcon').innerHTML = icon('rotateCcw');
    document.getElementById('settingTagIcon').innerHTML = icon('tag');
    document.getElementById('settingTutorialIcon').innerHTML = icon('info');
    document.getElementById('settingTutorialChevron').innerHTML = icon('chevronRight');
    document.getElementById('settingManualIcon').innerHTML = icon('bookOpen');
    document.getElementById('settingManualChevron').innerHTML = icon('chevronRight');
    document.getElementById('settingTermsIcon').innerHTML = icon('externalLink');
    document.getElementById('settingTermsChevron').innerHTML = icon('chevronRight');
    document.getElementById('settingPrivacyIcon').innerHTML = icon('shield');
    document.getElementById('settingPrivacyChevron').innerHTML = icon('chevronRight');

    // Contact & Support
    document.getElementById('contactEmailIcon').innerHTML = icon('mail');
    document.getElementById('contactGithubIcon').innerHTML = icon('github');
    document.getElementById('contactWebIcon').innerHTML = icon('globe');
    document.getElementById('contactBugIcon').innerHTML = icon('alertTriangle');
    if (document.getElementById('contactStarIcon')) {
      document.getElementById('contactStarIcon').innerHTML = icon('star');
    }

    // Detail back button
    document.getElementById('detailBack').innerHTML = icon('chevronLeft');

    // Onboarding icons
    document.getElementById('onb-icon-1').innerHTML = icon('lock', 36);
    document.getElementById('onb-icon-2').innerHTML = icon('fingerprint', 36);
    document.getElementById('onb-icon-3').innerHTML = icon('eyeOff', 36);
    document.getElementById('onb-icon-4').innerHTML = icon('shieldCheck', 36);
    document.getElementById('onboardingBtnIcon').innerHTML = icon('arrowRight');

    // Legal close
    document.getElementById('legalClose').innerHTML = icon('xCircle');
  }

  // ─── Theme Management ──────────────────────────────────────
  function applyTheme(theme) {
    document.documentElement.setAttribute('data-theme', theme);
    const themeToggle = document.getElementById('themeToggle');
    const themeDesc = document.getElementById('themeDesc');
    const themeIcon = document.getElementById('settingThemeIcon');
    if (theme === 'light') {
      themeToggle.classList.remove('active');
      themeDesc.textContent = 'Light';
      themeIcon.innerHTML = icon('eye');
    } else {
      themeToggle.classList.add('active');
      themeDesc.textContent = 'Dark';
      themeIcon.innerHTML = icon('moon');
    }
  }

  document.getElementById('themeToggle').addEventListener('click', () => {
    const current = document.documentElement.getAttribute('data-theme') || 'dark';
    const newTheme = current === 'dark' ? 'light' : 'dark';
    applyTheme(newTheme);
    chrome.storage.local.set({ theme: newTheme });
  });

  // Load saved theme
  chrome.storage.local.get(['theme'], (result) => {
    applyTheme(result.theme || 'dark');
  });

  // ─── View Router ────────────────────────────────────────────
  const views = ['dashboard', 'credentials', 'history', 'settings', 'about', 'error'];
  let currentView = 'dashboard';

  function showView(viewName) {
    views.forEach(v => {
      const viewEl = document.getElementById(`view-${v}`);
      const navEl = document.getElementById(`nav-${v}`);
      if (viewEl) viewEl.classList.toggle('active', v === viewName);
      if (navEl) navEl.classList.toggle('active', v === viewName);
    });
    currentView = viewName;

    // Refresh view data
    if (viewName === 'dashboard') renderDashboard();
    if (viewName === 'credentials') renderCredentials();
    if (viewName === 'history') renderHistory();
  }

  window.showError = function(message) {
    const errorText = document.getElementById('error-message-text');
    if (errorText) errorText.textContent = message || 'An unexpected error occurred.';
    showView('error');
  };

  // Bind the return button since showView is not global
  document.querySelector('#view-error .btn-primary').addEventListener('click', () => {
    showView('dashboard');
  });

  // Nav click handlers
  document.querySelectorAll('.nav-item').forEach(btn => {
    btn.addEventListener('click', () => {
      const view = btn.getAttribute('data-view');
      if (view) showView(view);
    });
  });

  // ─── Chrome Storage Helpers ─────────────────────────────────
  async function getCredentials() {
    return new Promise(resolve => {
      chrome.storage.local.get(['credentials'], result => {
        resolve(result.credentials || []);
      });
    });
  }

  async function getHistory() {
    return new Promise(resolve => {
      chrome.storage.local.get(['verificationHistory'], result => {
        resolve(result.verificationHistory || []);
      });
    });
  }

  async function clearCredentials() {
    return new Promise(resolve => {
      chrome.storage.local.set({ credentials: [] }, () => {
        chrome.action.setBadgeText({ text: '' });
        resolve();
      });
    });
  }

  async function resetVault() {
    return new Promise(resolve => {
      chrome.storage.local.clear(() => {
        chrome.action.setBadgeText({ text: '' });
        resolve();
      });
    });
  }

  // ─── Time Formatting ───────────────────────────────────────
  function timeAgo(dateStr) {
    const diff = Date.now() - new Date(dateStr).getTime();
    const mins = Math.floor(diff / 60000);
    if (mins < 1) return 'Just now';
    if (mins < 60) return `${mins}m ago`;
    const hrs = Math.floor(mins / 60);
    if (hrs < 24) return `${hrs}h ago`;
    const days = Math.floor(hrs / 24);
    return `${days}d ago`;
  }

  // ─── Store Name Formatting ───────────────────────────────────
  function getStoreName(storeID) {
    if (!storeID) return 'Unknown Store';
    // Known display name overrides (for demo/test merchants)
    const knownStores = {
      'ShopFresh-Demo': 'ShopFresh',
      'ShopFresh': 'ShopFresh',
    };
    if (knownStores[storeID]) return knownStores[storeID];
    // For any other store, format the ID cleanly:
    // e.g. 'my-store-123' → 'My Store 123'
    // Short 3-char or fewer IDs are likely test data — label them clearly
    if (storeID.length <= 4) return `Store (${storeID})`;
    return storeID
      .replace(/[-_]/g, ' ')
      .replace(/\b\w/g, c => c.toUpperCase())
      .trim();
  }

  // ─── Dashboard ──────────────────────────────────────────────
  async function renderDashboard() {
    const credentials = await getCredentials();
    const history = await getHistory();

    // Update counts
    document.getElementById('credCount').textContent = credentials.length;
    const verified = history.filter(h => h.verified).length;
    document.getElementById('verifiedCount').textContent = verified;

    const activityEl = document.getElementById('recentActivity');
    const explainerCard = document.querySelector('.explainer-card');
    
    // Dashboard
    if (credentials.length === 0) {
      if (explainerCard) {
        explainerCard.style.display = 'block';
        activityEl.parentNode.insertBefore(explainerCard, activityEl);
      }
      activityEl.innerHTML = `
        <div class="empty-state">
          <div class="empty-icon">${icon('vault', 40)}</div>
          <div class="empty-title">Your Vault is Empty</div>
          <div class="empty-desc">To get started, make a purchase on any VERA-supported store. Your secure receipt will automatically appear here.</div>
        </div>`;
      return;
    }
    
    if (explainerCard) {
      explainerCard.style.display = 'block';
      if (activityEl.nextSibling) {
        activityEl.parentNode.insertBefore(explainerCard, activityEl.nextSibling);
      } else {
        activityEl.parentNode.appendChild(explainerCard);
      }
    }

    // Show last 3 credentials as activity items
    const recent = [...credentials].reverse().slice(0, 3);
    activityEl.innerHTML = recent.map(cred => {
      const subject = cred.credential?.credentialSubject || {};
      return `
        <div class="activity-item">
          <div class="activity-icon">${icon('shieldCheck')}</div>
          <div class="activity-text">
            <div class="activity-title">Credential from ${getStoreName(subject.storeID)}</div>
            <div class="activity-time">${timeAgo(cred.storedAt)}</div>
          </div>
        </div>`;
    }).join('');
  }

  // ─── Credentials ────────────────────────────────────────────
  async function renderCredentials() {
    const credentials = await getCredentials();
    const listEl = document.getElementById('credentialsList');

    if (credentials.length === 0) {
      listEl.innerHTML = `
        <div class="empty-state">
          <div class="empty-icon">${icon('vault', 48)}</div>
          <div class="empty-title">Your Wallet is Empty</div>
          <div class="empty-desc">No digital credentials have been issued to you yet. Shop at a VERA-supported merchant to begin building your wallet.</div>
        </div>`;
      return;
    }

    listEl.innerHTML = [...credentials].reverse().map((cred, idx) => {
      const subject = cred.credential?.credentialSubject || {};
      const realIdx = credentials.length - 1 - idx;
      return `
        <div class="wallet-card" data-index="${realIdx}">
          <div class="wallet-card-header">
            <div class="wallet-store-info">
              <span class="wallet-store-icon">${icon('store')}</span>
              <span class="wallet-store-name">${getStoreName(subject.storeID)}</span>
            </div>
            <div class="wallet-date">${timeAgo(cred.storedAt)}</div>
          </div>
          <div class="wallet-card-body">
            <div class="wallet-sku-label">Product SKU</div>
            <div class="wallet-sku-value">${subject.itemSKU || 'N/A'}</div>
          </div>
          <div class="wallet-card-footer">
            <div class="wallet-status secured">
              <span class="wallet-status-icon">${icon('shieldCheck')}</span>
              <span>Secured in Vault</span>
            </div>
          </div>
        </div>`;
    }).join('');

    // Add click handlers
    listEl.querySelectorAll('.credential-card').forEach(card => {
      card.addEventListener('click', () => {
        const idx = parseInt(card.getAttribute('data-index'));
        openCredentialDetail(credentials[idx], idx);
      });
    });
  }

  // ─── Credential Detail ──────────────────────────────────────
  function openCredentialDetail(cred, index) {
    const detailView = document.getElementById('detailView');
    const detailBody = document.getElementById('detailBody');
    const subject = cred.credential?.credentialSubject || {};

    detailBody.innerHTML = `
      <div class="detail-section">
        <div class="detail-section-title">${icon('eye')} Revealed to Merchants</div>
        <div class="detail-field">
          <span class="detail-field-label">Store</span>
          <span class="detail-field-value revealed">${getStoreName(subject.storeID)}</span>
        </div>
        <div class="detail-field">
          <span class="detail-field-label">Item SKU</span>
          <span class="detail-field-value revealed">${subject.itemSKU || 'N/A'}</span>
        </div>
      </div>
      <div class="detail-section">
        <div class="detail-section-title">${icon('eyeOff')} Protected by Zero-Knowledge Proof</div>
        <div class="detail-field">
          <span class="detail-field-label">Invoice ID</span>
          <span class="detail-field-value hidden">${'\u2022'.repeat(12)}</span>
        </div>
        <div class="detail-field">
          <span class="detail-field-label">Purchase Date</span>
          <span class="detail-field-value hidden">${'\u2022'.repeat(12)}</span>
        </div>
      </div>
      <div class="detail-section">
        <div class="detail-section-title">${icon('info')} Metadata</div>
        <div class="detail-field">
          <span class="detail-field-label">Received</span>
          <span class="detail-field-value">${new Date(cred.storedAt).toLocaleString()}</span>
        </div>
        <div class="detail-field">
          <span class="detail-field-label">Issuer</span>
          <span class="detail-field-value" style="font-size:11px">${cred.credential?.issuer || 'Unknown'}</span>
        </div>
        <div class="detail-field">
          <span class="detail-field-label">Type</span>
          <span class="detail-field-value">BBS+ Signature</span>
        </div>
      </div>
      <button class="detail-delete" id="deleteCredBtn">
        ${icon('trash2')} Delete Credential
      </button>`;

    detailView.classList.add('active');

    // Delete handler
    document.getElementById('deleteCredBtn').addEventListener('click', () => {
      showConfirm(
        'Delete Credential',
        'This credential will be permanently removed from your vault. This action cannot be undone.',
        'Delete',
        async () => {
          const creds = await getCredentials();
          creds.splice(index, 1);
          await new Promise(resolve => {
            chrome.storage.local.set({ credentials: creds }, resolve);
          });
          if (creds.length > 0) {
            chrome.action.setBadgeText({ text: String(creds.length) });
          } else {
            chrome.action.setBadgeText({ text: '' });
          }
          detailView.classList.remove('active');
          showToast('Credential deleted', 'success');
          renderCredentials();
          renderDashboard();
        }
      );
    });
  }

  // Detail back button
  document.getElementById('detailBack').addEventListener('click', () => {
    document.getElementById('detailView').classList.remove('active');
  });

  function hashCode(str) {
    let hash = 0;
    for (let i = 0, len = str.length; i < len; i++) {
        let chr = str.charCodeAt(i);
        hash = (hash << 5) - hash + chr;
        hash |= 0;
    }
    return hash;
  }

  // ─── History ────────────────────────────────────────────────
  async function renderHistory() {
    const history = await getHistory();
    const listEl = document.getElementById('historyList');

    if (history.length === 0) {
      listEl.innerHTML = `
        <div class="empty-state">
          <div class="empty-icon">${icon('clock', 40)}</div>
          <div class="empty-title">No verification history</div>
          <div class="empty-desc">Once you use a credential to anonymously verify a review, your activity will appear here.</div>
        </div>`;
      return;
    }

    const total = history.length;
    listEl.innerHTML = [...history].reverse().map((h, idx) => {
      const isVerified = h.verified;
      const credNumber = total - idx;
      return `
        <div class="history-item">
          <div class="history-icon ${isVerified ? 'verified' : 'failed'}">
            ${isVerified ? icon('checkCircle') : icon('xCircle')}
          </div>
          <div class="history-info">
            <div class="history-title">Verified Credential #${credNumber}</div>
            <div class="history-meta">${timeAgo(h.timestamp)}</div>
          </div>
          <span class="history-badge ${isVerified ? 'verified' : 'failed'}">
            ${isVerified ? 'Verified' : 'Failed'}
          </span>
        </div>`;
    }).join('');
  }

  // ─── Toast Notifications ────────────────────────────────────
  function showToast(message, type = 'info') {
    const container = document.getElementById('toastContainer');
    const iconMap = {
      success: icon('checkCircle'),
      error: icon('xCircle'),
      warning: icon('alertTriangle'),
      info: icon('info'),
    };

    const toast = document.createElement('div');
    toast.className = `toast ${type}`;
    toast.innerHTML = `
      <span class="toast-icon">${iconMap[type] || iconMap.info}</span>
      <span class="toast-text">${message}</span>`;
    container.appendChild(toast);

    setTimeout(() => {
      toast.classList.add('dismissing');
      setTimeout(() => toast.remove(), 200);
    }, 3000);
  }

  // ─── Confirm Dialog ─────────────────────────────────────────
  let confirmCallback = null;

  function showConfirm(title, message, actionText, callback) {
    document.getElementById('confirmTitle').textContent = title;
    document.getElementById('confirmMessage').textContent = message;
    document.getElementById('confirmAction').textContent = actionText;
    confirmCallback = callback;
    document.getElementById('confirmOverlay').classList.add('active');
  }

  document.getElementById('confirmCancel').addEventListener('click', () => {
    document.getElementById('confirmOverlay').classList.remove('active');
    confirmCallback = null;
  });

  document.getElementById('confirmAction').addEventListener('click', async () => {
    document.getElementById('confirmOverlay').classList.remove('active');
    if (confirmCallback) {
      await confirmCallback();
      confirmCallback = null;
    }
  });

  // ─── Legal Modal ────────────────────────────────────────────
  function showLegal(type) {
    const content = LEGAL[type];
    if (!content) return;
    document.getElementById('legalTitle').textContent = content.title;
    document.getElementById('legalBody').innerHTML = content.body;
    document.getElementById('legalOverlay').classList.add('active');
  }

  function closeLegal() {
    document.getElementById('legalOverlay').classList.remove('active');
  }

  document.getElementById('legalClose').addEventListener('click', closeLegal);
  document.getElementById('legalDismiss').addEventListener('click', closeLegal);

  // Legal from onboarding consent screen
  document.getElementById('viewTerms').addEventListener('click', () => showLegal('terms'));
  document.getElementById('viewPrivacy').addEventListener('click', () => showLegal('privacy'));

  // Legal from settings
  document.getElementById('settingsTerms').addEventListener('click', () => showLegal('terms'));
  document.getElementById('settingsPrivacy').addEventListener('click', () => showLegal('privacy'));

  // ─── Settings Handlers ──────────────────────────────────────
  document.getElementById('resetVaultBtn').addEventListener('click', () => {
    showConfirm(
      'Reset Vault',
      'This will clear all data including credentials, verification history, and preferences. The onboarding screen will appear again on next open.',
      'Reset Everything',
      async () => {
        await resetVault();
        showToast('Vault has been reset', 'success');
        applyTheme('dark');
        renderDashboard();
        renderCredentials();
        renderHistory();
      }
    );
  });

  // Reopen Tutorial from Settings
  document.getElementById('reopenTutorial').addEventListener('click', () => {
    onboardingSlide = 0;
    updateOnboardingUI();
    document.getElementById('consentCheckbox').checked = false;
    document.getElementById('onboarding').classList.add('active');
  });

  // Open User Manual
  document.getElementById('openUserManual')?.addEventListener('click', () => {
    chrome.tabs.create({ url: 'https://vera-vault.vercel.app/assets/vera-user-manual.pdf' });
  });

  // Explainer toggle
  document.getElementById('explainerToggle').addEventListener('click', () => {
    const body = document.getElementById('explainerBody');
    const chevron = document.getElementById('explainerChevron');
    body.classList.toggle('open');
    chevron.style.transform = body.classList.contains('open') ? 'rotate(90deg)' : '';
  });

  // ─── Onboarding (Enhanced 5-Step with Consent) ──────────────
  const TOTAL_SLIDES = 5;
  let onboardingSlide = 0;

  function updateOnboardingUI() {
    // Update slides
    document.querySelectorAll('.onboarding-slide').forEach(s => s.classList.remove('active'));
    const targetSlide = document.querySelector(`[data-slide="${onboardingSlide}"]`);
    if (targetSlide) targetSlide.classList.add('active');

    // Update dots
    document.querySelectorAll('.onboarding-dot').forEach(d => d.classList.remove('active'));
    const targetDot = document.querySelector(`[data-dot="${onboardingSlide}"]`);
    if (targetDot) targetDot.classList.add('active');

    // Update button text
    const btnText = document.getElementById('onboardingBtnText');
    const btn = document.getElementById('onboardingBtn');

    if (onboardingSlide === TOTAL_SLIDES - 1) {
      btnText.textContent = 'Get Started';
      // Disable button until consent checkbox is checked
      btn.disabled = !document.getElementById('consentCheckbox').checked;
      btn.style.opacity = btn.disabled ? '0.5' : '1';
    } else {
      btnText.textContent = 'Next';
      btn.disabled = false;
      btn.style.opacity = '1';
    }
  }

  // Consent checkbox enables/disables the final button
  document.getElementById('consentCheckbox').addEventListener('change', (e) => {
    if (onboardingSlide === TOTAL_SLIDES - 1) {
      const btn = document.getElementById('onboardingBtn');
      btn.disabled = !e.target.checked;
      btn.style.opacity = btn.disabled ? '0.5' : '1';
    }
  });

  async function checkOnboarding() {
    return new Promise(resolve => {
      chrome.storage.local.get(['onboardingComplete'], result => {
        if (!result.onboardingComplete) {
          document.getElementById('onboarding').classList.add('active');
          updateOnboardingUI();
        }
        resolve();
      });
    });
  }

  document.getElementById('onboardingBtn').addEventListener('click', () => {
    if (document.getElementById('onboardingBtn').disabled) return;

    onboardingSlide++;
    if (onboardingSlide >= TOTAL_SLIDES) {
      // Complete onboarding
      chrome.storage.local.set({ onboardingComplete: true });
      document.getElementById('onboarding').classList.remove('active');
      showToast('Welcome to VERA Vault', 'success');
      return;
    }

    updateOnboardingUI();
  });

  // ─── Listen for Storage Changes (live updates) ──────────────
  chrome.storage.onChanged.addListener((changes, area) => {
    if (area === 'local') {
      if (changes.credentials) {
        const newCreds = changes.credentials.newValue || [];
        const oldCreds = changes.credentials.oldValue || [];
        if (newCreds.length > oldCreds.length) {
          showToast('Credential securely stored', 'success');
        }
        if (currentView === 'dashboard') renderDashboard();
        if (currentView === 'credentials') renderCredentials();
      }
      if (changes.verificationHistory) {
        const newHist = changes.verificationHistory.newValue || [];
        const oldHist = changes.verificationHistory.oldValue || [];
        if (newHist.length > oldHist.length) {
          const latest = newHist[newHist.length - 1];
          if (latest.verified) {
            showToast('Purchase verified successfully', 'success');
          } else {
            showToast('Verification failed', 'error');
          }
        }
        if (currentView === 'dashboard') renderDashboard();
        if (currentView === 'history') renderHistory();
      }
    }
  });

  // ─── Initialize ─────────────────────────────────────────────
  injectIcons();
  checkOnboarding();
  renderDashboard();

  window.addEventListener('error', (event) => {
    window.showError(event.message || 'A runtime error occurred.');
  });
  window.addEventListener('unhandledrejection', (event) => {
    window.showError(event.reason?.message || 'An unexpected action failed.');
  });
});
