/**
 * DashboardWidgetLoader — dynamically loads widget components (Task 5.25).
 */

import React, { lazy, Suspense } from 'react';
import { useTranslation } from 'react-i18next';
import { Skeleton } from '@/components/ui/Skeleton';
import type { DashboardWidgetDef } from '@/api/dashboard';

// Widget component registry — maps component paths to lazy-loaded components
const widgetRegistry: Record<string, React.LazyExoticComponent<React.ComponentType>> = {
  '@/components/dashboard/RecentContactsWidget': lazy(() =>
    import('@/components/dashboard/RecentContactsWidget').then(m => ({ default: m.RecentContactsWidget }))
  ),
  '@/components/dashboard/TasksSummaryWidget': lazy(() =>
    import('@/components/dashboard/TasksSummaryWidget').then(m => ({ default: m.TasksSummaryWidget }))
  ),
  '@/components/dashboard/CalendarUpcomingWidget': lazy(() =>
    import('@/components/dashboard/CalendarUpcomingWidget').then(m => ({ default: m.CalendarUpcomingWidget }))
  ),
};

interface DashboardWidgetLoaderProps {
  widget: DashboardWidgetDef;
}

export function DashboardWidgetLoader({ widget }: DashboardWidgetLoaderProps) {
  const { t } = useTranslation();
  const WidgetComponent = widgetRegistry[widget.component];

  if (!WidgetComponent) {
    return (
      <div className="p-4 border rounded-lg bg-secondary-50" data-testid={`widget-${widget.id}`}>
        <p className="text-sm text-secondary-500">
          {t('dashboard.widgetNotAvailable', { name: widget.label || widget.id })}
        </p>
      </div>
    );
  }

  return (
    <div data-testid={`widget-${widget.id}`}>
      <Suspense fallback={<Skeleton className="h-32" />}>
        <WidgetComponent />
      </Suspense>
    </div>
  );
}
