/* CareNav site — shared bits: header (audience switcher), in-view hooks, primitives */

window.useInView = function useInView(opts = { threshold: 0.2, once: true }) {
  const ref = React.useRef(null);
  const [inView, setInView] = React.useState(false);
  React.useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const obs = new IntersectionObserver(([e]) => {
      if (e.isIntersecting) { setInView(true); if (opts.once) obs.disconnect(); }
      else if (!opts.once) setInView(false);
    }, { threshold: opts.threshold });
    obs.observe(el);
    return () => obs.disconnect();
  }, []);
  return [ref, inView];
};

window.useScrollProgress = function useScrollProgress(ref) {
  const [p, setP] = React.useState(0);
  React.useEffect(() => {
    const onScroll = () => {
      const el = ref.current; if (!el) return;
      const r = el.getBoundingClientRect();
      const vh = window.innerHeight;
      const total = r.height + vh;
      const passed = vh - r.top;
      setP(Math.max(0, Math.min(1, passed / total)));
    };
    onScroll();
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);
  return p;
};

/* Single mobile breakpoint — narrow phones and below */
window.useIsMobile = function useIsMobile(breakpoint = 720) {
  const get = () => typeof window !== 'undefined' && window.innerWidth < breakpoint;
  const [isMobile, setIsMobile] = React.useState(get);
  React.useEffect(() => {
    const onResize = () => setIsMobile(get());
    onResize();
    window.addEventListener('resize', onResize);
    return () => window.removeEventListener('resize', onResize);
  }, [breakpoint]);
  return isMobile;
};

/* Audience switcher — sticky top bar with active state */
window.SiteHeader = function SiteHeader({ audience, setAudience }) {
  const isMobile = useIsMobile();
  const audiences = [
    { id: 'patients', label: isMobile ? 'Patients' : 'Patients & Families' },
    { id: 'clinicians', label: 'Clinicians' },
    { id: 'hospitals', label: isMobile ? 'Hospitals' : 'Hospital Groups' },
    { id: 'insurers', label: isMobile ? 'Insurers' : 'Medical Insurers' },
  ];
  const cta = {
    patients: isMobile ? 'Ask provider' : 'Ask your provider',
    clinicians: isMobile ? 'Refer' : 'Refer a patient',
    hospitals: isMobile ? 'Demo' : 'Book a demo',
    insurers: isMobile ? 'Partner' : 'Partner with us',
  }[audience] || 'Get started';

  const audienceNav = (
    <nav style={{
      display: 'flex',
      justifyContent: isMobile ? 'flex-start' : 'center',
      gap: isMobile ? 6 : 4,
      flexWrap: isMobile ? 'nowrap' : 'wrap',
      overflowX: isMobile ? 'auto' : 'visible',
      WebkitOverflowScrolling: 'touch',
      scrollbarWidth: 'none',
      padding: isMobile ? '0 16px 8px' : 0,
      margin: isMobile ? '0 -16px' : 0,
    }}>
      {audiences.map(a => {
        const active = audience === a.id;
        return (
          <button key={a.id} onClick={() => setAudience(a.id)} style={{
            background: active ? 'var(--cn-forest-800)' : 'transparent',
            color: active ? 'var(--cn-cream-100)' : 'var(--cn-ink-700)',
            border: 'none',
            fontFamily: 'var(--cn-font-sans)', fontSize: isMobile ? 12 : 13, fontWeight: 500,
            padding: isMobile ? '7px 12px' : '8px 14px',
            borderRadius: 999, cursor: 'pointer',
            transition: 'all 0.2s',
            whiteSpace: 'nowrap', flexShrink: 0,
          }}>{a.label}</button>
        );
      })}
    </nav>
  );

  return (
    <header style={{ position: 'sticky', top: 0, zIndex: 100, background: 'rgba(243,234,218,0.85)', backdropFilter: 'blur(20px)', borderBottom: '1px solid rgba(0,0,0,0.06)', overflowX: 'hidden' }}>
      <div style={{
        maxWidth: 1280, margin: '0 auto',
        padding: isMobile ? '10px 16px 0' : '14px 32px',
        display: 'grid',
        gridTemplateColumns: isMobile ? '1fr auto' : 'auto 1fr auto',
        alignItems: 'center',
        gap: isMobile ? 10 : 32,
      }}>
        <CNLogoLockup size={isMobile ? 18 : 20}/>
        {!isMobile && audienceNav}
        <div style={{ display: 'flex', alignItems: 'center', gap: isMobile ? 6 : 8 }}>
          <button onClick={() => window.scrollToId && window.scrollToId('contact')} style={{
            background: 'var(--cn-coral-600)', color: 'white', border: 'none',
            fontFamily: 'var(--cn-font-sans)', fontSize: isMobile ? 12 : 13, fontWeight: 600,
            padding: isMobile ? '8px 12px' : '10px 18px',
            borderRadius: 999, cursor: 'pointer',
            whiteSpace: 'nowrap',
          }}>{cta}{isMobile ? '' : ' →'}</button>
          <a href="https://app.carenav.co.za" onMouseEnter={(e) => { e.currentTarget.style.background = 'var(--cn-forest-800)'; e.currentTarget.style.color = 'var(--cn-cream-100)'; e.currentTarget.style.borderColor = 'var(--cn-forest-800)'; }} onMouseLeave={(e) => { e.currentTarget.style.background = 'transparent'; e.currentTarget.style.color = 'var(--cn-forest-800)'; e.currentTarget.style.borderColor = 'var(--cn-forest-700)'; }} style={{
            display: 'inline-flex', alignItems: 'center',
            background: 'transparent', color: 'var(--cn-forest-800)',
            border: '1px solid var(--cn-forest-700)',
            fontFamily: 'var(--cn-font-sans)', fontSize: isMobile ? 12 : 13, fontWeight: 600,
            padding: isMobile ? '7px 12px' : '9px 18px',
            borderRadius: 999, cursor: 'pointer',
            textDecoration: 'none',
            transition: 'background 0.2s, color 0.2s, border-color 0.2s',
          }}>Login</a>
        </div>
      </div>
      {isMobile && audienceNav}
    </header>
  );
};
