// Shared primitives + hooks used across sections.

function useReveal() {
  const ref = React.useRef(null);
  React.useEffect(() => {
    const el = ref.current;
    if (!el) return;
    // Eager check: if already in viewport at mount, reveal immediately.
    const r = el.getBoundingClientRect();
    const vh = window.innerHeight || document.documentElement.clientHeight;
    if (r.top < vh && r.bottom > 0) {
      el.classList.add('in');
      return;
    }
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => { if (e.isIntersecting) { el.classList.add('in'); io.disconnect(); } });
    }, { threshold: 0.08, rootMargin: '0px 0px -40px 0px' });
    io.observe(el);
    return () => io.disconnect();
  }, []);
  return ref;
}

function Reveal({ children, delay = 0, as = 'div', ...rest }) {
  const Tag = as;
  const style = { ...(rest.style || {}), animationDelay: delay ? `${delay}ms` : undefined };
  return <Tag {...rest} className={`reveal ${rest.className || ''}`} style={style}>{children}</Tag>;
}

function Logo({ name = 'Care', small = false }) {
  return (
    <a href="#top" className="brand" aria-label={`${name} home`}>
      <span className="brand-mark" aria-hidden>
        <svg viewBox="0 0 32 32" fill="none">
          <path d="M23.07 7.57 A11 11 0 1 0 23.07 24.43" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" />
          <path d="M20.18 11.02 A6.5 6.5 0 1 0 20.18 20.98" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" />
        </svg>
      </span>
      <span>{name}{small && <small> · home</small>}</span>
    </a>
  );
}

function Nav({ name, productName, setShowTweaksHint }) {
  const [scrolled, setScrolled] = React.useState(false);
  React.useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 8);
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);
  return (
    <nav className={`nav ${scrolled ? 'scrolled' : ''}`} data-screen-label="Top nav">
      <div className="wrap nav-inner">
        <Logo name={productName} small />
        <div className="nav-links">
          <a href="#difference">How it works</a>
          <a href="#use-cases">Use cases</a>
          <a href="#pricing">Pricing</a>
          <a href="#survey" className="btn sm accent nav-cta">Request beta access</a>
        </div>
      </div>
    </nav>
  );
}

/* Animated typewriter for short strings; reveal lines on first view. */
function useTypewriter(text, { speed = 22, start = true, delay = 0 } = {}) {
  const [out, setOut] = React.useState('');
  React.useEffect(() => {
    if (!start) { setOut(''); return; }
    let i = 0; let t = null; let cancelled = false;
    const begin = setTimeout(() => {
      const tick = () => {
        if (cancelled) return;
        i += 1;
        setOut(text.slice(0, i));
        if (i < text.length) t = setTimeout(tick, speed);
      };
      tick();
    }, delay);
    return () => { cancelled = true; clearTimeout(begin); clearTimeout(t); };
  }, [text, speed, start, delay]);
  return out;
}

/* In-view trigger: returns boolean once the el has entered viewport. */
function useInView(opts = { threshold: 0.25 }) {
  const ref = React.useRef(null);
  const [seen, setSeen] = React.useState(false);
  React.useEffect(() => {
    const el = ref.current; if (!el) return;
    const r = el.getBoundingClientRect();
    const vh = window.innerHeight || document.documentElement.clientHeight;
    if (r.top < vh && r.bottom > 0) { setSeen(true); return; }
    const io = new IntersectionObserver((e) => {
      e.forEach((x) => { if (x.isIntersecting) { setSeen(true); io.disconnect(); } });
    }, opts);
    io.observe(el);
    return () => io.disconnect();
  }, []);
  return [ref, seen];
}

/* Reusable phone bezel with adjustable inner content. */
function Phone({ children, scale = 1, style }) {
  return (
    <div className="phone" style={{ ...style, '--phone-scale': scale }}>
      <div className="phone-bezel">
        <div className="phone-notch" />
        <div className="phone-screen">{children}</div>
      </div>
      <div className="phone-shadow" aria-hidden />
    </div>
  );
}

/* Section heading block */
function SectionHead({ eyebrow, title, lead, align = 'left' }) {
  // One sentence per line: split a plain-string lead on sentence boundaries.
  const leadParts = typeof lead === 'string' ? lead.split(/(?<=[.?!])\s+/) : null;
  return (
    <Reveal className="stack" style={{ gap: 14, maxWidth: 760, marginLeft: align === 'center' ? 'auto' : 0, marginRight: align === 'center' ? 'auto' : 0, textAlign: align }}>
      {eyebrow && <div className="eyebrow">{eyebrow}</div>}
      {title && <h2>{title}</h2>}
      {lead && <p style={{ fontSize: 19, color: 'var(--ink-soft)', maxWidth: 640, marginLeft: align === 'center' ? 'auto' : 0, marginRight: align === 'center' ? 'auto' : 0 }}>
        {leadParts ? leadParts.map((s, i) => <React.Fragment key={i}>{i > 0 && <br />}{s}</React.Fragment>) : lead}
      </p>}
    </Reveal>
  );
}

Object.assign(window, { useReveal, Reveal, Logo, Nav, useTypewriter, useInView, Phone, SectionHead });
