// ============================================================
// One Roof Labs — shared components (dark, inverted from logo 07)
// ============================================================

// ---- Circuit engraving (lifted from the locked logo-ring system) ----
function CircuitEngraving({ radius = 84, color = '#100D09', density = 1 }) {
  const segments = [
    'M -11 0 l 4 0 M -7 -1.5 a 1.5 1.5 0 1 1 3 0 a 1.5 1.5 0 1 1 -3 0 M -3 0 l 14 0',
    'M -11 -2 l 5 0 l 0 4 l 6 0 l 0 -4 l 6 0',
    'M -11 0 l 22 0 M 0 0 l 0 5',
    'M -11 0 l 3 0 M -8 -1.4 a 1.4 1.4 0 1 1 2.8 0 a 1.4 1.4 0 1 1 -2.8 0 M -4 0 l 8 0 M 4 -1.4 a 1.4 1.4 0 1 1 2.8 0 a 1.4 1.4 0 1 1 -2.8 0 M 8 0 l 3 0',
    'M -11 -2 l 6 0 l 0 4 M -5 2 l 6 0 M 0 2 l 0 3 M -1.4 5 a 1.4 1.4 0 1 1 2.8 0 a 1.4 1.4 0 1 1 -2.8 0',
    'M -11 0 l 22 0 M -5 -1.2 a 1.2 1.2 0 1 1 2.4 0 a 1.2 1.2 0 1 1 -2.4 0 M 3 -1.2 a 1.2 1.2 0 1 1 2.4 0 a 1.2 1.2 0 1 1 -2.4 0',
    'M -11 -3 l 4 0 l 0 3 l 4 0 l 0 3 l 4 0 l 0 -3 l 4 0 l 0 -3 l 4 0',
    'M -11 0 l 5 0 M -6 -2 l 4 0 l 0 4 l -4 0 Z M -2 0 l 13 0',
    'M -11 0 l 22 0 M -4 0 l 0 4 M 4 0 l 0 -4',
    'M -11 0 l 6 0 M -5 -3 l 0 6 M -3 -3 l 0 6 M -3 0 l 14 0',
  ];
  const count = Math.floor(20 * density);
  const items = [];
  for (let i = 0; i < count; i++) {
    const angleDeg = (i / count) * 360 - 90;
    const rad = (angleDeg * Math.PI) / 180;
    const x = 100 + Math.cos(rad) * radius;
    const y = 100 + Math.sin(rad) * radius;
    const rotate = angleDeg + 90;
    const g = segments[i % segments.length];
    items.push(
      <g key={i} transform={`translate(${x.toFixed(2)} ${y.toFixed(2)}) rotate(${rotate.toFixed(2)})`}>
        <path d={g} stroke={color} strokeWidth="0.85" fill="none" strokeLinecap="round" strokeLinejoin="round" />
      </g>
    );
  }
  return <g>{items}</g>;
}

// ---- Inverted ring-O: band in paper, engraving cut in bg ----
function RingO({ size = 120, band = '#F1E6CF', engrave = '#100D09', glyphs = true, density = 1, style = {} }) {
  return (
    <svg viewBox="0 0 200 200" width={size} height={size} style={{ display: 'block', overflow: 'visible', ...style }}>
      <path
        d="M 100 4 a 96 96 0 1 1 0 192 a 96 96 0 1 1 0 -192 Z M 100 28 a 72 72 0 1 0 0 144 a 72 72 0 1 0 0 -144 Z"
        fillRule="evenodd" fill={band}
      />
      {glyphs ? <CircuitEngraving color={engrave} radius={84} density={density} /> : null}
    </svg>
  );
}

// ---- Wordmark: ring-O + "NE ROOF" in Cinzel ----
function Wordmark({ size = 30, color = '#F1E6CF' }) {
  return (
    <div className="nav-logo" onClick={() => { window.scrollTo({ top: 0, behavior: 'smooth' }); }}>
      <span className="ring" style={{ width: size, height: size }}>
        <RingO size={size} glyphs density={1} />
      </span>
      <span className="wm" style={{ color }}>NE&nbsp;ROOF</span>
    </div>
  );
}

// ---- Nav ----
function Nav({ active }) {
  const [scrolled, setScrolled] = React.useState(false);
  React.useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 24);
    onScroll();
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);
  const links = [
    ['How It Works', '#how'],
    ['Contractors', '#contractors'],
    ['Carriers', '#carriers'],
    ['The Map', '#map'],
    ['About', '#about'],
  ];
  return (
    <nav className={scrolled ? 'nav scrolled' : 'nav'}>
      <Wordmark />
      <div className="nav-links">
        {links.map(([label, href]) => (
          <a key={label} href={href}
             className={'nav-link' + (active === label ? ' active' : '')}>{label}</a>
        ))}
      </div>
      <a href="#map" className="btn" style={{ padding: '11px 18px' }}>
        See the Map <span className="arrow">→</span>
      </a>
    </nav>
  );
}

// ---- Footer ----
function Footer() {
  const cols = [
    ['Product', [['How It Works', '#how'], ['The Map', '#map'], ['For Contractors', '#contractors'], ['For Carriers', '#carriers']]],
    ['Company', [['About', '#about'], ['Markets', '#markets'], ['Contact', '#contact'], ['Investors', '#contact']]],
    ['Markets', [['Colorado Springs, CO', '#'], ['St. Louis, MO', '#'], ['San Diego, CA', '#'], ['Chattanooga, TN', '#']]],
  ];
  return (
    <footer className="footer">
      <div className="wrap">
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 48, justifyContent: 'space-between' }}>
          <div style={{ maxWidth: 360 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 4, marginBottom: 20 }}>
              <span style={{ width: 40, height: 40, display: 'block' }}><RingO size={40} /></span>
              <span className="display" style={{ fontSize: 24, letterSpacing: '0.12em' }}>NE&nbsp;ROOF&nbsp;LABS</span>
            </div>
            <p className="footer-tagline">The one roofing solution to rule them all.</p>
            <p className="mono" style={{ color: 'var(--faint)', fontSize: 12, letterSpacing: '0.1em', marginTop: 28 }}>
              38.8339° N&nbsp;&nbsp;/&nbsp;&nbsp;104.8214° W
            </p>
          </div>
          <div style={{ display: 'flex', gap: 56, flexWrap: 'wrap' }}>
            {cols.map(([title, items]) => (
              <div key={title}>
                <div className="kicker" style={{ fontSize: 11, marginBottom: 18 }}>{title}</div>
                <div style={{ display: 'flex', flexDirection: 'column', gap: 11 }}>
                  {items.map(([l, h]) => (
                    <a key={l} href={h} style={{ color: 'var(--muted)', fontSize: 14.5, transition: 'color .2s' }}
                       onMouseEnter={(e) => e.currentTarget.style.color = 'var(--paper)'}
                       onMouseLeave={(e) => e.currentTarget.style.color = 'var(--muted)'}>{l}</a>
                  ))}
                </div>
              </div>
            ))}
          </div>
        </div>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: 16,
                      marginTop: 64, paddingTop: 28, borderTop: '1px solid var(--hair)' }}>
          <span className="mono" style={{ color: 'var(--faint)', fontSize: 12, letterSpacing: '0.08em' }}>
            © 2026 ONE ROOF LABS, INC. — AERIAL ROOF INTELLIGENCE
          </span>
          <span className="mono" style={{ color: 'var(--faint)', fontSize: 12, letterSpacing: '0.08em' }}>
            SURVEY-GRADE LiDAR · RTK PRECISION · 1cm RMSE
          </span>
        </div>
      </div>
    </footer>
  );
}

// ---- Animated stat counter (counts up on first view) ----
function StatCounter({ value, prefix = '', suffix = '', decimals = 0, duration = 1400 }) {
  const ref = React.useRef(null);
  const [display, setDisplay] = React.useState(0);
  const started = React.useRef(false);
  React.useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => {
        if (e.isIntersecting && !started.current) {
          started.current = true;
          const t0 = performance.now();
          const tick = (now) => {
            const p = Math.min(1, (now - t0) / duration);
            const eased = 1 - Math.pow(1 - p, 3);
            setDisplay(value * eased);
            if (p < 1) requestAnimationFrame(tick);
            else setDisplay(value);
          };
          requestAnimationFrame(tick);
        }
      });
    }, { threshold: 0.4 });
    io.observe(el);
    return () => io.disconnect();
  }, [value, duration]);
  const formatted = display.toLocaleString('en-US', {
    minimumFractionDigits: decimals, maximumFractionDigits: decimals,
  });
  return <span ref={ref} className="tnum">{prefix}{formatted}{suffix}</span>;
}

// ---- scroll reveal hook ----
function useReveal() {
  React.useEffect(() => {
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => { if (e.isIntersecting) e.target.classList.add('in'); });
    }, { threshold: 0.12 });
    document.querySelectorAll('.reveal').forEach((el) => io.observe(el));
    return () => io.disconnect();
  }, []);
}

Object.assign(window, {
  CircuitEngraving, RingO, Wordmark, Nav, Footer, StatCounter, useReveal,
});
