/**
 * ds-asset-list.js
 * List view of design assets (icons, images, etc.)
 * UX Team Tool #3
 */

import { createGalleryView, setupGalleryHandlers } from '../../utils/tool-templates.js';
import { ComponentHelpers } from '../../utils/component-helpers.js';
import contextStore from '../../stores/context-store.js';

class DSAssetList extends HTMLElement {
  constructor() {
    super();
    this.assets = [];
    this.isLoading = false;
  }

  async connectedCallback() {
    this.render();
    await this.loadAssets();
  }

  async loadAssets() {
    this.isLoading = true;
    const container = this.querySelector('#asset-list-container');
    if (container) {
      container.innerHTML = ComponentHelpers.renderLoading('Loading design assets...');
    }

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

      // Call assets API
      const response = await fetch(`/api/assets/list?projectId=${context.project_id}`);
      if (!response.ok) {
        throw new Error(`Failed to load assets: ${response.statusText}`);
      }

      const result = await response.json();
      this.assets = result.assets || [];

      this.renderAssetGallery();
    } catch (error) {
      console.error('[DSAssetList] Failed to load assets:', error);
      if (container) {
        container.innerHTML = ComponentHelpers.renderError('Failed to load assets', error);
      }
    } finally {
      this.isLoading = false;
    }
  }

  renderAssetGallery() {
    const container = this.querySelector('#asset-list-container');
    if (!container) return;

    const config = {
      title: 'Design Assets',
      items: this.assets.map(asset => ({
        id: asset.id,
        src: asset.url || asset.thumbnailUrl,
        title: asset.name,
        subtitle: `${asset.type} • ${asset.size || 'N/A'}`
      })),
      onItemClick: (item) => this.viewAsset(item),
      onDelete: (item) => this.deleteAsset(item)
    };

    container.innerHTML = createGalleryView(config);
    setupGalleryHandlers(container, config);
  }

  viewAsset(item) {
    // Open asset in new tab or modal
    if (item.src) {
      window.open(item.src, '_blank');
    }
  }

  deleteAsset(item) {
    ComponentHelpers.showToast?.(`Deleted ${item.title}`, 'success');
    this.assets = this.assets.filter(a => a.id !== item.id);
    this.renderAssetGallery();
  }

  render() {
    this.innerHTML = `
      <div id="asset-list-container" style="height: 100%; overflow: hidden;">
        ${ComponentHelpers.renderLoading('Loading assets...')}
      </div>
    `;
  }
}

customElements.define('ds-asset-list', DSAssetList);

export default DSAssetList;
