// App.jsx – main shell: sidebar, topbar, role switcher, maturity widget, routing
const { useState: useStateApp, useEffect } = React;

const ROLES = ['Nephrologist','Radiologist','Pharmacist','Data Steward'];
const ROLE_COLORS = {
  'Nephrologist':'#5B7FA6', 'Radiologist':'#7A6FA6',
  'Pharmacist':'#4A8C6F', 'Data Steward':'#A67A4A'
};

const NAV_ITEMS = [
  { id:'home',       label:'Overview',          icon:'home' },
  { id:'list',       label:'Patient Cohort',    icon:'grid' },
  { id:'pipeline',   label:'Clinical Patient Journey', icon:'pipeline' },
  { id:'dashboard',  label:'Patient Dashboard',  icon:'user' },
  { id:'conference', label:'Case Conference',    icon:'users' },
  { id:'provenance', label:'Data Sources',    icon:'database' },
];

// Inline SVG icons (minimal, geometric only)
function Icon({ name, size=16, color='#4A4A4A' }) {
  const s = { width:size, height:size, display:'block', flexShrink:0 };
  if (name==='home') return (
    <svg viewBox="0 0 16 16" style={s} fill="none">
      <path d="M2 7L8 2l6 5v7a1 1 0 01-1 1H3a1 1 0 01-1-1V7z" stroke={color} strokeWidth="1.5" strokeLinejoin="round"/>
      <path d="M6 14V9h4v5" stroke={color} strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
    </svg>
  );
  if (name==='grid') return (
    <svg viewBox="0 0 16 16" style={s} fill="none">
      <rect x="1" y="1" width="6" height="6" rx="1" stroke={color} strokeWidth="1.5"/>
      <rect x="9" y="1" width="6" height="6" rx="1" stroke={color} strokeWidth="1.5"/>
      <rect x="1" y="9" width="6" height="6" rx="1" stroke={color} strokeWidth="1.5"/>
      <rect x="9" y="9" width="6" height="6" rx="1" stroke={color} strokeWidth="1.5"/>
    </svg>
  );
  if (name==='user') return (
    <svg viewBox="0 0 16 16" style={s} fill="none">
      <circle cx="8" cy="5" r="3" stroke={color} strokeWidth="1.5"/>
      <path d="M2 14c0-3.314 2.686-5 6-5s6 1.686 6 5" stroke={color} strokeWidth="1.5" strokeLinecap="round"/>
    </svg>
  );
  if (name==='users') return (
    <svg viewBox="0 0 16 16" style={s} fill="none">
      <circle cx="5.5" cy="5" r="2.5" stroke={color} strokeWidth="1.5"/>
      <circle cx="10.5" cy="5" r="2.5" stroke={color} strokeWidth="1.5"/>
      <path d="M1 14c0-2.5 2-4 4.5-4" stroke={color} strokeWidth="1.5" strokeLinecap="round"/>
      <path d="M15 14c0-2.5-2-4-4.5-4s-4.5 1.5-4.5 4" stroke={color} strokeWidth="1.5" strokeLinecap="round"/>
    </svg>
  );
  if (name==='pipeline') return (
    <svg viewBox="0 0 16 16" style={s} fill="none">
      <circle cx="2" cy="8" r="1.5" stroke={color} strokeWidth="1.5"/>
      <circle cx="8" cy="8" r="1.5" stroke={color} strokeWidth="1.5"/>
      <circle cx="14" cy="8" r="1.5" stroke={color} strokeWidth="1.5"/>
      <line x1="3.5" y1="8" x2="6.5" y2="8" stroke={color} strokeWidth="1.5"/>
      <line x1="9.5" y1="8" x2="12.5" y2="8" stroke={color} strokeWidth="1.5"/>
      <line x1="5" y1="5" x2="5" y2="11" stroke={color} strokeWidth="1" strokeDasharray="2 1" opacity=".5"/>
      <line x1="11" y1="5" x2="11" y2="11" stroke={color} strokeWidth="1" strokeDasharray="2 1" opacity=".5"/>
    </svg>
  );
  if (name==='database') return (
    <svg viewBox="0 0 16 16" style={s} fill="none">
      <ellipse cx="8" cy="4" rx="5.5" ry="2" stroke={color} strokeWidth="1.5"/>
      <path d="M2.5 4v4c0 1.105 2.462 2 5.5 2s5.5-.895 5.5-2V4" stroke={color} strokeWidth="1.5"/>
      <path d="M2.5 8v4c0 1.105 2.462 2 5.5 2s5.5-.895 5.5-2V8" stroke={color} strokeWidth="1.5"/>
    </svg>
  );
  if (name==='chevron') return (
    <svg viewBox="0 0 10 10" style={s} fill="none">
      <path d="M3 4l2 2 2-2" stroke={color} strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
    </svg>
  );
  return null;
}

function DiceLogo() {
  return (
    <div style={{display:'flex', alignItems:'baseline', gap:0, userSelect:'none'}}>
      <span style={{
        fontWeight:800, fontSize:17, letterSpacing:'-0.03em', color:'#1A1A1A',
        borderBottom:'2.5px solid #D32027', paddingBottom:0, lineHeight:1.2
      }}>DIC<span style={{color:'#D32027'}}>E</span></span>
      <span style={{fontWeight:800, fontSize:17, letterSpacing:'-0.03em', color:'#1A1A1A', lineHeight:1.2}}>-CD</span>
    </div>
  );
}

function MaturityWidget({ score=3.2 }) {
  const color = score >= 4 ? '#2E7D5B' : score >= 3 ? '#C77700' : '#D32027';
  return (
    <div title="DICE-CD Data Utilisation Maturity Score (AP5)" style={{
      display:'flex', alignItems:'center', gap:8, padding:'5px 12px',
      border:'1px solid #E5E5E7', borderRadius:4, background:'#F7F7F8', cursor:'default'
    }}>
      <div style={{display:'flex', gap:3}}>
        {[1,2,3,4,5].map(l => (
          <div key={l} style={{
            width:6, height:14, borderRadius:1,
            background: l <= Math.round(score) ? color : '#E5E5E7'
          }}/>
        ))}
      </div>
      <div style={{lineHeight:1}}>
        <div style={{fontSize:10, color:'#4A4A4A', fontWeight:600, textTransform:'uppercase', letterSpacing:'0.05em'}}>Maturity</div>
        <div style={{fontSize:13, fontWeight:700, color, lineHeight:1.2}}>{score.toFixed(1)} / 5</div>
      </div>
    </div>
  );
}

function TopBar({ role, onRoleChange, screen }) {
  const [roleOpen, setRoleOpen] = useStateApp(false);
  return (
    <div style={{
      height:48, background:'#fff', borderBottom:'1px solid #E5E5E7',
      display:'flex', alignItems:'center', padding:'0 20px', gap:16,
      position:'sticky', top:0, zIndex:100, flexShrink:0
    }}>
      {/* Back to portal */}
      <a href="/landing.html" style={{
        display:'flex', alignItems:'center', gap:5, fontSize:11, color:'#4A4A4A',
        textDecoration:'none', padding:'3px 8px', borderRadius:3,
        border:'1px solid #E5E5E7', background:'#F7F7F8',
      }}>← Portal</a>
      <div style={{width:1, height:20, background:'#E5E5E7'}}/>

      {/* Logo */}
      <DiceLogo/>
      <div style={{width:1, height:20, background:'#E5E5E7', marginLeft:4}}/>

      {/* Screen label */}
      <span style={{fontSize:13, color:'#4A4A4A', fontWeight:500}}>
        ADPKD · Tolvaptan Eligibility Dashboard
      </span>

      <div style={{flex:1}}/>

      {/* Prototype banner */}
      <div style={{
        padding:'3px 10px', background:'#1A1A1A', color:'#fff',
        fontSize:10, fontWeight:700, borderRadius:3, letterSpacing:'0.08em',
        textTransform:'uppercase'
      }}>Prototype – Synthetic data</div>

      {/* Maturity widget */}
      <MaturityWidget score={3.2}/>

      {/* Role switcher */}
      <div style={{position:'relative'}}>
        <button onClick={()=>setRoleOpen(o=>!o)} style={{
          display:'flex', alignItems:'center', gap:7, padding:'5px 12px',
          border:'1px solid #E5E5E7', borderRadius:4, background:'#fff',
          cursor:'pointer', fontSize:12, fontWeight:600, color:'#1A1A1A'
        }}>
          <div style={{width:8, height:8, borderRadius:'50%', background:ROLE_COLORS[role], flexShrink:0}}/>
          {role}
          <Icon name="chevron" size={10} color="#4A4A4A"/>
        </button>
        {roleOpen && (
          <div style={{
            position:'absolute', right:0, top:'calc(100% + 6px)',
            background:'#fff', border:'1px solid #E5E5E7', borderRadius:5,
            boxShadow:'0 4px 16px rgba(0,0,0,0.08)', minWidth:160, zIndex:200, overflow:'hidden'
          }}>
            <div style={{padding:'6px 10px', fontSize:10, color:'#4A4A4A', fontWeight:600, textTransform:'uppercase', letterSpacing:'0.06em', borderBottom:'1px solid #E5E5E7'}}>View as role</div>
            {ROLES.map(r => (
              <div key={r} onClick={()=>{ onRoleChange(r); setRoleOpen(false); }}
                style={{
                  display:'flex', alignItems:'center', gap:8, padding:'8px 12px',
                  fontSize:12, color:'#1A1A1A', cursor:'pointer',
                  background: r===role ? '#F7F7F8' : 'transparent',
                  fontWeight: r===role ? 600 : 400
                }}
                onMouseEnter={e=>{ if(r!==role) e.currentTarget.style.background='#FAFAFA'; }}
                onMouseLeave={e=>{ if(r!==role) e.currentTarget.style.background='transparent'; }}
              >
                <div style={{width:8, height:8, borderRadius:'50%', background:ROLE_COLORS[r]}}/>
                {r}
                {r===role && <span style={{marginLeft:'auto', fontSize:10, color:'#4A4A4A'}}>✓</span>}
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  );
}

function Sidebar({ screen, onNavigate, patientId, patients }) {
  const patient = patients.find(p=>p.id===patientId);
  return (
    <div style={{
      width:220, background:'#FAFAFA', borderRight:'1px solid #E5E5E7',
      display:'flex', flexDirection:'column', flexShrink:0, overflow:'hidden'
    }}>
      {/* Nav items */}
      <nav style={{padding:'12px 0', flex:1}}>
        {NAV_ITEMS.map(item => {
          const active = screen === item.id;
          return (
            <button key={item.id} onClick={()=>onNavigate(item.id)}
              style={{
                display:'flex', alignItems:'center', gap:9, width:'100%',
                padding:'9px 16px', background:'transparent', border:'none',
                borderLeft: active ? '3px solid #D32027' : '3px solid transparent',
                cursor:'pointer', textAlign:'left', transition:'all 0.1s'
              }}
              onMouseEnter={e=>{ if(!active) e.currentTarget.style.background='#F0F0F0'; }}
              onMouseLeave={e=>{ if(!active) e.currentTarget.style.background='transparent'; }}
            >
              <Icon name={item.icon} size={15} color={active?'#D32027':'#4A4A4A'}/>
              <span style={{fontSize:13, fontWeight: active?600:400, color: active?'#1A1A1A':'#4A4A4A'}}>
                {item.label}
              </span>
            </button>
          );
        })}
      </nav>

      {/* Selected patient card */}
      {patient && (
        <div style={{
          margin:10, padding:'10px 12px', border:'1px solid #E5E5E7',
          borderRadius:5, background:'#fff'
        }}>
          <div style={{fontSize:10, color:'#4A4A4A', fontWeight:600, textTransform:'uppercase', letterSpacing:'0.05em', marginBottom:6}}>Selected patient</div>
          <div style={{fontSize:13, fontWeight:600, color:'#1A1A1A'}}>{patient.alias}</div>
          <div style={{fontSize:11, color:'#4A4A4A', marginTop:1}}>{patient.id} · {patient.sex}, {patient.age} yr</div>
          <div style={{marginTop:6, display:'flex', gap:5}}>
            <span style={{
              fontSize:10, fontWeight:600, padding:'2px 6px', borderRadius:2,
              background: patient.decision==='Eligible'?'#F0FDF4':patient.decision==='Review'?'#FFFBEB':'#FEF2F2',
              color: patient.decision==='Eligible'?'#2E7D5B':patient.decision==='Review'?'#C77700':'#D32027'
            }}>{patient.decision}</span>
            <span style={{
              fontSize:10, fontWeight:600, padding:'2px 6px', borderRadius:2,
              background:'#F7F7F8', color:'#4A4A4A'
            }}>Mayo {patient.mayoClass}</span>
          </div>
        </div>
      )}

      {/* Footer */}
      <div style={{padding:'10px 14px', borderTop:'1px solid #E5E5E7', background:'#F7F7F8'}}>
        <div style={{fontSize:9, color:'#A0A0A0', lineHeight:1.6}}>
          Klinik für Translationale Nephrologie<br/>
          Uniklinik Köln · DICE-CD
        </div>
      </div>
    </div>
  );
}

function App() {
  const patients = window.DICE_DATA.patients;
  const [screen, setScreen] = useStateApp('home');
  const [selectedId, setSelectedId] = useStateApp('P-001');
  const [role, setRole] = useStateApp('Nephrologist');

  const patient = patients.find(p=>p.id===selectedId) || patients[0];

  const handleSelect = (id) => setSelectedId(id);
  const handleNavigate = (s) => setScreen(s);

  return (
    <div style={{display:'flex', flexDirection:'column', height:'100vh', background:'#fff', minWidth:1280}}>
      <TopBar role={role} onRoleChange={setRole} screen={screen}/>
      <div style={{flex:1, display:'flex', overflow:'hidden'}}>
        <Sidebar screen={screen} onNavigate={handleNavigate} patientId={selectedId} patients={patients}/>
        <main style={{flex:1, overflow:'hidden', display:'flex', flexDirection:'column', background:'#F7F7F8'}}>
          {screen==='home' && (
            <HomePage
              patients={patients}
              onSelect={handleSelect}
              onNavigate={handleNavigate}
              role={role}
            />
          )}
          {screen==='pipeline' && (
            <PipelineView
              patients={patients}
              selectedId={selectedId}
              onSelect={handleSelect}
              onNavigate={handleNavigate}
            />
          )}
          {screen==='list' && (
            <PatientList
              patients={patients}
              selectedId={selectedId}
              onSelect={handleSelect}
              onNavigate={handleNavigate}
            />
          )}
          {screen==='dashboard' && (
            <PatientDashboard
              patient={patient}
              role={role}
              onOpenProvenance={()=>setScreen('provenance')}
            />
          )}
          {screen==='conference' && (
            <CaseConference patient={patient}/>
          )}
          {screen==='provenance' && (
            <DataSourcesView onNavigate={handleNavigate}/>
          )}
        </main>
      </div>
    </div>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<App/>);
