/**
 * admin-ui/js/core/project-selector.js
 * Manages project selection in the header
 */

class ProjectSelector {
  constructor(containerElement) {
    if (!containerElement) return;
    this.container = containerElement;
    this.init();
  }

  init() {
    this.projects = this.getProjects();
    this.selectedProject = this.getSelectedProject();
    this.render();
    this.bindEvents();
  }

  getProjects() {
    // Sample projects - in production these would come from an API
    return [
      { id: 'dss', name: 'Design System Server', icon: '🎨' },
      { id: 'component-library', name: 'Component Library', icon: '📦' },
      { id: 'tokens-manager', name: 'Tokens Manager', icon: '🎯' },
      { id: 'figma-sync', name: 'Figma Sync', icon: '🔄' }
    ];
  }

  getSelectedProject() {
    const stored = localStorage.getItem('dss_selected_project');
    return stored || this.projects[0].id;
  }

  setSelectedProject(projectId) {
    this.selectedProject = projectId;
    localStorage.setItem('dss_selected_project', projectId);
    
    // Dispatch custom event
    window.dispatchEvent(new CustomEvent('project-changed', {
      detail: { projectId }
    }));
  }

  render() {
    const selectedProject = this.projects.find(p => p.id === this.selectedProject);
    
    this.container.innerHTML = `
      <div class="project-selector">
        <label for="project-select" class="project-selector__label">Project:</label>
        <select id="project-select" class="project-selector__select" aria-label="Select project">
          ${this.projects.map(project => `
            <option value="${project.id}" ${project.id === this.selectedProject ? 'selected' : ''}>
              ${project.icon} ${project.name}
            </option>
          `).join('')}
        </select>
      </div>
    `;
  }

  bindEvents() {
    const select = this.container.querySelector('#project-select');
    if (select) {
      select.addEventListener('change', (event) => {
        this.setSelectedProject(event.target.value);
        this.render();
        this.bindEvents();
      });
    }
  }
}

export default ProjectSelector;
