const { Icon: FMIcon } = window.UnderpinDesignSystem_726ee6;
const FM_EASE = 'cubic-bezier(.2,.7,.2,1)';
const FM_SPRING = 'cubic-bezier(.34,1.56,.64,1)';
const fmReduced = () => window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches;

function useInView(opts = { threshold: .25 }, fallback = 1200) {
  const ref = React.useRef(null); const [on, setOn] = React.useState(false);
  React.useEffect(() => {
    const el = ref.current; if (!el) return;
    const t = setTimeout(() => setOn(true), fallback);
    if (!('IntersectionObserver' in window)) { setOn(true); return () => clearTimeout(t); }
    const io = new IntersectionObserver(([e]) => { if (e.isIntersecting) { setOn(true); io.disconnect(); } }, opts);
    io.observe(el); return () => { io.disconnect(); clearTimeout(t); };
  }, []);
  return [ref, on];
}

// Words rise in one by one, masked by line. Accepts strings and inline elements.
function SplitWords({ children, delay = 0, stagger = 28, style }) {
  const [ref, on] = useInView({ threshold: .2 });
  let i = 0;
  const wrap = (node) => {
    if (typeof node === 'string') return node.split(/(\s+)/).map((w, k) => w.trim() === '' ? w : (
      <span key={k} style={{ display: 'inline-block', overflow: 'hidden', verticalAlign: 'bottom', paddingBottom: '.08em', marginBottom: '-.08em' }}>
        <span style={{ display: 'inline-block', transform: on ? 'none' : 'translateY(110%)', transition: `transform .9s ${FM_EASE} ${delay + (i++) * stagger}ms` }}>{w}</span>
      </span>));
    if (React.isValidElement(node)) return React.cloneElement(node, {}, React.Children.map(node.props.children, wrap));
    return node;
  };
  return <span ref={ref} style={style}>{React.Children.map(children, wrap)}</span>;
}

// Marker-drawn underline that strokes in once visible
function Underline({ children, color = 'var(--orange-500)', delay = 700, style }) {
  const [ref, on] = useInView({ threshold: .5 });
  return (
    <span ref={ref} style={{ position: 'relative', display: 'inline-block', whiteSpace: 'nowrap', ...style }}>
      {children}
      <svg aria-hidden="true" viewBox="0 0 200 12" preserveAspectRatio="none" style={{ position: 'absolute', left: '-2%', right: '-2%', bottom: '-.12em', width: '104%', height: '.28em', overflow: 'visible' }}>
        <path d="M2 8 C 40 3, 80 10, 120 6 S 180 4, 198 7" fill="none" stroke={color} strokeWidth="3" strokeLinecap="round" style={{ strokeDasharray: 220, strokeDashoffset: on ? 0 : 220, transition: `stroke-dashoffset 1.1s ${FM_EASE} ${delay}ms` }} />
      </svg>
    </span>
  );
}

// Count-up number: "$10M+" → animates 0→10 keeping prefix/suffix
function CountUp({ value, duration = 1400, delay = 0, style }) {
  const [ref, on] = useInView({ threshold: .6 });
  const m = String(value).match(/^([^\d]*)([\d.]+)(.*)$/);
  const [n, setN] = React.useState(() => fmReduced() && m ? parseFloat(m[2]) : 0);
  React.useEffect(() => {
    if (!on || !m) return; const target = parseFloat(m[2]); if (fmReduced() || document.hidden) { setN(target); return; }
    const dec = (m[2].split('.')[1] || '').length; let raf; const t0 = performance.now() + delay;
    const step = (t) => { const p = Math.min(1, Math.max(0, (t - t0) / duration)); const e = 1 - Math.pow(1 - p, 4); setN(+(target * e).toFixed(dec)); if (p < 1) raf = requestAnimationFrame(step); };
    raf = requestAnimationFrame(step); const safe = setTimeout(() => setN(target), delay + duration + 100);
    return () => { cancelAnimationFrame(raf); clearTimeout(safe); };
  }, [on]);
  if (!m) return <span ref={ref} style={style}>{value}</span>;
  return <span ref={ref} style={{ fontVariantNumeric: 'tabular-nums', ...style }}>{m[1]}{n}{m[3]}</span>;
}

// Odometer price: each digit rolls into place
function Odometer({ value = '$297', delay = 0, style }) {
  const [ref, on] = useInView({ threshold: .5 });
  const reduced = fmReduced();
  const chars = String(value).split('');
  return (
    <span ref={ref} aria-label={value} style={{ display: 'inline-flex', fontVariantNumeric: 'tabular-nums', ...style }}>
      {chars.map((c, i) => /\d/.test(c) ? (
        <span key={i} aria-hidden="true" style={{ display: 'inline-block', height: '1em', overflow: 'hidden', lineHeight: 1 }}>
          <span style={{ display: 'flex', flexDirection: 'column', transform: on || reduced ? `translateY(-${+c}em)` : 'none', transition: reduced ? 'none' : `transform ${1.2 + i * .25}s ${FM_EASE} ${delay}ms` }}>
            {[0,1,2,3,4,5,6,7,8,9].map(d => <span key={d} style={{ height: '1em', lineHeight: 1 }}>{d}</span>)}
          </span>
        </span>
      ) : <span key={i} aria-hidden="true" style={{ lineHeight: 1 }}>{c}</span>)}
    </span>
  );
}

// Hazard tape doubles as scroll progress: fills left → right
function ScrollProgress() {
  const [p, setP] = React.useState(0);
  React.useEffect(() => {
    const f = () => { const h = document.documentElement; setP(h.scrollTop / (h.scrollHeight - h.clientHeight)); };
    f(); window.addEventListener('scroll', f, { passive: true }); return () => window.removeEventListener('scroll', f);
  }, []);
  return (
    <div aria-hidden="true" style={{ position: 'fixed', top: 0, left: 0, right: 0, height: '4px', zIndex: 60, background: 'rgba(255,255,255,.06)' }}>
      <div style={{ height: '100%', width: `${p * 100}%`, background: 'repeating-linear-gradient(135deg, var(--orange-600) 0 12px, var(--ink-700) 12px 24px)', transition: 'width .12s linear' }} />
    </div>
  );
}

// 3D tilt-on-hover with mouse-tracked light. Wrap any card.
function Tilt({ children, max = 6, style }) {
  const ref = React.useRef(null); const [s, setS] = React.useState({ rx: 0, ry: 0, gx: 50, gy: 50, on: false });
  const move = (e) => { if (fmReduced()) return; const r = ref.current.getBoundingClientRect(); const px = (e.clientX - r.left) / r.width, py = (e.clientY - r.top) / r.height; setS({ rx: (py - .5) * -max * 2, ry: (px - .5) * max * 2, gx: px * 100, gy: py * 100, on: true }); };
  return (
    <div ref={ref} onMouseMove={move} onMouseLeave={() => setS({ rx: 0, ry: 0, gx: 50, gy: 50, on: false })} style={{ perspective: '1200px', ...style }}>
      <div style={{ position: 'relative', transform: `rotateX(${s.rx}deg) rotateY(${s.ry}deg)`, transition: s.on ? 'transform .12s ease-out' : `transform .8s ${FM_SPRING}`, transformStyle: 'preserve-3d' }}>
        {children}
        <div aria-hidden="true" style={{ position: 'absolute', inset: 0, pointerEvents: 'none', borderRadius: 'inherit', background: `radial-gradient(circle at ${s.gx}% ${s.gy}%, rgba(255,255,255,.14), transparent 45%)`, opacity: s.on ? 1 : 0, transition: 'opacity .4s' }} />
      </div>
    </div>
  );
}

// Fan of cards: spreads out slightly when hovered as a group
function FanGroup({ children, style }) {
  const [hov, setHov] = React.useState(false);
  const kids = React.Children.toArray(children); const mid = (kids.length - 1) / 2;
  return (
    <div onMouseEnter={() => setHov(true)} onMouseLeave={() => setHov(false)} style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', flexWrap: 'wrap', ...style }}>
      {kids.map((k, i) => <div key={i} style={{ transform: hov && !fmReduced() ? `translate(${(i - mid) * 22}px, ${Math.abs(i - mid) * -6}px) rotate(${(i - mid) * 1.5}deg)` : 'none', transition: `transform .7s ${FM_SPRING} ${Math.abs(i - mid) * 40}ms`, zIndex: i === Math.round(mid) ? 2 : 1 }}>{k}</div>)}
    </div>
  );
}

// Checkmark that draws its stroke when in view, then a stamp bump
function DrawCheck({ delay = 0, size = 18, color = 'var(--orange-600)' }) {
  const [ref, on] = useInView({ threshold: .8 });
  return (
    <svg ref={ref} width={size} height={size} viewBox="0 0 24 24" fill="none" aria-hidden="true" style={{ transform: on ? 'scale(1)' : 'scale(.6)', transition: `transform .5s ${FM_SPRING} ${delay + 350}ms` }}>
      <path d="M4 12.5l5 5L20 7" stroke={color} strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round" style={{ strokeDasharray: 30, strokeDashoffset: on ? 0 : 30, transition: `stroke-dashoffset .5s ${FM_EASE} ${delay}ms` }} />
    </svg>
  );
}

// Video frame with an inspector cursor and hover-scrub label
function InspectFrame({ children, caption = 'Watch the 3-minute walkthrough' }) {
  const [pos, setPos] = React.useState(null);
  const move = (e) => { const r = e.currentTarget.getBoundingClientRect(); setPos({ x: e.clientX - r.left, y: e.clientY - r.top }); };
  return (
    <div onMouseMove={move} onMouseLeave={() => setPos(null)} style={{ position: 'relative', cursor: 'none' }}>
      {children}
      {pos && !fmReduced() && (
        <div aria-hidden="true" style={{ position: 'absolute', left: pos.x, top: pos.y, transform: 'translate(-50%,-50%)', pointerEvents: 'none', zIndex: 5 }}>
          <div style={{ width: '54px', height: '54px', border: '1px solid var(--orange-500)', borderRadius: '50%', position: 'relative' }}>
            <span style={{ position: 'absolute', left: '50%', top: '-8px', width: '1px', height: '14px', background: 'var(--orange-500)' }} /><span style={{ position: 'absolute', left: '50%', bottom: '-8px', width: '1px', height: '14px', background: 'var(--orange-500)' }} />
            <span style={{ position: 'absolute', top: '50%', left: '-8px', height: '1px', width: '14px', background: 'var(--orange-500)' }} /><span style={{ position: 'absolute', top: '50%', right: '-8px', height: '1px', width: '14px', background: 'var(--orange-500)' }} />
          </div>
          <div style={{ position: 'absolute', left: '40px', top: '38px', whiteSpace: 'nowrap', fontFamily: 'var(--font-mono)', fontSize: '11px', letterSpacing: '.14em', textTransform: 'uppercase', color: '#fff', background: 'var(--ink-700)', padding: '6px 10px' }}>{caption}</div>
        </div>
      )}
    </div>
  );
}

// Crack path that draws with scroll depth inside its container
function ScrollCrack({ style, color = 'rgba(255,255,255,.22)' }) {
  const ref = React.useRef(null); const [p, setP] = React.useState(0);
  React.useEffect(() => {
    const f = () => { const el = ref.current; if (!el) return; const r = el.getBoundingClientRect(); const vh = window.innerHeight; const d = r.height + vh * .5; setP(d ? Math.min(1, Math.max(0, (vh - r.top) / d)) : 0); };
    f(); window.addEventListener('scroll', f, { passive: true }); return () => window.removeEventListener('scroll', f);
  }, []);
  const L = 700;
  return (
    <svg ref={ref} className="fa-desk" aria-hidden="true" viewBox="0 0 120 600" preserveAspectRatio="none" style={{ position: 'absolute', width: '120px', height: '100%', ...style }}>
      <path d="M62 0 L58 70 L71 118 L64 176 L79 238 L69 296 L84 340 L76 402 L90 470 L83 530 L95 600" fill="none" stroke={color} strokeWidth="1.4" strokeLinejoin="round" pathLength={L} style={{ strokeDasharray: L, strokeDashoffset: L * (1 - p) }} />
      <path d="M71 118 L48 140 L41 166" fill="none" stroke={color} strokeWidth="1" pathLength={100} style={{ strokeDasharray: 100, strokeDashoffset: 100 * (1 - Math.max(0, (p - .25) * 2)) }} />
      <path d="M84 340 L104 356 L110 384" fill="none" stroke={color} strokeWidth="1" pathLength={100} style={{ strokeDasharray: 100, strokeDashoffset: 100 * (1 - Math.max(0, (p - .55) * 2.5)) }} />
      <circle cx="64" cy="176" r={p > .3 ? 3.5 : 0} fill="var(--orange-600)" style={{ transition: 'r .4s ' + FM_SPRING }} />
    </svg>
  );
}

// Section label whose rule lines extend when in view
function DrawRule({ width = 22, delay = 0 }) {
  const [ref, on] = useInView({ threshold: .9 });
  return <span ref={ref} style={{ display: 'inline-block', width: `${width}px`, height: '1px', background: 'var(--orange-600)', transform: on ? 'scaleX(1)' : 'scaleX(0)', transition: `transform .7s ${FM_EASE} ${delay}ms` }} />;
}

Object.assign(window, { useInView, SplitWords, Underline, CountUp, Odometer, ScrollProgress, Tilt, FanGroup, DrawCheck, InspectFrame, ScrollCrack, DrawRule, FM_EASE, FM_SPRING });
