/**
 * qa-workdesk.js
 * QA Team workdesk - Console logs, network monitoring, DOM inspection
 * MVP2: Added metrics frontpage as default view
 */

import BaseWorkdesk from './base-workdesk.js';
import { hydrateComponent } from '../config/component-registry.js';
import '../components/tools/ds-console-viewer.js';

export default class QAWorkdesk extends BaseWorkdesk {
  constructor(shell) {
    super(shell);
    this.teamId = 'qa';
    this.teamName = 'QA Team';
    this.tools = [
      {
        id: 'frontpage',
        name: 'Dashboard',
        description: 'Team metrics and quick actions',
        component: 'ds-frontpage'
      },
      {
        id: 'figma-live-compare',
        name: 'Figma vs Live',
        description: 'QA validation: Figma design vs live implementation',
        component: 'ds-figma-live-compare'
      },
      {
        id: 'esre-editor',
        name: 'ESRE Editor',
        description: 'Edit Explicit Style Requirements and Expectations',
        component: 'ds-esre-editor'
      },
      {
        id: 'console-viewer',
        name: 'Console Viewer',
        description: 'Monitor browser console logs',
        mcpTool: 'browser_get_logs'
      },
      {
        id: 'network-monitor',
        name: 'Network Monitor',
        description: 'Track network requests',
        mcpTool: 'devtools_network_requests'
      },
      {
        id: 'error-tracker',
        name: 'Error Tracker',
        description: 'Track uncaught exceptions',
        mcpTool: 'browser_get_errors'
      }
    ];
    this.currentTool = 'frontpage';
  }

  async loadTool(tool) {
    const stage = this.shell.stageContent;
    if (!stage) return;

    // For tools with components, load them dynamically
    if (tool.component) {
      // Show loading state
      stage.innerHTML = `
        <div style="display: flex; align-items: center; justify-content: center; height: 100%; padding: 48px;">
          <div style="text-align: center;">
            <div style="font-size: 24px; margin-bottom: 12px;">⏳</div>
            <div style="font-size: 12px; color: var(--vscode-text-dim);">Loading ${tool.name}...</div>
          </div>
        </div>
      `;

      try {
        // Clear the stage and hydrate the component
        stage.innerHTML = '';
        await hydrateComponent(tool.component, stage);
        console.log(`[QAWorkdesk] Loaded component: ${tool.component}`);
      } catch (error) {
        console.error(`[QAWorkdesk] Failed to load tool ${tool.component}:`, error);
        stage.innerHTML = `
          <div style="padding: 24px;">
            <h2 style="margin-bottom: 16px; color: var(--vscode-error);">Error Loading Tool</h2>
            <p style="color: var(--vscode-text-dim);">${error.message}</p>
          </div>
        `;
      }
    } else {
      // Fall back to base implementation for MCP tools
      super.loadTool(tool);
    }
  }

  renderStage() {
    const stage = this.shell.stageContent;
    if (!stage) return;

    stage.innerHTML = `
      <div style="padding: 24px;">
        <h1 style="margin-bottom: 8px; font-size: 24px;">QA Team Workdesk</h1>
        <p style="color: var(--vscode-text-dim); margin-bottom: 32px;">
          QA validation, testing, and debugging tools
        </p>

        <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap: 16px;">
          ${this.createCard('QA Validation', `
            <p>Compare and validate implementations:</p>
            <ul style="margin-top: 8px; padding-left: 20px;">
              <li>Figma vs Live comparison</li>
              <li>Screenshot capture</li>
              <li>Visual validation</li>
              <li>Style requirements (ESRE)</li>
            </ul>
          `)}

          ${this.createCard('Console Monitoring', `
            <p>Real-time console log streaming:</p>
            <ul style="margin-top: 8px; padding-left: 20px;">
              <li>Log, warn, error levels</li>
              <li>Stack trace analysis</li>
              <li>Filter by severity</li>
              <li>Export logs</li>
            </ul>
          `)}

          ${this.createCard('Network Debugging', `
            <p>Track all HTTP requests:</p>
            <ul style="margin-top: 8px; padding-left: 20px;">
              <li>Request/response headers</li>
              <li>Payload inspection</li>
              <li>Timing analysis</li>
              <li>Failed requests</li>
            </ul>
          `)}
        </div>

        <div style="margin-top: 32px;">
          <h2 style="margin-bottom: 16px; font-size: 16px;">Quick Actions</h2>
          <div style="display: flex; gap: 12px; flex-wrap: wrap;">
            <button class="button" id="compare-btn">Figma vs Live</button>
            <button class="button" id="esre-btn">Edit ESRE</button>
            <button class="button" id="console-btn">Open Console</button>
            <button class="button" id="network-btn">Network Monitor</button>
          </div>
        </div>
      </div>
    `;

    // Setup button handlers
    stage.querySelector('#compare-btn')?.addEventListener('click', () => {
      this.onToolClick('figma-live-compare');
    });

    stage.querySelector('#esre-btn')?.addEventListener('click', () => {
      this.onToolClick('esre-editor');
    });

    stage.querySelector('#console-btn')?.addEventListener('click', () => {
      this.onToolClick('console-viewer');
      // Switch panel to console tab (component is already configured via panel-config.js)
      const panel = this.shell.querySelector('ds-panel');
      if (panel) {
        panel.switchTab('console');
      }
    });

    stage.querySelector('#network-btn')?.addEventListener('click', () => {
      this.onToolClick('network-monitor');
      // Switch panel to network tab (component is already configured via panel-config.js)
      const panel = this.shell.querySelector('ds-panel');
      if (panel) {
        panel.switchTab('network');
      }
    });
  }
}
