// S.O.L.O. WorkManager v1.0.68 — Meeting notes view
(function() {
  'use strict';

  var DB_VERSION = 4;
  var PANEL_ID = 'solo-workmanager-meeting-notes-panel';
  var STORE = 'settings';
  var KEY = 'meetingNotes';
  var ARCHIVE_STORE = 'deletedArchive';
  var expanded = {};

  function t(de, en) {
    return (localStorage.getItem('wm_language') || 'de') === 'en' ? en : de;
  }

  function log(level, message, data) {
    try {
      if (window._pwLog) window._pwLog(level, message, data || {});
      else console.log('[S.O.L.O. WorkManager Meeting Notes]', level, message, data || {});
    } catch(e) {}
  }

  function generateId() {
    return 'note_' + Date.now() + '_' + Math.random().toString(36).slice(2, 9);
  }

  function activeWorkspaceId() {
    return localStorage.getItem('wm_active_workspace');
  }

  function dbName(workspaceId) {
    return 'workmanager_' + workspaceId;
  }

  async function api(path, payload) {
    var res = await fetch(path, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload || {}) });
    var json = await res.json().catch(function(){ return { ok:false, error:'Invalid JSON response' }; });
    if (!res.ok || json.ok === false) throw new Error(json.error || ('API failed: ' + path));
    return json;
  }

  async function loadNotes() {
    var ws = activeWorkspaceId();
    if (!ws) return [];
    var rec = await api('/api/localdb/store/get', { workspaceId: ws, store: STORE, key: KEY });
    return rec.item && Array.isArray(rec.item.value) ? rec.item.value : [];
  }

  async function saveNotes(notes) {
    var ws = activeWorkspaceId();
    if (!ws) throw new Error('No active workspace');
    await api('/api/localdb/store/put', { workspaceId: ws, store: STORE, item: { key: KEY, value: notes, updatedAt: new Date().toISOString() } });
  }

  async function archiveDeletedNote(note) {
    var ws = activeWorkspaceId();
    if (!ws || !note) throw new Error('No active workspace');
    var preview = plainPreview(note.html);
    var archived = {
      id: 'arch_note_' + Date.now() + '_' + Math.random().toString(36).slice(2, 9),
      type: 'meetingNote',
      sourceId: note.id,
      deletedAt: new Date().toISOString(),
      data: {
        id: note.id,
        createdAt: note.createdAt,
        html: note.html || '',
        text: preview,
        title: t('Meeting-Notiz vom ', 'Meeting note from ') + formatDate(note.createdAt)
      }
    };
    await api('/api/localdb/store/put', { workspaceId: ws, store: ARCHIVE_STORE, item: archived });
    window.dispatchEvent(new Event('wm-archive-updated'));
    log('INFO', 'Meeting note deleted and archived', { noteId: note.id, createdAt: note.createdAt });
  }

  function sanitizeHtml(html) {
    var tpl = document.createElement('template');
    tpl.innerHTML = html || '';
    var allowed = { B:1, STRONG:1, I:1, EM:1, U:1, DIV:1, P:1, BR:1, SPAN:1, UL:1, OL:1, LI:1 };
    function clean(node) {
      Array.prototype.slice.call(node.childNodes).forEach(function(child) {
        if (child.nodeType === 1) {
          if (!allowed[child.tagName]) {
            var text = document.createTextNode(child.textContent || '');
            child.parentNode.replaceChild(text, child);
            return;
          }
          Array.prototype.slice.call(child.attributes).forEach(function(attr) {
            var name = attr.name.toLowerCase();
            if (name.indexOf('on') === 0) child.removeAttribute(attr.name);
            else if (name !== 'style') child.removeAttribute(attr.name);
          });
          if (child.hasAttribute('style')) {
            var color = child.style.color;
            var bg = child.style.backgroundColor;
            child.removeAttribute('style');
            if (color) child.style.color = color;
            if (bg) child.style.backgroundColor = bg;
          }
          clean(child);
        } else if (child.nodeType !== 3) {
          child.remove();
        }
      });
    }
    clean(tpl.content);
    return tpl.innerHTML.trim();
  }

  function formatDate(iso) {
    try {
      return new Date(iso).toLocaleString((localStorage.getItem('wm_language') || 'de') === 'en' ? 'en-US' : 'de-DE', {
        year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit'
      });
    } catch(e) { return iso || ''; }
  }

  function plainPreview(html) {
    var tmp = document.createElement('div');
    tmp.innerHTML = html || '';
    var txt = (tmp.textContent || '').replace(/\s+/g, ' ').trim();
    return txt || t('Leere Notiz', 'Empty note');
  }

  function exec(command, value) {
    try { document.execCommand(command, false, value || null); } catch(e) {}
    var editor = document.querySelector('#' + PANEL_ID + ' [data-meeting-editor]');
    if (editor) editor.focus();
  }

  function makeButton(label, title, onclick) {
    var btn = document.createElement('button');
    btn.type = 'button';
    btn.className = 'btn btn-ghost btn-sm';
    btn.textContent = label;
    btn.title = title || label;
    btn.onclick = onclick;
    return btn;
  }

  function renderToolbar(container) {
    container.appendChild(makeButton('B', t('Fett', 'Bold'), function() { exec('bold'); }));
    container.appendChild(makeButton('I', t('Kursiv', 'Italic'), function() { exec('italic'); }));
    container.appendChild(makeButton('U', t('Unterstrichen', 'Underline'), function() { exec('underline'); }));
    var colors = [
      ['#e5e7eb', t('Standard', 'Default')],
      ['#ef4444', t('Rot', 'Red')],
      ['#f59e0b', t('Gelb/Orange', 'Yellow/Orange')],
      ['#22c55e', t('Grün', 'Green')],
      ['#3b82f6', t('Blau', 'Blue')],
      ['#a855f7', t('Violett', 'Purple')]
    ];
    colors.forEach(function(pair) {
      var b = document.createElement('button');
      b.type = 'button';
      b.className = 'btn btn-ghost btn-sm';
      b.title = pair[1];
      b.style.cssText = 'width:28px;padding:0;display:inline-flex;align-items:center;justify-content:center;';
      var dot = document.createElement('span');
      dot.style.cssText = 'width:14px;height:14px;border-radius:50%;display:inline-block;border:1px solid var(--border);background:' + pair[0] + ';';
      b.appendChild(dot);
      b.onclick = function() { exec('foreColor', pair[0]); };
      container.appendChild(b);
    });
  }

  async function refreshList(panel) {
    var notes = await loadNotes();
    notes.sort(function(a, b) { return String(b.createdAt).localeCompare(String(a.createdAt)); });
    var list = panel.querySelector('[data-meeting-list]');
    list.innerHTML = '';
    if (!notes.length) {
      var empty = document.createElement('div');
      empty.className = 'empty-state';
      empty.style.cssText = 'height:100%;min-height:120px;';
      empty.innerHTML = '<div class="empty-state-title">' + t('Noch keine Meeting-Notizen', 'No meeting notes yet') + '</div>' +
        '<div class="empty-state-sub">' + t('Speichere oben deine erste Notiz.', 'Save your first note above.') + '</div>';
      list.appendChild(empty);
      return;
    }
    notes.forEach(function(note) {
      var isOpen = !!expanded[note.id];
      var item = document.createElement('div');
      item.className = 'card';
      item.style.cssText = 'padding:0;margin-bottom:8px;overflow:hidden;';
      var header = document.createElement('button');
      header.type = 'button';
      header.style.cssText = 'width:100%;display:flex;align-items:center;gap:10px;background:transparent;border:0;color:var(--text-primary);padding:11px 12px;text-align:left;cursor:pointer;';
      header.innerHTML = '<span style="font-size:13px;color:var(--text-muted);width:16px;">' + (isOpen ? '⌄' : '›') + '</span>' +
        '<span style="font-weight:800;white-space:nowrap;">' + formatDate(note.createdAt) + '</span>' +
        '<span class="text-muted" style="min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;flex:1;">' + escapeHtml(plainPreview(note.html)) + '</span>';
      header.onclick = function() { expanded[note.id] = !expanded[note.id]; refreshList(panel).catch(function(e){ log('WARN','Refresh failed',{error:e.message}); }); };
      var del = document.createElement('button');
      del.type = 'button';
      del.className = 'btn-icon';
      del.title = t('Notiz löschen', 'Delete note');
      del.style.cssText = 'color:var(--accent-red);margin-right:10px;';
      del.innerHTML = '🗑';
      del.onclick = async function(ev) {
        ev.stopPropagation();
        if (!confirm(t('Diese Meeting-Notiz wirklich löschen?', 'Really delete this meeting note?'))) return;
        try {
          var current = await loadNotes();
          await archiveDeletedNote(note);
          await saveNotes(current.filter(function(n) { return n.id !== note.id; }));
          delete expanded[note.id];
          await refreshList(panel);
        } catch(e) {
          alert(t('Meeting-Notiz konnte nicht gelöscht oder archiviert werden: ', 'Meeting note could not be deleted or archived: ') + e.message);
          log('ERROR', 'Delete meeting note failed', { noteId: note.id, error: e.message });
        }
      };
      var headWrap = document.createElement('div');
      headWrap.style.cssText = 'display:flex;align-items:center;border-bottom:' + (isOpen ? '1px solid var(--border)' : '0') + ';';
      headWrap.appendChild(header);
      headWrap.appendChild(del);
      item.appendChild(headWrap);
      if (isOpen) {
        var body = document.createElement('div');
        body.style.cssText = 'padding:14px 16px;line-height:1.55;color:var(--text-primary);font-size:14px;max-height:260px;overflow:auto;';
        body.innerHTML = sanitizeHtml(note.html || '');
        item.appendChild(body);
      }
      list.appendChild(item);
    });
  }

  function escapeHtml(s) {
    return String(s || '').replace(/[&<>"]/g, function(c) {
      return ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;'}[c]);
    });
  }

  function createPanel() {
    var panel = document.createElement('section');
    panel.id = PANEL_ID;
    panel.style.cssText = 'display:flex;flex-direction:column;height:100%;min-height:0;padding:20px;gap:14px;';
    panel.innerHTML = '' +
      '<div>' +
        '<h1 style="margin:0 0 4px;font-size:20px;color:var(--text-primary);">' + t('Meeting-Notizen', 'Meeting Notes') + '</h1>' +
        '<div class="text-muted" style="font-size:13px;">' + t('Notizen mit Datum und Uhrzeit speichern, einklappen und später wieder öffnen.', 'Save notes with date and time, collapse them and reopen them later.') + '</div>' +
      '</div>' +
      '<div class="card" style="height:42%;min-height:230px;display:flex;flex-direction:column;gap:10px;">' +
        '<div data-meeting-toolbar style="display:flex;align-items:center;gap:6px;flex-wrap:wrap;border-bottom:1px solid var(--border);padding-bottom:10px;"></div>' +
        '<div data-meeting-editor contenteditable="true" spellcheck="true" style="flex:1;min-height:0;overflow:auto;border:1px solid var(--border);border-radius:var(--radius-sm);padding:12px;background:var(--bg-input, var(--bg));color:var(--text-primary);line-height:1.5;outline:none;"></div>' +
        '<div style="display:flex;justify-content:flex-end;gap:8px;">' +
          '<button class="btn btn-ghost btn-sm" data-meeting-clear>' + t('Leeren', 'Clear') + '</button>' +
          '<button class="btn btn-primary btn-sm" data-meeting-save>' + t('Notiz speichern', 'Save note') + '</button>' +
        '</div>' +
      '</div>' +
      '<div class="card" style="flex:1;min-height:0;display:flex;flex-direction:column;">' +
        '<div style="font-weight:800;color:var(--text-primary);margin-bottom:10px;">' + t('Gespeicherte Notizen', 'Saved notes') + '</div>' +
        '<div data-meeting-list style="flex:1;min-height:0;overflow:auto;padding-right:4px;"></div>' +
      '</div>';
    renderToolbar(panel.querySelector('[data-meeting-toolbar]'));
    var editor = panel.querySelector('[data-meeting-editor]');
    panel.querySelector('[data-meeting-clear]').onclick = function() { editor.innerHTML = ''; editor.focus(); };
    panel.querySelector('[data-meeting-save]').onclick = async function() {
      var html = sanitizeHtml(editor.innerHTML);
      var tmp = document.createElement('div');
      tmp.innerHTML = html;
      if (!(tmp.textContent || '').trim()) { editor.focus(); return; }
      var btn = this;
      btn.disabled = true;
      try {
        var notes = await loadNotes();
        notes.push({ id: generateId(), createdAt: new Date().toISOString(), html: html });
        await saveNotes(notes);
        log('INFO', 'Meeting note saved', { noteId: notes[notes.length - 1].id, createdAt: notes[notes.length - 1].createdAt });
        editor.innerHTML = '';
        editor.focus();
        await refreshList(panel);
      } catch(e) {
        alert(t('Meeting-Notiz konnte nicht gespeichert werden: ', 'Meeting note could not be saved: ') + e.message);
        log('ERROR', 'Save meeting note failed', { error: e.message });
      } finally {
        btn.disabled = false;
      }
    };
    setTimeout(function(){ editor.focus(); }, 50);
    refreshList(panel).catch(function(e) {
      var list = panel.querySelector('[data-meeting-list]');
      list.innerHTML = '<div class="text-muted text-sm">' + t('Meeting-Notizen konnten nicht geladen werden: ', 'Meeting notes could not be loaded: ') + escapeHtml(e.message) + '</div>';
      log('WARN', 'Load meeting notes failed', { error: e.message });
    });
    return panel;
  }

  function render() {
    var host = document.querySelector('.solo-workmanager-custom-view-host') || document.querySelector('.main-content');
    if (!host) return;
    host.innerHTML = '';
    host.appendChild(createPanel());
  }

  window.SoloWorkManagerMeetingNotes = { render: render, loadNotes: loadNotes, saveNotes: saveNotes };
})();
