/* wrapped in an IIFE: keeps these declarations out of the global lexical scope,
   so each page's inline script can re-declare them from window. */
(function () {
/* global React */
/* ============================================================
   HospitAlert — shared site primitives (v2, app-aligned)
   Loaded by every page as <script type="text/babel" src="/js/shared.jsx">.
   Exposes on window: Icon, PATHS, LogoMark, BrandLogo, Nav, Footer,
   EKGMonitor, QRPlaceholder, EmergencyMedCard, AlertCard, CTA.
   ============================================================ */

const Icon = ({ d, size = 20, stroke = 2, fill = 'none' }) => (
  <svg viewBox="0 0 24 24" width={size} height={size} fill={fill} stroke="currentColor"
    strokeWidth={stroke} strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><path d={d} /></svg>
);

const PATHS = {
  pulse: "M3 12h4l2-4 3 8 2-4h5",
  bell: "M15 17h5l-1.4-1.4A2 2 0 0118 14.2V11a6 6 0 10-12 0v3.2a2 2 0 01-.6 1.4L4 17h5m6 0a3 3 0 11-6 0",
  shield: "M12 3l8 3v6c0 5-4 8-8 9-4-1-8-4-8-9V6l8-3z",
  lock: "M6 11h12v9H6zM9 11V8a3 3 0 016 0v3",
  phone: "M22 16.92v3a2 2 0 01-2.18 2 19.79 19.79 0 01-8.63-3.07 19.5 19.5 0 01-6-6A19.79 19.79 0 012.12 4.18 2 2 0 014.11 2h3a2 2 0 012 1.72c.12.91.31 1.8.57 2.66a2 2 0 01-.45 2.11L8 9.91a16 16 0 006 6l1.42-1.42a2 2 0 012.11-.45c.86.26 1.75.45 2.66.57A2 2 0 0122 16.92z",
  check: "M5 12l5 5L20 7",
  users: "M17 21v-2a4 4 0 00-4-4H7a4 4 0 00-4 4v2M9 11a4 4 0 100-8 4 4 0 000 8zm12 10v-2a4 4 0 00-3-3.87M16 3.13a4 4 0 010 7.75",
  clock: "M12 8v4l3 2M21 12a9 9 0 11-18 0 9 9 0 0118 0z",
  battery: "M2 9h16v6H2zM18 11h2v2h-2",
  map: "M9 20l-6-3V4l6 3 6-3 6 3v13l-6-3-6 3zM9 7v13M15 4v13",
  eye: "M1 12s4-7 11-7 11 7 11 7-4 7-11 7S1 12 1 12zM12 9a3 3 0 100 6 3 3 0 000-6z",
  play: "M6 4l14 8L6 20V4z",
  arrow: "M5 12h14M13 5l7 7-7 7",
  hospital: "M12 2v20M2 12h20M7 22V8h10v14M9 14h2m2 0h2M9 18h2m2 0h2",
  warn: "M10.3 3.9 1.8 18a2 2 0 0 0 1.7 3h17a2 2 0 0 0 1.7-3L13.7 3.9a2 2 0 0 0-3.4 0zM12 9v4m0 4h.01",
  volume: "M11 5 6 9H2v6h4l5 4V5zM15.5 8.5a5 5 0 0 1 0 7",
  drop: "M12 2.7 6.5 9.6a7 7 0 1 0 11 0L12 2.7z",
  person: "M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2M9 11a4 4 0 1 0 0-8 4 4 0 0 0 0 8z",
  chevronLeft: "M15 18l-6-6 6-6",
  chevronRight: "M9 18l6-6-6-6",
  pencil: "M12 20h9M16.5 3.5a2.1 2.1 0 013 3L7 19l-4 1 1-4 12.5-12.5z",
  filter: "M4 6h16M7 12h10M10 18h4",
  keyboard: "M2 6h20v12H2zM6 10h.01M10 10h.01M14 10h.01M18 10h.01M7 14h10",
};

const prefersReducedMotion = () =>
  typeof window !== 'undefined' && window.matchMedia
    ? window.matchMedia('(prefers-reduced-motion: reduce)').matches : false;

/* ---------- LOGO — flat mint tile, forest EKG stroke (matches the app icon) ---------- */
const LogoMark = ({ size = 48 }) => (
  <svg width={size} height={size} viewBox="0 0 100 100" fill="none" aria-hidden="true"
    style={{ filter: 'drop-shadow(0 6px 16px rgba(74,222,128,0.30))', flexShrink: 0 }}>
    <rect x="0" y="0" width="100" height="100" rx="27" fill="#4ADE80" />
    <path d="M 15 52 L 32 52 L 39 40 L 48 66 L 57 30 L 64 60 L 69 52 L 85 52"
      stroke="#0C2B1A" strokeWidth="7" strokeLinecap="round" strokeLinejoin="round" fill="none" />
  </svg>
);

const LOGO_SIZE = { sm: 34, md: 44, lg: 60, xl: 104 };
const LOGO_TEXT = { sm: 20, md: 26, lg: 36, xl: 58 };
const LOGO_GAP = { sm: 10, md: 13, lg: 16, xl: 22 };

const BrandLogo = ({ size = 'md', mono = false, href = '/' }) => (
  <a href={href} className={`brand-logo ${size}`} aria-label="HospitAlert home"
    style={{ display: 'inline-flex', alignItems: 'center', gap: LOGO_GAP[size] || 13, color: mono ? 'white' : '#0C2B1A' }}>
    <LogoMark size={LOGO_SIZE[size] || 44} />
    <span style={{ fontFamily: 'Urbanist, sans-serif', fontWeight: 800, fontSize: LOGO_TEXT[size] || 26, letterSpacing: '-0.03em', lineHeight: 1 }}>
      <span>Hospit</span><span style={{ color: '#4ADE80' }}>Alert</span>
    </span>
  </a>
);

/* ---------- EKG MONITOR — canvas heart-rate trace ---------- */
const EKGMonitor = ({ height = 180, color = '#4ADE80', hud = true, beats = 7, baseBpm = 72, tag = 'HospitAlert · live', bare = false }) => {
  const cvsRef = React.useRef(null);
  const bpmRef = React.useRef(null);
  const heartRef = React.useRef(null);
  React.useEffect(() => {
    const cvs = cvsRef.current; if (!cvs) return;
    const dpr = 2;
    const W = Math.max(600, cvs.offsetWidth) * dpr, H = height * dpr;
    cvs.width = W; cvs.height = H;
    const ctx = cvs.getContext('2d');
    const pxBeat = W / beats, mid = H * 0.56, amp = H * 0.38;
    const bump = (p, a, b, h) => (p >= a && p <= b) ? h * Math.sin(Math.PI * (p - a) / (b - a)) : 0;
    // P wave, Q dip, R spike, S dip, T wave — classic sinus rhythm
    const wave = p => bump(p, 0.08, 0.17, 0.11) + bump(p, 0.205, 0.235, -0.09) + bump(p, 0.235, 0.28, 1.0) + bump(p, 0.28, 0.315, -0.24) + bump(p, 0.42, 0.57, 0.20);
    let x = 0, py = mid, lastBeat = -1, raf, timers = [];
    const gap = W * 0.05, speed = Math.max(3, W / 1500) * 1.6;
    const step = () => {
      let nx = x + speed;
      if (nx >= W) { ctx.clearRect(0, 0, gap, H); x = 0; nx = speed; py = mid - wave(0) * amp; }
      const p = (nx / pxBeat) % 1;
      const beatIdx = Math.floor(nx / pxBeat);
      if (beatIdx !== lastBeat) {
        lastBeat = beatIdx;
        if (heartRef.current) {
          heartRef.current.classList.add('beat');
          timers.push(setTimeout(() => heartRef.current && heartRef.current.classList.remove('beat'), 150));
        }
        if (bpmRef.current && beatIdx % 2 === 0) bpmRef.current.textContent = baseBpm + Math.round((Math.random() - 0.5) * 7);
      }
      const ny = mid - (wave(p) + (Math.random() - 0.5) * 0.014) * amp;
      ctx.clearRect(x + 1, 0, gap, H);
      ctx.save();
      ctx.strokeStyle = color; ctx.lineWidth = 3; ctx.lineCap = 'round'; ctx.lineJoin = 'round';
      ctx.shadowColor = color; ctx.shadowBlur = 16;
      ctx.beginPath(); ctx.moveTo(x, py); ctx.lineTo(nx, ny); ctx.stroke();
      ctx.fillStyle = '#D7FFE6'; ctx.shadowBlur = 22;
      ctx.beginPath(); ctx.arc(nx, ny, 4.5, 0, Math.PI * 2); ctx.fill();
      ctx.restore();
      x = nx; py = ny;
      raf = requestAnimationFrame(step);
    };
    if (prefersReducedMotion()) {
      ctx.strokeStyle = color; ctx.lineWidth = 3; ctx.beginPath();
      for (let sx = 0; sx <= W; sx += 4) { const sy = mid - wave((sx / pxBeat) % 1) * amp; sx === 0 ? ctx.moveTo(sx, sy) : ctx.lineTo(sx, sy); }
      ctx.stroke();
    } else raf = requestAnimationFrame(step);
    return () => { cancelAnimationFrame(raf); timers.forEach(clearTimeout); };
  }, [height, color, beats, baseBpm]);
  return (
    <div className={bare ? '' : 'ekg-wrap'} style={{ height, position: 'relative', overflow: 'hidden' }}>
      {bare ? null : <div className="ekg-grid" aria-hidden="true"></div>}
      <canvas ref={cvsRef} className="ekg-cvs" style={{ height }} aria-hidden="true"></canvas>
      {bare || !tag ? null : <div className="ekg-tag">{tag}</div>}
      {hud ? (
        <div className="ekg-hud">
          <span ref={heartRef} className="ekg-heart"></span>
          <span ref={bpmRef} className="ekg-bpm">72</span>
          <span className="ekg-unit">BPM</span>
        </div>
      ) : null}
    </div>
  );
};

/* ---------- NAV ---------- */
const NAV_ITEMS = [
  { label: 'Demo', href: '/#demo' },
  { label: 'Features', href: '/features/' },
  { label: 'How it works', href: '/how-it-works/' },
  { label: 'Privacy', href: '/privacy/' },
  { label: 'FAQ', href: '/faq/' },
];

const Nav = ({ active = '' }) => {
  const [open, setOpen] = React.useState(false);
  const onHome = typeof window !== 'undefined' && /^\/(index\.html)?$/.test(window.location.pathname);
  return (
    <nav className={`nav ${open ? 'open' : ''}`} aria-label="Primary">
      <div className="wrap nav-inner">
        <BrandLogo size="md" mono />
        <ul id="primary-menu">
          {NAV_ITEMS.map(i => (
            <li key={i.label} className={i.label === active ? 'active' : ''}>
              <a href={onHome && i.href === '/#demo' ? '#demo' : i.href}
                aria-current={i.label === active ? 'page' : undefined}
                onClick={() => setOpen(false)}>{i.label}</a>
            </li>
          ))}
        </ul>
        <div className="right">
          <a href="/request-demo/" className="btn primary sm">Request Demo</a>
          <button className="menu-toggle" aria-label={open ? 'Close navigation' : 'Open navigation'}
            aria-expanded={open} aria-controls="primary-menu"
            onClick={() => setOpen(o => !o)}>{open ? '×' : '☰'}</button>
        </div>
      </div>
    </nav>
  );
};

/* ---------- FOOTER ---------- */
const Footer = () => (
  <footer className="footer">
    <div className="wrap">
      <div className="grid">
        <div>
          <BrandLogo size="lg" mono />
          <p className="body" style={{ marginTop: 16, maxWidth: 280 }}>
            Real-time alerts when a loved one reaches a hospital or ER. Privacy-first, mutual opt-in.
          </p>
          <div style={{ display: 'flex', gap: 10, marginTop: 20, flexWrap: 'wrap' }}>
            <a href="/request-demo/" className="btn primary sm">Request Demo</a>
          </div>
        </div>
        <div><h5>Product</h5><ul>
          <li><a href="/#demo">Demo</a></li>
          <li><a href="/features/">Features</a></li>
          <li><a href="/how-it-works/">How it works</a></li>
          <li><a href="/request-demo/">Request Demo</a></li>
        </ul></div>
        <div><h5>Trust</h5><ul>
          <li><a href="/privacy/">Privacy</a></li>
          <li><a href="/privacy-policy/">Privacy Policy</a></li>
          <li><a href="/security/">Security</a></li>
          <li><a href="/accessibility/">Accessibility</a></li>
        </ul></div>
        <div><h5>Company</h5><ul>
          <li><a href="mailto:admin@hospitalert.com">Contact</a></li>
          <li><a href="/request-demo/">Talk to sales</a></li>
        </ul></div>
        <div><h5>Support</h5><ul>
          <li><a href="/faq/">Help center</a></li>
          <li><a href="/faq/">FAQ</a></li>
          <li><a href="mailto:admin@hospitalert.com">admin@hospitalert.com</a></li>
        </ul></div>
      </div>
      <div className="legal">
        <div>© {new Date().getFullYear()} HospitAlert LLC. All rights reserved.</div>
        <div>
          <a href="/privacy/">Privacy</a>
          <a href="/privacy-policy/">Privacy Policy</a>
          <a href="/security/">Security</a>
          <a href="/accessibility/">Accessibility</a>
        </div>
      </div>
    </div>
  </footer>
);

/* ---------- QR PLACEHOLDER ----------
   Deterministic stand-in. Replace with a real QR to the health-record URL
   before launch. */
const QRPlaceholder = ({ size = 108 }) => {
  const cells = [];
  let seed = 7;
  for (let r = 0; r < 13; r++) for (let c = 0; c < 13; c++) {
    seed = (seed * 31 + r * 13 + c) % 97;
    if (seed % 2 === 0 && !((r < 4 && c < 4) || (r < 4 && c > 8) || (r > 8 && c < 4)))
      cells.push(<rect key={r + '-' + c} x={8 + c * 6} y={8 + r * 6} width={5} height={5} fill="#111" />);
  }
  const finder = (x, y) => (
    <g key={x + ',' + y}>
      <rect x={x} y={y} width={22} height={22} fill="#111" />
      <rect x={x + 4} y={y + 4} width={14} height={14} fill="#fff" />
      <rect x={x + 8} y={y + 8} width={6} height={6} fill="#111" />
    </g>
  );
  return (
    <svg width={size} height={size} viewBox="0 0 94 94" aria-hidden="true"
      style={{ display: 'block', background: 'white', borderRadius: 12, maxWidth: '100%' }}>
      {cells}{finder(8, 8)}{finder(64, 8)}{finder(8, 64)}
    </svg>
  );
};

/* ---------- EMERGENCY MEDICAL CARD — mirrors the app's Medical Card screen ---------- */
const EmergencyMedCard = () => {
  const rowStyle = { background: '#FDECEC', color: '#C0362C', borderRadius: 12, padding: '11px 16px', fontFamily: 'Poppins, sans-serif', fontSize: 14.5, lineHeight: 1.2 };
  const contact = (name, phone) => (
    <div key={name} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 12 }}>
      <span style={{ fontSize: 15, color: '#111827' }}>{name}</span>
      <span style={{ fontFamily: 'JetBrains Mono, monospace', fontSize: 14, color: '#9AA3AF' }}>{phone}</span>
    </div>
  );
  return (
    <div style={{ background: '#F4F5F7', borderRadius: 22, padding: 14, boxShadow: '0 18px 44px -18px rgba(0,0,0,0.45)', fontFamily: 'Poppins, sans-serif', display: 'flex', flexDirection: 'column', gap: 14 }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '2px 4px 0' }}>
        <div style={{ width: 34, height: 34, borderRadius: 999, background: 'white', display: 'grid', placeItems: 'center', color: '#111827', boxShadow: '0 1px 3px rgba(0,0,0,0.08)' }}>
          <Icon d={PATHS.chevronLeft} size={16} stroke={2.4} />
        </div>
        <div style={{ fontFamily: 'Urbanist, sans-serif', fontWeight: 700, fontSize: 20, color: '#111827', flex: 1 }}>Medical Card</div>
        <span style={{ color: '#111827', display: 'inline-flex' }}><Icon d={PATHS.pencil} size={18} stroke={1.8} /></span>
      </div>
      <div style={{ background: 'white', borderRadius: 18, padding: '20px 18px' }}>
        <div style={{ fontFamily: 'Urbanist, sans-serif', fontWeight: 700, fontSize: 24, color: '#111827', letterSpacing: '-0.01em' }}>Emily Carter</div>
        <div style={{ color: '#9AA3AF', fontSize: 15, marginTop: 2 }}>62 F</div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 9, marginTop: 16 }}>
          <div style={rowStyle}>Code: FULL</div>
          <div style={rowStyle}>Blood thinner: none</div>
          <div style={rowStyle}>No known drug allergies</div>
          <div style={rowStyle}>Contrast allergy</div>
        </div>
        <div style={{ fontFamily: 'Urbanist, sans-serif', fontWeight: 700, fontSize: 12, letterSpacing: '0.08em', color: '#9AA3AF', marginTop: 22 }}>EMERGENCY CONTACTS</div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10, marginTop: 12 }}>
          {contact('Sarah Mitchell', '(206) 555-0142')}
          {contact('David Carter', '(206) 555-0119')}
          {contact('Dr. Alan Reyes', '(425) 555-0187')}
        </div>
      </div>
      <div style={{ background: 'white', borderRadius: 18, padding: 18, display: 'grid', placeItems: 'center' }}>
        <QRPlaceholder size={190} />
      </div>
    </div>
  );
};

/* ---------- ALERT CARD — an Alert History entry, lifted out of the app ---------- */
const AlertCard = () => (
  <div style={{ background: 'white', borderRadius: 20, padding: '18px 20px', boxShadow: '0 18px 44px -18px rgba(0,0,0,0.45)', color: '#111827', fontFamily: 'Poppins, sans-serif' }}>
    <div style={{ fontSize: 13, color: '#9CA3AF' }}>Today · 9:25 AM</div>
    <div style={{ display: 'flex', alignItems: 'center', gap: 14, marginTop: 12 }}>
      <div style={{ width: 48, height: 48, borderRadius: 14, background: '#DCFCE7', color: '#16A34A', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
        <Icon d={PATHS.check} size={22} stroke={2.5} />
      </div>
      <div style={{ minWidth: 0 }}>
        <div style={{ fontFamily: 'Urbanist, sans-serif', fontWeight: 700, fontSize: 17, letterSpacing: '-0.01em' }}>Emily Carter</div>
        <div style={{ marginTop: 3, fontSize: 13.5, color: '#6B7280', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>at Lakeside Regional Medical Center, Seattle, WA</div>
      </div>
    </div>
  </div>
);

/* ---------- CLOSING CTA — shared across pages ---------- */
const CTA = ({ title = 'See it in action.', body = "Tell us a bit about your family or organization. We'll walk you through a live setup in 15 minutes." }) => (
  <section className="section" style={{ paddingTop: 0 }}>
    <div className="wrap">
      <div style={{ background: '#101828', border: '1px solid rgba(74,222,128,0.15)', borderRadius: 24, padding: '64px 48px', textAlign: 'center', position: 'relative', overflow: 'hidden', color: 'white' }}>
        <div aria-hidden="true" style={{ position: 'absolute', inset: 0, pointerEvents: 'none', background: 'radial-gradient(600px 300px at 50% -10%, rgba(74,222,128,0.18), transparent 60%)' }}></div>
        <div style={{ position: 'relative' }}>
          <h2 className="h-display h2" style={{ color: 'white' }}>{title}</h2>
          <p className="lede" style={{ marginTop: 14, maxWidth: 540, marginLeft: 'auto', marginRight: 'auto', color: 'rgba(255,255,255,0.7)' }}>{body}</p>
          <div className="hero-actions" style={{ justifyContent: 'center', marginTop: 28 }}>
            <a href="/request-demo/" className="btn primary lg">Request a demo</a>
            <a href="mailto:admin@hospitalert.com?subject=HospitAlert%20—%20talk%20to%20sales" className="btn ghost-dark lg">Talk to sales</a>
          </div>
        </div>
      </div>
    </div>
  </section>
);

Object.assign(window, {
  Icon, PATHS, prefersReducedMotion, LogoMark, BrandLogo, Nav, Footer,
  EKGMonitor, QRPlaceholder, EmergencyMedCard, AlertCard, CTA,
});
})();
