/* global React, lucide */
// YachtingStack Storefront — shared atoms. Exported to window for cross-file use.

// ---------- Icon (Lucide) ----------
function Icon({ name, size = 18, color = "currentColor", stroke = 1.6, style = {} }) {
  const r = React.useRef(null);
  React.useEffect(() => {
    if (!r.current) return;
    r.current.innerHTML = "";
    const node = window.lucide && (lucide[name] || (lucide.icons && lucide.icons[name]));
    if (!node) return;
    const el = lucide.createElement(node);
    el.setAttribute("width", size); el.setAttribute("height", size);
    el.setAttribute("stroke", color); el.setAttribute("stroke-width", stroke);
    r.current.appendChild(el);
  }, [name, size, color, stroke]);
  return <span ref={r} style={{ display: "inline-flex", lineHeight: 0, ...style }} />;
}

// ---------- Wordmark ----------
function Wordmark({ h = 30, fs = 19, mono = false }) {
  return (
    <span style={{ display: "inline-flex", alignItems: "center", gap: 9 }}>
      <img src="assets/logo/YachtingStack_Logo.svg" alt="YachtingStack" style={{ height: h, width: "auto" }} />
      <span style={{ fontFamily: "var(--font-ui)", fontWeight: 300, letterSpacing: "-0.01em", fontSize: fs }}>
        <span style={{ color: "var(--ink)" }}>Yachting</span><span style={{ color: "var(--cyan)" }}>Stack</span>
      </span>
    </span>
  );
}

// ---------- Eyebrow / kicker ----------
function Eyebrow({ children, tone = "cyan", style = {} }) {
  const c = tone === "cyan" ? "var(--cyan)" : tone === "bad" ? "var(--bad)" : "var(--ink-3)";
  return (
    <div style={{ fontFamily: "var(--font-mono)", fontSize: 11, fontWeight: 500, letterSpacing: "0.22em",
      textTransform: "uppercase", color: c, opacity: 0.85, ...style }}>{children}</div>
  );
}

// ---------- Button ----------
function Btn({ children, variant = "primary", size = "md", icon, iconRight, onClick, href, full, disabled, style = {} }) {
  const [h, setH] = React.useState(false);
  const [a, setA] = React.useState(false);
  const sz = { sm: { p: "0 14px", mh: 32, fs: 13 }, md: { p: "0 18px", mh: 40, fs: 14 }, lg: { p: "0 24px", mh: 46, fs: 14.5 } }[size];
  const variants = {
    primary: { base: { background: "var(--cyan)", color: "var(--cyan-ink)", border: "1px solid transparent", fontWeight: 500 },
      hover: { boxShadow: "0 0 0 1px rgba(250,204,21,.4), 0 8px 30px -8px rgba(250,204,21,.6)", background: "var(--cyan-2)" } },
    ghost: { base: { background: "transparent", color: "var(--ink-2)", border: "1px solid var(--hairline-2)", fontWeight: 400 },
      hover: { color: "var(--ink)", borderColor: "rgba(255,255,255,.34)", background: "rgba(255,255,255,.03)" } },
    soft: { base: { background: "rgba(250,204,21,.08)", color: "var(--cyan-2)", border: "1px solid rgba(250,204,21,.2)", fontWeight: 500 },
      hover: { background: "rgba(250,204,21,.14)", borderColor: "rgba(250,204,21,.34)" } },
  };
  const v = variants[variant] || variants.primary;
  const El = href ? "a" : "button";
  return (
    <El href={href} onClick={disabled ? undefined : onClick}
      onMouseEnter={() => setH(true)} onMouseLeave={() => { setH(false); setA(false); }}
      onMouseDown={() => setA(true)} onMouseUp={() => setA(false)}
      style={{ display: "inline-flex", alignItems: "center", justifyContent: "center", gap: 7,
        fontFamily: "var(--font-ui)", letterSpacing: ".01em", lineHeight: 1, cursor: disabled ? "not-allowed" : "pointer",
        textDecoration: "none", padding: sz.p, minHeight: sz.mh, fontSize: sz.fs, borderRadius: 7, whiteSpace: "nowrap",
        width: full ? "100%" : "auto", opacity: disabled ? 0.45 : 1,
        transition: "background .28s, color .28s, border-color .28s, box-shadow .28s, transform .12s",
        transform: a && !disabled ? "translateY(1px)" : "none", ...v.base, ...(h && !disabled ? v.hover : null), ...style }}>
      {icon && <Icon name={icon} size={15} />}{children}{iconRight && <Icon name={iconRight} size={15} />}
    </El>
  );
}

// ---------- Access-state badge ----------
function Access({ state, mini = false }) {
  const map = {
    live:    ["Live", "var(--good)", "rgba(52,211,153,.1)", "rgba(52,211,153,.28)"],
    signup:  ["Sign up", "var(--cyan-ink)", "var(--cyan)", "var(--cyan)"],
    contact: ["Contact sales", "var(--ink-2)", "rgba(255,255,255,.04)", "var(--hairline-2)"],
    onboard: ["Onboarding", "#fff", "rgba(255,255,255,.08)", "rgba(255,255,255,.2)"],
    beta:    ["Private beta", "var(--violet)", "rgba(167,139,250,.1)", "rgba(167,139,250,.28)"],
    internal:["Internal", "var(--ink-3)", "transparent", "var(--hairline)"],
    soon:    ["Coming soon", "var(--warn)", "rgba(251,191,36,.08)", "rgba(251,191,36,.24)"],
    freepro: ["Free · Pro", "var(--good)", "rgba(52,211,153,.08)", "rgba(52,211,153,.24)"],
    docs:    ["Docs · API", "var(--cyan-2)", "rgba(250,204,21,.07)", "rgba(250,204,21,.22)"],
    trial:   ["Free trial", "var(--cyan-2)", "rgba(250,204,21,.1)", "rgba(250,204,21,.3)"],
    reqaccess: ["Request access", "var(--ink-2)", "rgba(255,255,255,.04)", "var(--hairline-2)"],
    customdev: ["Custom Dev clients", "var(--violet)", "rgba(167,139,250,.1)", "rgba(167,139,250,.28)"],
    free: ["Free forever", "var(--good)", "rgba(52,211,153,.1)", "rgba(52,211,153,.28)"],
  };
  const [label, fg, bg, bd] = map[state] || map.live;
  return (
    <span style={{ fontFamily: "var(--font-mono)", fontSize: mini ? 9 : 10.5, fontWeight: 600, letterSpacing: ".04em",
      textTransform: "uppercase", color: fg, background: bg, border: `1px solid ${bd}`,
      padding: mini ? "2px 6px" : "4px 9px", borderRadius: 20, whiteSpace: "nowrap", lineHeight: 1.3 }}>{label}</span>
  );
}

// ---------- Reveal-on-scroll ----------
function useReveal(threshold = 0.16) {
  const ref = React.useRef(null);
  const [shown, setShown] = React.useState(() => (typeof document !== "undefined" && document.hidden) || (window.matchMedia && matchMedia("(prefers-reduced-motion: reduce)").matches));
  React.useEffect(() => {
    const el = ref.current; if (!el || shown) return;
    const io = new IntersectionObserver(([e]) => { if (e.isIntersecting) { setShown(true); io.disconnect(); } },
      { threshold, rootMargin: "0px 0px -7% 0px" });
    io.observe(el);
    const t = setTimeout(() => setShown(true), 1500); // fallback if IO never fires (backgrounded tab)
    return () => { io.disconnect(); clearTimeout(t); };
  }, [threshold]);
  return [ref, shown];
}
function Reveal({ children, delay = 0, style = {}, ...p }) {
  const [ref, shown] = useReveal();
  return (
    <div ref={ref} data-reveal="" className={shown ? "shown" : ""} style={{ transitionDelay: `${delay}ms`, ...style }} {...p}>
      {children}
    </div>
  );
}

// ---------- Count-up ----------
function useCountUp(target, run, dur = 1300) {
  const [n, setN] = React.useState(0);
  React.useEffect(() => {
    if (!run) return;
    if ((window.matchMedia && matchMedia("(prefers-reduced-motion: reduce)").matches) || document.hidden) { setN(target); return; }
    let raf, start;
    const step = (t) => { if (!start) start = t; const p = Math.min((t - start) / dur, 1);
      setN(Math.round((1 - Math.pow(1 - p, 3)) * target)); if (p < 1) raf = requestAnimationFrame(step); };
    raf = requestAnimationFrame(step); return () => raf && cancelAnimationFrame(raf);
  }, [target, run, dur]);
  return n;
}

Object.assign(window, { Icon, Wordmark, Eyebrow, Btn, Access, useReveal, Reveal, useCountUp });
