// Guided tour overlay. Reads the active scenario's tour script and
// anchors a step-card to the named region.
import { useEffect } from "react";
import { motion, AnimatePresence } from "framer-motion";
import { useApp, scenarioById } from "../state/store";
import { Sparkles, ChevL, ChevR, Close } from "./icons";

export default function Tour() {
  const tour = useApp((s) => s.tour);
  const scenarioId = useApp((s) => s.scenarioId);
  const endTour = useApp((s) => s.endTour);
  const tourPrev = useApp((s) => s.tourPrev);
  const tourNext = useApp((s) => s.tourNext);

  const sc = scenarioById(scenarioId);
  const step = sc?.tour[tour.index] ?? null;

  useEffect(() => {
    if (!tour.active) return;
    const onKey = (e: KeyboardEvent) => {
      if (e.key === "ArrowRight" || e.key === "Enter") { e.preventDefault(); tourNext(); }
      if (e.key === "ArrowLeft") { e.preventDefault(); tourPrev(); }
      if (e.key === "Escape") { e.preventDefault(); endTour(); }
    };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [tour.active, tourPrev, tourNext, endTour]);

  if (!tour.active || !step || !sc) return null;

  const last = tour.index === sc.tour.length - 1;
  const first = tour.index === 0;

  return (
    <AnimatePresence>
      <motion.div
        key={step.id}
        className={`tour-card tour-anchor-${step.anchor}`}
        initial={{ opacity: 0, y: 8, scale: 0.98 }}
        animate={{ opacity: 1, y: 0, scale: 1 }}
        exit={{ opacity: 0, y: -6 }}
        transition={{ duration: 0.22 }}
      >
        <div className="tour-head">
          <Sparkles size={14} />
          <span className="tour-eyebrow">Guided tour · {tour.index + 1} / {sc.tour.length}</span>
          <button className="tour-close" onClick={endTour} aria-label="End tour"><Close size={13} /></button>
        </div>
        <h3 className="tour-title">{step.title}</h3>
        <p className="tour-body">{step.body}</p>
        <div className="tour-actions">
          <button className="btn btn-ghost" onClick={tourPrev} disabled={first}>
            <ChevL size={13} /> Back
          </button>
          {last ? (
            <button className="btn btn-primary" onClick={endTour}>Finish</button>
          ) : (
            <button className="btn btn-primary" onClick={tourNext}>
              Next <ChevR size={13} />
            </button>
          )}
        </div>
      </motion.div>
    </AnimatePresence>
  );
}
