// S.O.L.O. WorkManager v1.0.68 — eigene System-Tabs fuer Lizenz und Backup
(function(){
  'use strict';

  var ACTIVE_CUSTOM_VIEW = null;

  function isEn(){ return (localStorage.getItem('wm_language') || 'de') === 'en'; }
  function t(de, en){ return isEn() ? en : de; }
  function esc(value){
    return String(value == null ? '' : value)
      .replace(/&/g, '&amp;')
      .replace(/</g, '&lt;')
      .replace(/>/g, '&gt;')
      .replace(/"/g, '&quot;')
      .replace(/'/g, '&#39;');
  }

  function systemIcon(kind){
    if(kind === 'license') return '<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="7.5" cy="15.5" r="5.5"></circle><path d="M12 12l8-8"></path><path d="M16 4l4 4"></path></svg>';
    return '<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2z"></path><path d="M17 21v-8H7v8"></path><path d="M7 3v5h8"></path></svg>';
  }

  function ensureSystemButtons(){ return; }

  function setActiveNav(view){
    document.querySelectorAll('.sidebar-nav .nav-item').forEach(function(btn){ btn.classList.remove('active'); });
    var btn = document.querySelector('[data-solo-workmanager-system-tab="' + view + '"]');
    if(btn) btn.classList.add('active');
  }

  function mainContent(){ return document.querySelector('.solo-workmanager-custom-view-host'); }

  function renderShell(title, subtitle, bodyHtml){
    var main = mainContent();
    if(!main) return null;
    main.innerHTML = '' +
      '<div style="display:flex;flex-direction:column;height:100%;">' +
        '<div class="page-header">' +
          '<div>' +
            '<h1 class="page-title">' + esc(title) + '</h1>' +
            '<p class="page-subtitle">' + esc(subtitle) + '</p>' +
          '</div>' +
        '</div>' +
        '<div class="page-body solo-workmanager-system-page" style="flex:1;overflow-y:auto;max-width:760px;">' + bodyHtml + '</div>' +
      '</div>';
    return main.querySelector('.solo-workmanager-system-page');
  }

  function licenseCardHtml(){
    var api = window.SoloWorkManagerLicense;
    var status = api && api.status ? api.status() : { valid:false, payload:{ type:'demo' } };
    var p = status.payload || {};
    var typeLabel = api && api.typeLabel ? api.typeLabel() : t('Demo-Version', 'Demo version');
    var statusText = status.valid ? t('Aktiviert', 'Activated') : t('Demo-Version', 'Demo version');
    var ownerText = p.owner || p.email || p.company || '—';
    var idText = p.licenseId || '—';
    var hint = t(
      'S.O.L.O. WorkManager startet als Demo und kann offline mit einem Lizenzschlüssel aktiviert werden. Der Schlüssel erkennt Privat- oder Gewerbelizenz.',
      'S.O.L.O. WorkManager starts as a demo and can be activated offline with a license key. The key can identify a private or business license.'
    );
    var limits = t(
      'Demo-Grenzen: 1 Workspace, 3 Projekte, 20 Aufgaben, 10 To-dos, 5 PSP-Elemente, 10 Tags, 10 Meilensteine.',
      'Demo limits: 1 workspace, 3 projects, 20 tasks, 10 to-dos, 5 PSP elements, 10 tags, 10 milestones.'
    );
    return '' +
      '<section class="license-card" data-solo-workmanager-license-page-card="1">' +
        '<div class="license-card-head">' +
          '<div>' +
            '<div class="license-title">' + t('Lizenz', 'License') + '</div>' +
            '<div class="license-sub">' + esc(hint) + '</div>' +
          '</div>' +
          '<span class="license-badge ' + (status.valid ? 'ok' : 'demo') + '">' + esc(typeLabel) + '</span>' +
        '</div>' +
        '<div class="license-grid">' +
          '<div><span>Status</span><strong>' + esc(statusText) + '</strong></div>' +
          '<div><span>' + t('Lizenztyp', 'License type') + '</span><strong>' + esc(typeLabel) + '</strong></div>' +
          '<div><span>' + t('Lizenziert für', 'Licensed to') + '</span><strong>' + esc(ownerText) + '</strong></div>' +
          '<div><span>' + t('Lizenz-ID', 'License ID') + '</span><strong>' + esc(idText) + '</strong></div>' +
        '</div>' +
        (status.valid ? '' : '<div class="license-limit-note">' + esc(limits) + '</div>') +
        '<div class="license-input-row">' +
          '<textarea class="form-input license-key-input" rows="3" placeholder="' + t('Lizenzschlüssel hier einfügen...', 'Paste license key here...') + '"></textarea>' +
          '<button class="btn btn-primary license-activate-btn">' + t('Lizenz aktivieren', 'Activate license') + '</button>' +
        '</div>' +
        '<div class="license-actions">' +
          '<button class="btn btn-ghost btn-sm license-reset-btn">' + t('Lokale Lizenz entfernen', 'Remove local license') + '</button>' +
          '<span class="license-message"></span>' +
        '</div>' +
      '</section>';
  }

  function renderLicensePage(){
    var page = renderShell(
      t('Lizenz', 'License'),
      t('Lizenzstatus prüfen, Lizenzschlüssel aktivieren oder lokale Lizenz entfernen.', 'Check license status, activate a license key, or remove the local license.'),
      licenseCardHtml()
    );
    if(!page) return;
    var card = page.querySelector('[data-solo-workmanager-license-page-card="1"]');
    var input = card.querySelector('.license-key-input');
    var msg = card.querySelector('.license-message');
    var activateBtn = card.querySelector('.license-activate-btn');
    var resetBtn = card.querySelector('.license-reset-btn');
    activateBtn.addEventListener('click', async function(){
      if(!window.SoloWorkManagerLicense || !window.SoloWorkManagerLicense.activate){
        msg.textContent = t('Lizenzmodul ist noch nicht geladen.', 'License module is not loaded yet.');
        return;
      }
      msg.textContent = t('Prüfe...', 'Checking...');
      activateBtn.disabled = true;
      try {
        var res = await window.SoloWorkManagerLicense.activate(input.value);
        msg.textContent = res.message || '';
        if(res.ok) {
          if(window.SoloWorkManagerLicense.refreshBadges) window.SoloWorkManagerLicense.refreshBadges();
          setTimeout(renderLicensePage, 300);
        }
      } finally {
        activateBtn.disabled = false;
      }
    });
    resetBtn.addEventListener('click', function(){
      if(!window.SoloWorkManagerLicense || !window.SoloWorkManagerLicense.reset) return;
      if(confirm(t('Lokal gespeicherte Lizenz entfernen?', 'Remove the locally stored license?'))){
        window.SoloWorkManagerLicense.reset();
        if(window.SoloWorkManagerLicense.refreshBadges) window.SoloWorkManagerLicense.refreshBadges();
        renderLicensePage();
      }
    });
  }

  function formatSize(bytes){
    if(window.SoloWorkManagerBackup && window.SoloWorkManagerBackup.formatSize) return window.SoloWorkManagerBackup.formatSize(bytes);
    if(!bytes) return '0 KB';
    if(bytes < 1024 * 1024) return Math.round(bytes / 1024) + ' KB';
    return (bytes / 1024 / 1024).toFixed(1) + ' MB';
  }
  function formatFileDate(name, modifiedAt){
    if(window.SoloWorkManagerBackup && window.SoloWorkManagerBackup.formatFileDate) return window.SoloWorkManagerBackup.formatFileDate(name, modifiedAt);
    return modifiedAt || name;
  }
  function backupKindLabel(name){
    if(window.SoloWorkManagerBackup && window.SoloWorkManagerBackup.backupKindLabel) return window.SoloWorkManagerBackup.backupKindLabel(name);
    if(String(name).indexOf('solo_workmanager_auto_backup_') === 0) return t('Automatisch', 'Automatic');
    if(String(name).indexOf('solo_workmanager_pre_restore_backup_') === 0) return t('Vor Wiederherstellung', 'Pre-restore');
    return t('Manuell', 'Manual');
  }

  async function refreshBackupList(page){
    var status = page.querySelector('[data-backup-status]');
    var list = page.querySelector('[data-backup-list]');
    var api = window.SoloWorkManagerBackup;
    if(!api || !api.listBackups){
      status.textContent = t('Backup-Modul ist noch nicht geladen.', 'Backup module is not loaded yet.');
      return;
    }
    try {
      var result = await api.listBackups();
      var files = result.files || [];
      var latest = files[0];
      status.textContent = latest
        ? t('Letztes Backup: ', 'Latest backup: ') + formatFileDate(latest.name, latest.modifiedAt) + ' · ' + t('Anzahl: ', 'Count: ') + files.length
        : t('Noch kein Backup vorhanden.', 'No backup available yet.');
      list.innerHTML = '';
      if(!files.length){
        list.innerHTML = '<div class="text-muted text-sm">' + t('Keine Sicherungen im lokalen backups-Ordner gefunden.', 'No backups found in the local backups folder.') + '</div>';
        return;
      }
      files.slice(0, 30).forEach(function(file){
        var row = document.createElement('div');
        row.style.cssText = 'display:flex;align-items:center;justify-content:space-between;gap:10px;padding:8px 0;border-top:1px solid var(--border);';
        row.innerHTML = '' +
          '<div style="min-width:0;">' +
            '<div style="font-weight:700;color:var(--text-primary);font-size:13px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">' + esc(backupKindLabel(file.name)) + ' · ' + esc(formatFileDate(file.name, file.modifiedAt)) + '</div>' +
            '<div class="text-muted" style="font-size:11px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">' + esc(file.name) + ' · ' + esc(formatSize(file.size)) + '</div>' +
          '</div>';
        var btn = document.createElement('button');
        btn.className = 'btn btn-ghost btn-sm';
        btn.textContent = t('Wiederherstellen', 'Restore');
        btn.addEventListener('click', async function(){
          if(!confirm(t('Aktuelle S.O.L.O. WorkManager-Daten werden durch dieses Backup ersetzt. Vorher wird automatisch eine Sicherheitskopie erstellt. Fortfahren?', 'Current S.O.L.O. WorkManager data will be replaced by this backup. A safety backup will be created first. Continue?'))) return;
          btn.disabled = true;
          btn.textContent = t('Lade...', 'Loading...');
          try {
            await api.createBackup('pre_restore');
            var snapshot = await api.readBackup(file.name);
            await api.restoreSnapshot(snapshot);
            alert(t('Backup wurde wiederhergestellt. S.O.L.O. WorkManager wird neu geladen.', 'Backup restored. S.O.L.O. WorkManager will reload.'));
            window.location.reload();
          } catch(e){
            btn.disabled = false;
            btn.textContent = t('Wiederherstellen', 'Restore');
            alert(t('Wiederherstellung fehlgeschlagen: ', 'Restore failed: ') + e.message);
          }
        });
        row.appendChild(btn);
        list.appendChild(row);
      });
    } catch(e){
      status.textContent = t('Backup-Status konnte nicht geladen werden: ', 'Backup status could not be loaded: ') + e.message;
    }
  }

  function renderBackupPage(){
    var html = '' +
      '<section class="card">' +
        '<div style="display:flex;justify-content:space-between;align-items:flex-start;gap:14px;flex-wrap:wrap;">' +
          '<div>' +
            '<h2 style="margin:0 0 6px;font-size:18px;color:var(--text-primary);">' + t('Datensicherung', 'Data backup') + '</h2>' +
            '<p class="text-muted" style="margin:0;font-size:13px;line-height:1.45;">' + t('S.O.L.O. WorkManager erstellt einmal täglich automatisch eine lokale JSON-Sicherung im Ordner backups der App. Die Sicherung liegt außerhalb des Browserprofils.', 'S.O.L.O. WorkManager automatically creates one local JSON backup per day in the app backups folder. The backup is stored outside the browser profile.') + '</p>' +
          '</div>' +
          '<button class="btn btn-primary btn-sm" data-backup-create>' + t('Jetzt Backup erstellen', 'Create backup now') + '</button>' +
        '</div>' +
        '<div data-backup-status class="text-muted" style="margin-top:12px;font-size:13px;">' + t('Backup-Status wird geladen...', 'Loading backup status...') + '</div>' +
        '<div style="margin-top:14px;font-weight:700;color:var(--text-primary);font-size:13px;">' + t('Vorhandene Backups', 'Available backups') + '</div>' +
        '<div data-backup-list class="solo-workmanager-backup-list"></div>' +
        '<div class="text-muted" style="margin-top:10px;font-size:11px;line-height:1.4;">' + t('Automatisch werden die letzten 30 Tages-Backups behalten. Vor jeder Wiederherstellung wird zusätzlich ein Pre-Restore-Backup erstellt.', 'The latest 30 automatic daily backups are kept. A pre-restore backup is also created before each restore.') + '</div>' +
      '</section>';
    var page = renderShell(
      t('Datensicherung', 'Backup'),
      t('Automatische Sicherungen prüfen, manuelles Backup erstellen oder Daten wiederherstellen.', 'Check automatic backups, create a manual backup, or restore data.'),
      html
    );
    if(!page) return;
    var createBtn = page.querySelector('[data-backup-create]');
    createBtn.addEventListener('click', async function(){
      var api = window.SoloWorkManagerBackup;
      if(!api || !api.createBackup){
        alert(t('Backup-Modul ist noch nicht geladen.', 'Backup module is not loaded yet.'));
        return;
      }
      createBtn.disabled = true;
      createBtn.textContent = t('Erstelle...', 'Creating...');
      try {
        var result = await api.createBackup('manual');
        alert(t('Backup erstellt: ', 'Backup created: ') + result.file.name);
        await refreshBackupList(page);
      } catch(e){
        alert(t('Backup fehlgeschlagen: ', 'Backup failed: ') + e.message);
      } finally {
        createBtn.disabled = false;
        createBtn.textContent = t('Jetzt Backup erstellen', 'Create backup now');
      }
    });
    refreshBackupList(page);
  }

  function renderCustomView(view){
    ACTIVE_CUSTOM_VIEW = view;
    setActiveNav(view);
    if(view === 'license') renderLicensePage();
    else renderBackupPage();
  }

  function init(){
    ensureSystemButtons();
    var obs = new MutationObserver(function(){
      clearTimeout(window.__pwSystemTabsTimer);
      window.__pwSystemTabsTimer = setTimeout(function(){
        ensureSystemButtons();
        if(ACTIVE_CUSTOM_VIEW && !document.querySelector('.solo-workmanager-system-page')) renderCustomView(ACTIVE_CUSTOM_VIEW);
      }, 100);
    });
    obs.observe(document.body, { childList:true, subtree:true });
    document.addEventListener('click', function(e){
      var navButton = e.target && e.target.closest ? e.target.closest('.sidebar-nav .nav-item') : null;
      if(navButton && !navButton.hasAttribute('data-solo-workmanager-system-tab')) ACTIVE_CUSTOM_VIEW = null;
    }, true);
    window.addEventListener('storage', ensureSystemButtons);
    window.SoloWorkManagerSystemTabs = { renderCustomView: renderCustomView };
  }

  if(document.readyState === 'loading') document.addEventListener('DOMContentLoaded', init);
  else init();
})();
