/**
 * Recent plots sidebar management
 */
export class RecentPlotsManager {
  constructor(maxRecentPlots = 20) {
    this.MAX_RECENT_PLOTS = maxRecentPlots;
    this.init();
  }

  init() {
    this.updateRecentPlotsDisplay();
    this.trackPlotClicks();
  }

  /**
   * Add plot to recent plots list
   */
  addToRecentPlots(plotHref) {
    const plotName = plotHref.split('/').pop().replace('.pdf', '');
    const pathParts = plotHref.split('/').filter(p => p !== '' && p !== plotName + '.pdf');
    const plotPath = pathParts.join(' / ');
    const thumbUrl = plotHref.replace('.pdf', '.png');
    
    // Determine the gallery page URL (directory containing the plot)
    const plotDir = plotHref.substring(0, plotHref.lastIndexOf('/'));
    const galleryUrl = plotDir + '/index.html';
    
    const plotInfo = {
      name: plotName,
      path: plotPath,
      href: plotHref,
      thumbUrl: thumbUrl,
      galleryUrl: galleryUrl,
      timestamp: Date.now()
    };
    
    let recentPlots = JSON.parse(localStorage.getItem('recentPlots') || '[]');
    recentPlots = recentPlots.filter(p => p.href !== plotHref);
    recentPlots.unshift(plotInfo);
    recentPlots = recentPlots.slice(0, this.MAX_RECENT_PLOTS);
    
    localStorage.setItem('recentPlots', JSON.stringify(recentPlots));
    this.updateRecentPlotsDisplay();
  }

  /**
   * Update recent plots sidebar display
   */
  updateRecentPlotsDisplay() {
    const sidebarContent = document.getElementById('sidebarContent');
    if (!sidebarContent) return;
    
    const recentPlots = JSON.parse(localStorage.getItem('recentPlots') || '[]');
    
    if (recentPlots.length === 0) {
      sidebarContent.innerHTML = `
        <div style="text-align: center; color: var(--breadcrumb-color); margin: 2rem 0;">
          📭 No recent plots yet<br>
          <small style="opacity: 0.7;">Open some plots to see them here</small>
        </div>
      `;
      return;
    }
    
    let html = '';
    recentPlots.forEach(plot => {
      html += `
        <div class="recent-plot" onclick="window.recentPlotsManager.openRecentPlot('${plot.galleryUrl || plot.href}', '${plot.name}')" title="${plot.name}">
          <img src="${plot.thumbUrl}" class="recent-plot-thumb" alt="${plot.name}" />
          <div class="recent-plot-info">
            <div class="recent-plot-name">${plot.name}</div>
            <div class="recent-plot-path">📍 ${plot.path}</div>
          </div>
        </div>
      `;
    });
    
    sidebarContent.innerHTML = html;
  }

  /**
   * Open recent plot gallery page and highlight thumbnail
   */
  openRecentPlot(galleryUrl, plotName) {
    // Navigate to gallery page with plot highlight parameter
    const url = new URL(galleryUrl, window.location.origin);
    url.searchParams.set('highlight', plotName);
    window.location.href = url.toString();
    this.toggleSidebar();
  }

  /**
   * Toggle recent plots sidebar
   */
  toggleSidebar() {
    const sidebar = document.getElementById('sidebar');
    const overlay = document.getElementById('sidebarOverlay');
    
    if (sidebar) sidebar.classList.toggle('open');
    if (overlay) overlay.classList.toggle('open');
  }

  /**
   * Track clicks on plot links
   */
  trackPlotClicks() {
    document.addEventListener('click', (e) => {
      const link = e.target.closest('a[href$=".pdf"]');
      if (link) {
        this.addToRecentPlots(link.href);
      }
    });
  }
}
