import React, { useState, useEffect } from 'react';
import { useBackupRestore, BackupRestoreStep } from '../BackupRestoreContext';
import { BackupStep } from '../steps/BackupStep';
import { RestoreStep } from '../steps/RestoreStep';
import { ExportStep } from '../steps/ExportStep';
import { ImportStep } from '../steps/ImportStep';

const allSteps: BackupRestoreStep[] = ['backup', 'restore', 'export', 'import'];

const stepComponents: Record<BackupRestoreStep, React.ComponentType> = {
  backup: BackupStep,
  restore: RestoreStep,
  export: ExportStep,
  import: ImportStep,
};

export const StepContent: React.FC = () => {
  const { currentStep } = useBackupRestore();

  // Lazy-mount: keep each step mounted once visited so state is preserved.
  const [mountedSteps, setMountedSteps] = useState<Set<BackupRestoreStep>>(
    () => new Set([currentStep])
  );

  useEffect(() => {
    setMountedSteps((prev) => {
      if (prev.has(currentStep)) return prev;
      return new Set([...prev, currentStep]);
    });
  }, [currentStep]);

  return (
    <div className="flex-1 overflow-y-auto p-8">
      {allSteps.map((step) => {
        if (!mountedSteps.has(step)) return null;
        const StepComponent = stepComponents[step];
        return (
          <div key={step} className={step === currentStep ? undefined : 'hidden'}>
            <StepComponent />
          </div>
        );
      })}
    </div>
  );
};
