/**
 * ds-storybook-live-compare.js
 * Side-by-side Storybook and Live Application comparison
 * UI Team Tool #2
 */

import { createComparisonView, setupComparisonHandlers } from '../../utils/tool-templates.js';
import { ComponentHelpers } from '../../utils/component-helpers.js';
import contextStore from '../../stores/context-store.js';
import apiClient from '../../services/api-client.js';

class DSStorybookLiveCompare extends HTMLElement {
  constructor() {
    super();
    this.storybookUrl = '';
    this.liveUrl = '';
  }

  async connectedCallback() {
    await this.loadProjectConfig();
    this.render();
    this.setupEventListeners();
  }

  async loadProjectConfig() {
    try {
      const context = contextStore.getMCPContext();
      if (!context.project_id) {
        throw new Error('No project selected');
      }

      const project = await apiClient.getProject(context.project_id);
      this.storybookUrl = project.storybook_url || '';
      this.liveUrl = project.live_url || window.location.origin;
    } catch (error) {
      console.error('[DSStorybookLiveCompare] Failed to load project config:', error);
    }
  }

  setupEventListeners() {
    const storybookInput = this.querySelector('#storybook-url-input');
    const liveInput = this.querySelector('#live-url-input');
    const loadBtn = this.querySelector('#load-comparison-btn');

    if (storybookInput) {
      storybookInput.value = this.storybookUrl;
    }

    if (liveInput) {
      liveInput.value = this.liveUrl;
    }

    if (loadBtn) {
      loadBtn.addEventListener('click', () => this.loadComparison());
    }

    const comparisonContainer = this.querySelector('#comparison-container');
    if (comparisonContainer) {
      setupComparisonHandlers(comparisonContainer, {});
    }
  }

  loadComparison() {
    const storybookInput = this.querySelector('#storybook-url-input');
    const liveInput = this.querySelector('#live-url-input');

    this.storybookUrl = storybookInput?.value || '';
    this.liveUrl = liveInput?.value || '';

    if (!this.storybookUrl || !this.liveUrl) {
      ComponentHelpers.showToast?.('Please enter both Storybook and Live application URLs', 'error');
      return;
    }

    try {
      new URL(this.storybookUrl);
      new URL(this.liveUrl);
    } catch (error) {
      ComponentHelpers.showToast?.('Invalid URL format', 'error');
      return;
    }

    const comparisonContainer = this.querySelector('#comparison-container');
    if (comparisonContainer) {
      comparisonContainer.innerHTML = createComparisonView({
        leftTitle: 'Storybook (Design System)',
        rightTitle: 'Live Application',
        leftSrc: this.storybookUrl,
        rightSrc: this.liveUrl
      });

      setupComparisonHandlers(comparisonContainer, {});
      ComponentHelpers.showToast?.('Comparison loaded', 'success');
    }
  }

  render() {
    this.innerHTML = `
      <div style="display: flex; flex-direction: column; height: 100%;">
        <!-- Configuration Panel -->
        <div style="padding: 16px; border-bottom: 1px solid var(--vscode-border); background: var(--vscode-sidebar);">
          <h3 style="font-size: 12px; font-weight: 600; margin-bottom: 12px;">Storybook vs Live Comparison</h3>

          <div style="display: grid; grid-template-columns: 1fr 1fr auto; gap: 12px; align-items: end;">
            <div>
              <label style="display: block; font-size: 11px; font-weight: 600; margin-bottom: 4px; color: var(--vscode-text-dim);">
                Storybook Component URL
              </label>
              <input
                type="url"
                id="storybook-url-input"
                placeholder="https://storybook.example.com/?path=/story/..."
                class="input"
                style="width: 100%; font-size: 11px;"
              />
            </div>

            <div>
              <label style="display: block; font-size: 11px; font-weight: 600; margin-bottom: 4px; color: var(--vscode-text-dim);">
                Live Application URL
              </label>
              <input
                type="url"
                id="live-url-input"
                placeholder="https://app.example.com/..."
                class="input"
                style="width: 100%; font-size: 11px;"
              />
            </div>

            <button id="load-comparison-btn" class="button" style="font-size: 11px; padding: 6px 16px;">
              🔍 Load Comparison
            </button>
          </div>

          <div style="margin-top: 8px; font-size: 10px; color: var(--vscode-text-dim);">
            💡 Tip: Compare the same component in design system vs production to identify drift
          </div>
        </div>

        <!-- Comparison View -->
        <div id="comparison-container" style="flex: 1; overflow: hidden;">
          ${this.storybookUrl && this.liveUrl ? createComparisonView({
            leftTitle: 'Storybook (Design System)',
            rightTitle: 'Live Application',
            leftSrc: this.storybookUrl,
            rightSrc: this.liveUrl
          }) : `
            <div style="display: flex; align-items: center; justify-content: center; height: 100%; text-align: center; padding: 48px;">
              <div>
                <div style="font-size: 48px; margin-bottom: 16px;">⚖️</div>
                <h3 style="font-size: 14px; font-weight: 600; margin-bottom: 8px;">No Comparison Loaded</h3>
                <p style="font-size: 12px; color: var(--vscode-text-dim);">
                  Enter Storybook and Live application URLs to compare design system vs implementation
                </p>
              </div>
            </div>
          `}
        </div>
      </div>
    `;
  }
}

customElements.define('ds-storybook-live-compare', DSStorybookLiveCompare);

export default DSStorybookLiveCompare;
