import { useEffect, useState } from 'react';
import { useParams } from 'react-router-dom';
import { loadSiteDefinition } from '../loaders/loadSiteDefinition';
import { renderLayout } from '../utils/layoutRenderer';
import type { SiteDefinition } from '../types';

function SiteRenderer() {
  const { siteId } = useParams<{ siteId: string }>();
  const [siteDefinition, setSiteDefinition] = useState<SiteDefinition | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    if (!siteId) {
      setError('Site ID is required');
      setLoading(false);
      return;
    }

    loadSiteDefinition(siteId)
      .then((definition) => {
        setSiteDefinition(definition);
        setLoading(false);
      })
      .catch((err) => {
        setError(err.message || 'Failed to load site');
        setLoading(false);
      });
  }, [siteId]);

  if (loading) {
    return <div>Loading site...</div>;
  }

  if (error) {
    return <div>Error: {error}</div>;
  }

  if (!siteDefinition) {
    return <div>Site not found</div>;
  }

  return (
    <div className="site-renderer">
      {renderLayout(siteDefinition)}
    </div>
  );
}

export default SiteRenderer;

