// CHW Portal — drawer for resident detail + campaign composer + app shell

// ───────────────────────────────────────────────
// Resident detail drawer
// ───────────────────────────────────────────────
const ChwDrawer = ({ resident, onClose, onCompose }) => {
  if (!resident) return null;
  const r = resident;
  const consentList = [
    ['contact', 'Contact'], ['share', 'Share with partners'],
    ['home', 'Home visits'], ['research', 'Research'], ['hipaa', 'HIPAA'],
  ];
  return (
    <div className="chw-drawer-bg" onClick={onClose}>
      <div className="chw-drawer" onClick={(e) => e.stopPropagation()}>
        <div className="chw-drawer-head">
          <div className="top">
            <ChwAv name={r.first + ' ' + r.last} size={56} />
            <div style={{ flex: 1, minWidth: 0 }}>
              <h2>{r.first} {r.last}</h2>
              <div className="sub">
                {r.age} · {r.town}, MA · DOB {r.dob}
                {r.tags.includes('High priority') && <span className="chw-tag" data-tone="warn" style={{ marginLeft: 8 }}>High priority</span>}
              </div>
              <div style={{ marginTop: 8, display: 'flex', gap: 6, flexWrap: 'wrap' }}>
                {r.tags.map(t => <span key={t} className="chw-tag">{t}</span>)}
              </div>
            </div>
            <button className="x" onClick={onClose}><ChwIcon name="x" size={16} /></button>
          </div>
          <div style={{ display: 'flex', gap: 8, marginTop: 14 }}>
            <button className="chw-btn chw-btn-primary" onClick={() => onCompose([r])}>
              <ChwIcon name="send" size={13} /> Send message
            </button>
            <button className="chw-btn chw-btn-soft"><ChwIcon name="phone" size={13} /> Call</button>
            <button className="chw-btn chw-btn-soft"><ChwIcon name="note" size={13} /> Add note</button>
            <button className="chw-btn chw-btn-soft" style={{ marginLeft: 'auto' }}><ChwIcon name="pen" size={13} /></button>
          </div>
        </div>

        <div className="chw-section">
          <h4>Contact</h4>
          <dl className="chw-kv">
            <dt>Phone</dt><dd>{r.phone}</dd>
            <dt>Email</dt><dd>{r.email || <span style={{ color: 'var(--eq-muted)' }}>—</span>}</dd>
            <dt>Preferred</dt><dd>{r.preferred} · {r.bestTime}</dd>
            <dt>Language</dt><dd>{r.language}</dd>
            <dt>Coordinator</dt><dd>{r.coordinator}</dd>
          </dl>
        </div>

        <div className="chw-section">
          <h4>Health</h4>
          <dl className="chw-kv">
            <dt>Conditions</dt>
            <dd>{r.conditions.length === 0 ? <span style={{ color: 'var(--eq-muted)' }}>None reported</span>
              : r.conditions.map(c => <span key={c} className="chw-tag">{c}</span>)}</dd>
            <dt>Provider</dt><dd>{r.provider}</dd>
            <dt>Insurance</dt><dd>{r.insurance}</dd>
            <dt>Lives alone</dt><dd>{r.livesAlone ? 'Yes' : 'No'}</dd>
          </dl>
        </div>

        <div className="chw-section">
          <h4>Access to care</h4>
          <dl className="chw-kv">
            <dt>Transport</dt><dd>{r.transport}</dd>
            <dt>Mobility</dt><dd>{r.mobility.length === 0 ? <span style={{ color: 'var(--eq-muted)' }}>None</span> : r.mobility.join(', ')}</dd>
            <dt>Distance to clinic</dt><dd>{r.distance} miles</dd>
          </dl>
        </div>

        <div className="chw-section">
          <h4>Services interested in</h4>
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
            {r.services.length === 0 && <span style={{ color: 'var(--eq-muted)', fontSize: 13 }}>None selected</span>}
            {r.services.map(s => <span key={s} className="chw-tag" data-tone="ok">{s}</span>)}
          </div>
        </div>

        <div className="chw-section">
          <h4>Consents on file</h4>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
            {consentList.map(([k, l]) => (
              <div key={k} style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 13 }}>
                <span style={{
                  width: 18, height: 18, borderRadius: 6, flexShrink: 0,
                  background: r.consents[k] ? 'var(--eq-sage-deep)' : 'var(--eq-line)',
                  color: '#fff', display: 'grid', placeItems: 'center',
                }}>
                  {r.consents[k] ? <ChwIcon name="check" size={11} stroke={2.5} /> : <ChwIcon name="x" size={11} stroke={2.5} />}
                </span>
                <span style={{ color: r.consents[k] ? 'var(--eq-ink)' : 'var(--eq-muted)' }}>{l}</span>
              </div>
            ))}
          </div>
        </div>

        <ChwSdohSection resident={r} />

        <EpicDrawerSection epic={getEpic(r.id)} resident={r} onBreakGlass={() => alert('Full access log for this resident opens here.')} />

        <div className="chw-section">
          <h4>Activity</h4>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
            {r.lastContact && (
              <div style={{ display: 'flex', gap: 10, fontSize: 13 }}>
                <div style={{ width: 6, height: 6, borderRadius: 999, background: 'var(--eq-sage-deep)', marginTop: 7 }} />
                <div>
                  <div>Last contacted by {r.coordinator}</div>
                  <div style={{ fontSize: 11, color: 'var(--eq-muted)' }}>{formatDate(r.lastContact)} · {daysAgo(r.lastContact)} days ago</div>
                </div>
              </div>
            )}
            <div style={{ display: 'flex', gap: 10, fontSize: 13 }}>
              <div style={{ width: 6, height: 6, borderRadius: 999, background: 'var(--eq-line)', marginTop: 7 }} />
              <div>
                <div>Registered</div>
                <div style={{ fontSize: 11, color: 'var(--eq-muted)' }}>{formatDate(r.registered)}</div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

// ───────────────────────────────────────────────
// Campaign composer modal
// ───────────────────────────────────────────────
const ChwComposer = ({ recipients, cohortName, onClose, onSend }) => {
  const [channel, setChannel] = React.useState('text');
  const [template, setTemplate] = React.useState(null);
  const [subject, setSubject] = React.useState('');
  const [body, setBody] = React.useState('');
  const [scheduled, setScheduled] = React.useState(false);
  const [scheduleDate, setScheduleDate] = React.useState('');

  const reachable = {
    text:  recipients.filter(r => r.preferred === 'Text message' || r.phone),
    call:  recipients.filter(r => r.phone),
    email: recipients.filter(r => r.email),
    mail:  recipients.filter(r => true),
  };

  const applyTemplate = (t) => {
    setTemplate(t.id);
    setSubject(t.subject);
    setBody(t.body);
  };

  const previewWith = recipients[0] || { first: 'Resident', town: 'your town', coordinator: 'your coordinator' };
  const renderPreview = (str) => str
    .replace(/\{\{first\}\}/g, previewWith.first)
    .replace(/\{\{town\}\}/g, previewWith.town)
    .replace(/\{\{coordinator\}\}/g, previewWith.coordinator);

  return (
    <div className="chw-modal-bg" onClick={onClose}>
      <div className="chw-modal" onClick={(e) => e.stopPropagation()}>
        {/* Sidebar */}
        <div className="chw-composer-side">
          <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: '0.1em', textTransform: 'uppercase', color: 'var(--eq-muted)', marginBottom: 6 }}>
            Sending to
          </div>
          <div style={{ fontFamily: 'var(--eq-serif)', fontSize: 22, fontWeight: 500, lineHeight: 1.1, marginBottom: 4 }}>
            {cohortName || `${recipients.length} resident${recipients.length === 1 ? '' : 's'}`}
          </div>
          <div style={{ fontSize: 12, color: 'var(--eq-muted)', marginBottom: 14 }}>
            {recipients.length} resident{recipients.length === 1 ? '' : 's'} · only those who consented
          </div>

          <div className="chw-recipient-tags">
            {recipients.slice(0, 14).map(r => (
              <span key={r.id} className="chw-recipient-tag">{r.first} {r.last[0]}.</span>
            ))}
            {recipients.length > 14 && <span className="chw-recipient-tag">+{recipients.length - 14} more</span>}
          </div>

          <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: '0.1em', textTransform: 'uppercase', color: 'var(--eq-muted)', margin: '20px 0 8px' }}>
            Channel
          </div>
          {[
            { v: 'text',  l: 'Text message', s: 'Best for short updates', ic: 'msg', count: reachable.text.length },
            { v: 'email', l: 'Email',       s: 'Longer, formatted',       ic: 'mail', count: reachable.email.length },
            { v: 'call',  l: 'Phone call list',  s: 'For coordinator follow-up', ic: 'phone', count: reachable.call.length },
            { v: 'mail',  l: 'Print mailers',    s: 'Postal — no internet needed', ic: 'home', count: reachable.mail.length },
          ].map(c => (
            <div key={c.v} className="chw-channel" data-on={channel === c.v} onClick={() => setChannel(c.v)}>
              <div className="ch-icon"><ChwIcon name={c.ic} size={15} /></div>
              <div>
                <b>{c.l}</b>
                <small>{c.s}</small>
              </div>
              <span className="reach">{c.count}/{recipients.length}</span>
            </div>
          ))}

          <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: '0.1em', textTransform: 'uppercase', color: 'var(--eq-muted)', margin: '20px 0 8px' }}>
            Templates
          </div>
          {EQ_CAMPAIGN_TEMPLATES.map(t => (
            <button key={t.id} onClick={() => applyTemplate(t)} style={{
              display: 'block', width: '100%', textAlign: 'left',
              padding: '10px 12px', borderRadius: 10, marginBottom: 6,
              background: template === t.id ? 'var(--eq-ink)' : 'var(--eq-surface)',
              color: template === t.id ? 'var(--eq-surface)' : 'var(--eq-ink)',
              border: '1px solid var(--eq-line)',
              fontSize: 12, fontWeight: 500,
            }}>
              {t.name}
            </button>
          ))}
        </div>

        {/* Main */}
        <div className="chw-composer-main">
          <div className="head">
            <h3>{template ? 'Compose from template' : 'New message'}</h3>
            <div style={{ marginLeft: 'auto', display: 'flex', alignItems: 'center', gap: 8, fontSize: 11, color: 'var(--eq-muted)' }}>
              <ChwIcon name="lock" size={12} />
              <span>HIPAA-compliant · audit logged</span>
            </div>
            <button className="chw-btn chw-btn-ghost" onClick={onClose} style={{ width: 32, height: 32, padding: 0 }}>
              <ChwIcon name="x" size={16} />
            </button>
          </div>
          <div className="chw-composer-body">
            {(channel === 'email' || channel === 'mail') && (
              <div>
                <label style={{ fontSize: 11, fontWeight: 700, letterSpacing: '0.08em', textTransform: 'uppercase', color: 'var(--eq-muted)', display: 'block', marginBottom: 6 }}>
                  Subject
                </label>
                <input className="chw-input" value={subject} onChange={(e) => setSubject(e.target.value)}
                       placeholder="Free vaccine clinic at {{town}} Town Hall" />
              </div>
            )}
            <div>
              <label style={{ fontSize: 11, fontWeight: 700, letterSpacing: '0.08em', textTransform: 'uppercase', color: 'var(--eq-muted)', display: 'block', marginBottom: 6 }}>
                Message
                <span style={{ marginLeft: 8, fontWeight: 500, color: 'var(--eq-muted)', textTransform: 'none', letterSpacing: 0 }}>
                  · Use <code style={{ background: 'var(--eq-surface-2)', padding: '1px 4px', borderRadius: 3 }}>{'{{first}}'}</code> <code style={{ background: 'var(--eq-surface-2)', padding: '1px 4px', borderRadius: 3 }}>{'{{town}}'}</code> <code style={{ background: 'var(--eq-surface-2)', padding: '1px 4px', borderRadius: 3 }}>{'{{coordinator}}'}</code>
                </span>
              </label>
              <textarea className="chw-input chw-textarea" value={body} onChange={(e) => setBody(e.target.value)}
                        placeholder={channel === 'text' ? 'Hi {{first}}, just checking in...' : 'Hi {{first}},\n\n...'} />
            </div>

            {body && (
              <div style={{
                background: 'var(--eq-surface-2)',
                border: '1px solid var(--eq-line)',
                borderRadius: 10, padding: 14,
              }}>
                <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: '0.08em', textTransform: 'uppercase', color: 'var(--eq-muted)', marginBottom: 8 }}>
                  Preview · for {previewWith.first} {previewWith.last || ''}
                </div>
                {(channel === 'email' || channel === 'mail') && subject && (
                  <div style={{ fontWeight: 600, marginBottom: 6, fontSize: 14 }}>{renderPreview(subject)}</div>
                )}
                <div style={{ fontSize: 13, lineHeight: 1.55, whiteSpace: 'pre-wrap', color: 'var(--eq-ink)' }}>
                  {renderPreview(body)}
                </div>
              </div>
            )}

            <label style={{ display: 'flex', alignItems: 'center', gap: 8, cursor: 'pointer', fontSize: 13, marginTop: 4 }}>
              <input type="checkbox" checked={scheduled} onChange={(e) => setScheduled(e.target.checked)} />
              Schedule for later
            </label>
            {scheduled && (
              <input className="chw-input" type="datetime-local" value={scheduleDate}
                     onChange={(e) => setScheduleDate(e.target.value)} style={{ width: 250 }} />
            )}
          </div>
          <div className="chw-composer-foot">
            <div style={{ fontSize: 12, color: 'var(--eq-muted)' }}>
              Will reach <b style={{ color: 'var(--eq-ink)' }}>{reachable[channel]?.length}</b> via {channel === 'call' ? 'phone' : channel}
            </div>
            <div style={{ flex: 1 }} />
            <button className="chw-btn chw-btn-ghost" onClick={onClose}>Cancel</button>
            <button className="chw-btn chw-btn-soft" onClick={() => alert('Saved as draft.')}>Save draft</button>
            <button className="chw-btn chw-btn-primary" disabled={!body}
                    style={{ opacity: body ? 1 : 0.45 }}
                    onClick={() => onSend({ channel, subject, body, count: reachable[channel]?.length || 0, scheduled, scheduleDate })}>
              <ChwIcon name="send" size={13} />
              {scheduled ? 'Schedule' : `Send to ${reachable[channel]?.length || 0}`}
            </button>
          </div>
        </div>
      </div>
    </div>
  );
};

// ───────────────────────────────────────────────
// Toast
// ───────────────────────────────────────────────
const ChwToast = ({ msg }) => msg ? (
  <div className="chw-toast">
    <ChwIcon name="check" size={14} stroke={2.5} />
    {msg}
  </div>
) : null;

// ───────────────────────────────────────────────
// App shell
// ───────────────────────────────────────────────
const ChwApp = () => {
  const [view, setView] = React.useState('dashboard');
  const [activeResident, setActiveResident] = React.useState(null);
  const [composer, setComposer] = React.useState(null); // { recipients, cohortName }
  const [toast, setToast] = React.useState('');
  const [activeCohort, setActiveCohort] = React.useState(null);
  const [initialRules, setInitialRules] = React.useState(null);

  const showToast = (m) => { setToast(m); setTimeout(() => setToast(''), 2400); };

  // Cohort templates → rules
  const cohortToRules = (c) => {
    if (c.id === 'c1') return [{ field: 'age', op: 'gte', value: '60' }, { field: 'condition', op: 'eq', value: 'Diabetes' }];
    if (c.id === 'c2') return [{ field: 'language', op: 'eq', value: 'Spanish' }];
    if (c.id === 'c3') return [{ field: 'livesAlone', op: 'eq', value: 'true' }, { field: 'transport', op: 'eq', value: 'I\u2019t have reliable transport' }];
    if (c.id === 'c4') return [{ field: 'insurance', op: 'eq', value: 'Uninsured' }];
    if (c.id === 'c5') return [{ field: 'status', op: 'eq', value: 'New' }];
    return [];
  };

  const openComposerForCohort = (c) => {
    if (c.residents) {
      setComposer({ recipients: c.residents.filter(r => r.consents.contact), cohortName: c.name });
    } else {
      const rules = cohortToRules(c);
      const recips = EQ_RESIDENTS.filter(r => matchesRules(r, rules) && r.consents.contact);
      setComposer({ recipients: recips, cohortName: c.name });
    }
  };

  const sendCampaign = (cfg) => {
    setComposer(null);
    showToast(cfg.scheduled ? `Campaign scheduled for ${cfg.count} recipients.` : `Sent to ${cfg.count} recipients.`);
  };

  return (
    <div className="chw">
      {/* Sidebar */}
      <aside className="chw-side">
        <div className="brand">
          <svg width="32" height="32" viewBox="0 0 40 40" fill="none">
            <path d="M20 5 C28 5 34 11 34 20 C34 27 29 33 20 36 C11 33 6 27 6 20 C6 11 12 5 20 5 Z" fill="var(--eq-sage)" />
            <path d="M13 22 L18 22 L20 17 L22 26 L24 22 L28 22"
                  stroke="var(--eq-sage-deep)" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round" fill="none" />
          </svg>
          <div>
            <div className="name">East Quabbin</div>
            <div className="role">CHW Portal</div>
          </div>
        </div>

        <h5>Workspace</h5>
        <div className="chw-nav" data-active={view === 'dashboard'} onClick={() => setView('dashboard')}>
          <ChwIcon name="activity" size={15} /> Dashboard
        </div>
        <div className="chw-nav" data-active={view === 'residents'} onClick={() => { setInitialRules([]); setActiveCohort(null); setView('residents'); }}>
          <ChwIcon name="users" size={15} /> Residents
          <span className="count">{EQ_RESIDENTS.length}</span>
        </div>
        <div className="chw-nav">
          <ChwIcon name="send" size={15} /> Campaigns
          <span className="count">3</span>
        </div>
        <div className="chw-nav">
          <ChwIcon name="calendar" size={15} /> Schedule
        </div>
        <div className="chw-nav">
          <ChwIcon name="note" size={15} /> Notes
        </div>

        <h5>Integrations</h5>
        <div className="chw-nav" data-active={view === 'epic'} onClick={() => setView('epic')}>
          <span style={{ display: 'inline-flex', alignItems: 'center', justifyContent: 'center', width: 15, height: 15, borderRadius: 4, background: '#C8102E', color: 'white', fontWeight: 700, fontSize: 9 }}>E</span>
          Epic EHR
          <span className="count" style={{ background: 'color-mix(in oklab, #3f9c5a 20%, transparent)', color: '#1f6d3f' }}>●</span>
        </div>
        <div className="chw-nav" data-active={view === 'identity'} onClick={() => setView('identity')}>
          <span style={{ display: 'inline-flex', alignItems: 'center', justifyContent: 'center', width: 15, height: 15, borderRadius: 4, background: 'var(--eq-sage-deep)', color: 'white', fontWeight: 700, fontSize: 9 }}>ID</span>
          Identity &amp; matching
          <span className="count" style={{ background: 'color-mix(in srgb, var(--eq-warn) 22%, transparent)', color: 'var(--eq-warn)' }}>3</span>
        </div>
        <div className="chw-nav" style={{ color: 'var(--eq-muted)' }}>
          <span style={{ display: 'inline-flex', alignItems: 'center', justifyContent: 'center', width: 15, height: 15, borderRadius: 4, background: 'var(--eq-line)', color: 'var(--eq-muted)', fontWeight: 700, fontSize: 9 }}>+</span>
          Add integration
        </div>

        <h5>Saved cohorts</h5>
        {EQ_COHORTS.map(c => (
          <div key={c.id} className="chw-cohort" data-active={activeCohort === c.id}
               onClick={() => {
                 setActiveCohort(c.id);
                 setInitialRules(cohortToRules(c));
                 setView('residents');
               }}>
            <span className="dot" style={{ background: c.color }} />
            <span style={{ flex: 1, minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{c.name}</span>
            <span className="ct">{c.count}</span>
          </div>
        ))}
        <div className="chw-cohort" style={{ color: 'var(--eq-muted)' }}>
          <ChwIcon name="plus" size={13} /> New cohort
        </div>

        <div className="me">
          <ChwAv name="Sarah Kowalski" />
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontWeight: 600, fontSize: 13 }}>Sarah Kowalski</div>
            <div style={{ fontSize: 11, color: 'var(--eq-muted)' }}>Lead CHW · Petersham</div>
          </div>
          <ChwIcon name="settings" size={14} color="var(--eq-muted)" />
        </div>
      </aside>

      {/* Main */}
      <main className="chw-main">
        <div className="chw-topbar">
          <div className="crumbs">
            <span>Workspace</span>
            <ChwIcon name="chevronRight" size={11} />
            <b>{view === 'dashboard' ? 'Dashboard' : view === 'epic' ? 'Epic EHR integration' : view === 'identity' ? 'Identity & matching' : 'Residents'}</b>
            {view === 'residents' && activeCohort && <>
              <ChwIcon name="chevronRight" size={11} />
              <b>{EQ_COHORTS.find(c => c.id === activeCohort)?.name}</b>
            </>}
          </div>
          <div className="chw-search">
            <ChwIcon name="search" size={14} />
            <input placeholder="Search residents, cohorts, campaigns..." />
          </div>
          <button className="chw-btn chw-btn-soft"><ChwIcon name="bell" size={14} /></button>
          <button className="chw-btn chw-btn-primary" onClick={() => setComposer({ recipients: EQ_RESIDENTS.filter(r => r.consents.contact), cohortName: 'All consented residents' })}>
            <ChwIcon name="send" size={13} /> New campaign
          </button>
        </div>

        <div className="chw-content">
          {view === 'dashboard' &&
            <ChwDashboard
              openComposer={openComposerForCohort}
              openResident={setActiveResident}
              goResidents={() => { setInitialRules([]); setActiveCohort(null); setView('residents'); }}
            />}
          {view === 'residents' &&
            <ChwResidents
              key={JSON.stringify(initialRules)}
              initialRules={initialRules}
              openResident={setActiveResident}
              openComposerForCohort={openComposerForCohort}
            />}
          {view === 'epic' && <EpicAdmin />}
          {view === 'identity' && <ChwIdentityPage />}
        </div>
      </main>

      {activeResident && <ChwDrawer resident={activeResident}
        onClose={() => setActiveResident(null)}
        onCompose={(rs) => { setActiveResident(null); setComposer({ recipients: rs.filter(r => r.consents.contact), cohortName: `${rs[0].first} ${rs[0].last}` }); }} />}

      {composer && <ChwComposer recipients={composer.recipients} cohortName={composer.cohortName}
        onClose={() => setComposer(null)} onSend={sendCampaign} />}

      <ChwToast msg={toast} />
    </div>
  );
};

window.ChwApp = ChwApp;
