// ─────────────────────────────────────────────────────────────
// Corda Calendar · Providers section
// Multi-patient (Nana + Papa), PCP highlight, search, add/edit form,
// detail, archive, restore, delete
// ─────────────────────────────────────────────────────────────

// ── Extended provider data — includes contact + patient assignment ──
const CAL_PROV_DATA = [
  {
    id: 'cp_williams', name: 'Dr. Sara Williams', spec: 'Primary Care',
    org: 'Sutter · Castro', nbhd: 'Castro', tone: 'sage',
    patient: 'both', isPCP: true,
    phone: '(415) 206-4200', address: '45 Castro St, San Francisco',
    hours: 'Mon–Fri · 8:00 AM – 5:00 PM',
    notes: 'Manages both Nana and Papa. Call the nurse line first for non-urgent questions. She prefers portal messages over phone.',
  },
  {
    id: 'cp_patel', name: 'Dr. Anika Patel', spec: 'Neurology',
    org: 'UCSF · Mission Bay', nbhd: 'Mission Bay', tone: 'plum',
    patient: 'nana', isPCP: false,
    phone: '(415) 353-2273', address: '1825 4th St, Suite 240, San Francisco',
    hours: 'Mon–Thu · 9:00 AM – 4:00 PM',
    notes: 'Prefers email follow-ups via patient portal. Will call back same-day if marked urgent. Nana likes morning slots — she\'s sharper before noon.',
  },
  {
    id: 'cp_tomas', name: 'Tomás Reyes, PT', spec: 'Physical Therapy',
    org: 'Bay Home Health', nbhd: 'Home visits', tone: 'amber',
    patient: 'nana', isPCP: false,
    phone: '(415) 555-0192', address: 'Home visits — Nana\'s home',
    hours: 'Tue, Thu, Fri · 10:00 AM – 12:00 PM',
    notes: '',
  },
  {
    id: 'cp_mreyes', name: 'Dr. Marco Reyes', spec: 'Cardiology',
    org: 'St. Mary\'s Heart Center', nbhd: 'Western Addition', tone: 'plum',
    patient: 'papa', isPCP: false,
    phone: '(415) 750-5800', address: '45 Stanyan St, San Francisco',
    hours: 'Mon–Fri · 9:00 AM – 5:00 PM',
    notes: 'Referred us to this practice from UCSF. Good communicator — always sends a visit summary.',
  },
  {
    id: 'cp_yang', name: 'Dr. Lily Yang', spec: 'Ophthalmology',
    org: 'Pacific Vision', nbhd: 'Sunset', tone: 'plum',
    patient: 'papa', isPCP: false,
    phone: '(415) 664-8901', address: '2340 Irving St, San Francisco',
    hours: 'Wed–Sat · 9:00 AM – 3:00 PM',
    notes: '',
  },
];

const CAL_PROV_ARCHIVED = [
  {
    id: 'cp_chang', name: 'Dr. Amy Chang', spec: 'Dermatology',
    org: 'SF Derm Associates', tone: 'plum', patient: 'nana',
    archivedDate: 'Jan 12',
  },
];

const CAL_PCP = CAL_PROV_DATA.find(p => p.isPCP);

// ── Shared provider atoms ─────────────────────────────────────

// Pill chrome button — same as visit view
const CalProvChrome = ({ children, calProvStyle }) => (
  <div style={{
    background: 'var(--surface)', borderRadius: 999,
    boxShadow: '0 1px 2px rgba(40,30,20,.06), 0 4px 12px rgba(40,30,20,.05)',
    display: 'inline-flex', alignItems: 'center',
    ...calProvStyle,
  }}>{children}</div>
);

// Patient pip row — used in list when "Both" is active
const CalProvPatientPips = ({ patient }) => {
  if (patient === 'both') return (
    <div style={{ display: 'inline-flex', alignItems: 'center', gap: -4 }}>
      <CalPatientChip p={CAL_PATIENTS.nana} size={16} />
      <CalPatientChip p={CAL_PATIENTS.papa} size={16} style={{ marginLeft: -6, border: '1.5px solid var(--surface)' }} />
    </div>
  );
  const p = CAL_PATIENTS[patient];
  if (!p) return null;
  return (
    <div style={{
      display: 'inline-flex', alignItems: 'center', gap: 5,
      padding: '2px 8px 2px 2px', borderRadius: 999, background: p.soft,
    }}>
      <CalPatientChip p={p} size={14} />
      <span style={{ fontSize: 10.5, fontWeight: 600, color: p.deep }}>{p.name}</span>
    </div>
  );
};

// Provider list row — compact, with optional patient pip
const CalProvRow = ({ prov, showPatient = true, isLast }) => {
  const initials = prov.name.replace('Dr. ', '').replace(/, (PT|RN|OT|PA)$/, '');
  return (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 12,
      padding: '13px 0',
      borderBottom: isLast ? 'none' : '0.5px solid var(--hairline-soft)',
      cursor: 'pointer',
    }}>
      <Avatar name={initials} size={38} tone={prov.tone} />
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 14.5, fontWeight: 500, color: 'var(--ink)', lineHeight: 1.25,
          overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
          {prov.name}
        </div>
        <div style={{ fontSize: 12.5, color: 'var(--ink-3)', marginTop: 2,
          overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
          {[prov.spec, prov.org].filter(Boolean).join(' · ')}
        </div>
      </div>
      {showPatient && (
        <CalProvPatientPips patient={prov.patient} />
      )}
      <Icon name="chevron" size={14} color="var(--ink-3)" />
    </div>
  );
};

// PCP highlight card at top of list
const CalPCPCard = ({ showPatient = true }) => {
  const p = CAL_PCP;
  return (
    <div style={{ padding: '0 22px 18px' }}>
      <div style={{
        fontSize: 11, fontWeight: 600, color: 'var(--ink-3)',
        textTransform: 'uppercase', letterSpacing: 0.8, marginBottom: 8,
      }}>Primary care</div>
      <div style={{
        background: 'linear-gradient(135deg, var(--sage-tint), var(--sage-soft))',
        borderRadius: 18, padding: '14px 16px',
        display: 'flex', alignItems: 'center', gap: 12, cursor: 'pointer',
      }}>
        <Avatar name="Sara Williams" size={46} tone="sage" />
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontSize: 15.5, fontWeight: 600, letterSpacing: -0.2, color: 'var(--ink)' }}>
            {p.name}
          </div>
          <div style={{ fontSize: 12.5, color: 'var(--sage-ink)', marginTop: 2 }}>
            {p.org}
          </div>
          {showPatient && (
            <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginTop: 7 }}>
              <CalProvPatientPips patient={p.patient} />
            </div>
          )}
        </div>
        <button style={{
          width: 38, height: 38, borderRadius: '50%', flexShrink: 0,
          background: 'var(--surface)', border: 'none', cursor: 'pointer',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          boxShadow: 'var(--sh-1)',
        }}>
          <Icon name="phone" size={16} color="var(--sage-deep)" />
        </button>
      </div>
    </div>
  );
};

// Form field components (inline, no colliding style vars)
const CalProvFieldLabel = ({ children, required }) => (
  <div style={{
    fontSize: 11, fontWeight: 600, color: 'var(--ink-3)',
    textTransform: 'uppercase', letterSpacing: 0.7, marginBottom: 6,
    display: 'flex', alignItems: 'center', gap: 5,
  }}>
    {children}
    {required && <span style={{ fontSize: 9.5, fontWeight: 500, textTransform: 'none',
      letterSpacing: 0, color: 'var(--ink-4)', fontStyle: 'italic' }}>required</span>}
  </div>
);

const CalProvInput = ({ label, value, placeholder, required, trailing, leading, multiline, focus }) => (
  <div>
    <CalProvFieldLabel required={required}>{label}</CalProvFieldLabel>
    <div style={{
      background: 'var(--surface)',
      border: focus ? '1.5px solid var(--sage-deep)' : '0.5px solid var(--hairline)',
      borderRadius: 14, padding: multiline ? '14px 16px' : '13px 16px',
      display: 'flex', alignItems: multiline ? 'flex-start' : 'center', gap: 10,
      minHeight: multiline ? 96 : 'auto',
      boxShadow: focus ? '0 0 0 3px var(--sage-tint)' : 'none',
    }}>
      {leading}
      <span style={{ flex: 1, fontSize: 15, fontWeight: value ? 500 : 400,
        color: value ? 'var(--ink)' : 'var(--ink-4)', lineHeight: 1.55 }}>
        {value || placeholder}
      </span>
      {trailing}
    </div>
  </div>
);

// Detail info row
const CalProvDetailRow = ({ icon, label, value, sub, last }) => (
  <div style={{
    display: 'flex', alignItems: 'flex-start', gap: 12, padding: '13px 16px',
    borderBottom: last ? 'none' : '0.5px solid var(--hairline-soft)',
  }}>
    <Icon name={icon} size={15} color="var(--ink-3)" style={{ marginTop: 2, flexShrink: 0 }} />
    <div style={{ flex: 1, minWidth: 0 }}>
      <div style={{ fontSize: 11, color: 'var(--ink-3)', textTransform: 'uppercase',
        letterSpacing: 0.6, fontWeight: 600, marginBottom: 3 }}>{label}</div>
      <div style={{ fontSize: 14.5, color: 'var(--ink)', fontWeight: 500, lineHeight: 1.4 }}>{value}</div>
      {sub && <div style={{ fontSize: 12, color: 'var(--ink-3)', marginTop: 1 }}>{sub}</div>}
    </div>
  </div>
);

// ─────────────────────────────────────────────────────────────
// 1 · Providers list
// ─────────────────────────────────────────────────────────────
const ScreenCalProviders = ({ activePatient = 'all' }) => {
  const filtered = activePatient === 'all'
    ? CAL_PROV_DATA.filter(p => !p.isPCP)
    : CAL_PROV_DATA.filter(p => !p.isPCP && (p.patient === activePatient || p.patient === 'both'));

  const total = activePatient === 'all'
    ? CAL_PROV_DATA.length
    : CAL_PROV_DATA.filter(p => p.patient === activePatient || p.patient === 'both').length;

  const showPatientPip = activePatient === 'all';

  return (
    <Screen navActive="providers">
      <div style={{ overflow: 'auto', height: '100%', paddingBottom: 110 }}>

        {/* Header — switcher row, then eyebrow + title (mirrors app ProvidersHeader) */}
        <div style={{ padding: '8px 22px 0', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <CalPatientSwitcherButton active={activePatient} />
          <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
            <IconBtn name="search" tone="soft" />
            <button style={{
              width: 38, height: 38, borderRadius: '50%', flexShrink: 0, cursor: 'pointer',
              background: 'var(--sage-deep)', border: 'none',
              display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
            }} aria-label="Add provider">
              <Icon name="plus" size={18} color="#fff" stroke={2.2} />
            </button>
          </div>
        </div>
        <div style={{ padding: '14px 22px 16px' }}>
          <div style={{
            fontSize: 11.5, fontWeight: 500, color: 'var(--ink-3)',
            textTransform: 'uppercase', letterSpacing: 0.8, marginBottom: 4,
          }}>{total} providers</div>
          <CalSerifTitle size={30}>Care team</CalSerifTitle>
        </div>

        {/* PCP highlight */}
        <CalPCPCard showPatient={showPatientPip} />

        {/* Care team — rest of providers, sorted A–Z under the PCP */}
        <div style={{ padding: '0 22px' }}>
          {filtered.map((p, i) => (
            <CalProvRow key={p.id} prov={p} showPatient={showPatientPip} isLast={i === filtered.length - 1} />
          ))}
        </div>

        {/* Archived link — ghost button */}
        <div style={{ padding: '18px 22px 0' }}>
          <button style={{
            width: '100%', padding: '12px 16px', borderRadius: 12,
            background: 'transparent', border: '0.5px solid var(--hairline)',
            display: 'flex', alignItems: 'center', gap: 10,
            cursor: 'pointer', fontFamily: 'inherit', textAlign: 'left',
          }}>
            <Icon name="lock" size={15} color="var(--ink-3)" />
            <span style={{ flex: 1, fontSize: 13.5, color: 'var(--ink-3)', fontWeight: 500 }}>
              Archived providers
            </span>
            <span style={{
              fontSize: 11.5, fontWeight: 600, padding: '2px 8px', borderRadius: 999,
              background: 'var(--surface-2)', color: 'var(--ink-3)',
            }}>{CAL_PROV_ARCHIVED.length}</span>
            <Icon name="chevron" size={13} color="var(--ink-3)" />
          </button>
        </div>
      </div>
    </Screen>
  );
};

// Variant — filtered to Nana only
const ScreenCalProvidersNana = () => <ScreenCalProviders activePatient="nana" />;

// ─────────────────────────────────────────────────────────────
// 2 · Provider search
// ─────────────────────────────────────────────────────────────
const ScreenCalProvidersSearch = () => {
  const query = 'patel';
  const results = CAL_PROV_DATA.filter(p =>
    p.name.toLowerCase().includes(query) ||
    p.spec.toLowerCase().includes(query) ||
    p.org.toLowerCase().includes(query)
  );

  return (
    <Screen navActive="providers">
      <div style={{ padding: '8px 16px 0', display: 'flex', alignItems: 'center', gap: 10 }}>
        <button style={{ background: 'transparent', border: 'none', padding: 6,
          cursor: 'pointer', display: 'inline-flex' }}>
          <Icon name="back" size={18} color="var(--ink-2)" />
        </button>
        <div style={{
          flex: 1, display: 'flex', alignItems: 'center', gap: 8,
          padding: '10px 16px', borderRadius: 999,
          background: 'var(--surface)', border: '1.5px solid var(--sage-deep)',
          boxShadow: '0 0 0 3px var(--sage-tint)',
        }}>
          <Icon name="search" size={15} color="var(--sage-deep)" />
          <span style={{ flex: 1, fontSize: 15, color: 'var(--ink)', fontWeight: 500 }}>{query}</span>
          <div style={{ width: 18, height: 18, borderRadius: '50%', background: 'var(--ink-3)',
            display: 'inline-flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer' }}>
            <Icon name="close" size={10} color="var(--bg)" />
          </div>
        </div>
        <span style={{ fontSize: 14, color: 'var(--sage-deep)', fontWeight: 500, cursor: 'pointer' }}>Cancel</span>
      </div>

      <div style={{ overflow: 'auto', height: 'calc(100% - 56px)', paddingBottom: 110 }}>
        <div style={{ padding: '14px 22px 6px', fontSize: 11, fontWeight: 600,
          color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: 0.8 }}>
          {results.length} match{results.length !== 1 ? 'es' : ''}
        </div>
        <div style={{ padding: '0 22px' }}>
          {results.map((p, i) => (
            <CalProvRow key={p.id} prov={p} showPatient isLast={i === results.length - 1} />
          ))}
          {results.length === 0 && (
            <div style={{ padding: '40px 0', textAlign: 'center', fontSize: 13.5, color: 'var(--ink-3)' }}>
              No providers match "{query}"
            </div>
          )}
        </div>

        {/* Other providers dimmed */}
        {results.length > 0 && (
          <>
            <div style={{ padding: '18px 22px 6px', fontSize: 11, fontWeight: 600,
              color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: 0.8 }}>
              All providers
            </div>
            <div style={{ padding: '0 22px', opacity: 0.35 }}>
              {CAL_PROV_DATA.filter(p => !results.find(r => r.id === p.id)).map((p, i, arr) => (
                <CalProvRow key={p.id} prov={p} showPatient isLast={i === arr.length - 1} />
              ))}
            </div>
          </>
        )}
      </div>
    </Screen>
  );
};

// ─────────────────────────────────────────────────────────────
// 3 · Provider detail — read-only with chrome pills
// ─────────────────────────────────────────────────────────────
const ScreenCalProviderDetail = () => {
  const prov = CAL_PROV_DATA.find(p => p.id === 'cp_patel');
  const pat  = CAL_PATIENTS[prov.patient];

  return (
    <Screen hideNav>
      {/* Top chrome — back pill + Edit pill */}
      <div style={{ padding: '8px 18px 0', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <CalProvChrome calProvStyle={{ width: 38, height: 38, justifyContent: 'center' }}>
          <Icon name="back" size={17} color="var(--ink)" />
        </CalProvChrome>
        <CalProvChrome calProvStyle={{ padding: '0 16px', height: 36, cursor: 'pointer' }}>
          <span style={{ fontSize: 13.5, fontWeight: 600, color: 'var(--sage-deep)' }}>Edit</span>
        </CalProvChrome>
      </div>

      <div style={{ overflow: 'auto', height: 'calc(100% - 46px)', paddingBottom: 32 }}>

        {/* Hero */}
        <div style={{ padding: '20px 26px 20px', textAlign: 'center' }}>
          <Avatar name="Anika Patel" size={76} tone={prov.tone} />
          <div style={{
            fontFamily: 'var(--font-serif)', fontStyle: 'italic',
            fontSize: 30, lineHeight: 1.08, letterSpacing: '-0.025em',
            color: 'var(--ink)', marginTop: 14,
          }}>{prov.name}</div>
          <div style={{ fontSize: 14, color: 'var(--ink-2)', marginTop: 6 }}>
            {prov.spec} · {prov.org}
          </div>
          <div style={{ display: 'flex', justifyContent: 'center', marginTop: 12 }}>
            <div style={{
              display: 'inline-flex', alignItems: 'center', gap: 6,
              padding: '3px 11px 3px 3px', borderRadius: 999, background: pat.soft,
            }}>
              <CalPatientChip p={pat} size={18} />
              <span style={{ fontSize: 12, fontWeight: 600, color: pat.deep }}>{pat.full}</span>
            </div>
          </div>
        </div>

        {/* Quick actions */}
        <div style={{ padding: '0 22px 20px', display: 'flex', gap: 10 }}>
          {[
            { icon: 'phone', label: 'Call',      bg: 'var(--sage-tint)',  fg: 'var(--sage-deep)' },
            { icon: 'pin',   label: 'Directions', bg: 'var(--surface-2)', fg: 'var(--ink-2)'     },
            { icon: 'note',  label: 'Notes',     bg: 'var(--surface-2)', fg: 'var(--ink-2)'     },
          ].map(a => (
            <button key={a.label} style={{
              flex: 1, padding: '12px 8px', borderRadius: 14,
              background: a.bg, border: 'none', cursor: 'pointer',
              display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6,
              fontFamily: 'inherit',
            }}>
              <Icon name={a.icon} size={18} color={a.fg} />
              <span style={{ fontSize: 12, fontWeight: 500, color: a.fg }}>{a.label}</span>
            </button>
          ))}
        </div>

        {/* Contact */}
        <div style={{ padding: '0 22px 0' }}>
          <CalSL>Contact</CalSL>
          <div style={{
            background: 'var(--surface)', border: '0.5px solid var(--hairline)', borderRadius: 14, padding: 0,
          }}>
            <CalProvDetailRow icon="phone"    label="Phone"    value={prov.phone} />
            <CalProvDetailRow icon="pin"      label="Address"  value={prov.address} sub={prov.org} />
            <CalProvDetailRow icon="clock"    label="Hours"    value={prov.hours} last />
          </div>
        </div>

        {/* Notes */}
        {prov.notes ? (
          <div style={{ padding: '20px 22px 0' }}>
            <CalSL>Notes</CalSL>
            <div style={{
              background: 'var(--surface)', border: '0.5px solid var(--hairline)',
              borderRadius: 14, padding: '16px 18px',
              fontSize: 14.5, lineHeight: 1.65, color: 'var(--ink)',
            }}>{prov.notes}</div>
          </div>
        ) : null}

        {/* Visit count */}
        <div style={{ padding: '20px 22px 0' }}>
          <div style={{
            display: 'flex', alignItems: 'center', gap: 10,
            padding: '12px 14px', background: 'var(--surface-2)', borderRadius: 12,
            fontSize: 13, color: 'var(--ink-2)',
          }}>
            <Icon name="note" size={14} color="var(--ink-3)" />
            <span>Added by you · May 2</span>
          </div>
        </div>

        <div style={{ height: 28 }} />
      </div>
    </Screen>
  );
};

// ─────────────────────────────────────────────────────────────
// 4a · Add provider — type chooser (bottom sheet shown before the form)
// ─────────────────────────────────────────────────────────────
const CAL_PROV_TYPES = [
  { id: 'medical',  label: 'Medical',        desc: 'PCP, specialists, neurology, cardiology…',  icon: 'stethoscope', bg: 'var(--sage-tint)', fg: 'var(--sage-deep)' },
  { id: 'therapy',  label: 'Therapy',        desc: 'Physical, occupational, and speech therapy', icon: 'activity',    bg: 'var(--plum-soft)', fg: 'var(--plum)' },
  { id: 'home',     label: 'Home & Nursing', desc: 'Home health nursing, aide, hospice',          icon: 'home',        bg: 'var(--amber-soft)', fg: 'oklch(0.45 0.08 70)' },
  { id: 'pharmacy', label: 'Pharmacy',       desc: 'Retail or mail-order pharmacy',               icon: 'pill',        bg: 'var(--clay-soft)', fg: 'oklch(0.48 0.16 20)' },
];

const ScreenCalProviderAddType = () => (
  <Screen hideNav>
    {/* dimmed care team behind */}
    <div style={{ height: '100%', opacity: 0.4, filter: 'saturate(0.9)', pointerEvents: 'none' }}>
      <div style={{ padding: '8px 22px 0', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <CalPatientSwitcherButton active="all" />
        <div style={{ display: 'flex', gap: 8 }}><IconBtn name="search" tone="soft" /></div>
      </div>
      <div style={{ padding: '14px 22px 16px' }}>
        <div style={{ fontSize: 11.5, fontWeight: 500, color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: 0.8, marginBottom: 4 }}>5 providers</div>
        <CalSerifTitle size={30}>Care team</CalSerifTitle>
      </div>
      <CalPCPCard showPatient />
    </div>
    <div style={{ position: 'absolute', inset: 0, background: 'rgba(26,20,14,0.45)', zIndex: 40 }} />
    {/* sheet */}
    <div style={{
      position: 'absolute', left: 0, right: 0, bottom: 0, zIndex: 50,
      background: 'var(--bg)', borderRadius: '24px 24px 0 0',
      boxShadow: '0 -12px 40px rgba(40,30,20,.18)', padding: '12px 0 30px',
    }}>
      <div style={{ width: 36, height: 4, borderRadius: 4, background: 'var(--hairline)', margin: '0 auto 6px' }} />
      <div style={{ padding: '6px 22px 14px' }}>
        <div style={{ fontSize: 18, fontWeight: 600, color: 'var(--ink)', letterSpacing: '-0.01em' }}>Add provider</div>
        <div style={{ fontSize: 13.5, color: 'var(--ink-3)', marginTop: 3 }}>What type of provider?</div>
      </div>
      <div style={{ padding: '0 22px', display: 'flex', flexDirection: 'column', gap: 10 }}>
        {CAL_PROV_TYPES.map(o => (
          <div key={o.id} style={{
            display: 'flex', alignItems: 'center', gap: 14, cursor: 'pointer',
            background: 'var(--surface)', border: '0.5px solid var(--hairline)', borderRadius: 16, padding: '14px 16px',
          }}>
            <div style={{ width: 46, height: 46, borderRadius: 14, background: o.bg, flexShrink: 0, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
              <Icon name={o.icon} size={22} color={o.fg} />
            </div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 15, fontWeight: 600, color: 'var(--ink)', letterSpacing: '-0.01em' }}>{o.label}</div>
              <div style={{ fontSize: 12.5, color: 'var(--ink-3)', marginTop: 2 }}>{o.desc}</div>
            </div>
            <Icon name="chevron" size={15} color="var(--ink-3)" />
          </div>
        ))}
      </div>
    </div>
  </Screen>
);

// ─────────────────────────────────────────────────────────────
// 4 · Provider add form
// ─────────────────────────────────────────────────────────────
const ScreenCalProviderAdd = () => (
  <Screen hideNav>
    <div style={{ padding: '4px 22px 0', display: 'flex', justifyContent: 'space-between', alignItems: 'center', minHeight: 40 }}>
      <span style={{ fontSize: 14.5, color: 'var(--ink-2)', cursor: 'pointer' }}>Cancel</span>
      <div style={{ fontSize: 14.5, fontWeight: 500 }}>Add provider</div>
      <span style={{ fontSize: 14.5, color: 'var(--ink-4)' }}>Save</span>
    </div>

    <div style={{ overflow: 'auto', height: 'calc(100% - 40px)', paddingBottom: 140 }}>
      <div style={{ padding: '14px 22px 0' }}>

        {/* Hero prompt */}
        <div style={{ marginBottom: 18 }}>
          <div style={{ fontSize: 11.5, fontWeight: 600, color: 'var(--sage-deep)', textTransform: 'uppercase', letterSpacing: 0.8, marginBottom: 6 }}>Medical provider</div>
          <CalSerifTitle size={24}>Who's joining the care team?</CalSerifTitle>
          <div style={{ fontSize: 14, color: 'var(--ink-2)', marginTop: 6, lineHeight: 1.5 }}>
            Required fields are marked. Everything else can come later.
          </div>
        </div>

        {/* Patient assignment — first decision */}
        <div style={{ marginBottom: 18 }}>
          <CalProvFieldLabel required>Which patient is this for?</CalProvFieldLabel>
          <div style={{ display: 'flex', gap: 8 }}>
            {[CAL_PATIENTS.nana, CAL_PATIENTS.papa].map(p => (
              <div key={p.id} style={{
                flex: 1, padding: '12px 10px',
                background: 'var(--surface)', border: '0.5px solid var(--hairline)',
                borderRadius: 14, cursor: 'pointer',
                display: 'flex', alignItems: 'center', gap: 10,
              }}>
                <CalPatientChip p={p} size={30} />
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 14, fontWeight: 600 }}>{p.full}</div>
                  <div style={{ fontSize: 11.5, color: 'var(--ink-3)' }}>{p.age} yrs</div>
                </div>
              </div>
            ))}
          </div>
          <div style={{ marginTop: 8 }}>
            <div style={{
              padding: '10px 14px', borderRadius: 12,
              background: 'var(--surface)', border: '0.5px solid var(--hairline)',
              display: 'flex', alignItems: 'center', gap: 10, cursor: 'pointer',
            }}>
              <div style={{
                width: 30, height: 30, borderRadius: '50%', background: 'var(--surface-2)',
                display: 'inline-flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
              }}>
                <Icon name="users" size={14} color="var(--ink-3)" />
              </div>
              <span style={{ flex: 1, fontSize: 13.5, color: 'var(--ink-2)' }}>Shared — for both Nana &amp; Papa</span>
              <Icon name="chevron" size={13} color="var(--ink-3)" />
            </div>
          </div>
        </div>

        {/* Basics */}
        <div style={{ fontSize: 11, fontWeight: 600, color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: 0.8, margin: '4px 0 12px' }}>Basics</div>

        {/* Find a practice — autofills address, phone, organization */}
        <div style={{ marginBottom: 14 }}>
          <CalProvInput label="Find a practice" placeholder="e.g. Mission Medical Group"
            leading={<Icon name="search" size={15} color="var(--ink-3)" />} />
          <div style={{ fontSize: 12, color: 'var(--ink-3)', marginTop: 6, paddingLeft: 2 }}>Autofills address, phone, and organization.</div>
        </div>

        {/* Specialty / type — picker */}
        <div style={{ marginBottom: 14 }}>
          <CalProvInput label="Specialty / type" required placeholder="Tap to choose"
            trailing={<Icon name="chevDown" size={15} color="var(--ink-3)" />} />
        </div>

        {/* Title */}
        <div style={{ marginBottom: 14 }}>
          <CalProvFieldLabel>Title / prefix</CalProvFieldLabel>
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 7 }}>
            {['MD', 'DO', 'NP', 'PA-C', 'No title', 'Other'].map((t) => {
              const sel = t === 'No title';
              return (
                <div key={t} style={{
                  padding: '7px 14px', borderRadius: 999,
                  background: sel ? 'var(--ink)' : 'var(--surface)',
                  color: sel ? 'var(--bg)' : 'var(--ink-2)',
                  border: sel ? 'none' : '0.5px solid var(--hairline)',
                  fontSize: 13, fontWeight: sel ? 600 : 400, cursor: 'pointer',
                  display: 'inline-flex', alignItems: 'center', gap: 5,
                }}>
                  {sel && <Icon name="check" size={11} color="var(--bg)" />}
                  {t}
                </div>
              );
            })}
          </div>
        </div>

        {/* First + Last name */}
        <div style={{ display: 'flex', gap: 10, marginBottom: 14 }}>
          <div style={{ flex: 1 }}><CalProvInput label="First name" placeholder="e.g. Anika" /></div>
          <div style={{ flex: 1 }}><CalProvInput label="Last name"  required placeholder="e.g. Patel" /></div>
        </div>

        {/* Organization */}
        <div style={{ marginBottom: 14 }}>
          <CalProvInput label="Organization / practice" placeholder="e.g. UCSF Mission Bay" />
        </div>

        {/* Phone */}
        <div style={{ marginBottom: 14 }}>
          <CalProvInput label="Phone" required placeholder="(415) 555-0123"
            leading={<Icon name="phone" size={15} color="var(--ink-3)" />} />
        </div>

        {/* Address */}
        <div style={{ marginBottom: 14 }}>
          <CalProvInput label="Address" placeholder="Search for address…"
            leading={<Icon name="search" size={15} color="var(--ink-3)" />}
            trailing={<Icon name="pin" size={13} color="var(--ink-4)" />} />
        </div>

        {/* Hours */}
        <div style={{ marginBottom: 14 }}>
          <CalProvInput label="Hours" placeholder="e.g. Mon–Fri · 9am–5pm"
            leading={<Icon name="clock" size={15} color="var(--ink-3)" />} />
        </div>

        {/* PCP toggle */}
        <div style={{ marginBottom: 14 }}>
          <div style={{
            display: 'flex', alignItems: 'center', gap: 12,
            padding: '13px 14px', background: 'var(--surface)',
            border: '0.5px solid var(--hairline)', borderRadius: 14,
          }}>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 14.5, fontWeight: 500, color: 'var(--ink)' }}>Set as Primary Care Provider</div>
              <div style={{ fontSize: 12, color: 'var(--ink-3)', marginTop: 1 }}>Pins them to the top of the care team</div>
            </div>
            <div style={{
              width: 44, height: 26, borderRadius: 999, background: 'var(--surface-2)',
              border: '0.5px solid var(--hairline)', position: 'relative', cursor: 'pointer',
            }}>
              <div style={{
                width: 20, height: 20, borderRadius: '50%', background: 'var(--ink-3)',
                position: 'absolute', top: 3, left: 3, transition: 'left .15s',
              }} />
            </div>
          </div>
        </div>

        {/* Notes */}
        <div style={{ marginBottom: 14 }}>
          <CalProvInput label="Notes" placeholder="e.g. Prefers email. Best time to call is morning."
            multiline />
        </div>
      </div>
    </div>

    <div style={{
      position: 'absolute', bottom: 0, left: 0, right: 0,
      padding: '14px 22px 32px',
      background: 'linear-gradient(to top, var(--bg) 70%, transparent)',
    }}>
      <button style={{
        width: '100%', height: 54, borderRadius: 16,
        background: 'var(--surface-2)', color: 'var(--ink-4)', border: 'none',
        fontSize: 16, fontWeight: 500, fontFamily: 'inherit', cursor: 'not-allowed',
      }}>Save provider</button>
      <div style={{ textAlign: 'center', marginTop: 8, fontSize: 12, color: 'var(--ink-3)' }}>
        Fill required fields to save
      </div>
    </div>
  </Screen>
);

// ─────────────────────────────────────────────────────────────
// 5 · Provider edit — same form, pre-filled, + archive in footer
// ─────────────────────────────────────────────────────────────
const ScreenCalProviderEdit = () => {
  const prov = CAL_PROV_DATA.find(p => p.id === 'cp_patel');
  const pat  = CAL_PATIENTS[prov.patient];

  return (
    <Screen hideNav>
      <div style={{ padding: '4px 22px 0', display: 'flex', justifyContent: 'space-between', alignItems: 'center', minHeight: 40 }}>
        <span style={{ fontSize: 14.5, color: 'var(--ink-2)', cursor: 'pointer' }}>Cancel</span>
        <div style={{ fontSize: 14.5, fontWeight: 500 }}>Edit provider</div>
        <span style={{ fontSize: 14.5, fontWeight: 500, color: 'var(--sage-deep)', cursor: 'pointer' }}>Save</span>
      </div>

      <div style={{ overflow: 'auto', height: 'calc(100% - 40px)', paddingBottom: 160 }}>
        <div style={{ padding: '14px 22px 0' }}>

          {/* Patient assignment — shows current, tap to change */}
          <div style={{ marginBottom: 18 }}>
            <CalProvFieldLabel>Patient</CalProvFieldLabel>
            <div style={{
              display: 'inline-flex', alignItems: 'center', gap: 8,
              padding: '8px 14px 8px 6px', borderRadius: 999,
              background: pat.soft, border: '0.5px solid ' + pat.pip,
              cursor: 'pointer',
            }}>
              <CalPatientChip p={pat} size={26} />
              <span style={{ fontSize: 14, fontWeight: 600, color: pat.deep }}>{pat.full}</span>
              <Icon name="chevDown" size={12} color={pat.deep} />
            </div>
          </div>

          {/* Title chips — medical set, MD selected */}
          <div style={{ marginBottom: 14 }}>
            <CalProvFieldLabel>Title / prefix</CalProvFieldLabel>
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 7 }}>
              {['MD', 'DO', 'NP', 'PA-C', 'No title', 'Other'].map((t) => {
                const sel = t === 'MD';
                return (
                  <div key={t} style={{
                    padding: '7px 14px', borderRadius: 999,
                    background: sel ? 'var(--ink)' : 'var(--surface)',
                    color: sel ? 'var(--bg)' : 'var(--ink-2)',
                    border: sel ? 'none' : '0.5px solid var(--hairline)',
                    fontSize: 13, fontWeight: sel ? 600 : 400, cursor: 'pointer',
                    display: 'inline-flex', alignItems: 'center', gap: 5,
                  }}>
                    {sel && <Icon name="check" size={11} color="var(--bg)" />}
                    {t}
                  </div>
                );
              })}
            </div>
          </div>

          {/* Provider type — Medical selected */}
          <div style={{ marginBottom: 14 }}>
            <CalProvFieldLabel>Provider type</CalProvFieldLabel>
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 7 }}>
              {['Medical', 'Therapy', 'Home & Nursing', 'Pharmacy'].map((t) => {
                const sel = t === 'Medical';
                return (
                  <div key={t} style={{
                    padding: '7px 14px', borderRadius: 999,
                    background: sel ? 'var(--sage-deep)' : 'var(--surface)',
                    color: sel ? '#fff' : 'var(--ink-2)',
                    border: sel ? 'none' : '0.5px solid var(--hairline)',
                    fontSize: 13, fontWeight: sel ? 600 : 400, cursor: 'pointer',
                  }}>{t}</div>
                );
              })}
            </div>
          </div>

          <div style={{ display: 'flex', gap: 10, marginBottom: 14 }}>
            <div style={{ flex: 1 }}><CalProvInput label="First name" required value="Anika" /></div>
            <div style={{ flex: 1 }}><CalProvInput label="Last name"  required value="Patel" /></div>
          </div>

          <div style={{ marginBottom: 14 }}>
            <CalProvInput label="Specialty" required value="Neurology"
              trailing={<Icon name="chevDown" size={15} color="var(--ink-3)" />} />
          </div>
          <div style={{ marginBottom: 14 }}>
            <CalProvInput label="Organization / practice" value="UCSF Mission Bay" />
          </div>
          <div style={{ marginBottom: 14 }}>
            <CalProvInput label="Phone" required value={prov.phone}
              leading={<Icon name="phone" size={15} color="var(--ink-3)" />} />
          </div>
          <div style={{ marginBottom: 14 }}>
            <CalProvInput label="Address" value="1825 4th St, Suite 240"
              leading={<Icon name="pin" size={15} color="var(--ink-3)" />} />
          </div>
          <div style={{ marginBottom: 14 }}>
            <CalProvInput label="Hours" value={prov.hours}
              leading={<Icon name="clock" size={15} color="var(--ink-3)" />} />
          </div>
          <div style={{ marginBottom: 14 }}>
            <CalProvInput label="Notes" value={prov.notes} multiline focus />
          </div>

          {/* Archive + Delete in form footer */}
          <div style={{ marginTop: 8 }}>
            <CalSL>Danger zone</CalSL>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
              <button style={{
                width: '100%', padding: '12px 14px', borderRadius: 12,
                background: 'transparent', border: '0.5px solid var(--hairline)',
                display: 'flex', alignItems: 'center', gap: 10,
                cursor: 'pointer', fontFamily: 'inherit', textAlign: 'left',
              }}>
                <Icon name="lock" size={15} color="oklch(0.45 0.08 70)" />
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 14, fontWeight: 500, color: 'var(--ink)' }}>Archive Dr. Patel</div>
                  <div style={{ fontSize: 12, color: 'var(--ink-3)' }}>Hide from care team — restoreable any time</div>
                </div>
                <Icon name="chevron" size={13} color="var(--ink-3)" />
              </button>
              <button style={{
                width: '100%', padding: '12px 14px', borderRadius: 12,
                background: 'transparent', border: '0.5px solid oklch(0.88 0.05 25)',
                display: 'flex', alignItems: 'center', gap: 10,
                cursor: 'pointer', fontFamily: 'inherit', textAlign: 'left',
              }}>
                <Icon name="close" size={15} color="oklch(0.48 0.16 20)" />
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 14, fontWeight: 500, color: 'oklch(0.48 0.16 20)' }}>Delete provider</div>
                  <div style={{ fontSize: 12, color: 'var(--ink-3)' }}>Permanent — cannot be undone</div>
                </div>
                <Icon name="chevron" size={13} color="oklch(0.48 0.16 20)" />
              </button>
            </div>
          </div>
        </div>
      </div>

      <div style={{
        position: 'absolute', bottom: 0, left: 0, right: 0,
        padding: '14px 22px 32px',
        background: 'linear-gradient(to top, var(--bg) 70%, transparent)',
      }}>
        <button style={{
          width: '100%', height: 54, borderRadius: 16,
          background: 'var(--ink)', color: 'var(--bg)', border: 'none',
          fontSize: 16, fontWeight: 500, fontFamily: 'inherit', cursor: 'pointer',
        }}>Save changes</button>
      </div>
    </Screen>
  );
};

// ─────────────────────────────────────────────────────────────
// 6 · Archived list
// ─────────────────────────────────────────────────────────────
const ScreenCalProviderArchived = () => (
  <Screen hideNav>
    <div style={{ padding: '4px 22px 0', display: 'flex', justifyContent: 'space-between', alignItems: 'center', minHeight: 40 }}>
      <IconBtn name="back" />
      <div style={{ fontSize: 14.5, fontWeight: 500 }}>Archived providers</div>
      <div style={{ width: 36 }} />
    </div>

    <div style={{ overflow: 'auto', height: 'calc(100% - 40px)', paddingBottom: 40 }}>
      <div style={{ padding: '14px 22px 8px' }}>
        <div style={{ fontSize: 14, color: 'var(--ink-2)', lineHeight: 1.5 }}>
          These providers are hidden from your care team. Restore to bring them back.
        </div>
      </div>

      <div style={{ padding: '8px 22px' }}>
        {CAL_PROV_ARCHIVED.map((prov, i) => {
          const pat = CAL_PATIENTS[prov.patient];
          return (
            <div key={prov.id} style={{
              display: 'flex', alignItems: 'center', gap: 12,
              padding: '13px 0',
              borderBottom: i < CAL_PROV_ARCHIVED.length - 1 ? '0.5px solid var(--hairline-soft)' : 'none',
              opacity: 0.7,
            }}>
              <Avatar name={prov.name.replace('Dr. ', '')} size={38} tone={prov.tone} />
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 14.5, fontWeight: 500, color: 'var(--ink)' }}>{prov.name}</div>
                <div style={{ fontSize: 12.5, color: 'var(--ink-3)', marginTop: 2 }}>
                  {prov.spec} · archived {prov.archivedDate}
                </div>
                {pat && (
                  <div style={{ marginTop: 5 }}>
                    <CalProvPatientPips patient={prov.patient} />
                  </div>
                )}
              </div>
              <button style={{
                padding: '7px 14px', borderRadius: 999,
                background: 'var(--surface)', border: '0.5px solid var(--hairline)',
                fontSize: 13, fontWeight: 500, color: 'var(--ink)',
                fontFamily: 'inherit', cursor: 'pointer',
              }}>Restore</button>
            </div>
          );
        })}
      </div>

      {CAL_PROV_ARCHIVED.length === 0 && (
        <div style={{ padding: '44px 22px', textAlign: 'center', fontSize: 13.5, color: 'var(--ink-3)' }}>
          No archived providers.
        </div>
      )}
    </div>
  </Screen>
);

// ─────────────────────────────────────────────────────────────
// 7 · Archived provider detail — Restore + Delete
// ─────────────────────────────────────────────────────────────
const ScreenCalProviderDetailArchived = () => {
  const prov = CAL_PROV_ARCHIVED[0];
  const pat  = CAL_PATIENTS[prov.patient];

  return (
    <Screen hideNav>
      <div style={{ padding: '8px 18px 0', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <CalProvChrome calProvStyle={{ width: 38, height: 38, justifyContent: 'center' }}>
          <Icon name="back" size={17} color="var(--ink)" />
        </CalProvChrome>
        <div style={{ display: 'inline-flex', alignItems: 'center', gap: 6,
          padding: '4px 10px', borderRadius: 999,
          background: 'var(--amber-soft)', fontSize: 11.5, fontWeight: 600,
          color: 'oklch(0.45 0.08 70)', letterSpacing: 0.3,
        }}>
          <Icon name="lock" size={12} color="oklch(0.45 0.08 70)" />
          Archived
        </div>
        <div style={{ width: 38 }} />
      </div>

      <div style={{ overflow: 'auto', height: 'calc(100% - 46px)', paddingBottom: 140 }}>
        <div style={{ padding: '20px 26px 20px', textAlign: 'center' }}>
          <div style={{ position: 'relative', display: 'inline-block' }}>
            <Avatar name={prov.name.replace('Dr. ', '')} size={76} tone={prov.tone} style={{ opacity: 0.5 }} />
          </div>
          <div style={{
            fontFamily: 'var(--font-serif)', fontStyle: 'italic',
            fontSize: 28, lineHeight: 1.08, letterSpacing: '-0.025em',
            color: 'var(--ink-2)', marginTop: 14,
          }}>{prov.name}</div>
          <div style={{ fontSize: 14, color: 'var(--ink-3)', marginTop: 6 }}>
            {prov.spec} · {prov.org}
          </div>
          <div style={{ display: 'flex', justifyContent: 'center', marginTop: 10 }}>
            <CalProvPatientPips patient={prov.patient} />
          </div>
          <div style={{ fontSize: 12.5, color: 'var(--ink-3)', marginTop: 8 }}>
            Archived {prov.archivedDate}
          </div>
        </div>

        {/* Restore + Delete */}
        <div style={{ padding: '0 22px' }}>
          <div style={{
            padding: '14px 16px', background: 'var(--sage-tint)',
            border: '0.5px solid var(--sage-soft)', borderRadius: 14, marginBottom: 12,
            display: 'flex', alignItems: 'flex-start', gap: 10,
          }}>
            <Icon name="activity" size={16} color="var(--sage-deep)" style={{ marginTop: 2, flexShrink: 0 }} />
            <div style={{ flex: 1, fontSize: 13.5, color: 'var(--sage-ink)', lineHeight: 1.5 }}>
              Restoring adds them back to the active care team. Their contact info and notes are preserved.
            </div>
          </div>
        </div>
      </div>

      <div style={{
        position: 'absolute', bottom: 0, left: 0, right: 0,
        padding: '14px 22px 32px',
        background: 'linear-gradient(to top, var(--bg) 70%, transparent)',
        display: 'flex', flexDirection: 'column', gap: 10,
      }}>
        <button style={{
          width: '100%', height: 54, borderRadius: 16,
          background: 'var(--ink)', color: 'var(--bg)', border: 'none',
          fontSize: 16, fontWeight: 500, fontFamily: 'inherit', cursor: 'pointer',
          display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
        }}>
          <Icon name="check" size={16} color="var(--bg)" />
          Restore to care team
        </button>
        <button style={{
          width: '100%', height: 44, borderRadius: 14,
          background: 'transparent', border: '0.5px solid oklch(0.88 0.05 25)',
          color: 'oklch(0.48 0.16 20)', fontSize: 15, fontWeight: 500,
          fontFamily: 'inherit', cursor: 'pointer',
        }}>Delete permanently</button>
      </div>
    </Screen>
  );
};

Object.assign(window, {
  ScreenCalProviders,
  ScreenCalProvidersNana,
  ScreenCalProvidersSearch,
  ScreenCalProviderDetail,
  ScreenCalProviderAddType,
  ScreenCalProviderAdd,
  ScreenCalProviderEdit,
  ScreenCalProviderArchived,
  ScreenCalProviderDetailArchived,
});
