// shared.jsx — Nav, Footer, AudienceToggle, motion utilities

const { useState, useEffect, useRef, useMemo } = React;

// Scroll-aware nav. Detects when a dark section sits behind it and swaps to a light variant.
const Nav = ({ active, audience }) => {
  const [scrolled, setScrolled] = useState(false);
  const [onDark, setOnDark] = useState(false);
  useEffect(() => {
    const isDark = (rgb) => {
      if (!rgb) return false;
      const m = rgb.match(/\d+(\.\d+)?/g);
      if (!m || m.length < 3) return false;
      const [r, g, b, a] = m.map(Number);
      if (a !== undefined && a < 0.5) return false;
      // Perceived luminance
      const lum = (0.299 * r + 0.587 * g + 0.114 * b) / 255;
      return lum < 0.5;
    };
    const gradientMinLuminance = (bgImage) => {
      if (!bgImage || bgImage === 'none') return null;
      const matches = [...bgImage.matchAll(/rgba?\(([^)]+)\)/g)];
      if (!matches.length) return null;
      let minLum = null;
      for (const m of matches) {
        const nums = m[1].split(',').map(s => parseFloat(s.trim())).filter(n => !Number.isNaN(n));
        if (nums.length < 3) continue;
        const [r, g, b] = nums;
        const a = nums.length >= 4 ? nums[3] : 1;
        if (a < 0.25) continue;
        const lum = (0.299 * r + 0.587 * g + 0.114 * b) / 255;
        minLum = minLum === null ? lum : Math.min(minLum, lum);
      }
      return minLum;
    };
    const findBgEl = (el) => {
      let cur = el;
      while (cur && cur !== document.body) {
        const cs = getComputedStyle(cur);
        const bg = cs.backgroundColor;
        if (bg && bg !== 'rgba(0, 0, 0, 0)' && bg !== 'transparent') return bg;
        const gradMin = gradientMinLuminance(cs.backgroundImage);
        if (gradMin !== null && gradMin < 0.5) return 'rgb(11, 18, 40)';
        cur = cur.parentElement;
      }
      return getComputedStyle(document.body).backgroundColor;
    };
    const onScroll = () => {
      const nextScrolled = window.scrollY > 12;
      setScrolled(nextScrolled);
      const navEl = document.querySelector('.nav');
      const navH = navEl ? navEl.offsetHeight : 60;
      const y = navH + 8;
      // Sample multiple x positions; for each, walk through stacked elements and skip
      // fixed/sticky overlays (the nav itself, audience toggle, etc.) so we read the
      // ACTUAL background section beneath.
      const xs = [window.innerWidth * 0.25, window.innerWidth * 0.5, window.innerWidth * 0.75];
      let darkVotes = 0;
      let totalVotes = 0;
      xs.forEach(x => {
        const stack = document.elementsFromPoint(x, y) || [];
        const isOverlay = (el) => {
          let cur = el;
          while (cur && cur !== document.body) {
            const pos = getComputedStyle(cur).position;
            if (pos === 'fixed' || pos === 'sticky') return true;
            cur = cur.parentElement;
          }
          return false;
        };
        const target = stack.find(el => !isOverlay(el));
        if (!target) return;
        const bg = findBgEl(target);
        totalVotes++;
        if (isDark(bg)) darkVotes++;
      });
      const sampledDark = totalVotes > 0 && darkVotes > totalVotes / 2;
      const homeClinicTop =
        !nextScrolled && active === 'home' && audience === 'clinic';
      setOnDark(homeClinicTop || sampledDark);
    };
    onScroll();
    // Re-sample after fonts/layout settle so initial state is correct
    setTimeout(onScroll, 0);
    setTimeout(onScroll, 200);
    window.addEventListener('scroll', onScroll, { passive: true });
    window.addEventListener('resize', onScroll);
    return () => {
      window.removeEventListener('scroll', onScroll);
      window.removeEventListener('resize', onScroll);
    };
  }, [active, audience]);
  const [menuOpen, setMenuOpen] = useState(false);
  useEffect(() => {
    document.body.style.overflow = menuOpen ? 'hidden' : '';
    return () => { document.body.style.overflow = ''; };
  }, [menuOpen]);
  const links = [
    { href: '/', label: 'Home', key: 'home' },
    { href: '/patients', label: 'For Patients', key: 'patients' },
    { href: '/provideros', label: 'ProviderOS', key: 'provideros' },
    { href: '/pricing', label: 'Pricing', key: 'pricing' },
    { href: '/trust', label: 'Trust', key: 'trust' },
    { href: '/about', label: 'About', key: 'about' },
    { href: '/contact', label: 'Contact', key: 'contact' },
  ];
  return (
    <nav className={'nav' + (scrolled ? ' scrolled' : '') + (onDark ? ' on-dark' : '') + (menuOpen ? ' menu-open' : '')}>
      <a href="/" className="nav-logo">
        <img
          src={onDark ? '/assets/logo_synced_full_white.svg' : '/assets/logo_synced_full.svg'}
          alt="Synced"
        />
      </a>
      <div className="nav-spacer"/>
      <div className="nav-links">
        {links.map(l => (
          <a key={l.key} href={l.href} className={active === l.key ? 'active' : ''}>{l.label}</a>
        ))}
      </div>
      <div className="nav-cta">
        <a href="/demo" className="btn btn-secondary nav-btn-secondary" style={{padding:'10px 18px', fontSize:14}}>Book a Demo</a>
        <a href="/#download" className="btn btn-primary nav-btn-primary" style={{padding:'10px 18px', fontSize:14}}>
          Get the App <span className="arrow">→</span>
        </a>
      </div>
      <button
        className="nav-burger"
        aria-label={menuOpen ? 'Close menu' : 'Open menu'}
        aria-expanded={menuOpen}
        onClick={() => setMenuOpen(o => !o)}
      >
        <span className="mi" style={{fontSize:24}}>{menuOpen ? 'close' : 'menu'}</span>
      </button>
      {menuOpen && (
        <div className="nav-mobile-panel" onClick={() => setMenuOpen(false)}>
          <div className="nav-mobile-inner" onClick={e => e.stopPropagation()}>
            <div className="nav-mobile-links">
              {links.map(l => (
                <a key={l.key} href={l.href} className={active === l.key ? 'active' : ''}>{l.label}<span className="mi" style={{fontSize:20, opacity:0.5}}>arrow_forward</span></a>
              ))}
            </div>
            <div className="nav-mobile-cta">
              <a href="/demo" className="btn btn-secondary" style={{justifyContent:'center'}}>Book a Demo</a>
              <a href="/#download" className="btn btn-primary" style={{justifyContent:'center'}}>Get the App <span className="arrow">→</span></a>
            </div>
          </div>
        </div>
      )}
    </nav>
  );
};

const AudienceToggle = ({ value, onChange }) => (
  <div className="audience-toggle">
    <button className={value === 'patient' ? 'active' : ''} onClick={() => onChange('patient')}>For Patients</button>
    <button className={value === 'clinic' ? 'active' : ''} onClick={() => onChange('clinic')}>For Clinics</button>
  </div>
);

const Footer = () => (
  <footer className="footer">
    <div className="footer-inner">
      <div className="footer-brand">
        <a href="/" className="footer-logo">
          <img src="/assets/logo_synced_full_white.svg" alt="Synced"/>
        </a>
        <p>Healthcare, finally in sync. Built in Canada.</p>
        <div className="row gap-8" style={{marginTop:20}}>
          <a href="/contact" aria-label="Contact" className="center" style={{width:36, height:36, borderRadius:'50%', background:'rgba(255,255,255,0.08)'}}>
            <span className="mi" style={{fontSize:18, color:'white'}}>alternate_email</span>
          </a>
          <a href="#" className="center" style={{width:36, height:36, borderRadius:'50%', background:'rgba(255,255,255,0.08)'}}>
            <span className="mi" style={{fontSize:18, color:'white'}}>language</span>
          </a>
          <a href="#" className="center" style={{width:36, height:36, borderRadius:'50%', background:'rgba(255,255,255,0.08)'}}>
            <span className="mi" style={{fontSize:18, color:'white'}}>chat</span>
          </a>
        </div>
      </div>
      <div>
        <h4>Patients</h4>
        <ul>
          <li><a href="/patients">Find care</a></li>
          <li><a href="/patients#coverage">Check coverage</a></li>
          <li><a href="/#download">Download app</a></li>
          <li><a href="#help">Help center</a></li>
        </ul>
      </div>
      <div>
        <h4>Clinics</h4>
        <ul>
          <li><a href="/provideros">ProviderOS</a></li>
          <li><a href="/founding">Founding clinics</a></li>
          <li><a href="/demo">Book a demo</a></li>
          <li><a href="/pricing">Pricing</a></li>
        </ul>
      </div>
      <div>
        <h4>Company</h4>
        <ul>
          <li><a href="/about">About</a></li>
          <li><a href="/contact">Contact</a></li>
          <li><a href="/trust">Trust & privacy</a></li>
          <li><a href="#careers">Careers</a></li>
          <li><a href="#press">Press</a></li>
        </ul>
      </div>
      <div>
        <h4>Legal</h4>
        <ul>
          <li><a href="#terms">Terms</a></li>
          <li><a href="#privacy">Privacy</a></li>
          <li><a href="/trust">Security</a></li>
          <li><a href="#cookies">Cookies</a></li>
        </ul>
      </div>
    </div>
    <div className="footer-bottom">
      <div>© 2026 Synced Health Inc. · Toronto, Canada</div>
      <div className="row gap-16">
        <span>PIPEDA & PHIPA compliant</span>
        <span>·</span>
        <span>TELUS Health certified</span>
      </div>
    </div>
  </footer>
);

// Reveal-on-scroll. Inline-style based so no CSS caching can break the visible default.
const useReveal = () => {
  useEffect(() => {
    const els = Array.from(document.querySelectorAll('.reveal'));
    if (!els.length) return;
    const vh = window.innerHeight || 800;
    // Hide only the elements that are clearly below the fold; everything in view stays visible.
    const hidden = [];
    els.forEach(el => {
      const r = el.getBoundingClientRect();
      if (r.top > vh * 0.9) {
        el.style.opacity = '0';
        el.style.transform = 'translateY(24px)';
        hidden.push(el);
      }
    });
    if (typeof IntersectionObserver === 'undefined') {
      hidden.forEach(el => { el.style.opacity = ''; el.style.transform = ''; });
      return;
    }
    const reveal = el => { el.style.opacity = ''; el.style.transform = ''; el.classList.add('in'); };
    const obs = new IntersectionObserver((entries) => {
      entries.forEach(e => {
        if (e.isIntersecting) { reveal(e.target); obs.unobserve(e.target); }
      });
    }, { threshold: 0.12, rootMargin: '0px 0px -8% 0px' });
    hidden.forEach(el => obs.observe(el));
    // Failsafe: nothing should stay invisible past 2s.
    const t = setTimeout(() => hidden.forEach(reveal), 2000);
    return () => { obs.disconnect(); clearTimeout(t); };
  }, []);
};

// Parallax helper for layers; pass refs and speeds
const useParallax = () => {
  useEffect(() => {
    const els = document.querySelectorAll('[data-parallax]');
    const onScroll = () => {
      const y = window.scrollY;
      els.forEach(el => {
        const speed = parseFloat(el.dataset.parallax) || 0.1;
        el.style.transform = `translate3d(0, ${y * speed}px, 0)`;
      });
    };
    onScroll();
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);
};

// Mock product cards (used across pages)
const AppointmentCard = ({ animated }) => (
  <div className="surface" style={{
    padding: 22, width: 320,
    border: '1px solid rgba(11,18,40,0.04)',
  }}>
    <div className="row gap-12" style={{alignItems:'center', marginBottom:14}}>
      <div className="center" style={{
        width: 36, height: 36, borderRadius: 12,
        background: 'var(--soft-mint)', color: '#1a7a3d'
      }}>
        <span className="mi mi-fill" style={{fontSize:20}}>check_circle</span>
      </div>
      <div className="col" style={{gap:2}}>
        <div style={{fontSize:11, fontWeight:600, letterSpacing:'0.08em', textTransform:'uppercase', color:'#1a7a3d'}}>Appointment Confirmed</div>
        <div style={{fontSize:13, color:'var(--grey-60)'}}>In Sync · 2 min ago</div>
      </div>
    </div>
    <div style={{fontFamily:'var(--serif)', fontSize:24, fontWeight:500, letterSpacing:'-0.01em', lineHeight:1.15, marginBottom:6}}>
      60-min Massage Therapy
    </div>
    <div style={{fontSize:14, color:'var(--grey-60)', marginBottom:18}}>
      with R. Chen, RMT · Mount Pleasant
    </div>
    <div className="row gap-12" style={{paddingBottom:14, borderBottom:'1px solid var(--grey-10)'}}>
      <div className="col flex-1">
        <div style={{fontSize:11, color:'var(--grey-60)', fontWeight:600, letterSpacing:'0.06em', textTransform:'uppercase'}}>Tuesday</div>
        <div style={{fontSize:18, fontWeight:600, color:'var(--ink)'}}>Oct 28 · 10:30 AM</div>
      </div>
      <div className="center" style={{
        width: 44, height: 44, borderRadius: 12,
        background: 'var(--brand-tertiary)'
      }}>
        <span className="mi" style={{fontSize:22, color:'var(--brand-primary)'}}>event</span>
      </div>
    </div>
    <div className="row" style={{justifyContent:'space-between', alignItems:'center', marginTop:14}}>
      <div className="col" style={{gap:2}}>
        <div style={{fontSize:11, color:'var(--grey-60)', fontWeight:600, letterSpacing:'0.06em', textTransform:'uppercase'}}>Your cost</div>
        <div className="row gap-8" style={{alignItems:'baseline'}}>
          <div style={{fontSize:22, fontWeight:700, color:'var(--ink)'}}>$0.00</div>
          <div style={{fontSize:12, color:'var(--grey-60)', textDecoration:'line-through'}}>$120</div>
        </div>
      </div>
      <div className="tag-pill" style={{background:'var(--soft-mint)', borderColor:'transparent', color:'#1a7a3d'}}>
        <span className="dot" style={{background:'#1a7a3d'}}></span>
        Fully covered
      </div>
    </div>
  </div>
);

const CoverageCard = () => (
  <div className="surface" style={{padding:18, width:280}}>
    <div style={{fontSize:11, fontWeight:600, letterSpacing:'0.08em', textTransform:'uppercase', color:'var(--grey-60)', marginBottom:14}}>
      Sun Life · Massage Therapy
    </div>
    <div className="row" style={{justifyContent:'space-between', alignItems:'baseline', marginBottom:10}}>
      <div style={{fontSize:13, color:'var(--grey-70)'}}>Annual maximum</div>
      <div style={{fontSize:13, fontWeight:600}}>$500</div>
    </div>
    <div style={{height:8, borderRadius:99, background:'var(--grey-5)', overflow:'hidden', marginBottom:6}}>
      <div style={{width:'62%', height:'100%', borderRadius:99, background:'linear-gradient(90deg, var(--mark-cyan), var(--brand-secondary))'}}></div>
    </div>
    <div className="row" style={{justifyContent:'space-between', fontSize:12, color:'var(--grey-60)'}}>
      <span>$310 used</span>
      <span style={{color:'var(--ink)', fontWeight:600}}>$190 left</span>
    </div>
    <div style={{height:1, background:'var(--grey-10)', margin:'14px 0'}}></div>
    <div className="row gap-8" style={{alignItems:'center'}}>
      <span className="mi" style={{fontSize:18, color:'#1a7a3d'}}>verified</span>
      <div style={{fontSize:12, color:'var(--grey-70)'}}>Verified just now · No surprises at checkout</div>
    </div>
  </div>
);

const ProviderCard = () => (
  <div className="surface" style={{padding:16, width:260}}>
    <div className="row gap-12" style={{alignItems:'center'}}>
      <div className="center" style={{width:48, height:48, borderRadius:'50%', background:'var(--soft-pink)', fontFamily:'var(--serif)', fontSize:20, color:'var(--brand-primary)', fontWeight:500}}>RC</div>
      <div className="col" style={{gap:2}}>
        <div style={{fontSize:14, fontWeight:600}}>Rachel Chen, RMT</div>
        <div style={{fontSize:12, color:'var(--grey-60)'}}>Massage · 8 yrs</div>
      </div>
    </div>
    <div className="row gap-8" style={{marginTop:12, flexWrap:'wrap'}}>
      <span className="tag-pill" style={{fontSize:11, padding:'4px 10px'}}>Deep tissue</span>
      <span className="tag-pill" style={{fontSize:11, padding:'4px 10px'}}>Prenatal</span>
    </div>
    <div className="row gap-8" style={{marginTop:14, alignItems:'center'}}>
      <span className="mi" style={{fontSize:16, color:'#F59E0B'}}>star</span>
      <div style={{fontSize:13, fontWeight:600}}>4.9</div>
      <div style={{fontSize:12, color:'var(--grey-60)'}}>· 184 reviews</div>
    </div>
  </div>
);

// Shared clinic UI mock (snapshot / soap / claim)
const ClinicMock = ({ kind, tone, icon }) => {
  if (kind === 'snapshot') {
    return (
      <div style={{position:'relative', height:340}}>
        <div className="surface" style={{padding:22, position:'absolute', inset:0}}>
          <div className="row gap-12" style={{alignItems:'center', marginBottom:16}}>
            <div className="center" style={{width:48, height:48, borderRadius:'50%', background:'var(--soft-pink)', fontFamily:'var(--serif)', fontWeight:600, color:'var(--brand-primary)'}}>JT</div>
            <div className="col flex-1">
              <div style={{fontWeight:600, fontSize:14}}>Jade Tang</div>
              <div style={{fontSize:12, color:'var(--grey-60)'}}>Returning · 9:30 AM · Physio</div>
            </div>
            <div className="tag-pill" style={{background:tone || 'var(--soft-mint)', borderColor:'transparent'}}>
              <span className="mi mi-fill" style={{fontSize:14, color:'#1a7a3d'}}>auto_awesome</span>
              AI Snapshot
            </div>
          </div>
          <div style={{padding:14, background:'var(--grey-5)', borderRadius:14, marginBottom:10}}>
            <div style={{fontSize:11, fontWeight:700, letterSpacing:'0.06em', textTransform:'uppercase', color:'var(--brand-primary)', marginBottom:6}}>Last visit (Oct 14)</div>
            <div style={{fontSize:13, lineHeight:1.5, color:'var(--grey-80)'}}>R lower back, L4-L5 mild radiculopathy. Improvement 40% post manual therapy. Home exercise compliance: high.</div>
          </div>
          <div style={{padding:14, background:'var(--grey-5)', borderRadius:14}}>
            <div style={{fontSize:11, fontWeight:700, letterSpacing:'0.06em', textTransform:'uppercase', color:'var(--brand-primary)', marginBottom:6}}>Plan today</div>
            <div style={{fontSize:13, lineHeight:1.5, color:'var(--grey-80)'}}>Continue manual therapy + progress to dynamic stabilization. Re-assess SLR.</div>
          </div>
        </div>
      </div>
    );
  }
  if (kind === 'soap') {
    return (
      <div style={{position:'relative', height:360}}>
        <div className="surface" style={{padding:22, position:'absolute', inset:0, fontFamily:'ui-monospace, monospace', fontSize:12, lineHeight:1.6, color:'var(--grey-80)'}}>
          <div className="row" style={{justifyContent:'space-between', alignItems:'center', marginBottom:14, fontFamily:'var(--font-sans)'}}>
            <div style={{fontSize:12, fontWeight:700, color:'var(--brand-primary)'}}>SOAP NOTE · Draft</div>
            <div className="tag-pill" style={{background:tone || 'var(--soft-sky)', borderColor:'transparent', fontFamily:'var(--font-sans)'}}>
              <span className="mi" style={{fontSize:14, color:'var(--brand-primary)'}}>auto_awesome</span>
              Generated · 4s
            </div>
          </div>
          <div><span style={{color:'var(--brand-primary)', fontWeight:700}}>S:</span> Pt reports L lower back pain 4/10, ↓from 7/10 last week. Sleeping better.</div>
          <div style={{marginTop:8}}><span style={{color:'var(--brand-primary)', fontWeight:700}}>O:</span> ROM lumbar flexion 70° (was 55°). SLR neg bilaterally.</div>
          <div style={{marginTop:8}}><span style={{color:'var(--brand-primary)', fontWeight:700}}>A:</span> Improving lumbar strain. Dynamic phase.</div>
          <div style={{marginTop:8}}><span style={{color:'var(--brand-primary)', fontWeight:700}}>P:</span> Manual therapy <span style={{background:'var(--brand-tertiary)', padding:'1px 4px', borderRadius:3}}>+ stab progression</span>. Re-eval 1 wk.</div>
          <div className="row gap-8" style={{marginTop:16, fontFamily:'var(--font-sans)'}}>
            <button className="btn btn-primary" style={{padding:'8px 14px', fontSize:12}}>Approve & Sign</button>
            <button className="btn btn-secondary" style={{padding:'8px 14px', fontSize:12}}>Edit</button>
          </div>
        </div>
      </div>
    );
  }
  return (
    <div style={{position:'relative', height:340}}>
      <div className="surface" style={{padding:22, position:'absolute', inset:0}}>
        <div className="row" style={{justifyContent:'space-between', alignItems:'center', marginBottom:18}}>
          <div style={{fontSize:13, fontWeight:700, color:'var(--brand-primary)'}}>Claim · TELUS Health</div>
          <div className="tag-pill" style={{background:'var(--soft-mint)', borderColor:'transparent', color:'#1a7a3d'}}>
            <span className="mi" style={{fontSize:14}}>check_circle</span>
            Ready to submit
          </div>
        </div>
        {[
          {label:'Patient policy match'},
          {label:'Service code (CMA-001)'},
          {label:'Provider credentials'},
          {label:'Diagnostic code present'},
          {label:'Coverage limit checked'},
        ].map((row, i) => (
          <div key={i} className="row gap-12" style={{alignItems:'center', padding:'10px 0', borderTop: i ? '1px solid var(--grey-10)':'none'}}>
            <span className="mi mi-fill" style={{fontSize:18, color:'#1a7a3d'}}>check_circle</span>
            <div style={{flex:1, fontSize:13, color:'var(--ink)'}}>{row.label}</div>
            <div style={{fontSize:11, color:'var(--grey-60)', fontWeight:600}}>OK</div>
          </div>
        ))}
        <div style={{padding:14, background:tone || 'var(--brand-tertiary)', borderRadius:12, marginTop:12, display:'flex', justifyContent:'space-between', alignItems:'center'}}>
          <div>
            <div style={{fontSize:11, fontWeight:700, letterSpacing:'0.06em', textTransform:'uppercase', color:'var(--brand-primary)'}}>Expected payment</div>
            <div style={{fontFamily:'var(--serif)', fontSize:24, fontWeight:600, marginTop:2}}>$98.40</div>
          </div>
          <div style={{fontSize:12, color:'var(--brand-primary)', fontWeight:600}}>3-5 days</div>
        </div>
      </div>
    </div>
  );
};

Object.assign(window, {
  Nav, AudienceToggle, Footer, useReveal, useParallax,
  AppointmentCard, CoverageCard, ProviderCard, ClinicMock,
});
