// note-editor.jsx — the progress note exactly as the chart shows it.
// No analysis, no provenance, no counts. Whatever the reader concludes about
// this document, they conclude by reading it.
// Exports on window: NoteEditor

const NOTE_TABS = [
  { id:'review', label:'Review' },
  { id:'notes', label:'Notes' },
  { id:'checklist', label:'Visit Checklist' },
  { id:'sign', label:'Sign Visit' },
  { id:'report', label:'Visit Report' },
];

const NOTE_TEMPLATES = ['Simple 1','CKD Initial 2','CKD FU 3','Procedure 4','Dietician 5',
                        'SW 6','BH 7','Telehealth 8','Chaperone 9'];

function NoteEditor({ day, setDay, copied, onCopyForward, silo, inserted = [], view = 'full', setView, digest }) {
  const meta = window.NOTE_DAY_META[day - 1];
  const sections = React.useMemo(() => window.buildNote(day), [day]);
  const bodyRef = React.useRef(null);
  const [tab, setTab] = React.useState('notes');

  const blank = day === 4 && !copied;
  // Silo view only exists once the addon is on — off, the note is always Full.
  const effectiveView = silo ? view : 'full';

  React.useEffect(() => { if (bodyRef.current) bodyRef.current.scrollTop = 0; }, [day, copied]);

  return (
    <div style={ne.root}>
      <div style={ne.tabStrip}>
        {NOTE_TABS.map(t => (
          <div key={t.id} data-gc={`note-tab-${t.id}`}
            style={{ ...ne.tab, ...(tab === t.id ? ne.tabActive : {}) }}
            onClick={() => setTab(t.id)}>
            {t.id === 'notes' && tab === 'notes' && <span style={ne.tabIcon}>📋</span>}
            {t.label}
          </div>
        ))}
      </div>

      <div style={ne.createRow}>
        <button style={ne.createBtn}>✚ Create Note ▾</button>
        <div style={ne.templateScroll}>
          {NOTE_TEMPLATES.map((t, i) => (
            <button key={i} style={ne.tmplBtn}>{t}</button>
          ))}
        </div>
      </div>

      <div style={ne.head}>
        <div style={ne.headLeft}>
          <span style={ne.noteType}>{meta.title}</span>
          <span style={ne.noteMeta}>{meta.date} · {meta.author} · Nephrology</span>
        </div>
      </div>

      <div style={ne.toolbar}>
        <span style={ne.tbLabel}>Day</span>
        <div style={ne.dayTrack}>
          {[1, 2, 3, 4].map(d => (
            <span key={d} data-gc={`note-day-${d}`}
              style={{ ...ne.dayPip, ...(day === d ? ne.dayPipOn : {}) }}
              onClick={() => setDay(d)}>{d}</span>
          ))}
        </div>
        <span style={ne.tbDate}>{meta.date}</span>
        <div style={{ flex: 1 }} />
        {silo && (
          <div style={ne.viewSwitch}>
            <span data-gc="note-view-full"
              style={{ ...ne.viewOpt, ...(effectiveView === 'full' ? ne.viewOptOn : {}) }}
              onClick={() => setView('full')}>Full</span>
            <span data-gc="note-view-summary"
              style={{ ...ne.viewOpt, ...(effectiveView === 'summary' ? ne.viewOptOnSilo : {}) }}
              onClick={() => setView('summary')}>Silo</span>
          </div>
        )}
      </div>

      {blank ? (
        <div style={ne.blankState}>
          <div style={ne.blankHint}>Progress note — 04/30/2026 — empty</div>
          <button style={ne.copyBtn} data-gc="note-copy-forward" onClick={onCopyForward}>
            ⟳ Copy Forward from 04/29
          </button>
        </div>
      ) : (
        <div style={ne.body} ref={bodyRef} data-gc="note-body">
          {effectiveView === 'summary' ? (
            <SiloSummary digest={digest} inserted={inserted} />
          ) : (
          <>
          {inserted.length > 0 && (
            <div style={ne.section}>
              <div style={ne.sectionLabel}>ADDED TODAY</div>
              {inserted.map(l => (
                <div key={l.id} style={ne.insertedLine}>{l.text}</div>
              ))}
            </div>
          )}
          {sections.map(sec => (
            <div key={sec.section} style={ne.section}>
              <div style={ne.sectionLabel}>{sec.section.toUpperCase()}</div>
              {sec.blocks.map(b => (
                <div key={b.id} style={ne.text}>{b.text}</div>
              ))}
            </div>
          ))}
          </>
          )}
          <div style={{ height: 20 }} />
        </div>
      )}
    </div>
  );
}

function SiloSummary({ digest, inserted }) {
  return (
    <div>
      <div style={ne.sumSection}>
        <div style={ne.sumLabel}>Where this patient stood yesterday</div>
        {digest.prior.map((l, i) => (
          <div key={i} style={ne.sumLine}><span style={ne.sumBullet}>—</span>{l}</div>
        ))}
      </div>
      <div style={ne.sumSection}>
        <div style={ne.sumLabel}>What is actually new today · {digest.newWords} words</div>
        {digest.today.map((t, i) => <div key={i} style={ne.sumNew}>{t}</div>)}
      </div>
      {inserted.length > 0 && (
        <div style={ne.sumSection}>
          <div style={ne.sumLabel}>Added from Silo</div>
          {inserted.map(l => <div key={l.id} style={ne.insertedLine}>{l.text}</div>)}
        </div>
      )}
      <div style={ne.sumFold}>
        {digest.carried.toLocaleString()} further words — templated review of systems and
        examination, auto-populated laboratory and medication tables, boilerplate attestation
        and billing text — are unchanged from yesterday and are hidden here.
      </div>
    </div>
  );
}

const EPIC_BLUE_N = '#0066CC';
const SILO_T = '#0B7A8C';
const ne = {
  viewSwitch: { display:'flex', border:'1px solid #CBD5E1', borderRadius:3, overflow:'hidden' },
  viewOpt: { fontSize:10, padding:'3px 8px', cursor:'pointer', color:'#4B5563', background:'white', whiteSpace:'nowrap' },
  viewOptOn: { background:'#374151', color:'white', fontWeight:600 },
  viewOptOnSilo: { background:SILO_T, color:'white', fontWeight:600 },
  insertedLine: { fontSize:12, lineHeight:1.65, color:'#111827', background:'#F0F9FA', borderLeft:`3px solid ${SILO_T}`, padding:'6px 9px', borderRadius:2, marginBottom:6 },
  sumSection: { marginBottom:14 },
  sumLabel: { fontSize:10, fontWeight:800, letterSpacing:0.6, color:SILO_T, textTransform:'uppercase', marginBottom:6 },
  sumLine: { display:'flex', gap:7, fontSize:12, color:'#374151', lineHeight:1.6, marginBottom:5 },
  sumBullet: { color:SILO_T, flexShrink:0 },
  sumNew: { fontSize:12, lineHeight:1.65, color:'#111827', background:'#DCFCE7', borderLeft:'3px solid #166534', padding:'7px 10px', borderRadius:2 },
  sumFold: { fontSize:10.5, color:'#9CA3AF', lineHeight:1.6, borderTop:'1px solid #E5E7EB', paddingTop:9 },
  tabStrip: { display:'flex', alignItems:'flex-end', background:'#F3F4F6', borderBottom:'2px solid #D1D5DB', padding:'0 6px', flexShrink:0, height:32 },
  tab: { display:'flex', alignItems:'center', gap:4, padding:'5px 10px', fontSize:11, color:'#6B7280', cursor:'pointer', borderRadius:'3px 3px 0 0', border:'1px solid transparent', borderBottom:'none', marginBottom:-2, whiteSpace:'nowrap' },
  tabActive: { background:'white', color:'#111827', fontWeight:600, border:'1px solid #D1D5DB', borderBottomColor:'white' },
  tabIcon: { fontSize:11 },
  createRow: { display:'flex', alignItems:'center', gap:4, padding:'5px 8px', background:'#F9FAFB', borderBottom:'1px solid #E5E7EB', flexShrink:0, overflow:'hidden' },
  createBtn: { fontSize:10.5, padding:'4px 11px', background:EPIC_BLUE_N, color:'white', border:'none', borderRadius:2, cursor:'pointer', fontWeight:600, flexShrink:0 },
  templateScroll: { display:'flex', gap:3, overflow:'hidden', flex:1 },
  tmplBtn: { fontSize:10, padding:'3px 8px', background:'white', border:'1px solid #CBD5E1', borderRadius:2, cursor:'pointer', color:'#374151', whiteSpace:'nowrap', flexShrink:0 },
  root: { width:'100%', height:'100%', display:'flex', flexDirection:'column', background:'white', borderLeft:'1px solid #D1D5DB', overflow:'hidden', fontFamily:'"Segoe UI", system-ui, sans-serif', fontSize:12 },
  head: { display:'flex', alignItems:'center', padding:'8px 12px', borderBottom:'1px solid #E5E7EB', background:'#F9FAFB', flexShrink:0 },
  headLeft: { display:'flex', flexDirection:'column', gap:2 },
  noteType: { fontSize:12.5, fontWeight:700, color:'#111827' },
  noteMeta: { fontSize:10, color:'#9CA3AF' },
  toolbar: { display:'flex', alignItems:'center', gap:7, padding:'5px 12px', borderBottom:'1px solid #F3F4F6', flexShrink:0 },
  tbLabel: { fontSize:10, fontWeight:700, color:'#6B7280' },
  dayTrack: { display:'flex', gap:3 },
  dayPip: { width:19, height:19, borderRadius:3, border:'1px solid #CBD5E1', display:'flex', alignItems:'center', justifyContent:'center', fontSize:11, cursor:'pointer', color:'#4B5563', background:'#fff' },
  dayPipOn: { background:'#0066CC', color:'#fff', borderColor:'#0066CC', fontWeight:700 },
  tbDate: { fontSize:10, color:'#9CA3AF' },
  blankState: { flex:1, display:'flex', flexDirection:'column', alignItems:'center', justifyContent:'center', gap:14, padding:'0 34px' },
  blankHint: { fontSize:11, color:'#9CA3AF' },
  copyBtn: { fontSize:14, fontWeight:600, padding:'11px 20px', background:'#0066CC', color:'#fff', border:'none', borderRadius:4, cursor:'pointer', boxShadow:'0 2px 8px rgba(0,102,204,0.28)' },
  body: { flex:1, overflowY:'auto', padding:'10px 12px', fontSize:12, lineHeight:1.65, color:'#374151' },
  section: { marginBottom:11 },
  sectionLabel: { fontSize:11.5, fontWeight:700, color:'#111827', marginBottom:4, paddingBottom:2, borderBottom:'1px solid #F1F5F9' },
  text: { fontSize:12, lineHeight:1.65, color:'#374151', marginBottom:7, transition:'color 160ms ease, background 160ms ease', borderRadius:2, padding:'2px 0' },
};

Object.assign(window, { NoteEditor });
