/* global React */
/* Shared primitives used across all three variations. */

const { useState, useEffect, useRef } = React;

/* --- Constants --------------------------------------------------- */
const C = {
  navy: '#1B2D4F',
  navyDark: '#121F36',
  navyMuted: '#CFD6E3',
  sage: '#7FA58B',
  sageTint: '#E5EEE8',
  orange: '#E2733B',
  orangeTint: '#FBE5D7',
  warm: '#F5F3EC',
  warmDark: '#EBE7D8',
  white: '#FFFFFF',
  ink: '#141B2A',
  muted: '#55606E',
  mutedSoft: '#8895AA',
  borderWarm: '#E3E0D6',
  borderLight: '#F0EDE2',
};

const FONT_DISP = "'Space Grotesk', ui-sans-serif, system-ui, sans-serif";
const FONT_SANS = "'Inter', ui-sans-serif, system-ui, sans-serif";

const TAGLINES = [
  'Decision systems,\nbuilt around how\nyour business actually runs.',
  'Tailored data.\nTrusted decisions.',
  'Dashboards built around\nthe work, not the tool.',
  'Data your team\nwill actually use.',
];

/* --- Hook: scroll position -------------------------------------- */
function useScrollY() {
  const [y, setY] = useState(0);
  useEffect(() => {
    let raf = 0;
    const onScroll = () => {
      cancelAnimationFrame(raf);
      raf = requestAnimationFrame(() => setY(window.scrollY));
    };
    window.addEventListener('scroll', onScroll, { passive: true });
    onScroll();
    return () => { window.removeEventListener('scroll', onScroll); cancelAnimationFrame(raf); };
  }, []);
  return y;
}

/* --- Hook: window width for responsive layouts ------------------ */
function useWindowWidth() {
  const [w, setW] = useState(() => window.innerWidth);
  useEffect(() => {
    const onResize = () => setW(window.innerWidth);
    window.addEventListener('resize', onResize);
    return () => window.removeEventListener('resize', onResize);
  }, []);
  return w;
}

/* --- Hook: intersection reveal ---------------------------------- */
function useReveal(opts = {}) {
  const ref = useRef(null);
  const [shown, setShown] = useState(false);
  useEffect(() => {
    if (!ref.current) return;
    const io = new IntersectionObserver(([entry]) => {
      if (entry.isIntersecting) { setShown(true); io.disconnect(); }
    }, { threshold: 0.15, rootMargin: '0px 0px -80px 0px', ...opts });
    io.observe(ref.current);
    return () => io.disconnect();
  }, []);
  return [ref, shown];
}

/* --- Hook: counter animation ------------------------------------ */
function useCountUp(target, { active = true, duration = 1400 } = {}) {
  const [v, setV] = useState(0);
  useEffect(() => {
    if (!active) return;
    let raf, start;
    const step = (t) => {
      if (!start) start = t;
      const p = Math.min(1, (t - start) / duration);
      const eased = 1 - Math.pow(1 - p, 3);
      setV(Math.round(target * eased));
      if (p < 1) raf = requestAnimationFrame(step);
    };
    raf = requestAnimationFrame(step);
    return () => cancelAnimationFrame(raf);
  }, [target, active, duration]);
  return v;
}

/* --- Button ----------------------------------------------------- */
function Button({ variant = 'primary', size = 'md', children, onClick, href, ...rest }) {
  const [hover, setHover] = useState(false);
  const [press, setPress] = useState(false);
  const base = {
    fontFamily: FONT_SANS, fontWeight: 700, cursor: 'pointer',
    border: 'none', borderRadius: 8,
    transition: 'background 180ms cubic-bezier(0.2,0.8,0.2,1), color 180ms cubic-bezier(0.2,0.8,0.2,1), filter 180ms, transform 120ms',
    display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
    textDecoration: 'none', whiteSpace: 'nowrap', gap: 8,
    transform: press ? 'translateY(1px)' : 'translateY(0)',
  };
  const sizes = {
    sm: { padding: '10px 18px', fontSize: 14, borderRadius: 6 },
    md: { padding: '14px 24px', fontSize: 16 },
    lg: { padding: '18px 30px', fontSize: 16 },
  };
  const variants = {
    primary:       { background: hover ? '#CF6632' : C.orange, color: '#fff' },
    navy:          { background: hover ? C.navyDark : C.navy,  color: '#fff' },
    secondary: {
      background: hover ? C.navy : 'transparent',
      color: hover ? '#fff' : C.navy,
      border: `1.5px solid ${C.navy}`,
    },
    outline_white: {
      background: hover ? '#fff' : 'transparent',
      color: hover ? C.navy : '#fff',
      border: `1.5px solid ${C.navyMuted}`,
    },
    ghost: { background: 'transparent', color: C.navy },
  };
  const Tag = href ? 'a' : 'button';
  return (
    <Tag
      href={href}
      onClick={onClick}
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => { setHover(false); setPress(false); }}
      onMouseDown={() => setPress(true)}
      onMouseUp={() => setPress(false)}
      style={{ ...base, ...sizes[size], ...variants[variant] }}
      {...rest}
    >
      {children}
    </Tag>
  );
}

/* --- Eyebrow ---------------------------------------------------- */
function Eyebrow({ children, color = C.sage, style }) {
  return (
    <div style={{
      fontFamily: FONT_SANS, fontWeight: 700, fontSize: 12,
      letterSpacing: '0.12em', textTransform: 'uppercase', color,
      ...style,
    }}>{children}</div>
  );
}

/* --- Logo mark + wordmark --------------------------------------- */
function Brand({ color = C.navy, size = 28 }) {
  return (
    <a href="#top" style={{ display: 'flex', alignItems: 'center', gap: 12, textDecoration: 'none' }}>
      <img src="assets/logos/mark_simplified.svg" width={size} height={size} alt="" />
      <span style={{
        fontFamily: FONT_DISP, fontWeight: 700, fontSize: 18, color,
        letterSpacing: '-0.01em',
      }}>Key Metrics</span>
    </a>
  );
}

/* --- Nav -------------------------------------------------------- */
function Nav({ bg = C.warm, variant = 'A' }) {
  const y = useScrollY();
  const w = useWindowWidth();
  const isMobile = w <= 768;
  const scrolled = y > 40;
  return (
    <header
      style={{
        position: 'sticky', top: 0, zIndex: 30,
        background: scrolled ? 'rgba(245,243,236,0.88)' : bg,
        backdropFilter: scrolled ? 'saturate(140%) blur(8px)' : 'none',
        WebkitBackdropFilter: scrolled ? 'saturate(140%) blur(8px)' : 'none',
        borderBottom: scrolled ? `1px solid ${C.borderWarm}` : '1px solid transparent',
        transition: 'background 180ms ease, border-color 180ms ease',
      }}
    >
      <nav style={{
        maxWidth: 1280, margin: '0 auto', padding: isMobile ? '0 20px' : '0 80px',
        height: 72, display: 'flex', alignItems: 'center', justifyContent: 'space-between',
      }}>
        <Brand />
        {isMobile ? (
          <Button variant="navy" size="sm" href="#contact">Book a call</Button>
        ) : (
          <div style={{ display: 'flex', alignItems: 'center', gap: 36 }}>
            <a href="#approach" style={navLink}>Approach</a>
            <a href="#work" style={navLink}>Work</a>
            <a href="#engagement" style={navLink}>Engagement</a>
            <a href="#contact" style={navLink}>Contact</a>
            <Button variant="navy" size="sm" href="#contact">Book a call</Button>
          </div>
        )}
      </nav>
    </header>
  );
}
const navLink = {
  fontFamily: FONT_SANS, fontSize: 14, fontWeight: 500,
  color: C.ink, textDecoration: 'none', cursor: 'pointer',
  transition: 'color 180ms',
};

/* --- Footer ----------------------------------------------------- */
function Footer() {
  const w = useWindowWidth();
  const isMobile = w <= 768;
  return (
    <footer style={{ background: C.navyDark }}>
      <div style={{
        maxWidth: 1280, margin: '0 auto',
        padding: isMobile ? '48px 24px 36px' : '64px 80px 48px',
        display: 'grid',
        gridTemplateColumns: isMobile ? '1fr' : '2fr 1fr 1fr',
        gap: isMobile ? 32 : 48,
      }}>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
            <img src="assets/logos/mark_mono_white.svg" width="28" height="28" alt="" />
            <span style={{ fontFamily: FONT_DISP, fontWeight: 700, fontSize: 18, color: '#fff' }}>
              Key Metrics
            </span>
          </div>
          <p style={{
            fontFamily: FONT_SANS, fontSize: 14, lineHeight: '22px',
            color: C.navyMuted, margin: 0, maxWidth: 360,
          }}>
            Decision systems, built around how your business actually runs.
          </p>
        </div>
        <FooterCol title="Site" links={[
          ['Approach', '#approach'],
          ['Work', '#work'],
          ['Engagement', '#engagement'],
        ]} />
        <FooterCol title="Contact" links={[
          ['insights@keymetrics.live', 'mailto:insights@keymetrics.live'],
          ['Book a 30-min call', '#contact'],
          ['LinkedIn', '#'],
        ]} />
      </div>
      <div style={{
        borderTop: '1px solid rgba(255,255,255,0.08)',
        maxWidth: 1280, margin: '0 auto',
        padding: isMobile ? '20px 24px' : '20px 80px',
        display: 'flex', justifyContent: 'space-between', alignItems: 'center',
        flexDirection: isMobile ? 'column' : 'row', gap: isMobile ? 6 : 0,
        fontFamily: FONT_SANS, fontSize: 12, color: C.mutedSoft,
      }}>
        <span>© 2026 Key Metrics · keymetrics.live</span>
        <span>Built for operators, not analysts.</span>
      </div>
    </footer>
  );
}
function FooterCol({ title, links }) {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
      <div style={{
        fontFamily: FONT_SANS, fontWeight: 700, fontSize: 12,
        letterSpacing: '0.12em', textTransform: 'uppercase', color: '#fff',
      }}>{title}</div>
      {links.map(([label, href]) => (
        <a key={label} href={href} style={{
          fontFamily: FONT_SANS, fontSize: 14, color: C.navyMuted,
          textDecoration: 'none',
        }}>{label}</a>
      ))}
    </div>
  );
}

Object.assign(window, { C, FONT_DISP, FONT_SANS, TAGLINES, Button, Eyebrow, Brand, Nav, Footer, useScrollY, useWindowWidth, useReveal, useCountUp });
