// Settings hub + Medications library + Ailment templates library
const { Icon, Phone, TabBar, HomeIndicator } = window;

// ═══════════════════════════════════════════════════════════
// Settings hub — single screen with everything
// ═══════════════════════════════════════════════════════════
function Settings() {
  const T = UN.d;

  const Row = ({ icon, title, sub, badge, last }) => (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 12,
      padding: '14px 16px',
      borderBottom: last ? 'none' : `1px solid ${T.line}`,
    }}>
      <div style={{
        width: 32, height: 32, borderRadius: 10,
        background: T.surface2, display: 'flex', alignItems: 'center', justifyContent: 'center',
      }}>
        <Icon name={icon} size={16} color={T.textDim} strokeWidth={1.9}/>
      </div>
      <div style={{ flex: 1 }}>
        <div style={{ fontSize: 14.5, color: T.text, fontWeight: 500, letterSpacing: -0.1 }}>{title}</div>
        {sub && <div style={{ fontSize: 11.5, color: T.textMute, marginTop: 1 }}>{sub}</div>}
      </div>
      {badge && (
        <div style={{
          padding: '3px 8px', borderRadius: 99, background: T.sageSoft,
          fontSize: 10.5, color: T.sage, fontWeight: 700, letterSpacing: 0.4,
        }}>{badge}</div>
      )}
      <Icon name="chev" size={14} color={T.textMute} strokeWidth={1.8}/>
    </div>
  );

  const Group = ({ header, children }) => (
    <div style={{ marginBottom: 22 }}>
      <div style={{
        padding: '0 22px 8px', fontSize: 11, color: T.textMute,
        letterSpacing: 0.7, fontWeight: 700, textTransform: 'uppercase',
      }}>{header}</div>
      <div style={{
        margin: '0 22px', background: T.surface, border: `1px solid ${T.line}`,
        borderRadius: 16, overflow: 'hidden',
      }}>{children}</div>
    </div>
  );

  return (
    <Phone mode="d" time="2:14">
      <div style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
        <div style={{ flex: 1, overflowY: 'auto', padding: '4px 0 16px' }}>
          <h1 style={{
            margin: 0, padding: '16px 22px 18px',
            fontSize: 32, fontWeight: 700, color: T.text, letterSpacing: -0.8,
          }}>Settings</h1>

          <Group header="Children">
            <Row icon="home" title="Maeve" sub="4 yrs · 15.4 kg · Stomach flu active" badge="SICK"/>
            <Row icon="home" title="Henry" sub="7 yrs · 22.1 kg · Well"/>
            <Row icon="plus" title="Add a kid" sub="Photo, name, weight" last/>
          </Group>

          <Group header="What we track">
            <Row icon="pill"   title="Medications" sub="3 saved · Tylenol, Motrin, amoxicillin"/>
            <Row icon="alert"  title="Ailment templates" sub="8 built-in · 1 custom"/>
            <Row icon="thermo" title="Severity thresholds" sub="Per-kid by age · AAP defaults"/>
            <Row icon="bell"   title="Alarms" sub="Vibrate + sound · snooze 15m" last/>
          </Group>

          <Group header="Who's watching">
            <Row icon="people" title="Caregivers" sub="3 active · Sarah, Grandma, you"/>
            <Row icon="share"  title="Doctor handoff link" sub="Pediatrician access · view-only" last/>
          </Group>

          <Group header="Units & display">
            <Row icon="thermo" title="Temperature" sub="Celsius · matches UK"/>
            <Row icon="thermo" title="Weight"     sub="kilograms"/>
            <Row icon="drop"   title="Fluids"     sub="millilitres + ounces"/>
            <Row icon="clock"  title="Date format" sub="DD/MM/YYYY · 24h"/>
            <Row icon="sun"    title="First day of week" sub="Monday" last/>
          </Group>

          <Group header="Notifications">
            <Row icon="bell"   title="Next-dose alarms" sub="Sound + haptic · all caregivers" badge="ON"/>
            <Row icon="alert"  title="Red-flag pushes"  sub="Phone wake · vibrates"/>
            <Row icon="people" title="Caregiver activity" sub="Get pinged when others log" last/>
          </Group>

          <Group header="Account">
            <Row icon="gear"   title="Subscription" sub="Unpanic Pro · trial · 5 days left" badge="PRO"/>
            <Row icon="doc"    title="Export history" sub="CSV · last 90 days"/>
            <Row icon="sun"    title="Appearance" sub="Always dark · honors system" last/>
          </Group>

          <div style={{ padding: '0 22px 12px', textAlign: 'center', fontSize: 11, color: T.textMute }}>
            Unpanic v1.0 · Tracker, not a doctor.
          </div>
        </div>
        <TabBar mode="d" active="set"/>
        <HomeIndicator mode="d"/>
      </div>
    </Phone>
  );
}

// ═══════════════════════════════════════════════════════════
// Medications library
// ═══════════════════════════════════════════════════════════
function MedsLibrary() {
  const T = UN.d;
  const meds = [
    {
      name: 'Tylenol', sub: 'acetaminophen',
      conc: '160mg / 5mL · children\u2019s liquid',
      saved: ['Maeve · 5.0mL', 'Henry · 7.5mL'],
      schedule: 'Every 4–6 hours · max 5/day',
      isOpen: true,
    },
    { name: 'Motrin',  sub: 'ibuprofen', conc: '100mg / 5mL · children\u2019s liquid', short: 'Maeve · 5mL · q6–8h' },
    { name: 'Amoxicillin', sub: 'antibiotic course', conc: '400mg / 5mL', short: 'Henry · 10mL · twice daily · 10 doses', course: '5/10' },
    { name: 'Saline drops', sub: 'nasal', conc: '0.65%', short: 'As needed' },
  ];

  return (
    <Phone mode="d" time="2:14">
      <div style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
        <div style={{ flex: 1, overflowY: 'auto', padding: '4px 0 80px' }}>
          {/* Header */}
          <div style={{ padding: '8px 22px 0', display: 'flex', alignItems: 'center', gap: 10 }}>
            <button style={{
              width: 36, height: 36, borderRadius: 99,
              background: T.surface, border: `1px solid ${T.line2}`, color: T.text,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
            }}>
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M15 6l-6 6 6 6"/></svg>
            </button>
            <div style={{ flex: 1, fontSize: 12, color: T.textMute, letterSpacing: 0.4, fontWeight: 600 }}>SETTINGS · </div>
          </div>
          <h1 style={{
            margin: '12px 0 4px', padding: '0 22px',
            fontSize: 28, fontWeight: 700, color: T.text, letterSpacing: -0.7,
          }}>Medications</h1>
          <p style={{ margin: 0, padding: '0 22px', fontSize: 13, color: T.textDim, lineHeight: 1.5 }}>
            Concentrations and per-kid dose defaults. We never recommend; you decide.
          </p>

          {/* Search / filter */}
          <div style={{
            margin: '18px 22px 8px',
            padding: '10px 14px', borderRadius: 12,
            background: T.surface, border: `1px solid ${T.line2}`,
            display: 'flex', alignItems: 'center', gap: 10,
            fontSize: 14, color: T.textMute,
          }}>
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke={T.textMute} strokeWidth="2" strokeLinecap="round"><circle cx="11" cy="11" r="7"/><path d="m20 20-3.5-3.5"/></svg>
            Search the library — Tylenol, Zofran, Albuterol…
          </div>

          {/* Meds list */}
          <div style={{ padding: '6px 22px 0' }}>
            {meds.map((m, i) => (
              <div key={i} style={{
                background: T.surface,
                border: `1px solid ${m.isOpen ? T.sageEdge : T.line}`,
                borderRadius: 16, marginBottom: 8, overflow: 'hidden',
              }}>
                <div style={{ padding: '14px 16px', display: 'flex', alignItems: 'center', gap: 12 }}>
                  <div style={{
                    width: 38, height: 38, borderRadius: 11,
                    background: m.course ? UN.d.trustSoft : UN.d.sageSoft,
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                  }}>
                    <Icon name="pill" size={18}
                          color={m.course ? UN.d.trust : T.sage} strokeWidth={1.9}/>
                  </div>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontSize: 15, color: T.text, fontWeight: 600, letterSpacing: -0.2 }}>
                      {m.name} <span style={{ color: T.textDim, fontWeight: 400, fontSize: 12.5 }}>· {m.sub}</span>
                    </div>
                    <div style={{ fontSize: 11.5, color: T.textMute, marginTop: 2 }}>
                      {m.conc}
                    </div>
                  </div>
                  {m.course && (
                    <div style={{
                      padding: '3px 8px', borderRadius: 99,
                      background: UN.d.trustSoft, color: UN.d.trust,
                      fontSize: 10.5, fontWeight: 700, letterSpacing: 0.4,
                    }}>{m.course}</div>
                  )}
                </div>
                {m.isOpen && (
                  <div style={{
                    padding: '4px 16px 14px',
                    borderTop: `1px solid ${T.line}`,
                    background: 'rgba(143,181,162,0.04)',
                  }}>
                    <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8, marginTop: 12 }}>
                      {m.saved.map((s, j) => (
                        <div key={j} style={{
                          padding: '10px 12px', borderRadius: 11,
                          background: T.surface, border: `1px solid ${T.line2}`,
                          fontSize: 12.5, color: T.text, fontWeight: 500,
                          fontVariantNumeric: 'tabular-nums', letterSpacing: -0.1,
                        }}>{s}</div>
                      ))}
                    </div>
                    <div style={{
                      marginTop: 10, padding: '10px 12px', borderRadius: 11,
                      background: T.surface2,
                      fontSize: 12, color: T.textDim, fontWeight: 500,
                      display: 'flex', alignItems: 'center', gap: 8,
                    }}>
                      <Icon name="clock" size={13} color={T.textDim} strokeWidth={1.9}/>
                      {m.schedule}
                    </div>
                  </div>
                )}
                {!m.isOpen && (
                  <div style={{
                    padding: '0 16px 12px', fontSize: 11.5, color: T.textDim,
                  }}>{m.short}</div>
                )}
              </div>
            ))}

            {/* Add */}
            <button style={{
              width: '100%', padding: '14px 16px', borderRadius: 16,
              background: 'transparent', border: `1.5px dashed ${T.line2}`,
              color: T.textDim, fontFamily: UN.font.body,
              fontSize: 14, fontWeight: 500,
              display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
            }}>
              <Icon name="plus" size={16} color={T.textDim} strokeWidth={2}/>
              Add a medication
            </button>
          </div>
        </div>
        <TabBar mode="d" active="set"/>
        <HomeIndicator mode="d"/>
      </div>
    </Phone>
  );
}

// ═══════════════════════════════════════════════════════════
// Ailment templates library — list + the editable detail of one
// ═══════════════════════════════════════════════════════════
function AilmentTemplates() {
  const T = UN.d;

  const templates = [
    { id: 'fever', t: 'Fever (unknown)',  icon: 'thermo', tracks: 4, used: '12×' },
    { id: 'stom',  t: 'Stomach flu',      icon: 'vomit',  tracks: 6, used: '3×' },
    { id: 'cold',  t: 'Cold',             icon: 'drop',   tracks: 4, used: '8×' },
    { id: 'ear',   t: 'Ear infection',    icon: 'alert',  tracks: 5, used: '2×' },
    { id: 'tons',  t: 'Tonsillitis',      icon: 'pill',   tracks: 6, used: '1×', sel: true },
    { id: 'rash',  t: 'Rash',             icon: 'camera', tracks: 4, used: '0' },
    { id: 'cof',   t: 'Croup / cough',    icon: 'mic',    tracks: 5, used: '0' },
    { id: 'ast',   t: 'Asthma flare',     icon: 'mic',    tracks: 5, used: '0', custom: true },
  ];

  return (
    <Phone mode="d" time="2:14">
      <div style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
        <div style={{ flex: 1, overflowY: 'auto', padding: '4px 0 80px' }}>
          <div style={{ padding: '8px 22px 0', display: 'flex', alignItems: 'center', gap: 10 }}>
            <button style={{
              width: 36, height: 36, borderRadius: 99,
              background: T.surface, border: `1px solid ${T.line2}`, color: T.text,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
            }}>
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M15 6l-6 6 6 6"/></svg>
            </button>
          </div>
          <h1 style={{
            margin: '10px 0 4px', padding: '0 22px',
            fontSize: 28, fontWeight: 700, color: T.text, letterSpacing: -0.7,
          }}>Templates</h1>
          <p style={{ margin: 0, padding: '0 22px', fontSize: 13, color: T.textDim, lineHeight: 1.5 }}>
            Each template pre-fills what to track and what counts as a red flag. Edit any of them.
          </p>

          {/* Grid */}
          <div style={{ padding: '16px 22px 8px', display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
            {templates.map(tp => (
              <div key={tp.id} style={{
                padding: '12px 12px',
                background: tp.sel ? T.sageSoft : T.surface,
                border: `1.5px solid ${tp.sel ? T.sage : T.line2}`,
                borderRadius: 14, position: 'relative',
              }}>
                {tp.custom && (
                  <div style={{
                    position: 'absolute', top: 8, right: 8,
                    fontSize: 9, color: UN.d.trust, fontWeight: 700, letterSpacing: 0.4,
                    padding: '2px 6px', borderRadius: 4, background: UN.d.trustSoft,
                  }}>CUSTOM</div>
                )}
                <div style={{
                  width: 30, height: 30, borderRadius: 9,
                  background: tp.sel ? T.sage : T.surface2,
                  display: 'flex', alignItems: 'center', justifyContent: 'center', marginBottom: 10,
                }}>
                  <Icon name={tp.icon} size={15}
                        color={tp.sel ? '#0E1A14' : T.textDim} strokeWidth={1.9}/>
                </div>
                <div style={{ fontSize: 13.5, color: T.text, fontWeight: 700, letterSpacing: -0.1 }}>{tp.t}</div>
                <div style={{ marginTop: 4, fontSize: 11, color: T.textDim, fontWeight: 500 }}>
                  {tp.tracks} tracks · used {tp.used}
                </div>
              </div>
            ))}
            <button style={{
              padding: '12px', borderRadius: 14,
              background: 'transparent', border: `1.5px dashed ${T.line2}`,
              color: T.textDim, fontFamily: UN.font.body, fontSize: 13, fontWeight: 500,
              display: 'flex', flexDirection: 'column', alignItems: 'flex-start', gap: 10,
            }}>
              <Icon name="plus" size={20} color={T.textDim} strokeWidth={2}/>
              Build custom
            </button>
          </div>

          {/* Selected template detail — what gets pulled in */}
          <div style={{ padding: '8px 22px' }}>
            <div style={{
              background: T.surface, border: `1.5px solid ${T.sageEdge}`,
              borderRadius: 18, overflow: 'hidden', marginTop: 8,
            }}>
              <div style={{
                padding: '14px 18px',
                borderBottom: `1px solid ${T.line}`,
                display: 'flex', alignItems: 'center', justifyContent: 'space-between',
              }}>
                <div>
                  <div style={{ fontSize: 16, fontWeight: 700, color: T.text, letterSpacing: -0.2 }}>
                    Tonsillitis · what this tracks
                  </div>
                  <div style={{ fontSize: 11.5, color: T.textDim, marginTop: 2 }}>
                    Toggle anything off. Long-press to reorder.
                  </div>
                </div>
              </div>
              {[
                { i: 'thermo', t: 'Temperature',    sub: 'Severity by age · ≥38.5°C warm', on: true },
                { i: 'pill',   t: 'Antibiotic course', sub: '10 doses · twice daily',     on: true, tag: 'course' },
                { i: 'pill',   t: 'PRN pain relief', sub: 'Tylenol / Motrin alternation', on: true },
                { i: 'camera', t: 'Throat photos',  sub: 'Daily prompt at 8am',           on: true },
                { i: 'alert',  t: 'Swallow pain',   sub: '1–5 visual scale',              on: true },
                { i: 'drop',   t: 'Fluid intake',   sub: 'oz · refusal flag',             on: true },
                { i: 'food',   t: 'Food refusal',   sub: 'Soft foods preferred',          on: false },
                { i: 'clock',  t: 'Sleep disruption', sub: 'Wake-ups, pain-related',      on: false },
              ].map((row,i,arr) => (
                <div key={i} style={{
                  padding: '12px 18px',
                  borderBottom: i < arr.length - 1 ? `1px solid ${T.line}` : 'none',
                  display: 'flex', alignItems: 'center', gap: 12,
                  opacity: row.on ? 1 : 0.5,
                }}>
                  <div style={{
                    width: 28, height: 28, borderRadius: 9,
                    background: T.surface2,
                    display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
                  }}>
                    <Icon name={row.i} size={14} color={T.textDim} strokeWidth={1.9}/>
                  </div>
                  <div style={{ flex: 1 }}>
                    <div style={{ fontSize: 13.5, color: T.text, fontWeight: 600, letterSpacing: -0.1 }}>
                      {row.t}
                      {row.tag && (
                        <span style={{
                          marginLeft: 6, fontSize: 9.5, color: UN.d.trust,
                          padding: '1px 6px', borderRadius: 4,
                          background: UN.d.trustSoft, fontWeight: 700, letterSpacing: 0.4,
                        }}>{row.tag.toUpperCase()}</span>
                      )}
                    </div>
                    <div style={{ fontSize: 11.5, color: T.textMute, marginTop: 1 }}>{row.sub}</div>
                  </div>
                  {/* toggle */}
                  <div style={{
                    width: 36, height: 22, borderRadius: 22,
                    background: row.on ? T.sage : T.surface2,
                    border: `1px solid ${row.on ? T.sage : T.line2}`,
                    position: 'relative', flexShrink: 0,
                  }}>
                    <div style={{
                      position: 'absolute', top: 2,
                      left: row.on ? 16 : 2, width: 16, height: 16, borderRadius: 16,
                      background: row.on ? '#0E1A14' : T.textMute, transition: 'all .15s',
                    }}/>
                  </div>
                </div>
              ))}
              <div style={{
                padding: '12px 18px',
                borderTop: `1px solid ${T.line}`,
                background: 'rgba(184,95,68,0.05)',
              }}>
                <div style={{ fontSize: 10.5, color: T.textMute, fontWeight: 700, letterSpacing: 0.8, textTransform: 'uppercase', marginBottom: 6 }}>
                  Red-flag thresholds
                </div>
                <div style={{ display: 'flex', flexWrap: 'wrap', gap: 4 }}>
                  {['Fluid refused 6h+', 'Drooling / mouth open', 'Fever ≥ 39.5°C', 'Stridor / breathing'].map((f,i) => (
                    <span key={i} style={{
                      fontSize: 11, color: UN.d.sev.hot, fontWeight: 500,
                      padding: '4px 8px', borderRadius: 99,
                      background: `${UN.d.sev.hot}1c`,
                      border: `1px solid ${UN.d.sev.hot}44`,
                    }}>{f}</span>
                  ))}
                </div>
              </div>
            </div>
          </div>
        </div>
        <TabBar mode="d" active="set"/>
        <HomeIndicator mode="d"/>
      </div>
    </Phone>
  );
}

Object.assign(window, { Settings, MedsLibrary, AilmentTemplates });
