// JammSanté Dermatologie — écrans 3 : consultation Jamm IA, télédermatologie, actes, agenda + shell + app

function DmConsultation({ onNavigate }) {
  const [rec, setRec] = useState(false);
  const [step, setStep] = useState(0);
  useEffect(() => {
    if (!rec) return;
    const id = setInterval(() => setStep(s => Math.min(s+1, DM_TRANSCRIPT.length)), 1400);
    return () => clearInterval(id);
  }, [rec]);
  const p = DM_PATIENTS[0];
  return <div>
    <SectionTitle eyebrow="Salle 1 · en cours" title="Consultation - Adama Cissé" sub="Nævus dos évolutif · sevrage dépigmentation · phototype VI" right={<Button variant="ghost" icon="x" onClick={()=>onNavigate('accueil')}>Terminer</Button>} />
    <div style={{ marginBottom:18 }}><DmAlerts patient={p} compact /></div>
    <div style={{ display:'grid', gridTemplateColumns:'1fr 380px', gap:20 }}>
      <Card>
        <div style={{ display:'flex', alignItems:'center', gap:12, marginBottom:16 }}>
          <button onClick={()=>{ setRec(!rec); if(!rec) setStep(0); }} style={{ width:52, height:52, borderRadius:'50%', border:'none', cursor:'pointer', background: rec?'#EF4444':'#0D9488', color:'#fff', display:'flex', alignItems:'center', justifyContent:'center', boxShadow: rec?'0 0 0 6px rgba(239,68,68,0.18)':'0 4px 14px rgba(13,148,136,0.35)', transition:'all 200ms' }}><Icon name={rec?'square':'mic'} size={22} /></button>
          <div style={{ flex:1 }}><div style={{ fontSize:14, fontWeight:600, color:'var(--d-fg)' }}>{rec?'Jamm IA - écoute en cours…':'Démarrer la dictée'}</div><div style={{ fontSize:12, color:'var(--d-fg-subtle)' }}>Transcription FR / Wolof · mains libres</div></div>
          {rec && <div style={{ display:'flex', gap:3, alignItems:'flex-end', height:28 }}>{[0,1,2,3,4].map(i=><span key={i} style={{ width:4, borderRadius:2, background:'#0D9488', height:'100%', animation:'dBar 900ms ease-in-out infinite', animationDelay:i*120+'ms', transformOrigin:'bottom' }} />)}</div>}
        </div>
        <div style={{ display:'flex', flexDirection:'column', gap:10, minHeight:180 }}>
          {DM_TRANSCRIPT.slice(0, rec?step:DM_TRANSCRIPT.length).map((l,i)=>(
            <div key={i} style={{ alignSelf: l.who==='praticien'?'flex-start':'flex-end', maxWidth:'82%', background: l.who==='praticien'?'var(--d-surface-2)':'var(--d-accent-bg)', padding:'9px 13px', borderRadius:12, animation:'dPop 240ms ease' }}>
              <div style={{ fontSize:10, fontWeight:700, letterSpacing:'0.08em', textTransform:'uppercase', color: l.who==='praticien'?'var(--d-fg-faint)':'#0D9488', marginBottom:3 }}>{l.who}</div>
              <div style={{ fontSize:13, color:'var(--d-fg)', lineHeight:1.45 }}>{l.t}</div>
            </div>
          ))}
        </div>
      </Card>
      <div style={{ display:'flex', flexDirection:'column', gap:16 }}>
        <Card style={{ borderColor:'transparent', background:'linear-gradient(135deg,#0D9488,#2DD4BF)', color:'#fff' }}>
          <div style={{ display:'flex', alignItems:'center', gap:8, marginBottom:10 }}><Icon name="sparkles" size={15} /><div style={{ fontSize:11, fontWeight:700, letterSpacing:'0.12em' }}>NOTE JAMM IA</div></div>
          {['Motif : nævus dos évolutif (4 mois) + suivi sevrage dépigmentation.','Examen : lésion 6 mm, asymétrique, bords irréguliers, dermoscopie atypique → ABCDE 3/5.','CAT : exérèse-biopsie 24/07 (consentement signé), envoi anapath Le Dantec.','Sevrage : passage étape S2, hydrocortisone 1 j/2, émollient, SPF50+.'].map((t,i)=>(
            <div key={i} style={{ fontSize:12.5, lineHeight:1.5, marginBottom:7, opacity: rec&&step<DM_TRANSCRIPT.length?0.5:1, display:'flex', gap:7 }}><span>•</span><span>{t}</span></div>
          ))}
          <Button variant="secondary" size="sm" icon="check" style={{ marginTop:6, background:'#fff', color:'#0D9488', width:'100%' }}>Valider la note</Button>
        </Card>
        <Card>
          <h3 style={{ margin:'0 0 12px', fontSize:14, fontWeight:600, color:'var(--d-fg)' }}>Ordonnance suggérée</h3>
          <div style={{ display:'flex', gap:10, padding:'10px 12px', borderRadius:10, background:'var(--d-warn-bg)', marginBottom:10, alignItems:'flex-start' }}>
            <Icon name="alert-triangle" size={15} color="#B45309" style={{ marginTop:1 }} /><div style={{ fontSize:12, color:'var(--d-fg-muted)', lineHeight:1.4 }}><strong style={{ color:'#B45309' }}>Vigilance :</strong> pas de corticoïde fort, sevrage dépigmentation en cours.</div>
          </div>
          {[['Hydrocortisone 1 %','1 appl. 1 j/2 - joues, 2 sem'],['Émollient (cérat)','2 appl./j - visage et corps'],['Écran solaire SPF50+','Chaque matin, renouveler à midi']].map(([m,d],i,arr)=>(
            <div key={i} style={{ display:'flex', justifyContent:'space-between', padding:'9px 0', borderBottom:i<arr.length-1?'1px solid var(--d-border)':'none' }}><span style={{ fontSize:13, fontWeight:600, color:'var(--d-fg)' }}>{m}</span><span style={{ fontSize:12, color:'var(--d-fg-subtle)' }}>{d}</span></div>
          ))}
          <Button variant="outline" size="sm" icon="printer" style={{ marginTop:12, width:'100%' }}>Imprimer l'ordonnance</Button>
        </Card>
      </div>
    </div>
  </div>;
}

// ---------- Télédermatologie ----------
function DmTelederm() {
  const avis = [
    { de:'Poste de santé Fatick - ICP Ndiaye', motif:'Placard annulaire prurigineux, enfant 9 ans', urg:false, tri:'Teigne corporelle probable', photos:2, t:'il y a 2 h' },
    { de:'Poste de santé Fatick - ICP Ndiaye', motif:'Ulcération jambe indolore, homme 45 ans', urg:true, tri:'⚠ À voir en présentiel, suspicion ulcère de Buruli', photos:3, t:'il y a 3 h' },
    { de:'Case de santé Niakhar', motif:'Éruption vésiculeuse hémithorax, femme 60 ans', urg:false, tri:'Zona - traitement démarré sur place', photos:1, t:'hier' },
    { de:'Poste de santé Diofior', motif:'Dépigmentation en confettis, femme 28 ans', urg:false, tri:'Complications xessal - RDV cabinet proposé', photos:2, t:'hier' },
  ];
  return <div>
    <SectionTitle eyebrow="Avis à distance" title="Télédermatologie" sub="Photos envoyées par les postes de santé, pré-triées par Jamm IA" right={<Badge tone="sky">4 en attente</Badge>} />
    <div style={{ display:'flex', flexDirection:'column', gap:14 }}>
      {avis.map((a,i)=>(
        <Card key={i} style={ a.urg ? { borderColor:'var(--d-danger-border)' } : {}}>
          <div style={{ display:'flex', gap:14, alignItems:'flex-start' }}>
            <div style={{ display:'flex', gap:6, flexShrink:0 }}>
              {Array.from({length:a.photos}).map((_,k)=>(
                <div key={k} style={{ width:64, height:48, borderRadius:8, background:'linear-gradient(135deg,#3b2f2a,#1f1815)', display:'flex', alignItems:'center', justifyContent:'center' }}><Icon name="image" size={16} color="rgba(255,255,255,0.4)" /></div>
              ))}
            </div>
            <div style={{ flex:1, minWidth:0 }}>
              <div style={{ display:'flex', alignItems:'center', gap:8, flexWrap:'wrap' }}>
                <span style={{ fontSize:13.5, fontWeight:600, color:'var(--d-fg)' }}>{a.motif}</span>
                {a.urg && <Badge tone="red">Urgent</Badge>}
              </div>
              <div style={{ fontSize:12, color:'var(--d-fg-subtle)', marginTop:3 }}>{a.de} · {a.t}</div>
              <div style={{ fontSize:12.5, marginTop:7, display:'flex', gap:7, alignItems:'flex-start' }}>
                <Icon name="sparkles" size={14} color="#0D9488" style={{ marginTop:1, flexShrink:0 }} />
                <span style={{ color:'var(--d-fg-muted)' }}><strong style={{ color:'#0D9488' }}>Pré-tri Jamm IA :</strong> {a.tri}</span>
              </div>
            </div>
            <div style={{ display:'flex', flexDirection:'column', gap:7, flexShrink:0 }}>
              <Button variant="primary" size="sm" icon="reply">Répondre</Button>
              <Button variant="ghost" size="sm" icon="calendar-plus">Convoquer</Button>
            </div>
          </div>
        </Card>
      ))}
    </div>
  </div>;
}

// ---------- Actes & petite chirurgie ----------
function DmActes() {
  const st = { programme:{l:'Programmé',t:'sky'}, fait:{l:'Réalisé',t:'green'} };
  return <div>
    <SectionTitle eyebrow="Plateau technique" title="Actes & petite chirurgie" sub="Biopsies, exérèses, cryothérapie - consentement et envoi anapath tracés" right={<Button variant="primary" icon="plus">Programmer un acte</Button>} />
    <Card padding={0}>
      <div style={{ display:'grid', gridTemplateColumns:'1.6fr 1.1fr 1fr 110px 1.2fr 110px', gap:12, padding:'11px 20px', borderBottom:'1px solid var(--d-border)', fontSize:10.5, fontWeight:700, letterSpacing:'0.08em', textTransform:'uppercase', color:'var(--d-fg-faint)' }}>
        <span>Acte</span><span>Patient</span><span>Date</span><span>Consentement</span><span>Anapath</span><span>Statut</span></div>
      {DM_ACTES.map((a,i,arr)=>(
        <div key={i} style={{ display:'grid', gridTemplateColumns:'1.6fr 1.1fr 1fr 110px 1.2fr 110px', gap:12, alignItems:'center', padding:'13px 20px', borderBottom:i<arr.length-1?'1px solid var(--d-border)':'none' }}>
          <div><div style={{ fontSize:13.5, fontWeight:600, color:'var(--d-fg)' }}>{a.acte}</div>{a.anesth!=='—' && <div style={{ fontSize:11.5, color:'var(--d-fg-subtle)', marginTop:2 }}>{a.anesth}</div>}</div>
          <div style={{ fontSize:12.5, color:'var(--d-fg-muted)' }}>{a.patient}</div>
          <div style={{ fontSize:12.5, color:'var(--d-fg-muted)', fontFamily:'JetBrains Mono, monospace' }}>{a.date}</div>
          <div>{a.consent ? <Badge tone="green" dot={false}>Signé</Badge> : <Badge tone="amber" dot={false}>À signer</Badge>}</div>
          <div style={{ fontSize:12, color:'var(--d-fg-muted)' }}>{a.envoi}</div>
          <Badge tone={st[a.statut].t}>{st[a.statut].l}</Badge>
        </div>
      ))}
    </Card>
  </div>;
}

// ---------- Agenda 2 salles ----------
function DmAgenda() {
  const hours = ['09:00','10:00','11:00','12:00','13:00','14:00','15:00','16:00'];
  const toneBg = { teal:'var(--d-accent-bg)', rose:'var(--d-rose-bg)', violet:'var(--d-violet-bg)', red:'var(--d-danger-bg)' };
  const toneFg = { teal:'#0D9488', rose:'#BE185D', violet:'#6D28D9', red:'#B91C1C' };
  const rowH = 64;
  return <div>
    <SectionTitle eyebrow="Lundi 20 juillet 2026" title="Agenda" sub="2 salles · rappels WhatsApp automatiques" right={<><Segmented items={['Jour','Semaine']} active="Jour" onChange={()=>{}} /><Button variant="primary" icon="plus">Nouveau RDV</Button></>} />
    <Card padding={0}>
      <div style={{ display:'grid', gridTemplateColumns:'60px repeat(2,1fr)', borderBottom:'1px solid var(--d-border)' }}>
        <div />
        {DM_PRATICIENS.map(pr=>(
          <div key={pr.id} style={{ padding:'12px 14px', borderLeft:'1px solid var(--d-border)', display:'flex', alignItems:'center', gap:9 }}>
            <span style={{ width:9, height:9, borderRadius:'50%', background:pr.color }} />
            <div><div style={{ fontSize:13, fontWeight:600, color:'var(--d-fg)' }}>{pr.name}</div><div style={{ fontSize:11, color:'var(--d-fg-subtle)' }}>{pr.salle}</div></div>
          </div>
        ))}
      </div>
      <div style={{ display:'grid', gridTemplateColumns:'60px repeat(2,1fr)' }}>
        <div>{hours.map(h=><div key={h} style={{ height:rowH, borderBottom:'1px solid var(--d-border)', fontSize:11, color:'var(--d-fg-faint)', padding:'4px 8px', fontFamily:'JetBrains Mono, monospace', textAlign:'right' }}>{h}</div>)}</div>
        {DM_PRATICIENS.map((pr,ci)=>(
          <div key={pr.id} style={{ borderLeft:'1px solid var(--d-border)', position:'relative' }}>
            {hours.map(h=><div key={h} style={{ height:rowH, borderBottom:'1px solid var(--d-border)' }} />)}
            {DM_RDV.filter(r=>r.salle===ci).map((r,i)=>{
              const hIdx = hours.indexOf(r.h.replace(/:30/,':00'));
              const top = (hIdx + (r.h.endsWith('30')?0.5:0))*rowH;
              return <div key={i} style={{ position:'absolute', top:top+2, left:4, right:4, height:(r.dur/60)*rowH-4, background:toneBg[r.tone], border:'1px solid '+toneFg[r.tone]+'44', borderLeft:'3px solid '+toneFg[r.tone], borderRadius:8, padding:'6px 9px', overflow:'hidden' }}>
                <div style={{ fontSize:12, fontWeight:600, color:'var(--d-fg)', display:'flex', alignItems:'center', gap:5 }}>{r.patient}{r.confirm && <Icon name="check-circle" size={11} color={toneFg[r.tone]} />}</div>
                <div style={{ fontSize:11, color:'var(--d-fg-subtle)', whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis' }}>{r.acte}</div>
              </div>;
            })}
          </div>
        ))}
      </div>
    </Card>
  </div>;
}

// ---------- Shell + App ----------
function DmShell({ children, screen, onNavigate, theme, onToggleTheme }) {
  const groups = [
    { g:'Clinique', items:[
      { id:'accueil', label:'Accueil', icon:'layout-dashboard' },
      { id:'patients', label:'Patients', icon:'users' },
      { id:'consultation', label:'Consultation', icon:'mic' },
      { id:'agenda', label:'Agenda', icon:'calendar' },
    ]},
    { g:'Registres', items:[
      { id:'reg-surveillance', label:'Lésions en surveillance', icon:'scan' },
      { id:'reg-chroniques', label:'Maladies chroniques', icon:'activity' },
      { id:'reg-xessal', label:'Dépigmentation', icon:'shield-alert' },
    ]},
    { g:'Transversal', items:[
      { id:'telederm', label:'Télédermatologie', icon:'smartphone' },
      { id:'actes', label:'Actes & chirurgie', icon:'slice' },
      { id:'ordonnances', label:'Ordonnances', icon:'pill' },
      { id:'laboratoire', label:'Laboratoire', icon:'flask-conical' },
      { id:'reference', label:'Référence', icon:'share-2' },
    ]},
  ];
  return (
    <div style={{ display:'grid', gridTemplateColumns:'248px 1fr', minHeight:'100vh', background:'var(--d-bg)' }}>
      <aside style={{ background:'var(--d-surface)', borderRight:'1px solid var(--d-border)', display:'flex', flexDirection:'column', padding:'20px 14px', position:'sticky', top:0, height:'100vh', overflowY:'auto' }}>
        <div style={{ display:'flex', alignItems:'center', gap:10, padding:'4px 8px 6px' }}>
          <img src="assets/logo-icon.svg" alt="" style={{ width:26, height:26 }} />
          <span style={{ fontSize:17, fontWeight:600, letterSpacing:'-0.02em', color:'var(--d-fg)' }}>jamm<span style={{ color:'#0D9488' }}>santé</span></span>
        </div>
        <div style={{ fontSize:10, fontWeight:700, color:'#BE185D', letterSpacing:'0.14em', padding:'0 8px 16px', textTransform:'uppercase' }}>Dermatologie</div>
        <button style={{ display:'flex', alignItems:'center', gap:10, padding:'8px 10px', margin:'0 0 16px', borderRadius:9, background:'var(--d-bg)', border:'1px solid var(--d-border)', cursor:'pointer', color:'var(--d-fg-faint)', fontSize:12, fontFamily:'inherit', textAlign:'left' }}>
          <Icon name="search" size={14} /><span style={{ flex:1 }}>Recherche rapide…</span>
          <span style={{ fontSize:10, fontFamily:'JetBrains Mono, monospace', padding:'1px 6px', borderRadius:4, background:'var(--d-surface)', border:'1px solid var(--d-border)' }}>⌘K</span>
        </button>
        <nav style={{ display:'flex', flexDirection:'column', gap:2 }}>
          {groups.map(grp => (
            <div key={grp.g} style={{ marginBottom:6 }}>
              <div style={{ fontSize:9.5, fontWeight:700, color:'var(--d-fg-faint)', letterSpacing:'0.14em', padding:'8px 10px 5px', textTransform:'uppercase' }}>{grp.g}</div>
              {grp.items.map(item => {
                const sel = screen === item.id || (item.id==='patients' && screen==='patient');
                return <button key={item.id} onClick={() => onNavigate(item.id)} style={{ width:'100%', display:'flex', alignItems:'center', gap:11, padding:'8px 10px', borderRadius:9, background: sel ? 'var(--d-accent-bg)' : 'transparent', border:'none', cursor:'pointer', textAlign:'left', color: sel ? '#0D9488' : 'var(--d-fg-muted)', fontSize:12.5, fontWeight: sel ? 600 : 500, fontFamily:'inherit', transition:'background 140ms' }}
                  onMouseEnter={e => { if(!sel) e.currentTarget.style.background = 'var(--d-bg)'; }}
                  onMouseLeave={e => { if(!sel) e.currentTarget.style.background = 'transparent'; }}>
                  <Icon name={item.icon} size={16} /><span style={{ flex:1 }}>{item.label}</span></button>;
              })}
            </div>
          ))}
        </nav>
        <div style={{ marginTop:'auto', paddingTop:16 }}>
          <div style={{ padding:14, borderRadius:13, background:'linear-gradient(135deg,#BE185D,#F472B6)', color:'#fff', position:'relative', overflow:'hidden' }}>
            <div style={{ position:'absolute', right:-10, bottom:-18, opacity:0.15 }}><Icon name="sparkles" size={80} color="#fff" strokeWidth={1} /></div>
            <div style={{ display:'flex', alignItems:'center', gap:8, marginBottom:6, position:'relative' }}><Icon name="sparkles" size={14} /><div style={{ fontSize:10, fontWeight:700, letterSpacing:'0.12em' }}>JAMM IA</div></div>
            <div style={{ fontSize:12, lineHeight:1.45, position:'relative', fontWeight:500 }}>Dictée, pré-tri téléderm & suivi photo des lésions.</div>
          </div>
        </div>
      </aside>
      <div style={{ display:'flex', flexDirection:'column', minWidth:0 }}>
        <header style={{ height:62, padding:'0 28px', background:'var(--d-topbar)', backdropFilter:'blur(16px)', WebkitBackdropFilter:'blur(16px)', borderBottom:'1px solid var(--d-border)', display:'flex', alignItems:'center', gap:18, position:'sticky', top:0, zIndex:20 }}>
          <div style={{ display:'flex', alignItems:'center', gap:9 }}>
            <Icon name="stethoscope" size={16} color="#BE185D" />
            <span style={{ fontSize:13, fontWeight:600, color:'var(--d-fg-muted)' }}>Cabinet Derma Teranga</span>
            <span style={{ fontSize:12, color:'var(--d-fg-faint)' }}>· Dakar · 2 salles</span>
          </div>
          <div style={{ marginLeft:'auto', display:'flex', alignItems:'center', gap:8 }}>
            <Button variant="secondary" size="sm" icon="mic" onClick={() => onNavigate('consultation')}>Nouvelle consultation</Button>
            <div style={{ width:1, height:22, background:'var(--d-border)', margin:'0 4px' }} />
            <IconButton icon={theme === 'dark' ? 'sun' : 'moon'} title="Thème" onClick={onToggleTheme} />
            <IconButton icon="bell" title="Notifications" />
            <div style={{ display:'flex', alignItems:'center', gap:9, padding:'4px 8px 4px 4px', borderRadius:999 }}>
              <Avatar name="Mariama Diop" size={30} color="#BE185D" />
              <div style={{ textAlign:'left' }}><div style={{ fontSize:13, fontWeight:600, color:'var(--d-fg)' }}>Dr. Diop</div><div style={{ fontSize:11, color:'var(--d-fg-subtle)' }}>Dermatologue</div></div>
            </div>
          </div>
        </header>
        <main style={{ flex:1, padding:'26px 28px', overflow:'auto' }}>{children}</main>
      </div>
    </div>
  );
}

function DmApp() {
  const [screen, setScreen] = useState('accueil');
  const [patient, setPatient] = useState(null);
  const [theme, setTheme] = useState('light');
  useEffect(() => { document.documentElement.setAttribute('data-theme', theme); }, [theme]);
  const openPatient = (p) => { setPatient(p); setScreen('patient'); window.scrollTo(0,0); };
  const nav = (s) => { setScreen(s); window.scrollTo(0,0); };
  let view;
  if (screen==='accueil') view = <DmAccueil onNavigate={nav} onOpenPatient={openPatient} />;
  else if (screen==='patients') view = <DmPatients onOpenPatient={openPatient} />;
  else if (screen==='patient' && patient) view = <DmPatientFile patient={patient} lesions={patient.id==='p1'?SEED_LESIONS:[]} onBack={()=>nav('patients')} onNavigate={nav} />;
  else if (screen==='consultation') view = <DmConsultation onNavigate={nav} />;
  else if (screen==='telederm') view = <DmTelederm />;
  else if (screen==='actes') view = <DmActes />;
  else if (screen==='agenda') view = <DmAgenda />;
  else if (screen==='reg-surveillance') view = <DmRegSurveillance onOpenPatient={openPatient} />;
  else if (screen==='reg-chroniques') view = <DmRegChroniques onOpenPatient={openPatient} />;
  else if (screen==='reg-xessal') view = <DmRegXessal onOpenPatient={openPatient} />;
  else if (screen==='ordonnances') view = <DmOrdonnances />;
  else if (screen==='laboratoire') view = <DmLaboratoire />;
  else if (screen==='reference') view = <DmReference />;
  else view = <DmAccueil onNavigate={nav} onOpenPatient={openPatient} />;
  return <DmShell screen={screen} onNavigate={nav} theme={theme} onToggleTheme={()=>setTheme(t=>t==='dark'?'light':'dark')}>{view}</DmShell>;
}

Object.assign(window, { DmConsultation, DmTelederm, DmActes, DmAgenda, DmShell, DmApp });
