/* global React */
const { useState: useStateApps } = React;

const APP_CATEGORIES = [
  { key: 'all',     icon: 'apps',             en: 'All',           fr: 'Toutes' },
  { key: 'doc',     icon: 'description',      en: 'Documentation', fr: 'Documentation' },
  { key: 'privacy', icon: 'shield',           en: 'Privacy',       fr: 'Confidentialité' },
  { key: 'ops',     icon: 'manage_accounts',  en: 'Operations',    fr: 'Opérations' }
];

const APPS = [
  {
    id: 1, icon: 'mic', cat: 'doc', color: 'primary',
    en: { name: 'Chart Whisperer', tag: 'Voice → SOAP notes with ICD-10.', stats: [['Accuracy','98.2%'],['ICD-10','✓']] },
    fr: { name: 'Chart Whisperer', tag: 'Voix → Notes SOAP avec CIM-10.', stats: [['Précision','98,2 %'],['CIM-10','✓']] }
  },
  {
    id: 2, icon: 'quick_reference', cat: 'doc', color: 'tertiary',
    en: { name: 'Document Q&A', tag: 'Cited answers across hospital docs.', stats: [['Sources','12.4k'],['Cited','100%']] },
    fr: { name: 'Document Q&R', tag: 'Réponses citées dans les documents hospitaliers.', stats: [['Sources','12,4 k'],['Cité','100 %']] }
  },
  {
    id: 3, icon: 'policy', cat: 'doc', color: 'secondary',
    en: { name: 'Policy Navigator', tag: 'Semantic policy search, source-grade.', stats: [['Policies','3.2k'],['Audit','ON']] },
    fr: { name: 'Policy Navigator', tag: 'Recherche sémantique de politiques, qualité source.', stats: [['Politiques','3,2 k'],['Audit','ACTIF']] }
  },
  {
    id: 4, icon: 'tune', cat: 'privacy', color: 'primary',
    en: { name: 'Data Forge', tag: 'Synthetic EHR. Differential privacy.', stats: [['ε','0.5'],['Rows','1M']] },
    fr: { name: 'Data Forge', tag: 'DME synthétique. Confidentialité différentielle.', stats: [['ε','0,5'],['Lignes','1 M']] }
  },
  {
    id: 5, icon: 'balance', cat: 'privacy', color: 'tertiary',
    en: { name: 'Equity Lens', tag: 'Real-time bias audits on risk scores.', stats: [['Cohorts','24'],['Drift','Low']] },
    fr: { name: 'Equity Lens', tag: 'Audits de biais en temps réel sur les scores de risque.', stats: [['Cohortes','24'],['Dérive','Faible']] }
  },
  {
    id: 6, icon: 'assignment_turned_in', cat: 'doc', color: 'secondary',
    en: { name: 'Discharge Summary', tag: 'Structured drafts in seconds.', stats: [['Avg time','8s'],['Draft','Ready']] },
    fr: { name: 'Résumé de congé', tag: 'Brouillons structurés en quelques secondes.', stats: [['Temps moy.','8 s'],['Brouillon','Prêt']] }
  },
  {
    id: 7, icon: 'swap_horiz', cat: 'ops', color: 'primary',
    en: { name: 'Shift Handoff', tag: '12 hours → one safe briefing.', stats: [['Patients','18'],['SBAR','✓']] },
    fr: { name: 'Passation de quart', tag: '12 heures → un transfert sécuritaire.', stats: [['Patients','18'],['SBAR','✓']] }
  },
  {
    id: 8, icon: 'outgoing_mail', cat: 'ops', color: 'tertiary',
    en: { name: 'Referral Letter', tag: 'Specialist PDFs from one prompt.', stats: [['Templates','42'],['Sign','E-sign']] },
    fr: { name: 'Lettre de référence', tag: 'PDF pour spécialistes en une seule invite.', stats: [['Modèles','42'],['Sign.','Sign-é']] }
  },
  {
    id: 9, icon: 'fact_check', cat: 'ops', color: 'secondary',
    en: { name: 'Vendor Scorecard', tag: 'Score AI vendors: safety, cost, bias.', stats: [['Vendors','37'],['Rated','Yes']] },
    fr: { name: 'Bulletin fournisseurs', tag: 'Évaluez les fournisseurs d’IA : sécurité, coût, biais.', stats: [['Fournisseurs','37'],['Noté','Oui']] }
  }
];

function Apps() {
  const lang = React.useContext(LangContext);
  const t = useT();
  const [cat, setCat] = useStateApps('all');
  const filtered = cat === 'all' ? APPS : APPS.filter(a => a.cat === cat);
  return (
    <section id="apps" className="section surface-divider">
      <div className="container">
        <div className="sec-head">
          <div data-reveal>
            <span className="eyebrow">{t('/ 02 · Platform', '/ 02 · Plateforme')}</span>
            <h2>
              {t('One platform.', 'Une plateforme.')}<br/>{t('Nine clinical workflows.', 'Neuf flux cliniques.')}
            </h2>
          </div>
          <p data-reveal data-reveal-delay="1">
            {t(
              'Every app runs on the same on-prem stack, sharing model weights, audit logs, and identity — one deployment, one invoice, one compliance story.',
              'Chaque application fonctionne sur la même pile sur site, partageant les poids de modèle, les journaux d’audit et l’identité — un seul déploiement, une seule facture, une seule histoire de conformité.'
            )}
          </p>
        </div>
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8, marginBottom: 32 }} data-reveal>
          {APP_CATEGORIES.map(c => (
            <button key={c.key} onClick={() => setCat(c.key)} className={`m3-chip ${cat === c.key ? 'selected' : ''}`}>
              {cat === c.key && <span className="material-symbols-outlined">check</span>}
              <span className="material-symbols-outlined" style={{ display: cat === c.key ? 'none' : 'inline-flex' }}>{c.icon}</span>
              {c[lang] || c.en}
            </button>
          ))}
        </div>
        <div style={{
          display: 'grid',
          gap: 16,
          gridTemplateColumns: 'repeat(auto-fit, minmax(300px, 1fr))'
        }}>
          {filtered.map((app, i) => (
            <AppCard key={app.id} app={app} idx={i} lang={lang} />
          ))}
        </div>
      </div>
    </section>
  );
}

function AppCard({ app, idx, lang }) {
  const t = useT();
  const copy = app[lang] || app.en;
  const colorBg = `var(--md-sys-${app.color}-container)`;
  const colorFg = `var(--md-sys-on-${app.color}-container)`;
  return (
    <article className="m3-card-elevated" data-reveal data-reveal-delay={String(Math.min(idx % 3, 3))} style={{
      padding: 24, display: 'flex', flexDirection: 'column', gap: 16, minHeight: 280, cursor: 'pointer'
    }}>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <div style={{
          width: 56, height: 56, borderRadius: 16,
          background: colorBg, color: colorFg,
          display: 'inline-flex', alignItems: 'center', justifyContent: 'center'
        }}>
          <span className="material-symbols-outlined" style={{ fontSize: 30, fontVariationSettings: "'FILL' 1" }}>{app.icon}</span>
        </div>
        <span style={{ font: '500 11px/1 var(--md-sys-typeface-mono)', letterSpacing: '0.22em', color: 'var(--md-sys-on-surface-variant)' }}>
          APP / 0{app.id}
        </span>
      </div>
      <div style={{ flex: 1 }}>
        <h3 style={{ margin: 0, font: '400 22px/28px var(--md-sys-typeface-brand)', letterSpacing: '-0.005em', color: 'var(--md-sys-on-surface)' }}>{copy.name}</h3>
        <p style={{ margin: '8px 0 0', font: '400 15px/22px var(--md-sys-typeface-plain)', color: 'var(--md-sys-on-surface-variant)' }}>{copy.tag}</p>
      </div>
      <div style={{ display: 'flex', gap: 8 }}>
        {copy.stats.map(([k, v]) => (
          <div key={k} style={{
            flex: 1, padding: '8px 12px',
            background: 'var(--md-sys-surface-container)',
            borderRadius: 8
          }}>
            <div style={{ font: '500 10px/1 var(--md-sys-typeface-mono)', letterSpacing: '0.2em', color: 'var(--md-sys-on-surface-variant)', textTransform: 'uppercase' }}>{k}</div>
            <div style={{ marginTop: 4, font: '500 14px/1 var(--md-sys-typeface-plain)', color: 'var(--md-sys-on-surface)' }}>{v}</div>
          </div>
        ))}
      </div>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginTop: 4 }}>
        <span className="m3-chip" style={{ height: 28, padding: '0 10px', font: '500 12px/1 var(--md-sys-typeface-plain)' }}>
          <span className="material-symbols-outlined" style={{ fontSize: 14 }}>shield</span>
          {t('On-prem', 'Sur site')}
        </span>
        <button className="m3-btn m3-btn--text" style={{ padding: '0 8px' }}>
          {t('Learn more', 'En savoir plus')}
          <span className="material-symbols-outlined">arrow_forward</span>
        </button>
      </div>
    </article>
  );
}

function Architecture() {
  const lang = React.useContext(LangContext);
  const t = useT();
  const LAYERS = [
    {
      n: '01', icon: 'devices', color: 'tertiary',
      en: { title: 'Clinical surfaces', items: ['Web portal', 'iPad bedside', 'Epic / Oscar sidecar'] },
      fr: { title: 'Surfaces cliniques', items: ['Portail web', 'iPad au chevet', 'Module Epic / Oscar'] }
    },
    {
      n: '02', icon: 'memory', color: 'primary',
      en: { title: 'Private inference', items: ['Llama 3.1 70B on-prem', 'vLLM + Triton', 'Signed audit events'] },
      fr: { title: 'Inférence privée', items: ['Llama 3.1 70B sur site', 'vLLM + Triton', 'Événements d’audit signés'] }
    },
    {
      n: '03', icon: 'database', color: 'secondary',
      en: { title: 'Hospital data', items: ['EHR over HL7 / FHIR', 'Encrypted at rest', 'No outbound rules'] },
      fr: { title: 'Données hospitalières', items: ['DME via HL7 / FHIR', 'Chiffré au repos', 'Aucune règle sortante'] }
    }
  ];
  return (
    <section id="architecture" className="section surface-divider">
      <div className="container">
        <div className="sec-head">
          <div data-reveal>
            <span className="eyebrow">{t('/ 03 · Architecture', '/ 03 · Architecture')}</span>
            <h2>
              {t('Three layers.', 'Trois couches.')}<br/>{t('Zero egress.', 'Aucune sortie.')}
            </h2>
          </div>
          <p data-reveal data-reveal-delay="1">
            {t(
              'A reference deployment you can audit end-to-end — your hardware, your identity provider, your model weights.',
              'Un déploiement de référence auditable de bout en bout — votre matériel, votre fournisseur d’identité, vos poids de modèle.'
            )}
          </p>
        </div>
        <div data-reveal style={{
          display: 'grid',
          gridTemplateColumns: 'repeat(auto-fit, minmax(280px, 1fr))',
          gap: 16
        }}>
          {LAYERS.map(l => {
            const copy = l[lang] || l.en;
            return (
              <div key={l.n} className="m3-card-filled" style={{ padding: 24 }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 16 }}>
                  <div style={{
                    width: 44, height: 44, borderRadius: 12,
                    background: `var(--md-sys-${l.color}-container)`,
                    color: `var(--md-sys-on-${l.color}-container)`,
                    display: 'inline-flex', alignItems: 'center', justifyContent: 'center'
                  }}>
                    <span className="material-symbols-outlined" style={{ fontSize: 24, fontVariationSettings: "'FILL' 1" }}>{l.icon}</span>
                  </div>
                  <div>
                    <div style={{ font: '500 11px/1 var(--md-sys-typeface-mono)', letterSpacing: '0.22em', color: 'var(--md-sys-on-surface-variant)' }}>
                      {t('LAYER', 'COUCHE')} {l.n}
                    </div>
                    <h3 style={{ margin: '6px 0 0', font: '400 22px/1 var(--md-sys-typeface-brand)', letterSpacing: '-0.005em' }}>{copy.title}</h3>
                  </div>
                </div>
                <ul style={{ listStyle: 'none', padding: 0, margin: 0, display: 'flex', flexDirection: 'column', gap: 8 }}>
                  {copy.items.map(it => (
                    <li key={it} style={{ display: 'flex', alignItems: 'center', gap: 10, font: '400 14px/20px var(--md-sys-typeface-plain)', color: 'var(--md-sys-on-surface-variant)' }}>
                      <span className="material-symbols-outlined" style={{ fontSize: 18, color: 'var(--md-sys-primary)' }}>check_circle</span>
                      {it}
                    </li>
                  ))}
                </ul>
              </div>
            );
          })}
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { Apps, Architecture });
