// Epic UI components — chip, panel, sparkline, problem/med/lab/encounter/appt/gap renderers

// Small provenance chip: tells user "this data came from Epic"
const EpicChip = ({ fresh = true, size = 'sm' }) => (
  <span className="epic-chip" title={fresh ? 'Live from Epic — synced within 15 min' : 'Epic — last sync > 1 hr'}>
    <span className="dot" />
    Epic
  </span>
);

// Status pill for the connection
const EpicStatusPill = ({ tone, children }) => (
  <span className="epic-status" data-tone={tone}>
    <span className="dot" />{children}
  </span>
);

// Small sparkline for lab trends
const EpicSpark = ({ values, width = 56, height = 18, color }) => {
  if (!values || values.length < 2) return null;
  const min = Math.min(...values), max = Math.max(...values);
  const range = max - min || 1;
  const stepX = width / (values.length - 1);
  const pts = values.map((v, i) => `${i * stepX},${height - ((v - min) / range) * height}`).join(' ');
  return (
    <svg className="epic-spark" width={width} height={height} viewBox={`0 0 ${width} ${height}`}>
      <polyline points={pts} fill="none" stroke={color || 'var(--epic-red)'} strokeWidth="1.5"
                strokeLinecap="round" strokeLinejoin="round" />
      <circle cx={(values.length - 1) * stepX} cy={height - ((values[values.length - 1] - min) / range) * height}
              r="2" fill={color || 'var(--epic-red)'} />
    </svg>
  );
};

// Unified Epic panel — header + body slot
const EpicPanel = ({ title, icon, sub, actions, children }) => (
  <div className="epic-panel">
    <div className="epic-panel-head">
      {icon && <ChwIcon name={icon} size={15} color="var(--epic-red)" />}
      <h4>{title}</h4>
      {sub && <span className="sub">· {sub}</span>}
      <div className="actions">
        <EpicChip />
        {actions}
      </div>
    </div>
    <div className="epic-panel-body">{children}</div>
  </div>
);

const EpicFlag = ({ f, children }) => <span className="epic-flag" data-f={f}>{children}</span>;

// ─── Resident drawer Epic block ──────────────────────────────────
const EpicDrawerSection = ({ epic, resident, onBreakGlass }) => {
  if (!epic) {
    return (
      <div className="chw-section">
        <h4>Epic record</h4>
        <div className="epic-link-state">
          <ChwIcon name="search" size={16} color="var(--epic-red)" />
          <div style={{ flex: 1 }}>
            <b>No Epic record linked.</b> Search by DOB + name to match this resident to their chart.
          </div>
          <button className="chw-btn chw-btn-soft" style={{ fontSize: 12 }}>Search Epic</button>
        </div>
      </div>
    );
  }

  const [tab, setTab] = React.useState('overview');
  const tabs = [
    { v: 'overview', l: 'Overview', ic: 'activity' },
    { v: 'problems', l: 'Problems', ic: 'note', n: epic.problems.filter(p => p.status === 'active').length },
    { v: 'meds', l: 'Meds', ic: 'pen', n: epic.meds.length },
    { v: 'labs', l: 'Labs & vitals', ic: 'activity', n: epic.labs.length },
    { v: 'encounters', l: 'Encounters', ic: 'calendar', n: epic.encounters.length },
    { v: 'appts', l: 'Appts', ic: 'calendar', n: epic.appointments.length },
    { v: 'gaps', l: 'Care gaps', ic: 'bell', n: epic.careGaps.filter(g => g.status === 'overdue').length },
    { v: 'imms', l: 'Immunizations', ic: 'check' },
    { v: 'sdoh', l: 'SDoH', ic: 'heart' },
  ];

  return (
    <div className="chw-section" style={{ background: 'transparent', padding: 0, border: 0, margin: '0 20px 16px' }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 10 }}>
        <h4 style={{ margin: 0, fontFamily: 'var(--eq-serif)', fontWeight: 500, fontSize: 15 }}>Epic record</h4>
        <EpicChip />
        <span style={{ fontSize: 11, color: 'var(--eq-muted)' }}>
          MRN {epic.mrn} · matched {epic.matchConfidence}%
        </span>
        <button className="chw-btn chw-btn-ghost" style={{ marginLeft: 'auto', fontSize: 11, height: 26 }}
                onClick={onBreakGlass}>
          <ChwIcon name="lock" size={11} /> Access log
        </button>
      </div>

      <div className="epic-panel">
        {/* Tab strip */}
        <div style={{
          display: 'flex', gap: 2, padding: '6px 8px',
          borderBottom: '1px solid var(--eq-line)',
          background: 'var(--eq-surface-2)',
          overflowX: 'auto',
        }}>
          {tabs.map(t => (
            <button key={t.v} onClick={() => setTab(t.v)}
              style={{
                display: 'flex', alignItems: 'center', gap: 5,
                padding: '7px 10px', borderRadius: 7, border: 0, cursor: 'pointer',
                background: tab === t.v ? 'var(--eq-surface)' : 'transparent',
                color: tab === t.v ? 'var(--eq-ink)' : 'var(--eq-muted)',
                fontWeight: tab === t.v ? 600 : 500, fontSize: 12,
                fontFamily: 'inherit', whiteSpace: 'nowrap',
                boxShadow: tab === t.v ? '0 1px 2px rgba(0,0,0,.05)' : 'none',
              }}>
              <ChwIcon name={t.ic} size={11} /> {t.l}
              {t.n !== undefined && <span style={{ fontSize: 10, opacity: 0.7 }}>{t.n}</span>}
            </button>
          ))}
        </div>

        <div style={{ padding: 16 }}>
          {tab === 'overview' && (
            <div style={{ display: 'grid', gap: 14 }}>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
                <div><div style={{ fontSize: 10, letterSpacing: '.08em', textTransform: 'uppercase', color: 'var(--eq-muted)', fontWeight: 700 }}>MRN</div>
                  <div style={{ fontFamily: 'var(--eq-mono, monospace)', fontSize: 13, marginTop: 2 }}>{epic.mrn}</div></div>
                <div><div style={{ fontSize: 10, letterSpacing: '.08em', textTransform: 'uppercase', color: 'var(--eq-muted)', fontWeight: 700 }}>Address on file</div>
                  <div style={{ fontSize: 13, marginTop: 2 }}>{epic.addressOnFile}</div></div>
                <div><div style={{ fontSize: 10, letterSpacing: '.08em', textTransform: 'uppercase', color: 'var(--eq-muted)', fontWeight: 700 }}>Primary care</div>
                  <div style={{ fontSize: 13, marginTop: 2 }}>{epic.pcp.name}<br /><span style={{ color: 'var(--eq-muted)', fontSize: 11 }}>{epic.pcp.clinic} · {epic.pcp.phone}</span></div></div>
                <div><div style={{ fontSize: 10, letterSpacing: '.08em', textTransform: 'uppercase', color: 'var(--eq-muted)', fontWeight: 700 }}>Care team ({epic.careTeam.length})</div>
                  <div style={{ fontSize: 12, marginTop: 2, color: 'var(--eq-ink-2)' }}>
                    {epic.careTeam.map(m => <div key={m.name}>{m.name} <span style={{ color: 'var(--eq-muted)' }}>· {m.role}</span></div>)}
                  </div></div>
              </div>

              {/* key flags */}
              {(epic.allergies.length > 0 || epic.careGaps.some(g => g.status === 'overdue')) && (
                <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
                  {epic.allergies.length > 0 && <EpicFlag f="high">⚠ {epic.allergies.length} allerg{epic.allergies.length === 1 ? 'y' : 'ies'}</EpicFlag>}
                  {epic.careGaps.filter(g => g.status === 'overdue').map(g =>
                    <EpicFlag key={g.label} f="overdue">Overdue: {g.label}</EpicFlag>)}
                </div>
              )}
            </div>
          )}

          {tab === 'problems' && (
            <table className="epic-dt">
              <thead><tr><th>Condition</th><th>ICD-10</th><th>Onset</th><th>Status</th></tr></thead>
              <tbody>{epic.problems.map(p => (
                <tr key={p.code}><td><b>{p.label}</b></td>
                  <td style={{ fontFamily: 'var(--eq-mono, monospace)', fontSize: 11 }}>{p.code}</td>
                  <td>{p.onset}</td>
                  <td>{p.status === 'active' ? <EpicFlag f="watch">Active</EpicFlag>
                    : p.status === 'remission' ? <EpicFlag f="ok">Remission</EpicFlag>
                    : <span style={{ color: 'var(--eq-muted)' }}>Resolved</span>}</td></tr>))}</tbody>
            </table>
          )}

          {tab === 'meds' && (
            <table className="epic-dt">
              <thead><tr><th>Medication</th><th>Dose</th><th>Frequency</th><th>Prescriber</th><th>Since</th></tr></thead>
              <tbody>{epic.meds.map(m => (
                <tr key={m.name}><td><b>{m.name}</b></td><td>{m.dose}</td><td>{m.freq}</td>
                  <td>{m.prescriber}</td>
                  <td style={{ color: 'var(--eq-muted)' }}>{m.since}</td></tr>))}</tbody>
            </table>
          )}

          {tab === 'labs' && (
            <table className="epic-dt">
              <thead><tr><th>Measure</th><th>Value</th><th>Flag</th><th>Ref range</th><th>Date</th><th>Trend</th></tr></thead>
              <tbody>{epic.labs.map(l => (
                <tr key={l.name + l.date}><td><b>{l.name}</b></td>
                  <td style={{ fontFamily: 'var(--eq-serif)', fontSize: 15, fontWeight: 500 }}>{l.value} <span style={{ fontSize: 11, color: 'var(--eq-muted)', fontFamily: 'var(--eq-sans)' }}>{l.unit}</span></td>
                  <td><EpicFlag f={l.flag}>{l.flag}</EpicFlag></td>
                  <td style={{ color: 'var(--eq-muted)', fontSize: 11 }}>{l.ref}</td>
                  <td style={{ color: 'var(--eq-muted)', fontSize: 11 }}>{l.date}</td>
                  <td>{l.trend && <EpicSpark values={l.trend} color={l.flag === 'high' || l.flag === 'low' ? 'var(--epic-red)' : 'var(--eq-sage-deep)'} />}</td>
                </tr>))}</tbody>
            </table>
          )}

          {tab === 'encounters' && (
            <table className="epic-dt">
              <thead><tr><th>Date</th><th>Kind</th><th>Provider</th><th>Reason</th></tr></thead>
              <tbody>{epic.encounters.map(e => (
                <tr key={e.date + e.reason}><td style={{ whiteSpace: 'nowrap' }}>{e.date}</td>
                  <td><EpicFlag f={e.kind === 'ER visit' ? 'high' : e.kind === 'Urgent care' ? 'watch' : 'ok'}>{e.kind}</EpicFlag></td>
                  <td>{e.provider}<div className="meta">{e.clinic}</div></td>
                  <td>{e.reason}</td></tr>))}</tbody>
            </table>
          )}

          {tab === 'appts' && (
            epic.appointments.length === 0 ? <div style={{ color: 'var(--eq-muted)', fontSize: 13 }}>No upcoming appointments on file.</div> :
            <table className="epic-dt">
              <thead><tr><th>Date</th><th>Time</th><th>Kind</th><th>Provider</th><th>Reason</th></tr></thead>
              <tbody>{epic.appointments.map(a => (
                <tr key={a.date + a.time}><td>{a.date}</td><td>{a.time}</td>
                  <td>{a.kind}</td><td>{a.provider}<div className="meta">{a.clinic}</div></td><td>{a.reason}</td></tr>))}</tbody>
            </table>
          )}

          {tab === 'gaps' && (
            <table className="epic-dt">
              <thead><tr><th>Care gap</th><th>Status</th><th>Due</th><th>Owner</th></tr></thead>
              <tbody>{epic.careGaps.map(g => (
                <tr key={g.label}><td><b>{g.label}</b></td>
                  <td><EpicFlag f={g.status}>{g.status}</EpicFlag></td>
                  <td>{g.dueDate}</td><td>{g.owner}</td></tr>))}</tbody>
            </table>
          )}

          {tab === 'imms' && (
            <table className="epic-dt">
              <thead><tr><th>Vaccine</th><th>Last given</th><th>Status</th></tr></thead>
              <tbody>{epic.immunizations.map(i => (
                <tr key={i.name}><td><b>{i.name}</b></td>
                  <td>{i.date || <span style={{ color: 'var(--eq-muted)' }}>—</span>}</td>
                  <td>{i.due ? (i.due.includes('Overdue') ? <EpicFlag f="overdue">{i.due}</EpicFlag> : <span style={{ color: 'var(--eq-muted)', fontSize: 11 }}>{i.due}</span>) : <EpicFlag f="ok">Up to date</EpicFlag>}</td></tr>))}</tbody>
            </table>
          )}

          {tab === 'sdoh' && (
            epic.sdoh.length === 0 ? <div style={{ color: 'var(--eq-muted)', fontSize: 13 }}>No SDoH screenings on file.</div> :
            <table className="epic-dt">
              <thead><tr><th>Screener</th><th>Response</th><th>Date</th></tr></thead>
              <tbody>{epic.sdoh.map((s, i) => (
                <tr key={i}><td><b>{s.q}</b></td>
                  <td><EpicFlag f={s.flag}>{s.a}</EpicFlag></td>
                  <td style={{ color: 'var(--eq-muted)' }}>{s.date}</td></tr>))}</tbody>
            </table>
          )}

          {/* Allergies always inline below */}
          {tab === 'overview' && epic.allergies.length > 0 && (
            <div style={{ marginTop: 0 }}>
              <div style={{ fontSize: 10, letterSpacing: '.08em', textTransform: 'uppercase', color: 'var(--eq-muted)', fontWeight: 700, marginBottom: 6 }}>
                ⚠ Allergies
              </div>
              {epic.allergies.map(a => (
                <div key={a.substance} style={{ fontSize: 13, padding: '6px 0', borderBottom: '1px dashed var(--eq-line)' }}>
                  <b>{a.substance}</b> · {a.reaction} <span style={{ color: 'var(--eq-muted)' }}>({a.severity})</span>
                </div>
              ))}
            </div>
          )}
        </div>
      </div>
    </div>
  );
};

// ─── Record-match modal (used during intake) ───────────────────
const EpicMatchModal = ({ onClose, onMatch, onCreate }) => {
  const [selected, setSelected] = React.useState(0);
  const [glass, setGlass] = React.useState(false);
  return (
    <div className="chw-modal-bg" onClick={onClose}>
      <div className="epic-match-modal" onClick={(e) => e.stopPropagation()}>
        <div className="epic-match-head">
          <div className="ic"><ChwIcon name="users" size={20} /></div>
          <div style={{ flex: 1 }}>
            <h2>Possible matches in Epic</h2>
            <div className="sub">
              Searching by DOB · last name · phone. Review before linking — accuracy matters.
            </div>
          </div>
          <EpicChip />
          <button className="chw-btn chw-btn-ghost" onClick={onClose} style={{ width: 32, height: 32, padding: 0 }}>
            <ChwIcon name="x" size={16} />
          </button>
        </div>

        <div style={{ padding: '18px 20px 4px', fontSize: 11, letterSpacing: '.08em', textTransform: 'uppercase', fontWeight: 700, color: 'var(--eq-muted)' }}>
          Search values
        </div>
        <div style={{ padding: '0 20px 14px', display: 'flex', gap: 8, flexWrap: 'wrap', fontSize: 12, color: 'var(--eq-ink-2)' }}>
          <span className="chw-tag">Dolores Fitzgerald</span>
          <span className="chw-tag">DOB 07/14/1948</span>
          <span className="chw-tag">(978) 555-0771</span>
          <span className="chw-tag">Petersham, MA</span>
        </div>

        <div style={{ padding: '0 20px 20px' }}>
          {EPIC_INTAKE_CANDIDATES.map((c, i) => (
            <div key={c.mrn} className="epic-candidate"
                 data-best={i === 0 && selected === i}
                 onClick={() => setSelected(i)}>
              <div className="conf">
                {c.confidence}%<small>match</small>
              </div>
              <div style={{ paddingRight: 80 }}>
                <h5>{c.first} {c.last}</h5>
                <div className="meta-row">
                  <span>MRN {c.mrn}</span>
                  <span>DOB {c.dob}</span>
                  <span>{c.phone}</span>
                </div>
                <div style={{ fontSize: 12, color: 'var(--eq-muted)', marginTop: 4 }}>
                  {c.address}
                </div>
                <div style={{ fontSize: 12, color: 'var(--eq-ink-2)', marginTop: 8 }}>
                  <b>PCP:</b> {c.pcp} · <b>Last visit:</b> {c.lastVisit} · <b>Problems:</b> {c.problems.join(', ')}
                </div>
                <div className="matched-on">
                  <span style={{ color: 'var(--eq-muted)', fontWeight: 600 }}>Matched on:</span>
                  {c.matchedOn.map(m => <span key={m} className="chw-tag" data-tone="ok">{m}</span>)}
                </div>
                {c.note && <div className="note">⚠ {c.note}</div>}
              </div>
              <div style={{ position: 'absolute', bottom: 16, right: 18 }}>
                <span style={{
                  width: 20, height: 20, borderRadius: 999, display: 'inline-grid', placeItems: 'center',
                  background: selected === i ? 'var(--eq-sage-deep)' : 'var(--eq-surface-2)',
                  border: selected === i ? '0' : '1.5px solid var(--eq-line)',
                  color: 'white',
                }}>{selected === i && <ChwIcon name="check" size={12} stroke={2.5} />}</span>
              </div>
            </div>
          ))}
        </div>

        <div style={{ padding: '14px 20px', borderTop: '1px solid var(--eq-line)', background: 'var(--eq-surface-2)', display: 'flex', alignItems: 'center', gap: 10 }}>
          <label style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 12, color: 'var(--eq-muted)' }}>
            <ChwIcon name="lock" size={11} />
            <input type="checkbox" checked={glass} onChange={(e) => setGlass(e.target.checked)} style={{ margin: 0 }} />
            Resident consented to link their Epic record
          </label>
          <div style={{ flex: 1 }} />
          <button className="chw-btn chw-btn-ghost" onClick={onCreate}>
            No match — create new
          </button>
          <button className="chw-btn chw-btn-primary" disabled={!glass}
                  style={{ opacity: glass ? 1 : 0.45 }}
                  onClick={() => onMatch(EPIC_INTAKE_CANDIDATES[selected])}>
            <ChwIcon name="check" size={13} stroke={2.5} /> Link to MRN {EPIC_INTAKE_CANDIDATES[selected].mrn}
          </button>
        </div>
      </div>
    </div>
  );
};

Object.assign(window, { EpicChip, EpicStatusPill, EpicSpark, EpicPanel, EpicFlag, EpicDrawerSection, EpicMatchModal });
