import { useMemo, useEffect, useState } from 'react';
import { Tour, Grid } from 'antd';
import { useTourStore } from '../../stores/tour.store';
import { useSettingsStore } from '../../stores/settings.store';
import { tourRegistry } from './tourRegistry';
import type { TourSectionId, TourStepContext } from './types';

interface PageTourProps {
  sectionId: TourSectionId;
}

/**
 * Page-level tour runner. Include this on any page that has a tour section.
 * Only renders the Tour overlay when this page's section is the active one.
 */
export function PageTour({ sectionId }: PageTourProps) {
  const { activeSectionId, activeStep, setStep, completeActiveSection, pauseActiveSection } = useTourStore();
  const settings = useSettingsStore((s) => s.settings);
  const screens = Grid.useBreakpoint();
  const isMobile = !screens.md;
  const [open, setOpen] = useState(false);

  const isActive = activeSectionId === sectionId;

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

  const ctx: TourStepContext | null = useMemo(
    () => settings ? { settings, isMobile } : null,
    [settings, isMobile]
  );

  const steps = useMemo(
    () => (section && ctx ? section.buildSteps(ctx) : []),
    [section, ctx]
  );

  // Open tour when this section becomes active, with delay for DOM readiness
  useEffect(() => {
    if (isActive && steps.length > 0) {
      const timer = setTimeout(() => setOpen(true), 400);
      return () => clearTimeout(timer);
    }
    setOpen(false);
  }, [isActive, steps.length]);

  if (!isActive || steps.length === 0) return null;

  const isLastStep = activeStep >= steps.length - 1;

  return (
    <Tour
      open={open}
      current={activeStep}
      steps={steps}
      onChange={(step) => setStep(step)}
      onClose={() => {
        setOpen(false);
        // If closed on the last step, treat as completed
        if (isLastStep) {
          completeActiveSection();
        } else {
          pauseActiveSection();
        }
      }}
      onFinish={() => {
        setOpen(false);
        completeActiveSection();
      }}
    />
  );
}
