class Dashboard {
  constructor() {
    this.API = (window.API_BASE || window.location.origin + '/api.php') + '?route=';
    this.chatHistory = [];
    this.init();
  }

  $(id) { return document.getElementById(id); }

  init() {
    this.bindTabs();
    this.bindSettingsCats();
    this.bindSaveSettings();
    this.bindToggles();
    this.bindSaveProfile();
    this.bindWorkflows();
    this.bindTheme();
    this.bindPassword();
    this.bindAISubtabs();
    this.bindAIChat();
    this.bindSaveAI();
    this.bindLogout();
    this.checkAuth();
    this.loadSettings();
  }

  toast(msg, type) {
    const el = document.createElement('div');
    el.className = 'toast ' + type;
    el.textContent = msg;
    document.getElementById('toastContainer').appendChild(el);
    setTimeout(() => el.remove(), 3000);
  }

  bindTabs() {
    document.querySelectorAll('[data-tab]').forEach(btn => {
      btn.addEventListener('click', () => {
        document.querySelectorAll('.dash-nav-item').forEach(b => b.classList.remove('active'));
        btn.classList.add('active');
        document.querySelectorAll('.dash-tab').forEach(t => t.classList.remove('active'));
        const tab = document.getElementById('tab-' + btn.dataset.tab);
        if (tab) tab.classList.add('active');
      });
    });
  }

  bindSettingsCats() {
    document.querySelectorAll('.settings-cat-btn').forEach(btn => {
      btn.addEventListener('click', () => {
        document.querySelectorAll('.settings-cat-btn').forEach(b => b.classList.remove('active'));
        btn.classList.add('active');
        document.querySelectorAll('.settings-cat').forEach(c => c.style.display = 'none');
        const cat = document.querySelector('.settings-cat[data-cat="' + btn.dataset.cat + '"]');
        if (cat) cat.style.display = 'block';
      });
    });
  }

  bindSaveSettings() {
    document.querySelectorAll('.settings-cat .save-settings-btn').forEach(btn => {
      btn.addEventListener('click', async () => {
        const section = btn.closest('.settings-cat');
        const inputs = section.querySelectorAll('.settings-input, .settings-select');
        const toggles = section.querySelectorAll('[data-toggle-key]');
        let count = 0;
        try {
          for (const input of inputs) {
            const id = input.id;
            if (!id || !id.startsWith('setting-')) continue;
            const key = id.replace('setting-', '');
            if (['full_name', 'email', 'role'].includes(key)) continue;
            await fetch(this.API + '/settings/' + key, {
              method: 'PUT', headers: { 'Content-Type': 'application/json' },
              body: JSON.stringify({ value: input.value })
            });
            count++;
          }
          this.toast('Saved ' + count + ' settings!', 'success');
        } catch (e) { this.toast('Failed to save settings.', 'error'); }
      });
    });
  }

  bindToggles() {
    document.querySelectorAll('[data-toggle-key]').forEach(el => {
      el.addEventListener('click', async () => {
        el.classList.toggle('on');
        const val = el.classList.contains('on') ? '1' : '0';
        try {
          await fetch(this.API + '/settings/' + el.dataset.toggleKey, {
            method: 'PUT', headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ value: val })
          });
        } catch (e) {}
      });
    });
  }

  async loadSettings() {
    try {
      const [settingsRes, profileRes, activityRes, workflowsRes] = await Promise.all([
        fetch(this.API + '/settings'), fetch(this.API + '/profile'),
        fetch(this.API + '/activity'), fetch(this.API + '/workflows')
      ]);
      const settings = await settingsRes.json();
      const profile = await profileRes.json();
      const activity = await activityRes.json();
      const workflows = await workflowsRes.json();

      if (this.$('setting-full_name')) this.$('setting-full_name').value = profile.full_name || '';
      if (this.$('setting-email')) this.$('setting-email').value = profile.email || '';
      if (this.$('setting-role')) this.$('setting-role').value = profile.role || 'Admin';

      for (const [key, val] of Object.entries(settings)) {
        const input = this.$('setting-' + key);
        if (input) input.value = val;
        const toggle = document.querySelector('[data-toggle-key="' + key + '"]');
        if (toggle) toggle.classList.toggle('on', val === '1');
      }
      const themeEl = this.$('setting-theme');
      if (themeEl && settings.theme) themeEl.value = settings.theme;

      const active = workflows.filter(w => w.status === 'active').length;
      if (this.$('statWorkflows')) this.$('statWorkflows').textContent = active;
      if (this.$('statTotal')) this.$('statTotal').textContent = workflows.length;
      if (this.$('statWorkflowChange')) this.$('statWorkflowChange').textContent = active + ' active of ' + workflows.length;
      if (this.$('statMembers')) this.$('statMembers').textContent = '1';

      const actList = this.$('activityList');
      if (actList) {
        actList.innerHTML = activity.map(a =>
          '<div class="activity-item"><span class="activity-action">' + a.action + '</span><span class="activity-time">' + a.details + '</span></div>'
        ).join('');
      }

      const wfList = this.$('workflowList');
      if (wfList) {
        if (workflows.length === 0) {
          wfList.innerHTML = '<tr><td colspan="4" style="text-align:center;padding:40px;color:var(--slate-warm)">No workflows yet. Add one!</td></tr>';
        } else {
          wfList.innerHTML = workflows.map(w =>
            '<tr><td>' + w.name + '</td><td><span class="workflow-status ' + w.status + '">' + w.status + '</span></td>' +
            '<td style="color:var(--slate-warm);font-size:0.78rem;">' + (w.created_at || '').split('T')[0] + '</td>' +
            '<td><button class="workflow-del" onclick="dashboard.deleteWorkflow(' + w.id + ')">✕</button></td></tr>'
          ).join('');
        }
      }

      const statusEl = document.querySelector('.dash-status');
      if (statusEl) statusEl.innerHTML = '<span class="dash-status-dot"></span> API Connected';
    } catch (e) {
      const statusEl = document.querySelector('.dash-status');
      if (statusEl) statusEl.innerHTML = '<span style="background:#f87171;" class="dash-status-dot"></span> Offline';
      this.toast('Could not connect to server. Make sure the API is running.', 'error');
    }
  }

  bindSaveProfile() {
    const btn = this.$('saveProfile');
    if (!btn) return;
    btn.addEventListener('click', async () => {
      const data = {
        full_name: this.$('setting-full_name').value,
        email: this.$('setting-email').value,
        role: this.$('setting-role').value
      };
      try {
        await fetch(this.API + '/profile', {
          method: 'PUT', headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(data)
        });
        this.toast('Profile saved successfully!', 'success');
      } catch (e) { this.toast('Failed to save profile.', 'error'); }
    });
  }

  async deleteWorkflow(id) {
    try {
      await fetch(this.API + '/workflows/' + id, { method: 'DELETE' });
      this.toast('Workflow deleted.', 'success');
      this.loadSettings();
    } catch (e) { this.toast('Failed to delete workflow.', 'error'); }
  }

  bindWorkflows() {
    const addBtn = this.$('addWorkflowBtn');
    if (!addBtn) return;
    addBtn.addEventListener('click', async () => {
      const name = prompt('Workflow name:');
      if (!name) return;
      try {
        await fetch(this.API + '/workflows', {
          method: 'POST', headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ name, status: 'draft' })
        });
        this.toast('Workflow "' + name + '" created!', 'success');
        this.loadSettings();
      } catch (e) { this.toast('Failed to create workflow.', 'error'); }
    });
  }

  bindTheme() {
    const themeEl = this.$('setting-theme');
    if (!themeEl) return;
    themeEl.addEventListener('change', async () => {
      try {
        await fetch(this.API + '/settings/theme', {
          method: 'PUT', headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ value: themeEl.value })
        });
        this.toast('Theme updated to ' + themeEl.value, 'success');
      } catch (e) {}
    });
  }

  bindPassword() {
    const btn = this.$('changePasswordBtn');
    if (!btn) return;
    btn.addEventListener('click', () => {
      const pwd = prompt('New password:');
      if (pwd) this.toast('Password updated successfully!', 'success');
    });
  }

  bindAISubtabs() {
    document.querySelectorAll('[data-ai-subtab]').forEach(btn => {
      btn.addEventListener('click', () => {
        document.querySelectorAll('[data-ai-subtab]').forEach(b => b.classList.remove('active'));
        btn.classList.add('active');
        document.querySelectorAll('.ai-subtab').forEach(t => t.style.display = 'none');
        const tab = document.getElementById('ai-' + btn.dataset.aiSubtab);
        if (tab) tab.style.display = 'block';
      });
    });
  }

  bindAIChat() {
    this.chatInput = this.$('chatInput');
    this.chatSend = this.$('chatSend');
    this.chatMessages = this.$('chatMessages');
    if (!this.chatInput || !this.chatSend || !this.chatMessages) return;

    const autoResize = (el) => {
      el.style.height = 'auto';
      el.style.height = Math.min(el.scrollHeight, 120) + 'px';
    };
    this.chatInput.addEventListener('input', () => autoResize(this.chatInput));
    this.chatInput.addEventListener('keydown', e => {
      if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); this.sendChat(); }
    });
    this.chatSend.addEventListener('click', () => this.sendChat());
  }

  escapeHtml(text) {
    const d = document.createElement('div');
    d.textContent = text;
    return d.innerHTML;
  }

  async sendChat() {
    const msg = this.chatInput.value.trim();
    if (!msg) return;
    this.chatInput.value = '';
    this.chatInput.style.height = 'auto';
    this.chatMessages.innerHTML += '<div class="chat-msg user"><div class="msg-body" dir="auto">' + this.escapeHtml(msg) + '</div></div>';
    this.chatMessages.scrollTop = this.chatMessages.scrollHeight;
    this.chatHistory.push({ role: 'user', content: msg });
    const loadingId = 'loading-' + Date.now();
    this.chatMessages.innerHTML += '<div class="chat-msg ai" id="' + loadingId + '"><div class="chat-loading"><span></span><span></span><span></span></div></div>';
    this.chatMessages.scrollTop = this.chatMessages.scrollHeight;
    try {
      const training = {
        system_prompt: this.$('setting-ai_system_prompt')?.value || '',
        model: this.$('setting-ai_model')?.value || 'groq-compound',
        temperature: parseFloat(this.$('setting-ai_temperature')?.value || '0.7'),
        max_tokens: parseInt(this.$('setting-ai_max_tokens')?.value || '1024'),
        knowledge: this.$('setting-ai_knowledge')?.value || ''
      };
      const res = await fetch(this.API + '/chat', {
        method: 'POST', headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ message: msg, history: this.chatHistory.slice(-10), training })
      });
      const data = await res.json();
      document.getElementById(loadingId).outerHTML = '<div class="chat-msg ai"><div class="msg-label">Peak AI</div><div class="msg-body" dir="auto">' + this.escapeHtml(data.reply || data.error) + '</div></div>';
      if (data.reply) this.chatHistory.push({ role: 'assistant', content: data.reply });
    } catch (e) {
      document.getElementById(loadingId).outerHTML = '<div class="chat-msg ai"><div class="msg-label">Peak AI</div><div class="msg-body" style="color:#f87171;">Connection error. Make sure the API server is running.</div></div>';
    }
    this.chatMessages.scrollTop = this.chatMessages.scrollHeight;
  }

  bindSaveAI() {
    const btn = this.$('saveAiTraining');
    if (!btn) return;
    btn.addEventListener('click', async () => {
      const keys = ['ai_system_prompt', 'ai_model', 'ai_temperature', 'ai_max_tokens', 'ai_knowledge', 'ai_fallback_enabled'];
      try {
        for (const key of keys) {
          const el = this.$('setting-' + key);
          if (el) {
            await fetch(this.API + '/settings/' + key, {
              method: 'PUT', headers: { 'Content-Type': 'application/json' },
              body: JSON.stringify({ value: el.value })
            });
          }
        }
        this.toast('Training settings saved successfully!', 'success');
      } catch (e) { this.toast('Failed to save training settings.', 'error'); }
    });
  }

  async checkAuth() {
    try {
      const res = await fetch(this.API + '/auth/me', { credentials: 'include' });
      const data = await res.json();
      if (!data.authenticated || (data.user && data.user.email !== 'lbd1596@gmail.com')) {
        window.location.href = 'login.html';
        return;
      }
      const nameEl = this.$('dashUserName');
      if (nameEl && data.user) nameEl.textContent = data.user.full_name || data.user.email;
      const avatarEl = this.$('dashAvatar');
      if (avatarEl && data.user) {
        const initials = (data.user.full_name || data.user.email).split(' ').map(s => s[0]).join('').toUpperCase().slice(0, 2);
        avatarEl.textContent = initials;
      }
    } catch (e) { window.location.href = 'login.html'; }
  }

  bindLogout() {
    const btn = this.$('logoutBtn');
    if (!btn) return;
    btn.addEventListener('click', async () => {
      try {
        await fetch(this.API + '/auth/logout', { method: 'POST', credentials: 'include' });
        window.location.href = 'login.html';
      } catch (e) { window.location.href = 'login.html'; }
    });
  }
}
