/**
 * preview-panel.mjs — File preview panel component
 * Shows previews of agent-created files (HTML in iframe, markdown rendered, code as text).
 * Auto-opens when the agent creates files via skills.
 */

import store from '../store.mjs';
import eventBus, { EVENTS } from '../event-bus.mjs';
import { createElement, icon, empty } from '../utils/dom.mjs';
import { renderMarkdown } from '../utils/markdown.mjs';
import api from '../api.mjs';

let panelEl = null;
let toolbarTitle = null;
let contentEl = null;
let currentFile = null;
let maximized = false;
let maximizeBtn = null;

const HTML_EXTS = ['.html', '.htm', '.svg'];
const MD_EXTS = ['.md', '.markdown'];

function tryParseMetadata(meta) {
  if (!meta) return {};
  if (typeof meta === 'object') return meta;
  try { return JSON.parse(meta); } catch { return {}; }
}

// ── Public API ──

export function init() {
  // Listen for file creation events via activity stream
  eventBus.on(EVENTS.ACTIVITY_EVENT, (data) => {
    if (!data) return;
    const kind = data.kind || data.type;
    if (kind !== 'file') return;

    const meta = tryParseMetadata(data.metadata);
    if (meta.path) {
      openPreview(meta.path);
    }
  });
}

export function createPanel() {
  panelEl = createElement('div', { className: 'preview-panel hidden' });

  // Toolbar
  const toolbar = createElement('div', { className: 'preview-toolbar' });

  toolbarTitle = createElement('span', { className: 'preview-toolbar-title' }, ['Preview']);
  toolbar.appendChild(toolbarTitle);

  // Download button
  const downloadBtn = createElement('button', {
    className: 'glass-button-icon',
    'aria-label': 'Download file',
    title: 'Download',
    type: 'button'
  });
  downloadBtn.appendChild(icon('download', { size: 16 }));
  downloadBtn.addEventListener('click', () => {
    if (currentFile) {
      const filename = decodeURIComponent(currentFile.split('/').pop());
      api.downloadFile(filename);
    }
  });
  toolbar.appendChild(downloadBtn);

  // Maximize / restore button
  maximizeBtn = createElement('button', {
    className: 'glass-button-icon',
    'aria-label': 'Maximize preview',
    title: 'Maximize',
    type: 'button'
  });
  maximizeBtn.appendChild(icon('maximize-2', { size: 16 }));
  maximizeBtn.addEventListener('click', () => toggleMaximize());
  toolbar.appendChild(maximizeBtn);

  // Open in new tab
  const openBtn = createElement('button', {
    className: 'glass-button-icon',
    'aria-label': 'Open in new tab',
    title: 'Open in new tab',
    type: 'button'
  });
  openBtn.appendChild(icon('external-link', { size: 16 }));
  openBtn.addEventListener('click', () => {
    if (currentFile) window.open(currentFile, '_blank');
  });
  toolbar.appendChild(openBtn);

  // Close button
  const closeBtn = createElement('button', {
    className: 'glass-button-icon',
    'aria-label': 'Close preview',
    type: 'button'
  });
  closeBtn.appendChild(icon('x', { size: 16 }));
  closeBtn.addEventListener('click', () => closePreview());
  toolbar.appendChild(closeBtn);

  panelEl.appendChild(toolbar);

  // Content area
  contentEl = createElement('div', { className: 'preview-content' });
  panelEl.appendChild(contentEl);

  return panelEl;
}

export function openPreview(filePath) {
  if (!panelEl || !contentEl) return;

  currentFile = filePath;
  panelEl.classList.remove('hidden');

  // Update toolbar title
  const filename = decodeURIComponent(filePath.split('/').pop());
  if (toolbarTitle) toolbarTitle.textContent = filename;

  empty(contentEl);

  const ext = ('.' + filename.split('.').pop()).toLowerCase();

  if (HTML_EXTS.includes(ext)) {
    const iframe = createElement('iframe', {
      src: filePath,
      sandbox: 'allow-scripts allow-same-origin',
      'aria-label': `Preview of ${filename}`
    });
    contentEl.appendChild(iframe);
  } else if (MD_EXTS.includes(ext)) {
    const mdContainer = createElement('div', { className: 'preview-markdown' });
    mdContainer.textContent = 'Loading...';
    contentEl.appendChild(mdContainer);

    fetch(filePath)
      .then(r => r.text())
      .then(text => renderMarkdown(text))
      .then(html => { mdContainer.innerHTML = html; })
      .catch(() => { mdContainer.textContent = 'Failed to load preview'; });
  } else {
    const codeContainer = createElement('div', { className: 'preview-code' });
    codeContainer.textContent = 'Loading...';
    contentEl.appendChild(codeContainer);

    fetch(filePath)
      .then(r => r.text())
      .then(text => { codeContainer.textContent = text; })
      .catch(() => { codeContainer.textContent = 'Failed to load preview'; });
  }

  // Update toggle button state
  const toggleBtn = document.querySelector('.preview-toggle-btn');
  if (toggleBtn) toggleBtn.classList.add('has-file');
}

export function closePreview() {
  if (maximized) toggleMaximize();
  if (panelEl) panelEl.classList.add('hidden');
  currentFile = null;
}

export function isVisible() {
  return panelEl && !panelEl.classList.contains('hidden');
}

export function toggle() {
  if (isVisible()) {
    closePreview();
  } else if (currentFile) {
    openPreview(currentFile);
  }
}

function toggleMaximize() {
  if (!panelEl || !maximizeBtn) return;

  maximized = !maximized;
  panelEl.classList.toggle('maximized', maximized);

  // Swap icon
  empty(maximizeBtn);
  maximizeBtn.appendChild(icon(maximized ? 'minimize-2' : 'maximize-2', { size: 16 }));
  maximizeBtn.setAttribute('aria-label', maximized ? 'Restore preview' : 'Maximize preview');
  maximizeBtn.title = maximized ? 'Restore' : 'Maximize';
}
