'use client';

import { useState, useEffect } from 'react';
import { Header } from './Header';
import { tasksClient } from '@/clients/tasks-client';

interface HeaderContainerProps {
  title: string;
  subtitle: string;
  initialStats: {
    total: number;
    completed: number;
    inProgress: number;
    todo: number;
    completionRate: number;
  };
}

export function HeaderContainer({ title, subtitle, initialStats }: HeaderContainerProps) {
  const [stats, setStats] = useState(initialStats);
  const [isHydrated, setIsHydrated] = useState(false);

  // Hydratation côté client
  useEffect(() => {
    setIsHydrated(true);
  }, []);

  // Rafraîchir les stats périodiquement côté client
  useEffect(() => {
    if (!isHydrated) return;

    const refreshStats = async () => {
      try {
        const response = await tasksClient.getTasks({ limit: 1 }); // Juste pour les stats
        setStats(response.stats);
      } catch (error) {
        console.error('Erreur lors du rafraîchissement des stats:', error);
      }
    };

    // Rafraîchir les stats toutes les 30 secondes
    const interval = setInterval(refreshStats, 30000);

    // Rafraîchir immédiatement après hydratation
    refreshStats();

    return () => clearInterval(interval);
  }, [isHydrated]);

  return (
    <Header 
      title={title}
      subtitle={subtitle}
      stats={stats}
    />
  );
}
