/* global React, ReactDOM */
const { useState, useEffect, useRef, createContext, useContext } = React;

// ============ Language context ============
const LangContext = createContext('en');
function useT() {
  const lang = useContext(LangContext);
  return (en, fr) => (lang === 'fr' ? fr : en);
}
Object.assign(window, { LangContext, useT });

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

// ============ Icon button ============
function IconBtn({ icon, onClick, label, title }) {
  return (
    <button className="m3-iconbtn" onClick={onClick} aria-label={label || title} title={title}>
      <span className="material-symbols-outlined">{icon}</span>
    </button>
  );
}

// ============ Top App Bar ============
function TopAppBar({ theme, onToggleTheme, lang, onLang }) {
  const t = useT();
  const [scrolled, setScrolled] = useState(false);
  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 8);
    onScroll();
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);
  return (
    <header className={`m3-appbar ${scrolled ? 'scrolled' : ''}`} role="banner">
      <div className="m3-appbar__inner">
        <a href="#top" className="m3-appbar__brand">
          <span className="m3-appbar__brand-mark">
            <span className="material-symbols-outlined">shield_lock</span>
          </span>
          WalledCare
        </a>
        <nav className="m3-appbar__nav" aria-label={t('Primary', 'Principal')}>
          <a href="#apps">{t('Apps', 'Applications')}</a>
          <a href="#architecture">{t('Architecture', 'Architecture')}</a>
          <a href="#reasons">{t('Why', 'Pourquoi')}</a>
          <a href="#blog">Blog</a>
          <a href="#pilot">{t('Pilot', 'Pilote')}</a>
          <a href="#contact">{t('Contact', 'Contact')}</a>
        </nav>
        <div className="m3-appbar__spacer" />
        <div className="m3-appbar__actions">
          <div className="m3-segmented" role="group" aria-label={t('Language', 'Langue')}>
            <button
              className={lang === 'en' ? 'active' : ''}
              aria-pressed={lang === 'en'}
              onClick={() => onLang('en')}
            >EN</button>
            <button
              className={lang === 'fr' ? 'active' : ''}
              aria-pressed={lang === 'fr'}
              onClick={() => onLang('fr')}
            >FR</button>
          </div>
          <IconBtn
            icon={theme === 'dark' ? 'light_mode' : 'dark_mode'}
            onClick={onToggleTheme}
            title={t('Toggle theme', 'Changer de thème')}
          />
          <a href="#contact" className="m3-btn m3-btn--filled hai-cta-desktop">
            <span className="material-symbols-outlined">bolt</span>
            {t('Request a pilot', 'Demander un pilote')}
          </a>
        </div>
      </div>
    </header>
  );
}

// ============ Hero ============
function Hero() {
  const t = useT();
  return (
    <section id="top" className="hero">
      <div className="hero__meshbg" aria-hidden="true" />
      <div className="container hero__grid">
        <div className="hero__content">
          <div data-reveal>
            <span className="eyebrow">{t('On-premises clinical AI', 'IA clinique sur site')}</span>
          </div>
          <h1 className="hero__title" data-reveal data-reveal-delay="1">
            {t('AI that stays', 'Une IA qui reste')}<br/><em>{t('inside the walls.', 'entre vos murs.')}</em>
          </h1>
          <p className="hero__sub" data-reveal data-reveal-delay="2">
            {t(
              'Nine clinical apps. One private network. Zero data leaving your hospital.',
              'Neuf applications cliniques. Un réseau privé. Aucune donnée ne quitte votre hôpital.'
            )}
          </p>
          <div className="hero__actions" data-reveal data-reveal-delay="3">
            <a href="#contact" className="m3-btn m3-btn--filled">
              {t('Request a pilot', 'Demander un pilote')}
              <span className="material-symbols-outlined">arrow_forward</span>
            </a>
            <a href="#apps" className="m3-btn m3-btn--outlined">{t('See the apps', 'Voir les applications')}</a>
          </div>
          <div className="hero__chips" data-reveal data-reveal-delay="4">
            <span className="m3-chip selected"><span className="material-symbols-outlined">verified_user</span>{t('PIPEDA', 'LPRPDE')}</span>
            <span className="m3-chip selected"><span className="material-symbols-outlined">verified_user</span>HIPAA</span>
            <span className="m3-chip"><span className="material-symbols-outlined">dns</span>{t('On-prem', 'Sur site')}</span>
            <span className="m3-chip"><span className="material-symbols-outlined">translate</span>EN / FR</span>
            <span className="m3-chip"><span className="material-symbols-outlined">update</span>v0.9</span>
          </div>
        </div>
        <div className="hero__visual" data-reveal data-reveal-delay="2">
          <HeroPortalMockup />
        </div>
      </div>
    </section>
  );
}

function HeroPortalMockup() {
  const t = useT();
  const rows = [
    { s: 'S', c: 'var(--md-sys-primary-container)', oc: 'var(--md-sys-on-primary-container)', text: t('54M, chest pain on exertion, 3d.', 'H 54 ans, douleur thoracique à l’effort, 3 j.') },
    { s: 'O', c: 'var(--md-sys-tertiary-container)', oc: 'var(--md-sys-on-tertiary-container)', text: t('BP 138/86. Sinus rhythm. Trop-I negative.', 'PA 138/86. Rythme sinusal. Trop-I négative.') },
    { s: 'A', c: 'var(--md-sys-secondary-container)', oc: 'var(--md-sys-on-secondary-container)', text: t('Unstable angina vs. MSK pain.', 'Angor instable vs. douleur MSK.') }
  ];
  const stats = [
    { k: t('PHI egress', 'Sortie RPS'), v: '0', c: 'var(--md-sys-primary)' },
    { k: t('Audit', 'Audit'), v: t('ON', 'ACTIF'), c: 'var(--md-sys-tertiary)' },
    { k: t('ICD-10', 'CIM-10'), v: 'I20.0', c: 'var(--md-sys-on-surface-variant)' }
  ];
  return (
    <div className="hai-portal-mock" style={{
      position: 'relative',
      width: '100%', height: '100%',
      background: 'var(--md-sys-surface-container-lowest)',
      borderRadius: 28,
      boxShadow: 'var(--md-sys-elevation-4)',
      overflow: 'hidden',
      border: '1px solid var(--md-sys-outline-variant)'
    }}>
      <div className="hai-portal-topbar" style={{
        height: 48, display: 'flex', alignItems: 'center', gap: 8, padding: '0 16px',
        background: 'var(--md-sys-surface-container)',
        borderBottom: '1px solid var(--md-sys-outline-variant)'
      }}>
        <span className="material-symbols-outlined" style={{ color: 'var(--md-sys-primary)', fontSize: 20, fontVariationSettings: "'FILL' 1" }}>shield_lock</span>
        <span style={{ font: '500 13px/1 var(--md-sys-typeface-plain)', color: 'var(--md-sys-on-surface)' }}>WalledCare</span>
        <span style={{
          marginLeft: 12, font: '500 10px/1 var(--md-sys-typeface-mono)',
          letterSpacing: '0.22em', color: 'var(--md-sys-primary)',
          padding: '4px 8px', borderRadius: 9999,
          background: 'var(--md-sys-primary-container)',
          display: 'inline-flex', alignItems: 'center', gap: 6
        }}>
          <span style={{ width: 6, height: 6, borderRadius: '50%', background: 'var(--md-sys-primary)', animation: 'pulse 1.8s infinite' }} />
          {t('LIVE · ON-PREM', 'EN DIRECT · SUR SITE')}
        </span>
        <div style={{ flex: 1 }} />
        <div className="hai-portal-topbar__actions" style={{ display: 'inline-flex', alignItems: 'center', gap: 8 }}>
          <span className="material-symbols-outlined" style={{ fontSize: 20, color: 'var(--md-sys-on-surface-variant)' }}>notifications</span>
          <div style={{ width: 28, height: 28, borderRadius: '50%', background: 'var(--md-sys-tertiary-container)', color: 'var(--md-sys-on-tertiary-container)', display: 'flex', alignItems: 'center', justifyContent: 'center', font: '500 11px/1 var(--md-sys-typeface-plain)' }}>DR</div>
        </div>
      </div>

      <div style={{ padding: 20, display: 'flex', flexDirection: 'column', gap: 14 }}>
        <div style={{ font: '500 11px/1 var(--md-sys-typeface-mono)', letterSpacing: '0.22em', color: 'var(--md-sys-on-surface-variant)' }}>
          {t('APP · 01 — CHART WHISPERER', 'APP · 01 — CHART WHISPERER')}
        </div>
        <div style={{ font: '500 22px/28px var(--md-sys-typeface-brand)', color: 'var(--md-sys-on-surface)', letterSpacing: '-0.01em' }}>
          {t('Voice → SOAP notes', 'Voix → Notes SOAP')}
        </div>

        <div style={{
          height: 64, borderRadius: 12,
          background: 'var(--md-sys-surface-container)',
          padding: '0 16px',
          display: 'flex', alignItems: 'center', gap: 3
        }}>
          {Array.from({ length: 48 }).map((_, i) => {
            const h = 6 + Math.abs(Math.sin(i * 0.5 + 1) * 30) + Math.abs(Math.cos(i * 0.3) * 12);
            return <div key={i} style={{
              width: 3, height: h, borderRadius: 2,
              background: i < 32 ? 'var(--md-sys-primary)' : 'var(--md-sys-outline-variant)',
              opacity: i < 32 ? 1 : 0.5
            }} />;
          })}
        </div>

        <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
          {rows.map((r, i) => (
            <div key={i} style={{ display: 'flex', gap: 10, alignItems: 'flex-start' }}>
              <div style={{
                width: 22, height: 22, borderRadius: '50%',
                background: r.c, color: r.oc,
                display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                font: '500 11px/1 var(--md-sys-typeface-plain)', flexShrink: 0
              }}>{r.s}</div>
              <div style={{ font: '400 13px/18px var(--md-sys-typeface-plain)', color: 'var(--md-sys-on-surface)' }}>{r.text}</div>
            </div>
          ))}
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 8, marginTop: 4 }}>
          {stats.map((s, i) => (
            <div key={i} style={{
              background: 'var(--md-sys-surface-container)',
              borderRadius: 8, padding: '10px 12px',
              border: '1px solid var(--md-sys-outline-variant)'
            }}>
              <div style={{ font: '500 10px/1 var(--md-sys-typeface-mono)', letterSpacing: '0.2em', color: 'var(--md-sys-on-surface-variant)', textTransform: 'uppercase' }}>{s.k}</div>
              <div style={{ marginTop: 6, font: '500 18px/1 var(--md-sys-typeface-brand)', color: s.c }}>{s.v}</div>
            </div>
          ))}
        </div>

        <div style={{ display: 'flex', gap: 8, marginTop: 4 }}>
          <button className="m3-btn m3-btn--tonal" style={{ height: 36, padding: '0 16px', font: '500 13px/36px var(--md-sys-typeface-plain)' }}>
            <span className="material-symbols-outlined" style={{ fontSize: 16 }}>mic</span>
            {t('Continue', 'Continuer')}
          </button>
          <button className="m3-btn m3-btn--text" style={{ height: 36, padding: '0 12px', font: '500 13px/36px var(--md-sys-typeface-plain)' }}>
            <span className="material-symbols-outlined" style={{ fontSize: 16 }}>content_copy</span>
            {t('Copy to EHR', 'Copier vers DME')}
          </button>
        </div>
      </div>

      <style>{`
        @keyframes pulse { 0%, 100% { opacity: 1; } 50% { opacity: 0.3; } }
      `}</style>
    </div>
  );
}

Object.assign(window, { useReveal, IconBtn, TopAppBar, Hero });
