import { assetRequestTypes, normalizeAssetCatalog } from './asset-browser-model.js';

const MODE_CONFIG = Object.freeze({
  media: {
    title: 'Select Media',
    filters: `
        <button class="asset-filter-tab active" data-filter="all">All</button>
        <button class="asset-filter-tab" data-filter="images">Images</button>
        <button class="asset-filter-tab" data-filter="videos">Videos</button>
        <input type="text" id="mediaSearchInput" class="media-search-input" placeholder="Search media..." style="padding:6px 12px;border:1px solid var(--line);border-radius:6px;background:rgba(0,0,0,0.3);color:var(--text);font:inherit;font-size:12px;width:160px;margin-left:auto;">
      `,
  },
  postfx: { title: 'Select Post Effect', filters: '', gridId: 'postfxAssetGrid' },
  shader: {
    title: 'Select Shader Effect',
    gridId: 'shaderPreviewAssetGrid',
    filters: `
        <input type="text" id="shaderSearchInput" class="shader-search-input" placeholder="Search shaders..." style="padding:6px 12px;border:1px solid var(--line);border-radius:6px;background:rgba(0,0,0,0.3);color:var(--text);font:inherit;font-size:12px;width:200px;">
      `,
  },
  audio: {
    title: 'Select Audio',
    gridId: 'audioPreviewAssetGrid',
    filters: `
        <button class="asset-filter-tab active" data-filter="all">All Audio</button>
      `,
  },
  scenes: {
    title: 'Select Scene',
    gridId: 'scenePreviewAssetGrid',
    filters: `
        <input type="text" id="sceneSearchInput" class="scene-search-input" placeholder="Search scenes..." style="padding:6px 12px;border:1px solid var(--line);border-radius:6px;background:rgba(0,0,0,0.3);color:var(--text);font:inherit;font-size:12px;width:200px;">
      `,
  },
  '3d': {
    title: 'Select 3D Model',
    filters: `
        <button class="asset-filter-tab active" data-filter="all">All Models</button>
      `,
  },
  lut: { title: 'Select LUT', filters: '', gridId: 'lutAssetGrid' },
});

export function assetBrowserModeConfig(mode) {
  return MODE_CONFIG[mode] || MODE_CONFIG.media;
}

export function assetBrowserGrid(documentTarget, fallbackGrid, mode) {
  const gridId = assetBrowserModeConfig(mode).gridId;
  return gridId ? documentTarget.getElementById(gridId) : fallbackGrid;
}

export async function loadAssetCatalog(api, mode) {
  const responses = await Promise.all(assetRequestTypes(mode).map(type => api.assets.list(type)));
  const catalogs = await Promise.all(responses.map(response => response.json()));
  return normalizeAssetCatalog(mode, catalogs);
}

const PREVIEW_MODES = Object.freeze({
  postfx: ['postfxPreviewLayout', 'postfx-preview-mode'],
  shader: ['shaderPreviewLayout', 'shader-preview-mode'],
  scenes: ['scenePreviewLayout', 'scene-preview-mode'],
  audio: ['audioPreviewLayout', 'audio-preview-mode'],
  lut: ['lutPreviewLayout', 'lut-preview-mode'],
});

export function createAssetBrowserShell({
  documentTarget,
  modal,
  title,
  filterTabs,
  refineButton,
  previewControllers = {},
}) {
  const modalPanel = documentTarget.querySelector('.asset-browser-modal');
  const standard = documentTarget.getElementById('assetBrowserStandard');
  const layouts = Object.values(PREVIEW_MODES).map(([id]) => documentTarget.getElementById(id));
  const previewClasses = Object.values(PREVIEW_MODES).map(([, className]) => className);
  const stopPreviews = () => {
    for (const controller of Object.values(previewControllers)) controller.stop?.();
  };

  return {
    open(mode) {
      stopPreviews();
      standard.style.display = 'none';
      for (const layout of layouts) layout.style.display = 'none';
      modalPanel.classList.remove(...previewClasses);
      const preview = PREVIEW_MODES[mode];
      if (preview) {
        documentTarget.getElementById(preview[0]).style.display = 'flex';
        modalPanel.classList.add(preview[1]);
        previewControllers[mode]?.reset?.();
        previewControllers[mode]?.start?.();
      } else {
        standard.style.display = 'block';
      }
      const previewMode = !!preview;
      documentTarget.getElementById('sceneActionBtns').style.display = 'none';
      documentTarget.getElementById('shaderActionBtns').style.display = 'none';
      documentTarget.getElementById('assetUploadBtn').style.display = previewMode ? 'none' : 'block';
      refineButton.style.display = 'none';
      const config = assetBrowserModeConfig(mode);
      title.textContent = config.title;
      filterTabs.innerHTML = config.filters;
      modal.classList.add('show');
      return config;
    },
    close() {
      modal.classList.remove('show');
      stopPreviews();
      modalPanel.classList.remove(...previewClasses);
    },
  };
}
