/**
 * VaultTab — Full Password Manager UI for Chrome Extension Side Panel
 * Ported from apps/zeq-vault/ UI logic.
 * Lock screen → entry sidebar + detail panel with password-based encryption.
 *
 * @version 1.287.5
 * @license CC BY 4.0 — Zeq. H / Zeq 1.287 Hz Limited
 */
const VaultTab = (() => {
  'use strict';

  let container = null;
  let selectedId = null;
  let editingId = null;
  let pendingDeleteId = null;

  // ── DOM refs ──────────────────────────────────────────────────────────────
  let $lockScreen, $vaultScreen, $masterInput, $masterPreview, $lockError,
      $btnUnlock, $btnCreateVault, $createPage, $unlockPage,
      $createInput, $createPreview, $btnCreateGo, $btnSwitchToUnlock,
      $entryList, $entryCount, $searchInput, $detailEmpty, $detailContent,
      $statusEntries, $statusAutolock, $modalEntry, $modalConfirm, $modalImport;

  let _generatedVaultPassword = null;

  // ── Init ──────────────────────────────────────────────────────────────────
  function init(containerId) {
    container = document.getElementById(containerId);
    if (!container) return;
    container.innerHTML = '';

    // Check if user is authenticated — if not, show "Log in" message
    if (typeof ZeqAuth !== 'undefined' && !ZeqAuth.isAuthenticated()) {
      _showLoginRequired();
      return;
    }

    _buildHTML();
    _cacheDOM();
    _bindEvents();
    _initLockScreen();

    VaultClient.on('lock', _onLock);
    VaultClient.on('unlock', _onUnlock);
    VaultClient.on('change', _onDataChange);
    VaultClient.on('autoLockTick', _onAutoLockTick);

    // Pass server credentials to VaultClient for sync
    if (typeof ZeqAuth !== 'undefined' && ZeqAuth.isAuthenticated()) {
      VaultClient.setServerCredentials(ZeqAuth.getToken());
    }

    // If already unlocked, show vault directly
    if (VaultClient.isUnlocked()) {
      _showVault();
      return;
    }

    // Auto-unlock: try stored password from login
    _attemptAutoUnlock();
  }

  async function _attemptAutoUnlock() {
    // Get the auth password from storage (chrome.storage or sessionStorage fallback)
    let password = null;
    try {
      if (typeof chrome !== 'undefined' && chrome.storage?.local) {
        const result = await new Promise(resolve =>
          chrome.storage.local.get('zeq_master_password', resolve)
        );
        password = result.zeq_master_password;
      }
    } catch { /* chrome.storage not available */ }
    // Fallback: check sessionStorage (used by dev server / browser testing)
    if (!password) password = sessionStorage.getItem('zeq_master_password');
    if (!password) return;

    try {
      if (!VaultClient.hasStoredVault()) {
        // No vault exists — auto-CREATE with the auth password
        console.log('[VaultTab] No vault found — auto-creating with auth password');
        await VaultClient.createVault(password);
        return; // createVault fires 'unlock' event → _onUnlock → _showVault
      }
      // Vault exists — try unlocking with auth password
      await VaultClient.unlockVault(password);
      // Sync from server
      if (typeof VaultClient.syncFromServer === 'function') {
        VaultClient.syncFromServer(password);
      }
    } catch {
      // Vault exists but auth password can't decrypt it (old vault from different account)
      // Clear old vault and create fresh — auth password is the source of truth
      console.log('[VaultTab] Old vault from different account — recreating with current auth password');
      localStorage.removeItem('zeq-vault-data');
      try {
        await VaultClient.createVault(password);
      } catch (e2) {
        console.warn('[VaultTab] Failed to create vault:', e2.message);
      }
    }
  }

  function _showLoginRequired() {
    container.innerHTML = `
      <div style="display:flex;flex-direction:column;align-items:center;justify-content:center;height:100%;padding:32px;text-align:center">
        <svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="rgba(139,92,246,0.4)" stroke-width="1.5">
          <rect x="3" y="11" width="18" height="11" rx="2"/><circle cx="12" cy="16" r="1"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/>
        </svg>
        <div style="font-size:16px;font-weight:600;color:#e2e8f0;margin-top:16px">Zeq Vault</div>
        <div style="font-size:13px;color:#64748b;margin-top:8px;max-width:240px">
          Log in with your Zeq ID to access the encrypted password vault.
        </div>
        <div style="font-size:11px;color:#475569;margin-top:16px">
          Use the header badge to log in.
        </div>
      </div>
    `;
  }

  function destroy() {
    VaultClient.off('lock', _onLock);
    VaultClient.off('unlock', _onUnlock);
    VaultClient.off('change', _onDataChange);
    VaultClient.off('autoLockTick', _onAutoLockTick);
    if (container) container.innerHTML = '';
  }

  // ── Build HTML ────────────────────────────────────────────────────────────
  function _buildHTML() {
    container.innerHTML = `
      <!-- Lock Screen -->
      <div class="vt-lock-screen" id="vt-lock-screen">
        <!-- Create Vault Page -->
        <div class="vt-lock-page" id="vt-create-page" style="display:none">
          <div class="vt-lock-logo">
            <svg width="40" height="40" viewBox="0 0 24 24" fill="none" stroke="#22d3ee" stroke-width="1.5"><rect x="3" y="11" width="18" height="11" rx="2"/><circle cx="12" cy="16" r="1"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/></svg>
          </div>
          <div class="vt-lock-title">Create New Vault</div>
          <div class="vt-lock-desc">Type a phrase to generate your secret equation key, or paste an existing equation.</div>
          <div class="vt-form-group">
            <label class="vt-label">Phrase Seed</label>
            <input type="text" class="vt-input vt-input-mono" id="vt-create-input" placeholder="e.g. quantum nebula beyond midnight" autocomplete="off" />
          </div>
          <div class="vt-eq-preview" id="vt-create-preview">Type a phrase (2+ words) to generate your equation key...</div>
          <div class="vt-error" id="vt-create-error" style="display:none"></div>
          <button class="vt-btn vt-btn-primary" id="vt-btn-create-go" disabled><span>Create Vault</span></button>
          <div class="vt-lock-links">
            <button class="vt-link" id="vt-btn-switch-to-unlock">I already have a vault</button>
          </div>
        </div>

        <!-- Unlock Vault Page -->
        <div class="vt-lock-page" id="vt-unlock-page" style="display:none">
          <div class="vt-lock-logo">
            <svg width="40" height="40" viewBox="0 0 24 24" fill="none" stroke="#8b5cf6" stroke-width="1.5"><rect x="3" y="11" width="18" height="11" rx="2"/><circle cx="12" cy="16" r="1"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/></svg>
          </div>
          <div class="vt-lock-title">Unlock Vault</div>
          <div class="vt-lock-desc">Enter the equation you saved when creating your vault.</div>
          <div class="vt-form-group">
            <label class="vt-label">Master Equation</label>
            <input type="text" class="vt-input vt-input-mono" id="vt-master-input" placeholder="Paste your equation key..." autocomplete="off" />
          </div>
          <div class="vt-eq-preview" id="vt-master-preview">Paste the equation you saved...</div>
          <div class="vt-error" id="vt-lock-error" style="display:none"></div>
          <button class="vt-btn vt-btn-purple" id="vt-btn-unlock" disabled><span>Unlock Vault</span></button>
          <div class="vt-lock-links">
            <button class="vt-link" id="vt-btn-create-vault">Create a new vault</button>
            <button class="vt-link" id="vt-btn-import-lock">Import backup</button>
          </div>
        </div>
      </div>

      <!-- Vault Screen -->
      <div class="vt-vault-screen" id="vt-vault-screen" style="display:none">
        <div class="vt-sidebar" id="vt-sidebar">
          <div class="vt-sidebar-header">
            <div class="vt-sidebar-title">Vault</div>
            <div class="vt-sidebar-actions">
              <button class="vt-btn-icon" id="vt-btn-add-entry" title="Add Entry">
                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>
              </button>
              <button class="vt-btn-icon" id="vt-btn-lock" title="Lock Vault">
                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="3" y="11" width="18" height="11" rx="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/></svg>
              </button>
            </div>
          </div>
          <div class="vt-search-wrap">
            <input type="text" class="vt-search" id="vt-search" placeholder="Search entries..." autocomplete="off" />
          </div>
          <div class="vt-entry-list" id="vt-entry-list"></div>
          <div class="vt-sidebar-footer">
            <span id="vt-entry-count">0</span> entries
          </div>
        </div>
        <div class="vt-sidebar-overlay" id="vt-sidebar-overlay"></div>
        <div class="vt-detail" id="vt-detail-area">
          <div class="vt-detail-empty" id="vt-detail-empty">
            <svg width="40" height="40" viewBox="0 0 24 24" fill="none" stroke="rgba(139,92,246,0.3)" stroke-width="1.5"><rect x="3" y="11" width="18" height="11" rx="2"/><circle cx="12" cy="16" r="1"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/></svg>
            <div class="vt-detail-empty-text">Select an entry to view details</div>
          </div>
          <div class="vt-detail-content" id="vt-detail-content" style="display:none"></div>
        </div>
        <div class="vt-status-bar">
          <span class="vt-status-crypto">AES-256-GCM</span>
          <span id="vt-status-entries">0 entries</span>
          <span class="vt-status-hz">1.287 Hz</span>
          <span id="vt-status-autolock">Auto-lock: 5:00</span>
        </div>
      </div>

      <!-- Toolbar (mobile) -->
      <button class="vt-btn-mobile-menu" id="vt-btn-mobile-menu">
        <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="3" y1="12" x2="21" y2="12"/><line x1="3" y1="6" x2="21" y2="6"/><line x1="3" y1="18" x2="21" y2="18"/></svg>
      </button>

      <!-- Entry Modal -->
      <div class="vt-modal" id="vt-modal-entry">
        <div class="vt-modal-content">
          <div class="vt-modal-header" id="vt-modal-entry-title"><span>Add New Entry</span></div>
          <div class="vt-modal-body">
            <div class="vt-form-group"><label class="vt-label">Service Name *</label><input type="text" class="vt-input" id="vt-entry-service" placeholder="e.g. GitHub" /></div>
            <div class="vt-form-group"><label class="vt-label">URL</label><input type="text" class="vt-input" id="vt-entry-url" placeholder="e.g. github.com" /></div>
            <div class="vt-form-group"><label class="vt-label">Username</label><input type="text" class="vt-input" id="vt-entry-username" placeholder="e.g. zeq@example.com" /></div>
            <div class="vt-form-group">
              <label class="vt-label">Equation (Password) *</label>
              <div style="display:flex;gap:6px">
                <input type="text" class="vt-input vt-input-mono" id="vt-entry-equation" placeholder="e.g. sin(x) + cos(y*pi)" style="flex:1" />
                <button class="vt-btn vt-btn-ghost vt-btn-sm" id="vt-btn-generate-eq" title="Generate">⚡</button>
              </div>
              <div class="vt-eq-preview" id="vt-entry-eq-preview">Enter an equation...</div>
              <div class="vt-strength-bar" id="vt-entry-strength-bar" data-strength="0">
                <div class="seg"></div><div class="seg"></div><div class="seg"></div><div class="seg"></div><div class="seg"></div>
                <div class="seg"></div><div class="seg"></div><div class="seg"></div><div class="seg"></div><div class="seg"></div>
              </div>
              <div class="vt-strength-label" id="vt-entry-strength-label" data-strength="0"></div>
            </div>
            <div class="vt-form-group"><label class="vt-label">Notes</label><textarea class="vt-input" id="vt-entry-notes" rows="3" placeholder="Optional notes..."></textarea></div>
          </div>
          <div class="vt-modal-footer">
            <button class="vt-btn vt-btn-ghost" id="vt-btn-cancel-entry">Cancel</button>
            <button class="vt-btn vt-btn-primary" id="vt-btn-save-entry">Save</button>
          </div>
        </div>
      </div>

      <!-- Confirm Delete Modal -->
      <div class="vt-modal" id="vt-modal-confirm">
        <div class="vt-modal-content vt-modal-sm">
          <div class="vt-modal-header"><span>Confirm Delete</span></div>
          <div class="vt-modal-body"><p id="vt-confirm-body"></p></div>
          <div class="vt-modal-footer">
            <button class="vt-btn vt-btn-ghost" id="vt-btn-confirm-cancel">Cancel</button>
            <button class="vt-btn vt-btn-danger" id="vt-btn-confirm-ok">Delete</button>
          </div>
        </div>
      </div>

      <!-- Import Modal -->
      <div class="vt-modal" id="vt-modal-import">
        <div class="vt-modal-content">
          <div class="vt-modal-header"><span>Import Backup</span></div>
          <div class="vt-modal-body">
            <div class="vt-form-group">
              <label class="vt-label">Backup File</label>
              <div style="display:flex;gap:8px;align-items:center">
                <button class="vt-btn vt-btn-ghost vt-btn-sm" id="vt-btn-pick-file">Choose File</button>
                <span id="vt-import-file-name" style="font-size:12px;color:var(--text-secondary,#a0a0b8)"></span>
              </div>
              <input type="file" id="vt-import-file-hidden" accept=".json" style="display:none" />
            </div>
            <div class="vt-form-group">
              <label class="vt-label">Master Equation (for backup)</label>
              <input type="text" class="vt-input vt-input-mono" id="vt-import-eq" placeholder="Enter the equation used for the backup..." />
            </div>
          </div>
          <div class="vt-modal-footer">
            <button class="vt-btn vt-btn-ghost" id="vt-btn-cancel-import">Cancel</button>
            <button class="vt-btn vt-btn-primary" id="vt-btn-do-import">Import</button>
          </div>
        </div>
      </div>
    `;
  }

  function _cacheDOM() {
    $lockScreen = container.querySelector('#vt-lock-screen');
    $vaultScreen = container.querySelector('#vt-vault-screen');
    $masterInput = container.querySelector('#vt-master-input');
    $masterPreview = container.querySelector('#vt-master-preview');
    $lockError = container.querySelector('#vt-lock-error');
    $btnUnlock = container.querySelector('#vt-btn-unlock');
    $btnCreateVault = container.querySelector('#vt-btn-create-vault');
    $createPage = container.querySelector('#vt-create-page');
    $unlockPage = container.querySelector('#vt-unlock-page');
    $createInput = container.querySelector('#vt-create-input');
    $createPreview = container.querySelector('#vt-create-preview');
    $btnCreateGo = container.querySelector('#vt-btn-create-go');
    $btnSwitchToUnlock = container.querySelector('#vt-btn-switch-to-unlock');
    $entryList = container.querySelector('#vt-entry-list');
    $entryCount = container.querySelector('#vt-entry-count');
    $searchInput = container.querySelector('#vt-search');
    $detailEmpty = container.querySelector('#vt-detail-empty');
    $detailContent = container.querySelector('#vt-detail-content');
    $statusEntries = container.querySelector('#vt-status-entries');
    $statusAutolock = container.querySelector('#vt-status-autolock');
    $modalEntry = container.querySelector('#vt-modal-entry');
    $modalConfirm = container.querySelector('#vt-modal-confirm');
    $modalImport = container.querySelector('#vt-modal-import');
  }

  // ── Bind Events ───────────────────────────────────────────────────────────
  function _bindEvents() {
    // Create vault - phrase input
    $createInput.addEventListener('input', _updateCreatePreview);
    $createInput.addEventListener('keydown', (e) => {
      if (e.key === 'Enter' && !$btnCreateGo.disabled) $btnCreateGo.click();
    });

    // Create vault button
    $btnCreateGo.addEventListener('click', async () => {
      const pwd = _generatedVaultPassword;
      if (!pwd) return;
      $btnCreateGo.disabled = true;
      $btnCreateGo.querySelector('span').textContent = 'Creating...';
      try {
        await VaultClient.createVault(pwd);
      } catch (err) {
        const errEl = container.querySelector('#vt-create-error');
        errEl.textContent = 'Failed: ' + err.message;
        errEl.style.display = 'block';
        $btnCreateGo.disabled = false;
        $btnCreateGo.querySelector('span').textContent = 'Create Vault';
      }
    });

    // Switch between create/unlock
    $btnSwitchToUnlock.addEventListener('click', () => {
      $createPage.style.display = 'none';
      $unlockPage.style.display = 'flex';
      $masterInput.focus();
    });
    $btnCreateVault.addEventListener('click', () => {
      $unlockPage.style.display = 'none';
      $createPage.style.display = 'flex';
      $createInput.focus();
    });

    // Master equation input
    $masterInput.addEventListener('input', _updateMasterPreview);
    $masterInput.addEventListener('keydown', (e) => {
      if (e.key === 'Enter' && !$btnUnlock.disabled) $btnUnlock.click();
    });

    // Unlock button
    $btnUnlock.addEventListener('click', async () => {
      const eq = $masterInput.value.trim();
      if (!eq) return;
      $lockError.style.display = 'none';
      $btnUnlock.disabled = true;
      $btnUnlock.querySelector('span').textContent = 'Decrypting...';
      try {
        await VaultClient.unlockVault(eq);
      } catch (err) {
        $lockError.textContent = 'Wrong equation. Could not decrypt.';
        $lockError.style.display = 'block';
        $btnUnlock.disabled = false;
        $btnUnlock.querySelector('span').textContent = 'Unlock Vault';
      }
    });

    // Lock button
    container.querySelector('#vt-btn-lock').addEventListener('click', () => VaultClient.lockVault());

    // Add entry
    container.querySelector('#vt-btn-add-entry').addEventListener('click', _openAddModal);

    // Search
    $searchInput.addEventListener('input', () => _renderEntryList());

    // Entry modal
    container.querySelector('#vt-entry-equation').addEventListener('input', _updateEntryPreview);
    container.querySelector('#vt-btn-generate-eq').addEventListener('click', () => {
      const eq = VaultClient.generateEquation(Math.floor(Math.random() * 3) + 3);
      container.querySelector('#vt-entry-equation').value = eq;
      _updateEntryPreview();
    });
    container.querySelector('#vt-btn-cancel-entry').addEventListener('click', () => $modalEntry.classList.remove('active'));
    container.querySelector('#vt-btn-save-entry').addEventListener('click', _saveEntry);

    // Delete confirm
    container.querySelector('#vt-btn-confirm-cancel').addEventListener('click', () => { $modalConfirm.classList.remove('active'); pendingDeleteId = null; });
    container.querySelector('#vt-btn-confirm-ok').addEventListener('click', _doDelete);

    // Import
    container.querySelector('#vt-btn-import-lock').addEventListener('click', () => $modalImport.classList.add('active'));
    container.querySelector('#vt-btn-pick-file').addEventListener('click', () => container.querySelector('#vt-import-file-hidden').click());
    container.querySelector('#vt-import-file-hidden').addEventListener('change', (e) => {
      const file = e.target.files[0];
      if (file) container.querySelector('#vt-import-file-name').textContent = file.name;
    });
    container.querySelector('#vt-btn-cancel-import').addEventListener('click', () => $modalImport.classList.remove('active'));
    container.querySelector('#vt-btn-do-import').addEventListener('click', _doImport);

    // Export
    // (added to detail actions below via event delegation)

    // Mobile sidebar toggle
    container.querySelector('#vt-btn-mobile-menu').addEventListener('click', () => {
      container.querySelector('#vt-sidebar').classList.toggle('open');
      container.querySelector('#vt-sidebar-overlay').classList.toggle('open');
    });
    container.querySelector('#vt-sidebar-overlay').addEventListener('click', () => {
      container.querySelector('#vt-sidebar').classList.remove('open');
      container.querySelector('#vt-sidebar-overlay').classList.remove('open');
    });

    // Close modals on overlay click
    [$modalEntry, $modalConfirm, $modalImport].forEach(m => {
      m.addEventListener('click', (e) => { if (e.target === m) m.classList.remove('active'); });
    });

    // Activity resets auto-lock
    container.addEventListener('mousemove', () => VaultClient.resetAutoLock());
    container.addEventListener('keydown', () => VaultClient.resetAutoLock());
    container.addEventListener('click', () => VaultClient.resetAutoLock());
  }

  // ── Lock Screen ───────────────────────────────────────────────────────────
  function _initLockScreen() {
    if (VaultClient.hasStoredVault()) {
      $createPage.style.display = 'none';
      $unlockPage.style.display = 'flex';
    } else {
      $createPage.style.display = 'flex';
      $unlockPage.style.display = 'none';
    }
  }

  // ── Create Preview ────────────────────────────────────────────────────────
  function _updateCreatePreview() {
    const password = $createInput.value.trim();
    if (!password) {
      $createPreview.textContent = 'Enter a password to create your vault...';
      $createPreview.style.color = '';
      $btnCreateGo.disabled = true;
      _generatedVaultPassword = null;
      return;
    }

    // Validate password strength
    _generatedVaultPassword = password;
    const strength = _calculatePasswordStrength(password);
    $createPreview.innerHTML =
      '<div style="font-size:11px;margin-bottom:6px">Password strength: <strong style="color:' + strength.color + '">' + strength.strength + '</strong></div>' +
      '<div style="height:4px;background:rgba(255,255,255,0.1);border-radius:2px;overflow:hidden">' +
      '<div style="height:100%;width:' + strength.score + '%;background:' + strength.color + ';transition:width 0.3s"></div>' +
      '</div>';
    $createPreview.style.color = '';
    $btnCreateGo.disabled = false;
  }

  function _calculatePasswordStrength(pwd) {
    let score = 0;
    let strength = 'Weak';
    let color = '#ff4466';

    if (!pwd) return { score, strength, color };

    if (pwd.length >= 8) score += 20;
    if (pwd.length >= 12) score += 15;
    if (pwd.length >= 16) score += 15;
    if (/[a-z]/.test(pwd)) score += 15;
    if (/[A-Z]/.test(pwd)) score += 15;
    if (/[0-9]/.test(pwd)) score += 15;
    if (/[^a-zA-Z0-9]/.test(pwd)) score += 20;

    const words = pwd.split(/\s+/).filter(Boolean);
    if (words.length >= 2) score += 10;
    if (words.length >= 3) score += 10;

    score = Math.min(score, 100);

    if (score >= 80) {
      strength = 'Fortress';
      color = '#10b981';
    } else if (score >= 60) {
      strength = 'Strong';
      color = '#06b6d4';
    } else if (score >= 40) {
      strength = 'Fair';
      color = '#eab308';
    }

    return { score, strength, color };
  }

  // ── Master Preview ────────────────────────────────────────────────────────
  function _updateMasterPreview() {
    const eq = $masterInput.value.trim();
    if (!eq) {
      $masterPreview.textContent = 'Paste the equation you saved...';
      $masterPreview.style.color = '';
      $btnUnlock.disabled = true;
      return;
    }
    const result = VaultClient.evaluateEquation(eq);
    if (result !== null) {
      $masterPreview.innerHTML = 'f(1.287, 0.777) = <strong>' + result.toPrecision(10) + '</strong>';
      $masterPreview.style.color = '#22d3ee';
      $btnUnlock.disabled = false;
    } else {
      $masterPreview.textContent = 'Invalid equation...';
      $masterPreview.style.color = '#ff4466';
      $btnUnlock.disabled = true;
    }
  }

  // ── Show Vault / Lock ─────────────────────────────────────────────────────
  function _showVault() {
    $lockScreen.style.display = 'none';
    $vaultScreen.style.display = 'flex';
    $masterInput.value = '';
    selectedId = null;
    _renderEntryList();
    _showDetailEmpty();
  }

  function _showLock() {
    $vaultScreen.style.display = 'none';
    $lockScreen.style.display = 'flex';
    _initLockScreen();
    $masterInput.focus();
  }

  function _showDetailEmpty() {
    $detailEmpty.style.display = 'flex';
    $detailContent.style.display = 'none';
  }

  // ── Event Handlers ────────────────────────────────────────────────────────
  function _onLock() { _showLock(); }
  function _onUnlock() { _showVault(); }
  function _onDataChange() { _renderEntryList(); if (selectedId) _showDetail(selectedId); }
  function _onAutoLockTick(remaining) {
    if ($statusAutolock) {
      const min = Math.floor(remaining / 60);
      const sec = remaining % 60;
      $statusAutolock.textContent = 'Auto-lock: ' + min + ':' + String(sec).padStart(2, '0');
    }
  }

  // ── Render Entry List ─────────────────────────────────────────────────────
  function _renderEntryList() {
    const entries = VaultClient.getEntries();
    const q = ($searchInput ? $searchInput.value : '').toLowerCase();
    const filtered = entries.filter(e =>
      !q || e.service.toLowerCase().includes(q) || (e.username || '').toLowerCase().includes(q) || (e.url || '').toLowerCase().includes(q)
    ).sort((a, b) => a.service.localeCompare(b.service));

    $entryList.innerHTML = '';
    if (filtered.length === 0) {
      $entryList.innerHTML = '<div class="vt-no-entries">' +
        (entries.length === 0 ? 'No entries yet. Click + to add.' : 'No matching entries.') + '</div>';
    }

    filtered.forEach(entry => {
      const color = VaultClient.entryColor(entry.service);
      const div = document.createElement('div');
      div.className = 'vt-entry-item' + (entry.id === selectedId ? ' active' : '');
      div.innerHTML =
        '<div class="vt-entry-icon" style="background:' + color + '20;color:' + color + '">' + VaultClient.entryInitial(entry.service) + '</div>' +
        '<div class="vt-entry-info">' +
          '<div class="vt-entry-name">' + _esc(entry.service) + '</div>' +
          '<div class="vt-entry-user">' + _esc(entry.username || entry.url || '') + '</div>' +
        '</div>';
      div.addEventListener('click', () => _selectEntry(entry.id));
      $entryList.appendChild(div);
    });

    $entryCount.textContent = entries.length;
    if ($statusEntries) $statusEntries.textContent = entries.length + ' entr' + (entries.length === 1 ? 'y' : 'ies');
  }

  function _selectEntry(id) {
    selectedId = id;
    _renderEntryList();
    _showDetail(id);
    // Close mobile sidebar
    container.querySelector('#vt-sidebar').classList.remove('open');
    container.querySelector('#vt-sidebar-overlay').classList.remove('open');
  }

  // ── Show Detail ───────────────────────────────────────────────────────────
  function _showDetail(id) {
    const entry = VaultClient.getEntry(id);
    if (!entry) { _showDetailEmpty(); return; }

    $detailEmpty.style.display = 'none';
    $detailContent.style.display = 'block';

    const color = VaultClient.entryColor(entry.service);
    const result = VaultClient.evaluateEquation(entry.equation);
    const strength = VaultClient.equationStrength(entry.equation);
    const resultStr = result !== null ? result.toPrecision(10) : 'N/A';

    $detailContent.innerHTML =
      '<div class="vt-detail-card">' +
        '<div class="vt-detail-header">' +
          '<div class="vt-detail-icon" style="background:' + color + '20;color:' + color + '">' + VaultClient.entryInitial(entry.service) + '</div>' +
          '<div><div class="vt-detail-title">' + _esc(entry.service) + '</div>' +
            '<div class="vt-detail-url">' + (entry.url ? '<a href="' + _escAttr(_normalizeUrl(entry.url)) + '" target="_blank">' + _esc(entry.url) + '</a>' : '<span style="opacity:0.4">No URL</span>') + '</div>' +
          '</div>' +
        '</div>' +
        '<div class="vt-detail-section"><div class="vt-detail-section-title">Credentials</div>' +
          '<div class="vt-detail-row"><span class="vt-row-label">Username</span><span class="vt-row-value">' + _esc(entry.username || 'N/A') + '</span>' +
            '<button class="vt-copy-btn" data-copy="' + _escAttr(entry.username || '') + '">Copy</button></div>' +
        '</div>' +
        '<div class="vt-detail-section"><div class="vt-detail-section-title">Equation (Password)</div>' +
          '<div class="vt-detail-row"><span class="vt-row-label">Equation</span><span class="vt-row-value vt-mono">' + _esc(entry.equation) + '</span>' +
            '<button class="vt-copy-btn" data-copy="' + _escAttr(entry.equation) + '">Copy</button></div>' +
          '<div class="vt-detail-row"><span class="vt-row-label">Result</span><span class="vt-row-value vt-mono">f(1.287, 0.777) = ' + _esc(resultStr) + '</span>' +
            '<button class="vt-copy-btn" data-copy="' + _escAttr(resultStr) + '">Copy</button></div>' +
          '<div style="padding:6px 0"><div class="vt-strength-bar" data-strength="' + strength.level + '">' +
            '<div class="seg"></div><div class="seg"></div><div class="seg"></div><div class="seg"></div><div class="seg"></div>' +
            '<div class="seg"></div><div class="seg"></div><div class="seg"></div><div class="seg"></div><div class="seg"></div></div>' +
            '<div class="vt-strength-label" data-strength="' + strength.level + '">' + strength.label + '</div></div>' +
        '</div>' +
        (entry.notes ? '<div class="vt-detail-section"><div class="vt-detail-section-title">Notes</div><div class="vt-detail-notes">' + _esc(entry.notes) + '</div></div>' : '') +
        '<div class="vt-detail-meta"><span>Created: ' + _timeAgo(entry.created) + '</span><span>Modified: ' + _timeAgo(entry.modified) + '</span></div>' +
        '<div class="vt-detail-actions">' +
          '<button class="vt-btn vt-btn-ghost vt-btn-sm" id="vt-btn-edit-detail">Edit</button>' +
          '<button class="vt-btn vt-btn-ghost vt-btn-sm" id="vt-btn-export">Export</button>' +
          '<button class="vt-btn vt-btn-danger vt-btn-sm" id="vt-btn-delete-detail">Delete</button>' +
        '</div>' +
      '</div>';

    // Wire copy buttons
    $detailContent.querySelectorAll('.vt-copy-btn').forEach(btn => {
      btn.addEventListener('click', () => {
        navigator.clipboard.writeText(btn.getAttribute('data-copy')).then(() => {
          btn.textContent = 'Copied!';
          setTimeout(() => { btn.textContent = 'Copy'; }, 1500);
        });
      });
    });

    // Wire edit
    const editBtn = $detailContent.querySelector('#vt-btn-edit-detail');
    if (editBtn) editBtn.addEventListener('click', () => _openEditModal(id));

    // Wire delete
    const deleteBtn = $detailContent.querySelector('#vt-btn-delete-detail');
    if (deleteBtn) deleteBtn.addEventListener('click', () => _confirmDelete(id));

    // Wire export
    const exportBtn = $detailContent.querySelector('#vt-btn-export');
    if (exportBtn) exportBtn.addEventListener('click', _doExport);
  }

  // ── Add / Edit Modal ──────────────────────────────────────────────────────
  function _openAddModal() {
    editingId = null;
    container.querySelector('#vt-modal-entry-title span').textContent = 'Add New Entry';
    container.querySelector('#vt-entry-service').value = '';
    container.querySelector('#vt-entry-url').value = '';
    container.querySelector('#vt-entry-username').value = '';
    container.querySelector('#vt-entry-equation').value = '';
    container.querySelector('#vt-entry-notes').value = '';
    container.querySelector('#vt-entry-eq-preview').textContent = 'Enter an equation...';
    container.querySelector('#vt-entry-strength-bar').dataset.strength = '0';
    container.querySelector('#vt-entry-strength-label').textContent = '';
    $modalEntry.classList.add('active');
    container.querySelector('#vt-entry-service').focus();
  }

  function _openEditModal(id) {
    const entry = VaultClient.getEntry(id);
    if (!entry) return;
    editingId = id;
    container.querySelector('#vt-modal-entry-title span').textContent = 'Edit Entry';
    container.querySelector('#vt-entry-service').value = entry.service;
    container.querySelector('#vt-entry-url').value = entry.url || '';
    container.querySelector('#vt-entry-username').value = entry.username || '';
    container.querySelector('#vt-entry-equation').value = entry.equation;
    container.querySelector('#vt-entry-notes').value = entry.notes || '';
    _updateEntryPreview();
    $modalEntry.classList.add('active');
    container.querySelector('#vt-entry-service').focus();
  }

  function _updateEntryPreview() {
    const eq = container.querySelector('#vt-entry-equation').value;
    const previewEl = container.querySelector('#vt-entry-eq-preview');
    const strengthBar = container.querySelector('#vt-entry-strength-bar');
    const strengthLabel = container.querySelector('#vt-entry-strength-label');

    const result = VaultClient.evaluateEquation(eq);
    if (result !== null) {
      previewEl.textContent = 'f(1.287, 0.777) = ' + result.toPrecision(10);
      previewEl.style.color = '#22d3ee';
    } else if (eq.trim()) {
      previewEl.textContent = 'Invalid equation...';
      previewEl.style.color = '#ff4466';
    } else {
      previewEl.textContent = 'Enter an equation...';
      previewEl.style.color = '';
    }
    const strength = VaultClient.equationStrength(eq);
    strengthBar.dataset.strength = strength.level;
    strengthLabel.dataset.strength = strength.level;
    strengthLabel.textContent = strength.label;
  }

  async function _saveEntry() {
    const service = container.querySelector('#vt-entry-service').value.trim();
    const equation = container.querySelector('#vt-entry-equation').value.trim();
    if (!service) { alert('Service name is required.'); return; }
    if (!equation || VaultClient.evaluateEquation(equation) === null) { alert('Valid equation is required.'); return; }

    const data = {
      service,
      url: container.querySelector('#vt-entry-url').value.trim(),
      username: container.querySelector('#vt-entry-username').value.trim(),
      equation,
      notes: container.querySelector('#vt-entry-notes').value.trim(),
    };

    try {
      if (editingId) {
        await VaultClient.updateEntry(editingId, data);
        selectedId = editingId;
      } else {
        const newEntry = await VaultClient.addEntry(data);
        selectedId = newEntry.id;
      }
      $modalEntry.classList.remove('active');
      editingId = null;
    } catch (err) {
      alert('Error: ' + err.message);
    }
  }

  // ── Delete ────────────────────────────────────────────────────────────────
  function _confirmDelete(id) {
    const entry = VaultClient.getEntry(id);
    if (!entry) return;
    pendingDeleteId = id;
    container.querySelector('#vt-confirm-body').textContent = 'Delete "' + entry.service + '"? This cannot be undone.';
    $modalConfirm.classList.add('active');
  }

  async function _doDelete() {
    if (pendingDeleteId) {
      try {
        await VaultClient.deleteEntry(pendingDeleteId);
        if (selectedId === pendingDeleteId) { selectedId = null; _showDetailEmpty(); }
      } catch (err) {
        alert('Delete failed: ' + err.message);
      }
    }
    $modalConfirm.classList.remove('active');
    pendingDeleteId = null;
  }

  // ── Export ────────────────────────────────────────────────────────────────
  async function _doExport() {
    try {
      const backup = await VaultClient.exportBackup();
      const blob = new Blob([JSON.stringify(backup, null, 2)], { type: 'application/json' });
      const url = URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = 'zeq-vault-backup-' + new Date().toISOString().slice(0, 10) + '.json';
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
      URL.revokeObjectURL(url);
    } catch (err) {
      alert('Export failed: ' + err.message);
    }
  }

  // ── Import ────────────────────────────────────────────────────────────────
  async function _doImport() {
    const fileInput = container.querySelector('#vt-import-file-hidden');
    const file = fileInput.files[0];
    const eq = container.querySelector('#vt-import-eq').value.trim();
    if (!file) { alert('Please select a backup file.'); return; }
    if (!eq) { alert('Please enter the master equation.'); return; }

    try {
      const text = await file.text();
      const backup = JSON.parse(text);
      const result = await VaultClient.importBackup(backup, eq);
      $modalImport.classList.remove('active');
      fileInput.value = '';
      alert('Imported ' + result.added + ' new entries (' + result.skipped + ' already existed).');
    } catch (err) {
      alert('Import failed: Wrong equation or invalid file.');
    }
  }

  // ── Helpers ───────────────────────────────────────────────────────────────
  function _timeAgo(ts) {
    const diff = Date.now() - ts;
    const secs = Math.floor(diff / 1000);
    if (secs < 60) return 'Just now';
    const mins = Math.floor(secs / 60);
    if (mins < 60) return mins + ' min ago';
    const hours = Math.floor(mins / 60);
    if (hours < 24) return hours + 'h ago';
    const days = Math.floor(hours / 24);
    if (days < 30) return days + 'd ago';
    return new Date(ts).toLocaleDateString();
  }

  function _esc(str) {
    const div = document.createElement('div');
    div.textContent = str || '';
    return div.innerHTML;
  }

  function _escAttr(str) {
    return (str || '').replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/'/g, '&#39;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
  }

  function _normalizeUrl(url) {
    if (!url) return '#';
    if (!/^https?:\/\//i.test(url)) return 'https://' + url;
    return url;
  }

  return { init, destroy };
})();
