'use client';

import { useState, useEffect } from 'react';
import { useParams } from 'next/navigation';
import { LeagueRulebookTemplate } from '@/templates/LeagueRulebookTemplate';
import { useServices } from '@/lib/services/ServiceProvider';
import { LeagueDetailPageViewModel } from '@/lib/view-models/LeagueDetailPageViewModel';

export default function LeagueRulebookInteractive() {
  const params = useParams();
  const leagueId = params.id as string;

  const { leagueService } = useServices();

  const [viewModel, setViewModel] = useState<LeagueDetailPageViewModel | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    async function loadData() {
      try {
        const data = await leagueService.getLeagueDetailPageData(leagueId);
        if (!data) {
          setLoading(false);
          return;
        }

        setViewModel(data);
      } catch (err) {
        console.error('Failed to load scoring config:', err);
      } finally {
        setLoading(false);
      }
    }

    loadData();
  }, [leagueId, leagueService]);

  if (!viewModel && !loading) {
    return (
      <div className="text-center text-gray-400 py-12">
        Unable to load rulebook
      </div>
    );
  }

  return <LeagueRulebookTemplate viewModel={viewModel!} loading={loading} />;
}