// DataProvenance.jsx – FHIR resource-level provenance panel (DIZ / Data Steward view)
const { useState: useStateProv } = React;

const SYSTEM_COLORS = {
  'LIS (Swisslab)':'#5B7FA6', 'PACS (Syngo.via)':'#7A6FA6',
  'KIS (Orbis)':'#4A8C6F', 'DIZ (GenomicsDB)':'#A67A4A',
  'DIZ – MeDIC':'#A67A4A', 'PACS + Radiology':'#7A6FA6'
};
const SYSTEM_SHORT = {
  'LIS (Swisslab)':'LIS', 'PACS (Syngo.via)':'PACS',
  'KIS (Orbis)':'KIS', 'DIZ (GenomicsDB)':'DIZ',
  'DIZ – MeDIC':'DIZ', 'PACS + Radiology':'PACS'
};
const STATUS_STYLE = {
  'Validated':{ bg:'#F0FDF4', color:'#2E7D5B' },
  'Active':{ bg:'#F0FDF4', color:'#2E7D5B' },
  'Manual entry':{ bg:'#FFFBEB', color:'#C77700' },
  'Pending':{ bg:'#FEF2F2', color:'#D32027' },
};
const CONSENT_STYLE = {
  'Broad MII':{ bg:'#F0FDF4', color:'#2E7D5B' },
  'Specific (genetics)':{ bg:'#EFF6FF', color:'#3B6FA6' },
  'Withdrawn':{ bg:'#FEF2F2', color:'#D32027' },
};

function SystemBadge({ system }) {
  const color = SYSTEM_COLORS[system] || '#4A4A4A';
  const label = SYSTEM_SHORT[system] || system;
  return (
    <span style={{
      display:'inline-block', padding:'2px 6px', borderRadius:2,
      background:`${color}18`, color, fontSize:10, fontWeight:700,
      letterSpacing:'0.04em', border:`1px solid ${color}44`
    }}>{label}</span>
  );
}

function FhirResourceGraph({ provenance }) {
  // Simple resource graph visualization
  const systems = [...new Set(provenance.map(p=>SYSTEM_SHORT[p.system]||p.system))];
  return (
    <div style={{padding:16, background:'#F7F7F8', border:'1px solid #E5E5E7', borderRadius:5}}>
      <div style={{fontSize:11, fontWeight:600, color:'#4A4A4A', textTransform:'uppercase', letterSpacing:'0.06em', marginBottom:12}}>
        FHIR resource flow – {provenance.length} resources
      </div>
      <div style={{display:'flex', alignItems:'center', gap:0, overflowX:'auto', paddingBottom:4}}>
        {/* Source systems */}
        <div style={{display:'flex', flexDirection:'column', gap:6, minWidth:100}}>
          <div style={{fontSize:10, color:'#4A4A4A', fontWeight:600, marginBottom:4}}>Source systems</div>
          {systems.map(s => (
            <div key={s} style={{
              padding:'4px 8px', borderRadius:3, fontSize:11, fontWeight:600,
              background: SYSTEM_COLORS[Object.keys(SYSTEM_SHORT).find(k=>SYSTEM_SHORT[k]===s)||s]||'#4A4A4A',
              color:'#fff', textAlign:'center'
            }}>{s}</div>
          ))}
        </div>
        {/* Arrow */}
        <div style={{flex:1, display:'flex', alignItems:'center', justifyContent:'center', minWidth:60}}>
          <div style={{display:'flex', flexDirection:'column', alignItems:'center', gap:4}}>
            <div style={{width:'100%', height:1, background:'#D1D1D6', position:'relative'}}>
              <div style={{position:'absolute', right:-6, top:-4, color:'#4A4A4A', fontSize:12}}>▶</div>
            </div>
            <span style={{fontSize:9, color:'#4A4A4A', whiteSpace:'nowrap'}}>FHIR R4 · HL7</span>
            <span style={{fontSize:9, color:'#4A4A4A', whiteSpace:'nowrap'}}>MII Kerndatensatz</span>
          </div>
        </div>
        {/* MeDIC */}
        <div style={{
          padding:'12px 14px', borderRadius:4, background:'#1A1A1A', color:'#fff',
          fontSize:11, fontWeight:700, textAlign:'center', minWidth:80
        }}>
          MeDIC<br/>
          <span style={{fontSize:9, fontWeight:400, opacity:0.7}}>DIZ-UKK</span>
        </div>
        {/* Arrow */}
        <div style={{flex:1, display:'flex', alignItems:'center', justifyContent:'center', minWidth:60}}>
          <div style={{display:'flex', flexDirection:'column', alignItems:'center', gap:4}}>
            <div style={{width:'100%', height:1, background:'#D1D1D6', position:'relative'}}>
              <div style={{position:'absolute', right:-6, top:-4, color:'#4A4A4A', fontSize:12}}>▶</div>
            </div>
            <span style={{fontSize:9, color:'#4A4A4A', whiteSpace:'nowrap'}}>Pseudonymized</span>
            <span style={{fontSize:9, color:'#4A4A4A', whiteSpace:'nowrap'}}>+ consent-checked</span>
          </div>
        </div>
        {/* Dashboard */}
        <div style={{
          padding:'12px 14px', borderRadius:4, background:'#D32027', color:'#fff',
          fontSize:11, fontWeight:700, textAlign:'center', minWidth:90
        }}>
          DICE-CD<br/>Dashboard<br/>
          <span style={{fontSize:9, fontWeight:400, opacity:0.8}}>ADPKD CDS</span>
        </div>
      </div>
    </div>
  );
}

function MaturityBreakdown({ patient }) {
  const items = [
    { label:'Lab data (eGFR, creatinine, LFT)', level:5, note:'Automated FHIR ingestion, LOINC-coded' },
    { label:'Imaging / TKV', level:4, note:'AI-segmented, not yet FHIR-native at PACS' },
    { label:'Genetic data', level:4, note:'Structured, awaiting FHIR Genomics profile' },
    { label:'Clinical notes / family history', level:2, note:'Manual entry, free-text – not structured' },
    { label:'Patient preferences', level:1, note:'Not yet integrated into data pipeline' },
    { label:'Follow-up scheduling', level:3, note:'Semi-automated via KIS interface' },
  ];
  const overall = Math.round(items.reduce((a,b)=>a+b.level,0)/items.length*10)/10;
  return (
    <div style={{border:'1px solid #E5E5E7', borderRadius:5, overflow:'hidden'}}>
      <div style={{padding:'10px 14px', borderBottom:'1px solid #E5E5E7', background:'#FAFAFA', display:'flex', alignItems:'center', justifyContent:'space-between'}}>
        <div style={{fontSize:12, fontWeight:700, color:'#1A1A1A', textTransform:'uppercase', letterSpacing:'0.06em'}}>Data utilisation maturity</div>
        <div style={{display:'flex', alignItems:'center', gap:8}}>
          <span style={{fontSize:11, color:'#4A4A4A'}}>Overall score</span>
          <div style={{
            padding:'2px 10px', borderRadius:3, background:'#1A1A1A', color:'#fff',
            fontSize:14, fontWeight:700
          }}>Level {Math.round(overall)} / 5</div>
        </div>
      </div>
      <div style={{padding:14, display:'flex', flexDirection:'column', gap:8}}>
        {items.map((item, i) => (
          <div key={i} style={{display:'flex', alignItems:'center', gap:10}}>
            <div style={{flex:1, minWidth:0}}>
              <div style={{fontSize:12, color:'#1A1A1A', marginBottom:2}}>{item.label}</div>
              <div style={{fontSize:10, color:'#4A4A4A'}}>{item.note}</div>
            </div>
            <div style={{display:'flex', gap:3, flexShrink:0}}>
              {[1,2,3,4,5].map(l => (
                <div key={l} style={{
                  width:14, height:14, borderRadius:2,
                  background: l<=item.level ? (item.level>=4?'#2E7D5B':item.level>=3?'#C77700':'#D32027') : '#E5E5E7'
                }}/>
              ))}
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

function DataProvenance({ patient }) {
  const [selected, setSelected] = useStateProv(null);
  const [filterSystem, setFilterSystem] = useStateProv('All');

  const prov = patient.provenance.length > 0 ? patient.provenance : [
    {field:'eGFR (CKD-EPI)', system:'LIS (Swisslab)', date:'2026-04-14', loinc:'62238-1', consent:'Broad MII', status:'Validated', standardization:'LOINC'},
    {field:'Blood pressure', system:'KIS (Orbis)', date:'2026-04-10', loinc:'55284-4', consent:'Broad MII', status:'Validated', standardization:'LOINC'},
  ];

  const systems = ['All', ...new Set(prov.map(p=>SYSTEM_SHORT[p.system]||p.system))];
  const filtered = filterSystem === 'All' ? prov : prov.filter(p=>(SYSTEM_SHORT[p.system]||p.system)===filterSystem);

  return (
    <div style={{height:'100%', display:'flex', flexDirection:'column', overflow:'hidden'}}>
      {/* Header */}
      <div style={{padding:'20px 24px 16px', borderBottom:'1px solid #E5E5E7', background:'#fff', flexShrink:0}}>
        <div style={{display:'flex', alignItems:'center', justifyContent:'space-between'}}>
          <div>
            <h1 style={{fontSize:18, fontWeight:700, color:'#1A1A1A', marginBottom:2}}>Data Provenance</h1>
            <p style={{fontSize:13, color:'#4A4A4A'}}>
              {patient.alias} · {patient.id} · FHIR resource quality + consent audit
            </p>
          </div>
          <div style={{display:'flex', gap:6}}>
            {systems.map(s => (
              <button key={s} onClick={()=>setFilterSystem(s)} style={{
                padding:'4px 10px', borderRadius:4, fontSize:11, fontWeight:600,
                border: filterSystem===s ? '2px solid #1A1A1A' : '1px solid #E5E5E7',
                background: filterSystem===s ? '#1A1A1A' : '#fff',
                color: filterSystem===s ? '#fff' : '#4A4A4A',
                cursor:'pointer'
              }}>{s}</button>
            ))}
          </div>
        </div>
      </div>

      <div style={{flex:1, overflow:'auto', padding:20, display:'flex', flexDirection:'column', gap:16}}>

        {/* FHIR flow graph */}
        <FhirResourceGraph provenance={prov}/>

        {/* Resource table */}
        <div style={{border:'1px solid #E5E5E7', borderRadius:5, overflow:'hidden'}}>
          <div style={{padding:'10px 14px', borderBottom:'1px solid #E5E5E7', background:'#FAFAFA', display:'flex', alignItems:'center', justifyContent:'space-between'}}>
            <div style={{fontSize:12, fontWeight:700, color:'#1A1A1A', textTransform:'uppercase', letterSpacing:'0.06em'}}>FHIR resources · {filtered.length} records</div>
            <span style={{fontSize:11, color:'#4A4A4A'}}>Click row for full resource detail</span>
          </div>
          <table style={{width:'100%', borderCollapse:'collapse', fontSize:12}}>
            <thead>
              <tr style={{background:'#FAFAFA'}}>
                {['Data field','Source system','Timestamp','Code (LOINC/SNOMED/ICD)','Consent','Standardization','Quality'].map(h => (
                  <th key={h} style={{
                    padding:'8px 12px', textAlign:'left', fontSize:10, fontWeight:600,
                    color:'#4A4A4A', textTransform:'uppercase', letterSpacing:'0.06em',
                    borderBottom:'2px solid #E5E5E7', whiteSpace:'nowrap'
                  }}>{h}</th>
                ))}
              </tr>
            </thead>
            <tbody>
              {filtered.map((row, i) => {
                const isSelected = selected === i;
                return (
                  <tr key={i}
                    onClick={()=>setSelected(isSelected?null:i)}
                    style={{
                      background: isSelected?'#F7F7F8':'#fff',
                      borderLeft: isSelected?'3px solid #D32027':'3px solid transparent',
                      cursor:'pointer'
                    }}
                    onMouseEnter={e=>{ if(!isSelected) e.currentTarget.style.background='#FAFAFA'; }}
                    onMouseLeave={e=>{ if(!isSelected) e.currentTarget.style.background='#fff'; }}
                  >
                    <td style={{padding:'10px 12px', borderBottom:'1px solid #E5E5E7', fontWeight:500, color:'#1A1A1A'}}>{row.field}</td>
                    <td style={{padding:'10px 12px', borderBottom:'1px solid #E5E5E7'}}>
                      <SystemBadge system={row.system}/><br/>
                      <span style={{fontSize:10, color:'#4A4A4A', marginTop:2, display:'block'}}>{row.system}</span>
                    </td>
                    <td style={{padding:'10px 12px', borderBottom:'1px solid #E5E5E7', color:'#4A4A4A', fontFamily:'monospace', fontSize:11, whiteSpace:'nowrap'}}>{row.date}</td>
                    <td style={{padding:'10px 12px', borderBottom:'1px solid #E5E5E7', fontFamily:'monospace', fontSize:10, color:'#4A4A4A'}}>{row.loinc}</td>
                    <td style={{padding:'10px 12px', borderBottom:'1px solid #E5E5E7'}}>
                      <span style={{
                        padding:'2px 6px', borderRadius:2, fontSize:10, fontWeight:600,
                        background: (CONSENT_STYLE[row.consent]||{bg:'#F7F7F8'}).bg,
                        color: (CONSENT_STYLE[row.consent]||{color:'#4A4A4A'}).color
                      }}>{row.consent}</span>
                    </td>
                    <td style={{padding:'10px 12px', borderBottom:'1px solid #E5E5E7', fontSize:11, color:'#4A4A4A'}}>{row.standardization}</td>
                    <td style={{padding:'10px 12px', borderBottom:'1px solid #E5E5E7'}}>
                      <span style={{
                        padding:'2px 6px', borderRadius:2, fontSize:10, fontWeight:600,
                        background: (STATUS_STYLE[row.status]||{bg:'#F7F7F8'}).bg,
                        color: (STATUS_STYLE[row.status]||{color:'#4A4A4A'}).color
                      }}>{row.status}</span>
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>

        {/* Maturity breakdown */}
        <MaturityBreakdown patient={patient}/>

        {/* Consent summary */}
        <div style={{border:'1px solid #E5E5E7', borderRadius:5, padding:14, background:'#fff'}}>
          <div style={{fontSize:12, fontWeight:700, color:'#1A1A1A', textTransform:'uppercase', letterSpacing:'0.06em', marginBottom:10}}>Consent status summary</div>
          <div style={{display:'grid', gridTemplateColumns:'repeat(3,1fr)', gap:10}}>
            {[
              {label:'Broad consent (MII)', value:'Active', detail:'Signed 2026-01-12', ok:true},
              {label:'Specific – genetic data', value:'Active', detail:'Signed 2025-10-28', ok:true},
              {label:'Secondary research use', value:'Active', detail:'Opt-in confirmed', ok:true},
            ].map((c, i) => (
              <div key={i} style={{padding:'10px 12px', background:c.ok?'#F0FDF4':'#FEF2F2', border:`1px solid ${c.ok?'#2E7D5B44':'#D3202744'}`, borderRadius:4}}>
                <div style={{fontSize:11, fontWeight:600, color:c.ok?'#2E7D5B':'#D32027', marginBottom:2}}>{c.ok?'✓':''} {c.value}</div>
                <div style={{fontSize:12, color:'#1A1A1A', fontWeight:500}}>{c.label}</div>
                <div style={{fontSize:11, color:'#4A4A4A', marginTop:2}}>{c.detail}</div>
              </div>
            ))}
          </div>
        </div>

      </div>
    </div>
  );
}

Object.assign(window, { DataProvenance });
