// MedLink — Guided Demo Tour
// Cross-portal scripted walkthrough of the hero flow:
// Pflege creates Anfrage → Arzt approves → Apotheke delivers.
//
// Drives the App via window events:
//   medlink:navigate   { portal?, route?, heim? }  → App switches
//   medlink:setView    { portal, view }            → Portal switches inner view
//   medlink:toast      "text"                      → App shows toast
//
// Targets are found via [data-tour="..."] attributes on portal JSX.

const DEMO_SCRIPT = [
  {
    portal: "heim",
    view: "dashboard",
    target: null,
    title: "Willkommen bei MedLink",
    body: "Wir zeigen in 20 Sekunden den kompletten Medikamenten-Workflow — von der Pflege über den Arzt bis zur Apotheke.",
    dwell: 4200,
  },
  {
    portal: "heim",
    view: "dashboard",
    target: '[data-tour="heim-kpi"]',
    position: "bottom",
    title: "Alles im Blick",
    body: "Offene Anfragen, laufende Visiten, Belegung — die Heimleitung sieht den Tag auf einen Blick.",
    dwell: 4200,
  },
  {
    portal: "heim",
    view: "anfragen",
    target: '[data-tour="heim-new"]',
    position: "bottom",
    title: "Neue Anfrage",
    body: "Die Pflegekraft erstellt in 30 Sekunden eine strukturierte Medikamenten-Anfrage — statt Fax, Telefon oder WhatsApp.",
    dwell: 5200,
  },
  {
    portal: "heim",
    view: "anfragen",
    target: null,
    title: "ANF-250 · Metformin 500 mg",
    body: "Die Anfrage ist raus. Dr. Schneider wird benachrichtigt — auch auf seinem Handy.",
    dwell: 3600,
    action: () => {
      window.dispatchEvent(new CustomEvent("medlink:toast", { detail: "ANF-250 an Dr. Schneider gesendet" }));
      window.dispatchEvent(new CustomEvent("medlink:notify", {
        detail: { kind: "new", icon: "inbox", title: "Neue Anfrage · ANF-250 (Demo)", sub: "Metformin 500 mg · Hr. Müller · Rosenhof" }
      }));
    },
  },
  {
    portal: "arzt",
    view: "queue",
    target: '[data-tour="arzt-row"]',
    position: "bottom",
    title: "Perspektive: Arzt",
    body: "Die Anfrage landet sofort in der Warteschlange — priorisiert, mit Kontext: Diagnose, Dauertherapie, Allergien.",
    dwell: 5000,
  },
  {
    portal: "arzt",
    view: "queue",
    target: '[data-tour="arzt-approve"]',
    position: "left",
    title: "Ein-Tipp-Freigabe",
    body: "Zwischen zwei Patienten: ein Klick. Mobil. Signiert. Audit-fest dokumentiert.",
    dwell: 5000,
  },
  {
    portal: "arzt",
    view: "queue",
    target: null,
    title: "Freigegeben · eRezept erstellt",
    body: "Das eRezept ist signiert und auf dem Weg zur Hausapotheke — automatisch zugeordnet.",
    dwell: 3600,
    action: () => {
      window.dispatchEvent(new CustomEvent("medlink:toast", { detail: "ANF-250 freigegeben · eRezept gesendet" }));
      window.dispatchEvent(new CustomEvent("medlink:notify", {
        detail: { kind: "approve", icon: "check", title: "ANF-250 freigegeben (Demo)", sub: "Dr. Schneider · eRezept an Adler-Apotheke" }
      }));
    },
  },
  {
    portal: "apotheke",
    view: "eingang",
    target: '[data-tour="apo-row"]',
    position: "bottom",
    title: "Perspektive: Apotheke",
    body: "Das eRezept ist eingegangen. Dispensierung, Kommissionierung und Lieferung — alles im selben Flow.",
    dwell: 4800,
  },
  {
    portal: "apotheke",
    view: "eingang",
    target: null,
    title: "Lieferung bestätigt",
    body: "Der Kurier quittiert im System. Die Pflege sieht Ankunft und Charge — lückenlos.",
    dwell: 3600,
    action: () => {
      window.dispatchEvent(new CustomEvent("medlink:toast", { detail: "ANF-250 kommissioniert · Lieferung heute 14:30" }));
      window.dispatchEvent(new CustomEvent("medlink:notify", {
        detail: { kind: "delivery", icon: "truck", title: "Apotheke bestätigt Lieferung (Demo)", sub: "ANF-250 · Adler-Apotheke · heute 14:30" }
      }));
    },
  },
  {
    portal: "apotheke",
    view: "eingang",
    target: null,
    title: "Fertig.",
    body: "18 Sekunden über drei Rollen — vorher dauerte das 1–3 Tage. Melden Sie sich jetzt an und probieren Sie's selbst.",
    dwell: 5800,
    final: true,
  },
];

const TourTooltip = ({ step, index, total, onNext, onSkip, targetRect }) => {
  const ref = React.useRef(null);
  const [style, setStyle] = React.useState({ top: "50%", left: "50%", transform: "translate(-50%, -50%)" });
  const [arrow, setArrow] = React.useState(null);

  React.useLayoutEffect(() => {
    if (!targetRect) {
      // Center it
      setStyle({ top: "50%", left: "50%", transform: "translate(-50%, -50%)" });
      setArrow(null);
      return;
    }
    const el = ref.current;
    if (!el) return;
    const pad = 18;
    const tw = el.offsetWidth;
    const th = el.offsetHeight;
    const vw = window.innerWidth;
    const vh = window.innerHeight;
    const r = targetRect;
    const pos = step.position || "bottom";
    let top, left, arr;
    const clamp = (v, min, max) => Math.max(min, Math.min(max, v));
    switch (pos) {
      case "top":
        top = r.top - th - pad;
        left = clamp(r.left + r.width / 2 - tw / 2, 10, vw - tw - 10);
        arr = "bottom";
        break;
      case "left":
        top = clamp(r.top + r.height / 2 - th / 2, 10, vh - th - 10);
        left = r.left - tw - pad;
        arr = "right";
        break;
      case "right":
        top = clamp(r.top + r.height / 2 - th / 2, 10, vh - th - 10);
        left = r.right + pad;
        arr = "left";
        break;
      case "bottom":
      default:
        top = r.bottom + pad;
        left = clamp(r.left + r.width / 2 - tw / 2, 10, vw - tw - 10);
        arr = "top";
    }
    // If the preferred position overflows, flip.
    if (pos === "bottom" && top + th > vh - 10) { top = r.top - th - pad; arr = "bottom"; }
    if (pos === "top" && top < 50) { top = r.bottom + pad; arr = "top"; }
    if (pos === "right" && left + tw > vw - 10) { left = r.left - tw - pad; arr = "right"; }
    if (pos === "left" && left < 10) { left = r.right + pad; arr = "left"; }

    setStyle({ top: `${top}px`, left: `${left}px`, transform: "none" });
    setArrow(arr);
  }, [targetRect, step]);

  return (
    <div ref={ref} className="tour-tooltip" style={style} data-arrow={arrow || ""}>
      {arrow && <span className="tt-arrow" />}
      <div className="tt-title">Schritt {index + 1} / {total}</div>
      <div className="tt-body" style={{ fontSize: 13, fontWeight: 500, color: "var(--fg)", marginBottom: 4 }}>{step.title}</div>
      <div className="tt-body" style={{ color: "var(--fg-muted)" }}>{step.body}</div>
      <div style={{ display: "flex", gap: 6, marginTop: 10 }}>
        <button
          onClick={onSkip}
          style={{
            background: "transparent", border: "1px solid var(--border)", color: "var(--fg-muted)",
            padding: "5px 10px", borderRadius: 6, fontSize: 11, cursor: "pointer",
          }}
        >Überspringen</button>
        <div style={{ flex: 1 }} />
        <button
          onClick={onNext}
          style={{
            background: "var(--accent)", border: "none", color: "#fff",
            padding: "5px 12px", borderRadius: 6, fontSize: 11.5, fontWeight: 500, cursor: "pointer",
            display: "inline-flex", alignItems: "center", gap: 6,
          }}
        >
          {step.final ? "Fertig" : "Weiter"} <Icon name={step.final ? "check" : "arrowRight"} size={11} />
        </button>
      </div>
    </div>
  );
};

const DemoTour = () => {
  const [active, setActive] = React.useState(false);
  const [stepIdx, setStepIdx] = React.useState(0);
  const [targetRect, setTargetRect] = React.useState(null);
  const targetElRef = React.useRef(null);
  const dwellTimerRef = React.useRef(null);

  const step = active ? DEMO_SCRIPT[stepIdx] : null;

  // Public API: start/stop
  React.useEffect(() => {
    const start = () => { setStepIdx(0); setActive(true); };
    const stop = () => setActive(false);
    window.addEventListener("medlink:demoStart", start);
    window.addEventListener("medlink:demoStop", stop);
    return () => {
      window.removeEventListener("medlink:demoStart", start);
      window.removeEventListener("medlink:demoStop", stop);
    };
  }, []);

  const cleanupHighlight = () => {
    if (targetElRef.current) {
      targetElRef.current.classList.remove("tour-highlight");
      targetElRef.current = null;
    }
  };

  // Run side-effects for the current step
  React.useEffect(() => {
    if (!active || !step) { cleanupHighlight(); return; }

    // 1. Drive the App: portal/route/view switch
    if (step.portal) window.dispatchEvent(new CustomEvent("medlink:navigate", { detail: { route: "app", portal: step.portal } }));
    if (step.view) {
      // Fire after a tick so the portal has mounted
      setTimeout(() => {
        window.dispatchEvent(new CustomEvent("medlink:setView", { detail: { portal: step.portal, view: step.view } }));
      }, 60);
    }

    // 2. Run custom action (toast, notify, data mutation)
    if (step.action) setTimeout(() => step.action(), 400);

    // 3. Find target and highlight. Retry for up to 1.2s (portal mount + view swap).
    cleanupHighlight();
    let tries = 0;
    let rafId;
    const tryFind = () => {
      if (!step.target) { setTargetRect(null); return; }
      const el = document.querySelector(step.target);
      if (el) {
        targetElRef.current = el;
        el.classList.add("tour-highlight");
        try { el.scrollIntoView({ behavior: "smooth", block: "center" }); } catch {}
        const updateRect = () => setTargetRect(el.getBoundingClientRect());
        updateRect();
        // re-measure once after scroll settles
        setTimeout(updateRect, 350);
        return;
      }
      if (tries++ < 24) rafId = setTimeout(tryFind, 60);
      else setTargetRect(null);
    };
    // small delay so view switch can settle
    rafId = setTimeout(tryFind, step.view ? 200 : 60);

    // 4. Auto-advance after dwell unless final
    if (!step.final && step.dwell) {
      dwellTimerRef.current = setTimeout(() => {
        setStepIdx((i) => Math.min(DEMO_SCRIPT.length - 1, i + 1));
      }, step.dwell);
    }

    return () => {
      clearTimeout(rafId);
      clearTimeout(dwellTimerRef.current);
      cleanupHighlight();
    };
  }, [active, stepIdx]);

  // Toggle body class
  React.useEffect(() => {
    document.body.classList.toggle("demo-running", active);
    return () => document.body.classList.remove("demo-running");
  }, [active]);

  // Re-measure on window resize
  React.useEffect(() => {
    if (!targetElRef.current) return;
    const onResize = () => setTargetRect(targetElRef.current.getBoundingClientRect());
    window.addEventListener("resize", onResize);
    window.addEventListener("scroll", onResize, true);
    return () => {
      window.removeEventListener("resize", onResize);
      window.removeEventListener("scroll", onResize, true);
    };
  }, [step]);

  if (!active || !step) return null;

  const next = () => {
    clearTimeout(dwellTimerRef.current);
    if (step.final) { setActive(false); return; }
    setStepIdx((i) => Math.min(DEMO_SCRIPT.length - 1, i + 1));
  };
  const prev = () => {
    clearTimeout(dwellTimerRef.current);
    setStepIdx((i) => Math.max(0, i - 1));
  };
  const skip = () => { clearTimeout(dwellTimerRef.current); setActive(false); };

  return (
    <>
      <div className="tour-backdrop" />
      <div className="tour-bar">
        <span className="dot-live" />
        <span>Demo-Tour</span>
        <span className="progress">{stepIdx + 1} / {DEMO_SCRIPT.length}</span>
        <span className="title">{step.title}</span>
        <button onClick={prev} disabled={stepIdx === 0} style={{ opacity: stepIdx === 0 ? 0.5 : 1 }}>
          <Icon name="back" size={11} /> Zurück
        </button>
        <button onClick={skip}>
          <Icon name="x" size={11} /> Beenden
        </button>
        <button className="primary" onClick={next}>
          {step.final ? "Fertig" : "Weiter"} <Icon name={step.final ? "check" : "arrowRight"} size={11} />
        </button>
      </div>
      <TourTooltip
        step={step}
        index={stepIdx}
        total={DEMO_SCRIPT.length}
        onNext={next}
        onSkip={skip}
        targetRect={targetRect}
      />
    </>
  );
};
window.DemoTour = DemoTour;
