// Modals: Start episode (with template journey preview), Log dose, Red-flag
const { Icon, Phone, HomeIndicator } = window;

function ModalShell({ title, subtitle, children, mode = 'd', cta, footer, headerExtra, gear }) {
  const T = UN[mode];
  const { btnPrimaryStyle, btnIconStyle } = window;
  return (
    <Phone mode={mode} time="11:42">
      <div style={{
        height: '100%',
        background: mode === 'd' ? 'rgba(0,0,0,0.55)' : 'rgba(42,40,38,0.32)',
        display: 'flex', flexDirection: 'column',
      }}>
        <div style={{ flex: '0 0 44px' }} />
        <div style={{
          flex: 1, background: T.bg,
          borderTopLeftRadius: 28, borderTopRightRadius: 28,
          boxShadow: '0 -20px 40px rgba(0,0,0,0.4)',
          display: 'flex', flexDirection: 'column',
          border: mode === 'd' ? `1px solid ${T.line}` : 'none',
        }}>
          <div style={{ display: 'flex', justifyContent: 'center', padding: '8px 0 4px' }}>
            <div style={{
              width: 36, height: 5, borderRadius: 99,
              background: mode === 'd' ? 'rgba(255,255,255,0.18)' : 'rgba(0,0,0,0.18)',
            }} />
          </div>
          <div style={{
            display: 'flex', alignItems: 'center', justifyContent: 'space-between',
            padding: '14px 22px 6px', gap: 8,
          }}>
            <div style={{ flex: 1, minWidth: 0 }}>
              <h2 style={{
                margin: 0, fontSize: 22, fontWeight: 700, color: T.text,
                letterSpacing: -0.5,
              }}>{title}</h2>
              {subtitle && (
                <div style={{ marginTop: 3, fontSize: 12, color: T.textMute }}>
                  {subtitle}
                </div>
              )}
            </div>
            {headerExtra}
            {gear !== false && (
              <button style={btnIconStyle(mode)} title="Adjust template">
                <Icon name="gear" size={15} color={T.textDim} strokeWidth={1.8}/>
              </button>
            )}
            <button style={btnIconStyle(mode)}>
              <Icon name="x" size={15} color={T.textDim} strokeWidth={2}/>
            </button>
          </div>
          <div style={{ flex: 1, overflowY: 'auto', padding: '12px 22px' }}>
            {children}
          </div>
          {(cta || footer) && (
            <div style={{
              padding: '12px 22px 4px',
              borderTop: `1px solid ${T.line}`,
            }}>
              {footer}
              {cta && (
                <button style={btnPrimaryStyle(mode, { height: 54, radius: 16 })}>{cta}</button>
              )}
            </div>
          )}
          <HomeIndicator mode={mode}/>
        </div>
      </div>
    </Phone>
  );
}

function Label({ children, mode = 'd' }) {
  return <div style={{
    fontSize: 11, color: UN[mode].textDim,
    textTransform: 'uppercase', fontWeight: 700, letterSpacing: 1,
  }}>{children}</div>;
}

// ═══════════════════════════════════════════════════════════
// Start episode — pick child + ailment template (showing what each pulls in)
// ═══════════════════════════════════════════════════════════
function StartEpisode() {
  const T = UN.d;

  // Tonsillitis selected — preview shows what gets pulled in
  const tonsillitis = {
    name: 'Tonsillitis',
    desc: 'Throat + antibiotic course',
    tracks: [
      { i: 'thermo', t: 'Temperature' },
      { i: 'pill',   t: 'Antibiotic course · 10 doses', highlight: true },
      { i: 'camera', t: 'Throat photos · daily' },
      { i: 'alert',  t: 'Swallow pain · 1–5' },
      { i: 'drop',   t: 'Fluid intake' },
      { i: 'food',   t: 'Food refusal' },
    ],
    redFlags: ['Refusing fluids 6h+', 'Drooling / mouth open', 'Fever ≥ 39.5°C'],
  };

  const ailments = [
    { id: 'fever', t: 'Fever (unknown cause)', icon: 'thermo' },
    { id: 'stom',  t: 'Stomach flu',           icon: 'vomit' },
    { id: 'cold',  t: 'Cold',                  icon: 'drop' },
    { id: 'ear',   t: 'Ear infection',         icon: 'alert' },
    { id: 'rash',  t: 'Rash',                  icon: 'camera' },
    { id: 'tons',  t: 'Tonsillitis',           icon: 'pill', sel: true },
    { id: 'cof',   t: 'Croup / cough',         icon: 'mic' },
    { id: 'cus',   t: 'Custom',                icon: 'plus' },
  ];

  return (
    <ModalShell
      mode="d"
      title="Start an episode"
      subtitle="Pick a template"
      cta={<><Icon name="plus" size={16} color="#0E1A14" strokeWidth={2.4}/>Track Maeve's tonsillitis</>}
    >
      {/* For */}
      <Label>For</Label>
      <div style={{ display: 'flex', gap: 8, marginTop: 8, marginBottom: 18 }}>
        {[
          { name: 'Maeve', age: '4 yrs', sel: true, tone: '#d3a89a' },
          { name: 'Henry', age: '7 yrs', sel: false, tone: '#a5b8c9' },
        ].map(k => (
          <div key={k.name} style={{
            flex: 1, padding: '12px 14px', borderRadius: 14,
            background: k.sel ? T.sageSoft : T.surface,
            border: `1.5px solid ${k.sel ? T.sage : T.line2}`,
            display: 'flex', alignItems: 'center', gap: 10,
          }}>
            <div style={{
              width: 32, height: 32, borderRadius: 32,
              background: `linear-gradient(135deg, ${k.tone}, ${T.sageDeep})`,
              color: '#fff', fontWeight: 700, fontSize: 13,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
            }}>{k.name[0]}</div>
            <div>
              <div style={{ fontSize: 14, color: T.text, fontWeight: 600, letterSpacing: -0.1 }}>{k.name}</div>
              <div style={{ fontSize: 11.5, color: T.textDim }}>{k.age}</div>
            </div>
          </div>
        ))}
      </div>

      {/* Ailment grid */}
      <Label>What's going on?</Label>
      <div style={{ marginTop: 8, marginBottom: 16, display: 'grid', gridTemplateColumns: '1fr 1fr 1fr 1fr', gap: 6 }}>
        {ailments.map(a => (
          <div key={a.id} style={{
            padding: '12px 8px',
            background: a.sel ? T.sageSoft : T.surface,
            border: `1.5px solid ${a.sel ? T.sage : T.line2}`,
            borderRadius: 12,
            display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6,
            textAlign: 'center',
          }}>
            <Icon name={a.icon} size={18}
                  color={a.sel ? T.sage : T.textDim} strokeWidth={1.8}/>
            <div style={{
              fontSize: 10.5, fontWeight: a.sel ? 700 : 500,
              color: a.sel ? T.text : T.textDim,
              lineHeight: 1.15, letterSpacing: -0.05,
            }}>{a.t}</div>
          </div>
        ))}
      </div>

      {/* Selected template preview */}
      <div style={{
        background: T.surface, border: `1.5px solid ${T.sageEdge}`,
        borderRadius: 16, overflow: 'hidden',
      }}>
        <div style={{
          padding: '12px 16px',
          background: T.sageSoft,
          borderBottom: `1px solid ${T.sageEdge}`,
          display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        }}>
          <div>
            <div style={{ fontSize: 14, fontWeight: 700, color: T.text, letterSpacing: -0.2 }}>
              Tonsillitis template
            </div>
            <div style={{ fontSize: 11.5, color: T.textDim, marginTop: 1 }}>
              Throat-focused · 7–10 day course
            </div>
          </div>
          <button style={{
            fontSize: 11.5, color: T.sage, fontWeight: 600,
            background: 'transparent', border: 'none',
          }}>Edit</button>
        </div>

        <div style={{ padding: '14px 16px 4px' }}>
          <div style={{ fontSize: 10.5, color: T.textMute, fontWeight: 700, letterSpacing: 0.8, textTransform: 'uppercase', marginBottom: 8 }}>
            Tracks
          </div>
          {tonsillitis.tracks.map((tk, i) => (
            <div key={i} style={{
              display: 'flex', alignItems: 'center', gap: 10, padding: '7px 0',
            }}>
              <div style={{
                width: 26, height: 26, borderRadius: 8,
                background: tk.highlight ? UN.d.trustSoft : T.surface2,
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                flexShrink: 0,
              }}>
                <Icon name={tk.i} size={13}
                      color={tk.highlight ? UN.d.trust : T.textDim} strokeWidth={1.9}/>
              </div>
              <div style={{ flex: 1, fontSize: 13, color: T.text, fontWeight: 500 }}>{tk.t}</div>
              <Icon name="check" size={14} color={T.sage} strokeWidth={2.4}/>
            </div>
          ))}
        </div>
        <div style={{ padding: '6px 16px 14px' }}>
          <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 }}>
            {tonsillitis.redFlags.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>
    </ModalShell>
  );
}

// ═══════════════════════════════════════════════════════════
// Log dose
// ═══════════════════════════════════════════════════════════
function LogDose() {
  const T = UN.d;
  return (
    <ModalShell
      mode="d"
      title="Log a dose"
      subtitle="Maeve · 15.4 kg"
      cta="Log dose"
    >
      <Label>Medication</Label>
      <div style={{ marginTop: 8, marginBottom: 16 }}>
        {[
          { t: 'Tylenol', s: 'children\u2019s liquid · 160mg/5mL', last: '6h 02m ago' },
          { t: 'Motrin',  s: 'children\u2019s liquid · 100mg/5mL', sel: true, last: 'Safe to dose' },
          { t: 'Amoxicillin', s: 'antibiotic · 5 of 10', course: true },
        ].map((m, i) => (
          <div key={i} style={{
            padding: '14px',
            background: m.sel ? T.sageSoft : T.surface,
            border: `1.5px solid ${m.sel ? T.sage : T.line2}`,
            borderRadius: 14, marginBottom: 6,
            display: 'flex', alignItems: 'center', gap: 12,
          }}>
            <div style={{
              width: 36, height: 36, borderRadius: 10,
              background: m.course ? UN.d.trustSoft : T.surface2,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
            }}>
              <Icon name="pill" size={18} color={m.course ? UN.d.trust : T.textDim} strokeWidth={1.9}/>
            </div>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 15, color: T.text, fontWeight: 600, letterSpacing: -0.1 }}>{m.t}</div>
              <div style={{ fontSize: 11.5, color: T.textDim, marginTop: 1 }}>{m.s}</div>
            </div>
            {m.last && <div style={{
              fontSize: 11, color: m.sel ? T.sage : T.textMute, fontWeight: 600,
              textAlign: 'right',
            }}>{m.last}</div>}
            {m.course && (
              <div style={{ width: 40 }}>
                <div style={{ height: 4, borderRadius: 4, background: T.surface2, overflow: 'hidden' }}>
                  <div style={{ width: '50%', height: '100%', background: UN.d.trust }}/>
                </div>
              </div>
            )}
          </div>
        ))}
      </div>

      {/* Big amount stepper */}
      <Label>Amount</Label>
      <div style={{
        marginTop: 8, marginBottom: 16,
        background: T.surface, borderRadius: 18, border: `1px solid ${T.line2}`,
        padding: '22px 14px',
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
      }}>
        <button style={{
          width: 52, height: 52, borderRadius: 52,
          background: T.surface2, border: `1px solid ${T.line2}`,
          display: 'flex', alignItems: 'center', justifyContent: 'center', color: T.text,
        }}>
          <Icon name="minus" size={22} color={T.text} strokeWidth={2.2}/>
        </button>
        <div style={{ textAlign: 'center' }}>
          <div style={{
            fontFamily: UN.font.num, fontSize: 56, fontWeight: 600, letterSpacing: -2,
            color: T.text, fontVariantNumeric: 'tabular-nums', lineHeight: 1,
          }}>
            5.0<span style={{ fontSize: 20, color: T.textDim, fontWeight: 500, marginLeft: 4 }}>mL</span>
          </div>
          <div style={{
            marginTop: 8, fontSize: 11, color: T.sage, fontWeight: 600,
            letterSpacing: 0.3,
          }}>
            ✓ Recommended for 15.4 kg
          </div>
        </div>
        <button style={{
          width: 52, height: 52, borderRadius: 52,
          background: T.sageSoft, border: `1px solid ${T.sageEdge}`,
          display: 'flex', alignItems: 'center', justifyContent: 'center', color: T.sage,
        }}>
          <Icon name="plus" size={22} color={T.sage} strokeWidth={2.2}/>
        </button>
      </div>

      {/* When + stay down */}
      <Label>When</Label>
      <div style={{ marginTop: 8, marginBottom: 16, display: 'flex', gap: 8 }}>
        <button style={{
          flex: 1, padding: '14px 12px', borderRadius: 14,
          background: T.sageSoft, border: `1.5px solid ${T.sage}`,
          color: T.text, fontFamily: UN.font.body, fontSize: 14, fontWeight: 600,
          textAlign: 'left',
        }}>
          Just now
          <div style={{ fontSize: 12, color: T.textDim, fontWeight: 400, marginTop: 2 }}>11:42 PM</div>
        </button>
        <button style={{
          flex: 1, padding: '14px 12px', borderRadius: 14,
          background: T.surface, border: `1.5px solid ${T.line2}`,
          color: T.textDim, fontFamily: UN.font.body, fontSize: 14, fontWeight: 500,
          textAlign: 'left',
        }}>
          Earlier
          <div style={{ fontSize: 12, color: T.textMute, fontWeight: 400, marginTop: 2 }}>Pick a time →</div>
        </button>
      </div>

      <Label>Did it stay down?</Label>
      <div style={{ marginTop: 8, display: 'flex', gap: 8 }}>
        {[
          { t: 'Yes', sel: true },
          { t: 'Spit some up' },
          { t: 'Vomited' },
        ].map((s, i) => (
          <button key={i} style={{
            flex: 1, padding: '12px 8px', borderRadius: 12,
            background: s.sel ? T.sageSoft : T.surface,
            border: `1.5px solid ${s.sel ? T.sage : T.line2}`,
            color: s.sel ? T.text : T.textDim,
            fontFamily: UN.font.body, fontSize: 13, fontWeight: s.sel ? 600 : 500,
          }}>{s.t}</button>
        ))}
      </div>
    </ModalShell>
  );
}

// ═══════════════════════════════════════════════════════════
// Red-flag detail — wet diaper history view, expanded
// ═══════════════════════════════════════════════════════════
function RedFlag() {
  const T = UN.d;

  // last 8 hours visualized as hour cells, with diaper events marked
  const cells = Array.from({ length: 8 });
  const diaperHours = [];

  return (
    <ModalShell
      mode="d"
      title="Wet diapers"
      subtitle="Hydration check"
    >
      {/* Hero — big visual statement */}
      <div style={{
        marginTop: 4, marginBottom: 14,
        padding: '20px 18px', borderRadius: 18,
        background: 'linear-gradient(135deg, rgba(232,176,92,0.10), rgba(232,176,92,0.04))',
        border: `1px solid rgba(232,176,92,0.32)`,
        position: 'relative', overflow: 'hidden',
      }}>
        <div style={{
          display: 'flex', alignItems: 'center', gap: 14, marginBottom: 14,
        }}>
          <div style={{
            width: 52, height: 52, borderRadius: 16,
            background: 'rgba(232,176,92,0.22)',
            border: `1px solid rgba(232,176,92,0.32)`,
            display: 'flex', alignItems: 'center', justifyContent: 'center',
          }}>
            <Icon name="drop" size={26} color={UN.d.sev.warm} strokeWidth={1.9}/>
          </div>
          <div style={{ flex: 1 }}>
            <div style={{
              fontFamily: UN.font.num, fontSize: 44, fontWeight: 600, letterSpacing: -1.5,
              color: T.text, fontVariantNumeric: 'tabular-nums', lineHeight: 1,
            }}>7<span style={{ fontSize: 18, color: T.textDim, fontWeight: 500, marginLeft: 4 }}>h</span></div>
            <div style={{ fontSize: 12, color: UN.d.sev.warm, fontWeight: 700, letterSpacing: 0.3, textTransform: 'uppercase', marginTop: 3 }}>
              Since last wet
            </div>
          </div>
        </div>

        {/* 8h threshold bar */}
        <div style={{ marginTop: 8 }}>
          <div style={{
            height: 8, borderRadius: 8, background: T.surface2, overflow: 'hidden', position: 'relative',
          }}>
            <div style={{
              width: '87.5%', height: '100%', background: UN.d.sev.warm,
            }}/>
            {/* threshold marker at 8h */}
            <div style={{
              position: 'absolute', right: 0, top: -4, bottom: -4,
              width: 2, background: UN.d.sev.hot,
            }}/>
          </div>
          <div style={{ marginTop: 6, display: 'flex', justifyContent: 'space-between', fontSize: 10, color: T.textMute, fontWeight: 600 }}>
            <span>0h</span><span style={{ color: UN.d.sev.hot, fontWeight: 700 }}>8h ⚑</span>
          </div>
        </div>
      </div>

      {/* Last 24h history */}
      <Label>Last 24 hours</Label>
      <div style={{
        marginTop: 8, marginBottom: 16,
        background: T.surface, border: `1px solid ${T.line2}`,
        borderRadius: 14, padding: '14px 16px',
      }}>
        {/* hour strip with diaper markers */}
        <div style={{ display: 'flex', gap: 2, alignItems: 'flex-end', marginBottom: 10 }}>
          {Array.from({ length: 24 }).map((_, h) => {
            const events = [3, 8, 14, 17];   // hours with wet diapers (5 total in 24h, last at h17 = 7h ago since "now"=24)
            const isEvent = events.includes(h);
            return (
              <div key={h} style={{
                flex: 1, height: isEvent ? 28 : 6, borderRadius: 2,
                background: isEvent ? T.sage : T.surface2,
                opacity: isEvent ? 0.4 + (h / 30) : 1,
              }}/>
            );
          })}
        </div>
        <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 9.5, color: T.textMute, letterSpacing: 0.3, fontWeight: 600 }}>
          <span>YESTERDAY 2am</span>
          <span>8am</span>
          <span>2pm</span>
          <span>8pm</span>
          <span>NOW</span>
        </div>

        <div style={{
          marginTop: 12, paddingTop: 12, borderTop: `1px solid ${T.line}`,
          display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        }}>
          <div>
            <div style={{ fontSize: 10.5, color: T.textMute, fontWeight: 700, letterSpacing: 0.4, textTransform: 'uppercase' }}>
              Wet diapers
            </div>
            <div style={{
              fontFamily: UN.font.num, fontSize: 22, fontWeight: 700, color: T.text,
              fontVariantNumeric: 'tabular-nums', letterSpacing: -0.3, marginTop: 2,
            }}>5 <span style={{ fontSize: 13, color: T.textMute, fontWeight: 500 }}>last 24h</span></div>
          </div>
          <div style={{ height: 30, width: 1, background: T.line2 }}/>
          <div>
            <div style={{ fontSize: 10.5, color: T.textMute, fontWeight: 700, letterSpacing: 0.4, textTransform: 'uppercase' }}>
              Healthy range
            </div>
            <div style={{ fontSize: 13, color: T.text, fontWeight: 600, marginTop: 4 }}>≥ 6 per day</div>
          </div>
          <div style={{ height: 30, width: 1, background: T.line2 }}/>
          <div>
            <div style={{ fontSize: 10.5, color: T.textMute, fontWeight: 700, letterSpacing: 0.4, textTransform: 'uppercase' }}>
              Last
            </div>
            <div style={{ fontSize: 13, color: T.text, fontWeight: 600, marginTop: 4 }}>7:14 pm</div>
          </div>
        </div>
      </div>

      {/* What the threshold means — info expansion (collapsed by default) */}
      <button style={{
        width: '100%', padding: '12px 14px', borderRadius: 12,
        background: T.surface, border: `1px solid ${T.line2}`,
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        marginBottom: 14, color: T.text,
        fontFamily: UN.font.body, fontSize: 13.5, fontWeight: 600, letterSpacing: -0.1,
      }}>
        <span style={{ display: 'inline-flex', alignItems: 'center', gap: 8 }}>
          <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke={UN.d.textDim} strokeWidth="2" strokeLinecap="round">
            <circle cx="12" cy="12" r="9"/>
            <path d="M12 8h.01M11 12h1v4"/>
          </svg>
          About the 8-hour threshold
        </span>
        <Icon name="chev" size={14} color={UN.d.textDim} strokeWidth={2}/>
      </button>

      {/* Primary action — log, not call */}
      <button style={{
        width: '100%', height: 56, borderRadius: 16,
        background: T.sage, color: '#0E1A14', border: 'none',
        fontFamily: UN.font.body, fontSize: 15, fontWeight: 700,
        letterSpacing: -0.1,
        display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
        marginBottom: 8,
      }}>
        <Icon name="drop" size={18} color="#0E1A14" strokeWidth={2.2}/>
        Log a wet diaper now
      </button>
      <button style={{
        width: '100%', height: 44, borderRadius: 14,
        background: 'transparent', border: 'none',
        color: T.textDim, fontFamily: UN.font.body, fontSize: 13, fontWeight: 500,
      }}>
        Mark as resolved
      </button>
    </ModalShell>
  );
}

Object.assign(window, { ModalShell, Label, StartEpisode, LogDose, RedFlag });
