// ─────────────────────────────────────────────────────────
// ChefVerse · Guided Tour overlay
// Hotspot coach-marks that walk a NEW chef through the
// home after onboarding. Anchors to elements via [data-tour].
// ─────────────────────────────────────────────────────────
const { useState: useStateTour, useEffect: useEffectTour, useRef: useRefTour, useLayoutEffect: useLayoutEffectTour } = React;

const TOUR_STEPS = {
  en: [
    {
      anchor: "fr-paths",
      title: "Pick your learning path",
      body: "Working chefs teach what actually moved their numbers. Tap the featured path to see modules, outcomes, and your instructor — then enroll when you're ready.",
      placement: "bottom-start",
    },
    {
      anchor: "fr-starter",
      title: "Start here — Module 01",
      body: "Picked from your onboarding goals. About 8 minutes of short chapters with hands-on practice and a quick check at the end. Modules unlock in order as you finish each one.",
      placement: "bottom",
    },
    {
      anchor: "fr-briefs",
      title: "Real briefs, real budgets",
      body: "UFS brand teams post paid briefs every week. Pick one when you're ready — read the brief, film it, submit before the deadline.",
      placement: "top-start",
    },
    {
      anchor: "fr-brief-card",
      title: "Tap a brief to see the details",
      body: "You'll see what to film, the deadline, the payout, and how to submit. No commitment until you claim it.",
      placement: "top",
    },
    {
      anchor: "fr-rewards",
      title: "What you'll unlock",
      body: "Real kit and recognition shipped to you as you complete modules and briefs — a tripod, a chef knife, a featured-chef bundle. Earned, not gifted.",
      placement: "left",
    },
    {
      anchor: "fr-nav",
      title: "Find everything from here",
      body: "Dashboard, learning, briefs, rewards, community — all live in the side nav. You can come back to this guide anytime from the help menu.",
      placement: "right",
    },
  ],
  de: [
    {
      anchor: "fr-paths",
      title: "Wähle deinen Lernpfad",
      body: "Arbeitende Köche zeigen, was wirklich Reichweite gebracht hat. Tippe auf den empfohlenen Pfad für Module, Ergebnisse und deine Lehrkraft.",
      placement: "bottom-start",
    },
    {
      anchor: "fr-starter",
      title: "Starte hier — Modul 01",
      body: "Auf Basis deiner Onboarding-Ziele ausgewählt. Etwa 8 Minuten in kurzen Kapiteln mit Praxis und einem Test am Ende. Module schalten sich nacheinander frei.",
      placement: "bottom",
    },
    {
      anchor: "fr-briefs",
      title: "Echte Briefings, echte Budgets",
      body: "UFS-Brand-Teams posten jede Woche bezahlte Briefings. Lies, dreh, reiche ein.",
      placement: "top-start",
    },
    {
      anchor: "fr-brief-card",
      title: "Tippe ein Briefing an",
      body: "Was zu drehen ist, Deadline, Honorar und Einreichung — alles auf einer Seite.",
      placement: "top",
    },
    {
      anchor: "fr-rewards",
      title: "Was du freischaltest",
      body: "Echtes Material und Anerkennung, geliefert zu dir, während du Module und Briefings abschließt.",
      placement: "left",
    },
    {
      anchor: "fr-nav",
      title: "Alles findest du hier",
      body: "Dashboard, Lernen, Briefings, Belohnungen, Community — alle leben in der Seitennavigation.",
      placement: "right",
    },
  ],
  id: [
    {
      anchor: "fr-paths",
      title: "Pilih jalur belajarmu",
      body: "Chef aktif mengajar hal yang benar-benar mengangkat angka mereka. Ketuk jalur pilihan untuk lihat modul, hasil, dan pengajar.",
      placement: "bottom-start",
    },
    {
      anchor: "fr-starter",
      title: "Mulai di sini — Modul 01",
      body: "Dipilih dari tujuan onboarding-mu. Sekitar 8 menit, bab-bab pendek dengan praktik dan kuis di akhir. Modul terbuka berurutan.",
      placement: "bottom",
    },
    {
      anchor: "fr-briefs",
      title: "Brief nyata, budget nyata",
      body: "Tim brand UFS memposting brief berbayar tiap minggu. Pilih satu, baca, syuting, kirim sebelum deadline.",
      placement: "top-start",
    },
    {
      anchor: "fr-brief-card",
      title: "Ketuk brief untuk detail",
      body: "Apa yang difilmkan, deadline, honor, dan cara submit — semua di satu halaman.",
      placement: "top",
    },
    {
      anchor: "fr-rewards",
      title: "Yang akan kamu buka",
      body: "Perlengkapan & pengakuan nyata dikirim ke kamu seiring kamu selesaikan modul dan brief.",
      placement: "left",
    },
    {
      anchor: "fr-nav",
      title: "Semua dari sini",
      body: "Dashboard, belajar, brief, reward, komunitas — semua di navigasi samping.",
      placement: "right",
    },
  ],
};

const TOUR_UI = {
  en: { skip: "Skip tour", next: "Next", back: "Back", finish: "I'm in", step: "Step" },
  de: { skip: "Tour überspringen", next: "Weiter", back: "Zurück", finish: "Los geht's", step: "Schritt" },
  id: { skip: "Lewati tour", next: "Lanjut", back: "Kembali", finish: "Saya siap", step: "Langkah" },
};

function GuidedTour({ locale, onClose }) {
  // Filter out steps whose anchor element doesn't exist on this version of the page.
  // (e.g. v2 home omits some v1 sections.) This prevents step 2 from landing on a
  // missing anchor and the popover hiding mid-tour.
  const allSteps = TOUR_STEPS[locale];
  const steps = useRefTour(null);
  if (!steps.current) {
    steps.current = allSteps.filter(s => document.querySelector(`[data-tour="${s.anchor}"]`));
    if (steps.current.length === 0) steps.current = allSteps; // fail-soft
  }
  const ui = TOUR_UI[locale];
  const [i, setI] = useStateTour(0);
  const [rect, setRect] = useStateTour(null);
  const step = steps.current[i];

  // recompute target rect on step change, scroll, resize
  useLayoutEffectTour(() => {
    let raf;
    const update = () => {
      const el = document.querySelector(`[data-tour="${step.anchor}"]`);
      if (!el) { setRect(null); return; }
      const r = el.getBoundingClientRect();
      // scroll into view if needed
      if (r.top < 80 || r.bottom > window.innerHeight - 80) {
        el.scrollIntoView({ behavior: "smooth", block: "center" });
        raf = requestAnimationFrame(() => {
          const r2 = el.getBoundingClientRect();
          setRect({ top: r2.top, left: r2.left, width: r2.width, height: r2.height });
        });
      } else {
        setRect({ top: r.top, left: r.left, width: r.width, height: r.height });
      }
    };
    update();
    window.addEventListener("resize", update);
    window.addEventListener("scroll", update, true);
    return () => {
      cancelAnimationFrame(raf);
      window.removeEventListener("resize", update);
      window.removeEventListener("scroll", update, true);
    };
  }, [i, step.anchor]);

  // ESC to close
  useEffectTour(() => {
    const onKey = (e) => {
      if (e.key === "Escape") onClose();
      if (e.key === "ArrowRight") setI(x => Math.min(x + 1, steps.current.length - 1));
      if (e.key === "ArrowLeft") setI(x => Math.max(x - 1, 0));
    };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [onClose]);

  const next = () => i < steps.current.length - 1 ? setI(i + 1) : onClose();
  const back = () => i > 0 && setI(i - 1);

  // popover positioning
  const popStyle = (() => {
    if (!rect) return { display: "none" };
    const pad = 12;
    const popW = 340;
    const popH = 320;
    const p = step.placement || "bottom";
    let top = 0, left = 0;
    if (p.startsWith("bottom")) top = rect.top + rect.height + pad;
    else if (p.startsWith("top")) top = rect.top - popH - pad;
    else if (p === "left") top = rect.top + rect.height / 2 - popH / 2;
    else if (p === "right") top = rect.top + rect.height / 2 - popH / 2;

    if (p === "left") left = rect.left - popW - pad;
    else if (p === "right") left = rect.left + rect.width + pad;
    else if (p.endsWith("end")) left = rect.left + rect.width - popW;
    else if (p.endsWith("start")) left = rect.left;
    else left = rect.left + rect.width / 2 - popW / 2;

    // clamp to viewport
    left = Math.max(16, Math.min(left, window.innerWidth - popW - 16));
    top = Math.max(16, Math.min(top, window.innerHeight - popH - 16));

    return { top, left, width: popW };
  })();

  // spotlight cutout via clip-path on the dim layer
  const spotlight = rect ? {
    clipPath: `polygon(
      0 0, 100% 0, 100% 100%, 0 100%, 0 0,
      ${rect.left - 8}px ${rect.top - 8}px,
      ${rect.left - 8}px ${rect.top + rect.height + 8}px,
      ${rect.left + rect.width + 8}px ${rect.top + rect.height + 8}px,
      ${rect.left + rect.width + 8}px ${rect.top - 8}px,
      ${rect.left - 8}px ${rect.top - 8}px
    )`,
  } : {};

  return (
    <div className="tour-root" role="dialog" aria-modal="true">
      <div className="tour-dim" style={spotlight} onClick={onClose} />

      {rect && (
        <div className="tour-ring" style={{
          top: rect.top - 8,
          left: rect.left - 8,
          width: rect.width + 16,
          height: rect.height + 16,
        }} />
      )}

      <div className="tour-pop" style={popStyle}>
        <div className="tour-pop-h">
          <span className="tour-step-lab">{ui.step} {i + 1} / {steps.current.length}</span>
          <button className="tour-close" onClick={onClose} aria-label="Close">
            <Icon name="x" size={14} />
          </button>
        </div>
        <h3 className="tour-pop-title">{step.title}</h3>
        <p className="tour-pop-body">{step.body}</p>

        <div className="tour-dots">
          {steps.current.map((_, k) => (
            <button key={k} className={"tour-dot " + (k === i ? "on" : k < i ? "past" : "")} onClick={() => setI(k)} aria-label={`Step ${k + 1}`} />
          ))}
        </div>

        <div className="tour-pop-actions">
          <button className="tour-skip-btn" onClick={onClose}>{ui.skip}</button>
          <div className="tour-pop-right">
            {i > 0 && <button className="btn btn-outline btn-sm" onClick={back}>{ui.back}</button>}
            <button className="btn btn-primary btn-sm" onClick={next}>
              {i === steps.current.length - 1 ? ui.finish : ui.next}
              {i < steps.current.length - 1 && <Icon name="arrow-right" size={11} />}
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}

window.GuidedTour = GuidedTour;
