"use client";

// src/hooks/use-coach-mark.ts
import * as React from "react";
var STORAGE_PREFIX = "exxat-coach-mark:";
var COACH_MARK_FLOW_COMPLETED_EVENT = "exxat-coach-mark-flow-completed";
function isDismissed(flowId) {
  if (typeof window === "undefined") return false;
  try {
    return localStorage.getItem(`${STORAGE_PREFIX}${flowId}`) === "dismissed";
  } catch {
    return false;
  }
}
function setDismissed(flowId) {
  if (typeof window === "undefined") return;
  try {
    localStorage.setItem(`${STORAGE_PREFIX}${flowId}`, "dismissed");
  } catch {
  }
}
function clearDismissed(flowId) {
  if (typeof window === "undefined") return;
  try {
    localStorage.removeItem(`${STORAGE_PREFIX}${flowId}`);
  } catch {
  }
}
function getAllCoachMarkKeys() {
  if (typeof window === "undefined") return [];
  const keys = [];
  try {
    for (let i = 0; i < localStorage.length; i++) {
      const key = localStorage.key(i);
      if (key?.startsWith(STORAGE_PREFIX)) {
        keys.push(key.replace(STORAGE_PREFIX, ""));
      }
    }
  } catch {
  }
  return keys;
}
function resetCoachMarkFlow(flowId) {
  clearDismissed(flowId);
}
function resetAllCoachMarks() {
  if (typeof window === "undefined") return;
  try {
    const toRemove = [];
    for (let i = 0; i < localStorage.length; i++) {
      const key = localStorage.key(i);
      if (key?.startsWith(STORAGE_PREFIX)) toRemove.push(key);
    }
    toRemove.forEach((k) => localStorage.removeItem(k));
  } catch {
  }
}
function useCoachMark({
  flowId,
  steps,
  delay = 500,
  onComplete,
  force = false,
  enabled = true,
  dependsOnDismissedFlowId
}) {
  const [isOpen, setIsOpen] = React.useState(false);
  const [currentStep, setCurrentStep] = React.useState(0);
  const [targetEl, setTargetEl] = React.useState(null);
  const [anchorRect, setAnchorRect] = React.useState(null);
  const [prereqMet, setPrereqMet] = React.useState(() => {
    if (!dependsOnDismissedFlowId) return true;
    return isDismissed(dependsOnDismissedFlowId);
  });
  React.useEffect(() => {
    if (!dependsOnDismissedFlowId) {
      setPrereqMet(true);
      return;
    }
    setPrereqMet(isDismissed(dependsOnDismissedFlowId));
  }, [dependsOnDismissedFlowId]);
  React.useEffect(() => {
    if (!dependsOnDismissedFlowId) return;
    const handler = (e) => {
      const d = e.detail;
      if (d?.flowId === dependsOnDismissedFlowId) setPrereqMet(true);
    };
    window.addEventListener(COACH_MARK_FLOW_COMPLETED_EVENT, handler);
    return () => window.removeEventListener(COACH_MARK_FLOW_COMPLETED_EVENT, handler);
  }, [dependsOnDismissedFlowId]);
  const totalSteps = steps.length;
  const isFlow = totalSteps > 1;
  const step = steps[currentStep] ?? null;
  const isFirst = currentStep === 0;
  const isLast = currentStep === totalSteps - 1;
  React.useEffect(() => {
    if (enabled === false) return;
    if (dependsOnDismissedFlowId && !prereqMet) return;
    if (!force && isDismissed(flowId)) return;
    const timer = setTimeout(() => setIsOpen(true), delay);
    return () => clearTimeout(timer);
  }, [flowId, delay, force, enabled, dependsOnDismissedFlowId, prereqMet]);
  React.useEffect(() => {
    if (!isOpen || !step?.target) {
      return;
    }
    let cancelled = false;
    const timeouts = [];
    const schedule = (fn, ms) => {
      const id = setTimeout(fn, ms);
      timeouts.push(id);
      return id;
    };
    setAnchorRect(null);
    setTargetEl(null);
    let attempts = 0;
    const maxAttempts = 30;
    const intervalMs = 100;
    const tryResolve = () => {
      if (cancelled) return;
      const el = document.querySelector(step.target);
      if (!el) {
        attempts += 1;
        if (attempts < maxAttempts) schedule(tryResolve, intervalMs);
        return;
      }
      el.scrollIntoView({ behavior: "smooth", block: "center", inline: "nearest" });
      schedule(() => {
        if (cancelled) return;
        const rect = el.getBoundingClientRect();
        setAnchorRect({
          x: rect.left,
          y: rect.top,
          width: rect.width,
          height: rect.height
        });
        setTargetEl(el);
      }, 350);
    };
    schedule(tryResolve, 100);
    return () => {
      cancelled = true;
      timeouts.forEach(clearTimeout);
    };
  }, [isOpen, step?.target, currentStep]);
  React.useEffect(() => {
    if (!isOpen || !targetEl) return;
    const measure = () => {
      if (!targetEl.isConnected) return;
      const rect = targetEl.getBoundingClientRect();
      setAnchorRect({
        x: rect.left,
        y: rect.top,
        width: rect.width,
        height: rect.height
      });
    };
    window.addEventListener("scroll", measure, { passive: true, capture: true });
    window.addEventListener("resize", measure, { passive: true });
    return () => {
      window.removeEventListener("scroll", measure, true);
      window.removeEventListener("resize", measure);
    };
  }, [isOpen, targetEl]);
  const complete = React.useCallback(() => {
    setIsOpen(false);
    setTargetEl(null);
    setAnchorRect(null);
    setDismissed(flowId);
    if (typeof window !== "undefined") {
      window.dispatchEvent(
        new CustomEvent(COACH_MARK_FLOW_COMPLETED_EVENT, { detail: { flowId } })
      );
    }
    onComplete?.();
  }, [flowId, onComplete]);
  const next = React.useCallback(() => {
    if (isLast) {
      complete();
    } else {
      setCurrentStep((s) => s + 1);
    }
  }, [isLast, complete]);
  const prev = React.useCallback(() => {
    setCurrentStep((s) => Math.max(0, s - 1));
  }, []);
  const skip = React.useCallback(() => {
    complete();
  }, [complete]);
  const open = React.useCallback(() => {
    setCurrentStep(0);
    setIsOpen(true);
  }, []);
  const reset = React.useCallback(() => {
    clearDismissed(flowId);
    setCurrentStep(0);
    setIsOpen(true);
  }, [flowId]);
  return {
    isOpen,
    currentStep,
    totalSteps,
    step,
    targetEl,
    anchorRect,
    isFlow,
    isFirst,
    isLast,
    next,
    prev,
    skip,
    open,
    reset
  };
}
export {
  COACH_MARK_FLOW_COMPLETED_EVENT,
  getAllCoachMarkKeys,
  resetAllCoachMarks,
  resetCoachMarkFlow,
  useCoachMark
};
//# sourceMappingURL=use-coach-mark.js.map