const SectorDemo = () => {
  const [sectors, setSectors] = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const [error, setError] = React.useState(null);

  React.useEffect(() => {
    const controller = new AbortController();
    const API_URL = window.SECTOR_API_URL || "http://localhost:4000/api/sectors";

    async function fetchSectors() {
      try {
        const response = await fetch(API_URL, { signal: controller.signal });
        if (!response.ok) {
          throw new Error("No pudimos cargar los sectores en la demo");
        }
        const payload = await response.json();
        setSectors(payload.sectors || []);
      } catch (err) {
        if (err.name !== "AbortError") {
          setError(err.message);
        }
      } finally {
        setLoading(false);
      }
    }

    fetchSectors();

    return () => controller.abort();
  }, []);

  if (loading) {
    return (
      <div className="sector-loader">
        <span className="sector-spinner" aria-hidden="true" />
        <p className="mb-0">Cargando sectores...</p>
      </div>
    );
  }

  if (error) {
    return (
      <div className="sector-error">
        <p className="mb-0">{error}</p>
        <p className="small text-secondary mb-0">Asegurate de tener el servidor Node ejecutándose.</p>
      </div>
    );
  }

  const badgeClass = {
    disponible: "sector-badge-success",
    reservada: "sector-badge-warning",
    ocupada: "sector-badge-danger",
  };

  return (
    <div className="sector-grid">
      {sectors.map((sector) => (
        <article key={sector.id} className="sector-card">
          <div>
            <h3>{sector.name}</h3>
            <p>{sector.description}</p>
            <span className="sector-card__count">
              {sector.available} de {sector.total} mesas libres
            </span>
          </div>
          <ul className="sector-table-list" aria-label={`Mesas del sector ${sector.name}`}>
            {sector.tables.map((table) => (
              <li key={table.id} className={`sector-table ${badgeClass[table.status] || ""}`}>
                <span className="sector-table__label">{table.label}</span>
                <span className="sector-table__capacity">{table.capacity} pax</span>
                <span className="sector-table__status">{table.status}</span>
              </li>
            ))}
          </ul>
        </article>
      ))}
    </div>
  );
};

const rootElement = document.getElementById("sector-demo-root");

if (rootElement) {
  const root = ReactDOM.createRoot(rootElement);
  root.render(<SectorDemo />);
}

