import { useMemo, useCallback } from 'react';
import { useNavigate } from 'react-router-dom';
import { Grid } from 'antd';
import { useTourStore } from '../../stores/tour.store';
import { useSettingsStore } from '../../stores/settings.store';
import { tourRegistry } from './tourRegistry';
import type { TourSectionId } from './types';

/**
 * Hook to launch a specific tour section from any component.
 * Handles navigation to the section's route if needed.
 */
export function useTourLauncher(sectionId: TourSectionId) {
  const navigate = useNavigate();
  const { sections, launchSection } = useTourStore();
  const settings = useSettingsStore((s) => s.settings);
  const screens = Grid.useBreakpoint();
  const isMobile = !screens.md;

  const section = useMemo(
    () => tourRegistry.find((s) => s.id === sectionId),
    [sectionId]
  );

  const available = useMemo(() => {
    if (!section || !settings) return false;
    if (section.featureFlag && !settings[section.featureFlag]) return false;
    return true;
  }, [section, settings]);

  const progress = sections[sectionId] ?? null;
  const inProgress = progress !== null && !progress.completed && progress.currentStep > 0;
  const completed = progress?.completed ?? false;

  const launch = useCallback(() => {
    if (!section || !settings) return;
    const ctx = { settings, isMobile };
    const steps = section.buildSteps(ctx);
    if (steps.length === 0) return;

    launchSection(sectionId, steps.length);

    // Navigate to the section's page if it has a route
    if (section.route) {
      navigate(section.route);
    }
  }, [section, settings, isMobile, sectionId, launchSection, navigate]);

  return { available, launch, inProgress, completed, progress };
}
