"use client";
import { useEffect, useState } from 'react';

export default function ProjectSwitcher() {
  const [projects, setProjects] = useState([]);
  const [active, setActive] = useState('');

  useEffect(() => {
    setActive(localStorage.getItem('madarx.activeProjectId') || '');
    fetch('/api/projects')
      .then((r) => r.json())
      .then((d) => setProjects(d.projects || []))
      .catch(() => {});
  }, []);

  function change(value) {
    setActive(value);
    if (value) localStorage.setItem('madarx.activeProjectId', value);
    else localStorage.removeItem('madarx.activeProjectId');
    window.dispatchEvent(
      new CustomEvent('madarx:project-change', {
        detail: { project_id: value || null },
      })
    );
  }

  return (
    <div className="project-switcher" data-project-switcher>
      <select
        value={active}
        onChange={(e) => change(e.target.value)}
        aria-label="Active project"
      >
        <option value="">All projects</option>
        {projects.map((p) => (
          <option key={p.id} value={p.id}>
            {p.name}
          </option>
        ))}
      </select>
    </div>
  );
}
