// ============ WALKTHROUGH ============
// Spotlight tour for first-time visitors. Triggered from the "Take a tour"
// button in the topbar. Walks through the 9 main surfaces of the dashboard,
// switching tabs as it goes and dimming everything except the highlighted
// element. Esc, Skip, or click Done to exit.

const TOUR_STEPS = [
  {
    title: "Welcome to Citrus",
    body: "Quick walkthrough — about 60 seconds. Skip any time, or open this again from the topbar.",
  },
  {
    tab: "agents",
    target: ".ds-side",
    side: "right",
    title: "Your sidebar",
    body: "Every section lives here. Day-to-day work at the top, build tools in the middle, account stuff at the bottom.",
  },
  {
    tab: "agents",
    target: ".ds-new",
    side: "right",
    title: "Hire a new agent",
    body: "Tap any time. Type a brief in plain English (\"answer customers on WhatsApp, send leads to my phone\") and Citrus turns it into a working agent in about 3 minutes.",
  },
  {
    tab: "agents",
    target: ".ag-grid",
    side: "top",
    title: "Your roster",
    body: "Each card is one agent — live status, this-week stats, your star rating. Click 'Chat' to talk to one, or 'Open' for the full detail view.",
  },
  {
    tab: "inbox",
    target: ".ix-list",
    side: "right",
    title: "Shared inbox",
    body: "Every customer thread your agents are handling, all in one place. Click 'Take over' on any thread to step in and reply as yourself.",
  },
  {
    tab: "approvals",
    target: ".ap-list",
    side: "top",
    title: "Sign-offs waiting on you",
    body: "Anything an agent kicks up — refunds, big quotes, unusual contracts. Approve, edit inline before sending, or reject. Two clicks each.",
  },
  {
    tab: "insights",
    target: ".in-summary",
    side: "bottom",
    title: "How they're doing",
    body: "Topline numbers, the goals you set, and standout moments your agents flagged. Switch the period at the top.",
  },
  {
    tab: "tools",
    target: ".tl-tabs",
    side: "bottom",
    title: "Connections, schedules, alerts",
    body: "Three sub-tabs: what they can touch (Gmail, WhatsApp, Stripe…), when each one works, and when they should ping you.",
  },
  {
    tab: "settings",
    target: ".st-side",
    side: "right",
    title: "Pick your model",
    body: "Settings → Model is where you pick the LLM. Claude, ChatGPT, or your own self-hosted endpoint — keys come from the .env file at the project root.",
  },
  {
    title: "You're set.",
    body: "Browse around. Anything you want to do, an agent can probably help. Open 'Take a tour' from the topbar any time to see this again.",
  },
];

function Walkthrough({ open, onClose, onSwitchTab }) {
  const [stepIndex, setStepIndex] = useState(0);
  const [rect, setRect]           = useState(null);

  const step       = TOUR_STEPS[stepIndex];
  const isFirst    = stepIndex === 0;
  const isLast     = stepIndex === TOUR_STEPS.length - 1;
  const hasTarget  = !!step.target;

  // Reset to step 0 every time the tour opens.
  useEffect(() => {
    if (open) setStepIndex(0);
  }, [open]);

  // Switch tabs + measure target whenever the step (or window) changes.
  useEffect(() => {
    if (!open) return;
    if (step.tab) onSwitchTab(step.tab);

    const measure = () => {
      if (!step.target) { setRect(null); return; }
      const el = document.querySelector(step.target);
      if (!el) { setRect(null); return; }
      el.scrollIntoView({ block: "nearest", behavior: "smooth" });
      requestAnimationFrame(() => {
        const r = el.getBoundingClientRect();
        setRect({ top: r.top, left: r.left, width: r.width, height: r.height });
      });
    };

    // Wait a beat for the tab switch to render.
    const tid = setTimeout(measure, 220);
    window.addEventListener("resize", measure);
    window.addEventListener("scroll", measure, true);
    return () => {
      clearTimeout(tid);
      window.removeEventListener("resize", measure);
      window.removeEventListener("scroll", measure, true);
    };
  }, [stepIndex, open]);

  // Esc to skip.
  useEffect(() => {
    if (!open) return;
    const onKey = (e) => {
      if (e.key === "Escape") onClose();
      else if (e.key === "ArrowRight" && !isLast) setStepIndex(s => s + 1);
      else if (e.key === "ArrowLeft" && !isFirst) setStepIndex(s => s - 1);
    };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [open, isFirst, isLast]);

  if (!open) return null;

  // Position the tooltip relative to the target rect, or center it if none.
  const PAD = 18;
  let tipStyle;
  if (!rect) {
    tipStyle = { left: "50%", top: "50%", transform: "translate(-50%, -50%)" };
  } else if (step.side === "right") {
    tipStyle = { left: Math.min(window.innerWidth - 380, rect.left + rect.width + PAD), top: Math.max(20, rect.top) };
  } else if (step.side === "left") {
    tipStyle = { left: Math.max(20, rect.left - 360 - PAD), top: Math.max(20, rect.top) };
  } else if (step.side === "top") {
    tipStyle = { left: Math.max(20, Math.min(window.innerWidth - 380, rect.left)), top: Math.max(20, rect.top - 200) };
  } else {
    tipStyle = { left: Math.max(20, Math.min(window.innerWidth - 380, rect.left)), top: Math.min(window.innerHeight - 220, rect.top + rect.height + PAD) };
  }

  return (
    <>
      {/* SVG overlay: full-screen dim with a transparent rect-shaped hole around the target.
          Captures all pointer events, so the dashboard underneath is locked. */}
      <svg
        className="tour-svg"
        width="100%"
        height="100%"
        xmlns="http://www.w3.org/2000/svg"
      >
        <defs>
          <mask id="tour-mask">
            <rect width="100%" height="100%" fill="white" />
            {rect && (
              <rect
                x={rect.left - 6}
                y={rect.top - 6}
                width={rect.width + 12}
                height={rect.height + 12}
                rx="10"
                fill="black"
              />
            )}
          </mask>
        </defs>
        <rect width="100%" height="100%" fill="rgba(15,8,4,0.62)" mask="url(#tour-mask)" />
        {rect && (
          <rect
            x={rect.left - 6}
            y={rect.top - 6}
            width={rect.width + 12}
            height={rect.height + 12}
            rx="10"
            fill="none"
            stroke="var(--accent)"
            strokeWidth="2"
            strokeDasharray="0"
            className="tour-spot-ring"
          />
        )}
      </svg>

      {/* Tooltip card */}
      <div className="tour-card" style={{ position: "fixed", ...tipStyle }}>
        <div className="tour-step">Step {stepIndex + 1} of {TOUR_STEPS.length}</div>
        <h3 className="tour-title">{step.title}</h3>
        <p className="tour-body">{step.body}</p>

        <div className="tour-progress">
          {TOUR_STEPS.map((_, i) => (
            <span key={i} className={`tour-dot ${i === stepIndex ? "is-on" : ""} ${i < stepIndex ? "is-done" : ""}`} />
          ))}
        </div>

        <div className="tour-foot">
          <button className="btn btn-ghost btn-sm tour-skip" onClick={onClose}>
            {isLast ? "Close" : "Skip tour"}
          </button>
          <div className="tour-cta">
            {!isFirst && (
              <button className="btn btn-ghost btn-sm" onClick={() => setStepIndex(s => s - 1)}>← Back</button>
            )}
            {isLast
              ? <button className="btn btn-primary btn-sm" onClick={onClose}>Done</button>
              : <button className="btn btn-primary btn-sm" onClick={() => setStepIndex(s => s + 1)}>Next →</button>}
          </div>
        </div>
      </div>
    </>
  );
}

window.Walkthrough = Walkthrough;
