// Additional landing animations: marquee, count-up, real-time clock, shimmer button.

const { useState: useStateNew, useEffect: useEffectNew, useRef: useRefNew } = React;

// ── MarqueeTicker ─ full-width infinite scroll strip ─────────────
function MarqueeTicker({ items, speed = 40 }) {
  const text = (
    <span style={{ display: 'inline-flex', alignItems: 'center', gap: 36, padding: '0 18px' }}>
      {items.map((it, i) => (
        <React.Fragment key={i}>
          <span style={{
            fontFamily: 'var(--display)',
            fontSize: 22, fontWeight: 800,
            letterSpacing: '-0.02em',
            textTransform: 'uppercase',
            color: '#fff',
          }}>{it}</span>
          <span style={{
            width: 8, height: 8, borderRadius: '50%',
            background: 'var(--coral)',
            flexShrink: 0,
            boxShadow: '0 0 12px rgba(255,97,85,0.6)',
          }} />
        </React.Fragment>
      ))}
    </span>
  );
  return (
    <div style={{
      width: '100%', overflow: 'hidden',
      borderTop: '1px solid rgba(255,255,255,0.06)',
      borderBottom: '1px solid rgba(255,255,255,0.06)',
      padding: '20px 0',
      background: 'var(--bg)',
      position: 'relative', zIndex: 1,
    }}>
      <div style={{
        display: 'inline-flex', whiteSpace: 'nowrap',
        animation: `prove-marquee ${speed}s linear infinite`,
      }}>
        {text}{text}{text}
      </div>
    </div>
  );
}

// ── AnimatedCount ─ tweens from 0 to target on scroll into view ──
function AnimatedCount({ value, suffix = '', duration = 2500, style }) {
  const [n, setN] = useStateNew(0);
  const ref = useRefNew(null);
  const startedRef = useRefNew(false);
  useEffectNew(() => {
    if (prefersReducedMotion()) { setN(value); return; }
    const el = ref.current;
    if (!el) return;
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => {
        if (e.isIntersecting && !startedRef.current) {
          startedRef.current = true;
          const start = performance.now();
          const tick = (t) => {
            const p = Math.min(1, (t - start) / duration);
            const eased = 1 - Math.pow(1 - p, 3); // cubic ease-out
            setN(value * eased);
            if (p < 1) requestAnimationFrame(tick);
          };
          requestAnimationFrame(tick);
          io.unobserve(el);
        }
      });
    }, { threshold: 0.3 });
    io.observe(el);
    return () => io.disconnect();
  }, [value, duration]);
  // Format: keep one decimal for non-integer values, no decimal for percentages
  const display = Number.isInteger(value)
    ? Math.round(n).toString()
    : n.toFixed(1);
  return (
    <span ref={ref} style={{
      fontFamily: 'var(--mono)',
      fontVariantNumeric: 'tabular-nums',
      ...style,
    }}>{display}{suffix}</span>
  );
}

// ── LiveClock ─ analog clock face with real-time hands + coral arc
//    Coral arc covers 6AM–11:59PM (the PROVE Window).
function LiveClock({ size = 220 }) {
  const [now, setNow] = useStateNew(new Date());
  useEffectNew(() => {
    const t = setInterval(() => setNow(new Date()), 1000);
    return () => clearInterval(t);
  }, []);

  const r = size / 2;
  const cx = r, cy = r;
  const ringR = r - 12;
  const handLenH = r * 0.5;
  const handLenM = r * 0.7;
  const handLenS = r * 0.78;

  const hours = now.getHours() + now.getMinutes() / 60;
  const minutes = now.getMinutes() + now.getSeconds() / 60;
  const seconds = now.getSeconds();
  const hourAngle = (hours / 12) * 360;     // 12h dial
  const minAngle = (minutes / 60) * 360;
  const secAngle = (seconds / 60) * 360;

  // Coral arc: 6AM–11:59PM = 18 hours of 24, but visualized on 12h dial means
  // covering essentially the full 12h circle minus the 6h "night" segment.
  // Show as a clean arc from 6 to 12 to 6 on the 12h face — coral over the
  // "active part of the day". We'll draw it from 6 o'clock around the top
  // back to 6 o'clock (270° arc, leaving the bottom-most segment uncolored).
  // Simpler: arc from angle 330° to angle 210° going clockwise (covers most of dial).
  const arcStart = -60;    // 10 o'clock position
  const arcEnd   = 240;    // ~7 o'clock position
  const polar = (deg, rad = ringR) => {
    const a = (deg - 90) * Math.PI / 180;
    return [cx + Math.cos(a) * rad, cy + Math.sin(a) * rad];
  };
  const [ax1, ay1] = polar(arcStart);
  const [ax2, ay2] = polar(arcEnd);
  const largeArc = arcEnd - arcStart > 180 ? 1 : 0;

  const isOpen = hours >= 6 && hours < 24;

  return (
    <div style={{ position: 'relative', display: 'inline-block', filter: 'drop-shadow(0 0 32px rgba(255,97,85,0.25))' }}>
      <svg width={size} height={size} viewBox={`0 0 ${size} ${size}`}>
        {/* Outer faint ring */}
        <circle cx={cx} cy={cy} r={ringR} fill="none" stroke="rgba(255,255,255,0.06)" strokeWidth={1.5} />
        {/* Coral PROVE Window arc */}
        <path
          d={`M ${ax1} ${ay1} A ${ringR} ${ringR} 0 ${largeArc} 1 ${ax2} ${ay2}`}
          fill="none"
          stroke="var(--coral)"
          strokeWidth={6}
          strokeLinecap="round"
          style={{
            animation: isOpen ? 'prove-coral-pulse 2.4s ease-in-out infinite' : 'none',
            opacity: isOpen ? 1 : 0.35,
          }}
        />
        {/* Hour ticks */}
        {Array.from({ length: 12 }).map((_, i) => {
          const a = (i / 12) * Math.PI * 2 - Math.PI / 2;
          const r1 = ringR - 4;
          const r2 = ringR - (i % 3 === 0 ? 14 : 9);
          return (
            <line key={i}
              x1={cx + Math.cos(a) * r1} y1={cy + Math.sin(a) * r1}
              x2={cx + Math.cos(a) * r2} y2={cy + Math.sin(a) * r2}
              stroke={i % 3 === 0 ? 'rgba(255,255,255,0.5)' : 'rgba(255,255,255,0.25)'}
              strokeWidth={i % 3 === 0 ? 2 : 1}
              strokeLinecap="round"
            />
          );
        })}
        {/* Hour hand */}
        <line x1={cx} y1={cy}
          x2={cx + Math.cos((hourAngle - 90) * Math.PI / 180) * handLenH}
          y2={cy + Math.sin((hourAngle - 90) * Math.PI / 180) * handLenH}
          stroke="#fff" strokeWidth={4} strokeLinecap="round" />
        {/* Minute hand */}
        <line x1={cx} y1={cy}
          x2={cx + Math.cos((minAngle - 90) * Math.PI / 180) * handLenM}
          y2={cy + Math.sin((minAngle - 90) * Math.PI / 180) * handLenM}
          stroke="rgba(255,255,255,0.85)" strokeWidth={2.5} strokeLinecap="round" />
        {/* Second hand (coral) */}
        <line x1={cx} y1={cy}
          x2={cx + Math.cos((secAngle - 90) * Math.PI / 180) * handLenS}
          y2={cy + Math.sin((secAngle - 90) * Math.PI / 180) * handLenS}
          stroke="var(--coral)" strokeWidth={1.5} strokeLinecap="round"
          style={{ transition: 'transform 0.05s linear' }}
        />
        {/* Center dot */}
        <circle cx={cx} cy={cy} r={5} fill="var(--coral)" />
        <circle cx={cx} cy={cy} r={2.5} fill="#fff" />
      </svg>
    </div>
  );
}

// ── ShimmerButton ─ wraps children, renders a diagonal sweep highlight
function ShimmerButton({ children, style }) {
  return (
    <span style={{
      position: 'relative', display: 'inline-block', overflow: 'hidden',
      borderRadius: 999, isolation: 'isolate',
      ...style,
    }}>
      {children}
      <span style={{
        position: 'absolute', inset: 0,
        background: 'linear-gradient(115deg, transparent 30%, rgba(255,255,255,0.45) 50%, transparent 70%)',
        animation: 'prove-shimmer 3s ease-in-out infinite',
        pointerEvents: 'none', zIndex: 2,
        mixBlendMode: 'overlay',
      }} />
    </span>
  );
}

Object.assign(window, { MarqueeTicker, AnimatedCount, LiveClock, ShimmerButton });
