// Log Observation modal + Full Timeline view + Edit Entry modal + Quick Log grid + Log Symptom
const { Icon, Phone, TabBar, HomeIndicator, ModalShell, Label, TopBar, Stepper, Scale5 } = window;

// ═══════════════════════════════════════════════════════════
// 1. LOG OBSERVATION — structured qualitative entry
// ═══════════════════════════════════════════════════════════
const ENERGY  = ['Lethargic', 'Weak', 'Tired', 'Normal', 'Perky'];
const MOOD    = ['Inconsolable', 'Crying', 'Fussy', 'Calm', 'Cheerful'];
const APPETITE= ['Refusing', 'Picky', 'Some', 'Eating', 'Hungry'];

function ObservationAxis({ title, options, value, color }) {
  const T = UN.d;
  return (
    <div style={{ marginBottom: 14 }}>
      <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: 8 }}>
        <Label>{title}</Label>
        <span style={{ fontSize: 13, color: T.text, fontWeight: 600, letterSpacing: -0.1 }}>
          {options[value - 1]}
        </span>
      </div>
      <div style={{ display: 'flex', gap: 4 }}>
        {options.map((opt, i) => {
          const sel = i + 1 === value;
          const intensity = sel ? 1 : 0.35;
          return (
            <button key={opt} style={{
              flex: 1, padding: '10px 4px', borderRadius: 11,
              background: sel ? color : T.surface,
              border: `1.5px solid ${sel ? color : T.line2}`,
              color: sel ? '#0E1A14' : T.textDim,
              fontFamily: UN.font.body, fontSize: 10.5, fontWeight: sel ? 700 : 500,
              letterSpacing: 0.1,
            }}>{opt}</button>
          );
        })}
      </div>
    </div>
  );
}

function LogObservation() {
  const T = UN.d;
  return (
    <ModalShell mode="d" title="Observation" subtitle="Maeve" cta="Log observation">
      <ObservationAxis title="Energy"   options={ENERGY}   value={2} color={UN.d.sev.warm}/>
      <ObservationAxis title="Mood"     options={MOOD}     value={3} color={UN.d.trust}/>
      <ObservationAxis title="Appetite" options={APPETITE} value={2} color={UN.d.sev.warm}/>

      {/* Add note */}
      <Label>Casual note · optional</Label>
      <div style={{
        marginTop: 8, marginBottom: 14,
        padding: '14px 14px', borderRadius: 14,
        background: T.surface, border: `1px solid ${T.line2}`,
        minHeight: 80, fontSize: 14, color: T.text,
        fontStyle: 'italic', lineHeight: 1.45,
      }}>
        "Just kind of slumped on the couch. Drank a few sips of Pedialyte but pushed away the toast."
        <div style={{
          marginTop: 10, display: 'inline-flex', alignItems: 'center', gap: 6,
          fontSize: 11, color: T.sage, fontWeight: 600, fontStyle: 'normal',
          padding: '4px 9px', borderRadius: 99,
          background: T.sageSoft,
        }}>
          <Icon name="mic" size={11} color={T.sage} strokeWidth={2}/>
          Transcribed · just now
        </div>
      </div>

      {/* Quick tag chips */}
      <Label>Or tap a quick tag</Label>
      <div style={{ marginTop: 8, display: 'flex', flexWrap: 'wrap', gap: 5 }}>
        {[
          'Slumping', 'Doesn\u2019t want to play', 'Whiny',
          'Cold hands', 'Sweaty', 'Pulling at ear',
          'Rash spreading', 'Breathing fast', 'Clingy',
        ].map((t,i) => (
          <button key={i} style={{
            padding: '6px 11px', borderRadius: 99,
            background: T.surface, border: `1px solid ${T.line2}`,
            fontSize: 11.5, color: T.textDim, fontWeight: 500,
          }}>{t}</button>
        ))}
      </div>
    </ModalShell>
  );
}

// ═══════════════════════════════════════════════════════════
// 2. FULL TIMELINE — parent's chronological log with edit affordances
// Stack of dimension tracks at the top, then a scrollable event list.
// ═══════════════════════════════════════════════════════════
function TimelineFull() {
  const T = UN.d;

  return (
    <Phone mode="d" time="2:14">
      <div style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
        <TopBar mode="d" kidName="Maeve" kidTone="#d3a89a" dot="warm" subtitle="DAY 3 · TIMELINE"/>

        <div style={{ flex: 1, overflowY: 'auto' }}>
          <h1 style={{ margin: '12px 22px 4px', fontSize: 26, fontWeight: 700, color: T.text, letterSpacing: -0.6 }}>
            Full timeline
          </h1>
          <p style={{ margin: '0 22px', fontSize: 13, color: T.textDim, lineHeight: 1.4 }}>
            Every event. Swipe any row to edit or delete.
          </p>

          {/* Filter chips */}
          <div style={{ padding: '14px 22px 8px', display: 'flex', gap: 6, overflowX: 'auto' }}>
            {[
              { t: 'All · 42', sel: true },
              { t: 'Temp · 18' },
              { t: 'Doses · 4' },
              { t: 'Fluids · 11' },
              { t: 'Vomit · 3' },
              { t: 'Observations · 6' },
            ].map((c,i) => (
              <button key={i} style={{
                flexShrink: 0, padding: '7px 12px', borderRadius: 10,
                background: c.sel ? T.sageSoft : T.surface,
                border: `1.5px solid ${c.sel ? T.sage : T.line2}`,
                color: c.sel ? T.text : T.textDim,
                fontFamily: UN.font.body, fontSize: 12, fontWeight: c.sel ? 700 : 500,
              }}>{c.t}</button>
            ))}
          </div>

          {/* Compact multi-track minimap */}
          <div style={{
            margin: '0 22px 14px',
            background: T.surface, border: `1px solid ${T.line}`,
            borderRadius: 16, padding: '12px 14px',
          }}>
            <div style={{ fontSize: 10.5, color: T.textMute, fontWeight: 700, letterSpacing: 0.7, textTransform: 'uppercase', marginBottom: 8 }}>
              Day 3 at a glance
            </div>
            {[
              { i: 'thermo', l: 'Temp',     row: '·····●●●●●●●●●●●●●●●●●●', colors: ['mild','mild','warm','warm','hot','hot','hot','warm','warm','warm','mild','mild','mild','mild','mild','warm','warm','warm','warm','warm','warm','warm','warm','mild','mild','mild','mild','warm','warm','warm'].slice(0, 24) },
              { i: 'pill',   l: 'Doses',    sparse: [4,9,14,19,23], color: T.trust },
              { i: 'vomit',  l: 'Vomit',    sparse: [3,7,16], color: UN.d.sev.warm },
              { i: 'drop',   l: 'Fluids',   sparse: [2,6,10,14,18,22], color: T.sage },
              { i: 'diaper', l: 'Wet',      sparse: [5,11,16], color: T.sage },
              { i: 'alert',  l: 'Energy',   obs: [3,2,2,3,3,4,4,3,2,2,2,2], color: UN.d.trust },
            ].map((row,i,arr) => (
              <div key={i} style={{
                display: 'flex', alignItems: 'center', gap: 10,
                padding: '4px 0',
                borderBottom: i < arr.length - 1 ? `1px solid ${T.line}` : 'none',
              }}>
                <div style={{
                  width: 24, height: 24, borderRadius: 7, background: T.surface2,
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                }}>
                  <Icon name={row.i} size={12} color={T.textDim} strokeWidth={1.9}/>
                </div>
                <div style={{ width: 44, fontSize: 10.5, color: T.textDim, fontWeight: 600 }}>
                  {row.l}
                </div>
                {/* track */}
                <div style={{ flex: 1, display: 'flex', gap: 2, alignItems: 'center' }}>
                  {row.colors && row.colors.map((c, j) => (
                    <div key={j} style={{
                      flex: 1, height: 12, borderRadius: 2,
                      background: UN.d.sev[c],
                    }}/>
                  ))}
                  {row.sparse && Array.from({ length: 24 }).map((_, j) => (
                    <div key={j} style={{
                      flex: 1, height: 12, borderRadius: 2,
                      background: row.sparse.includes(j) ? row.color : T.surface2,
                    }}/>
                  ))}
                  {row.obs && Array.from({ length: 24 }).map((_, j) => {
                    const idx = Math.floor(j / 2);
                    const v = row.obs[idx] ?? 3;
                    const intensity = Math.abs(v - 3) / 2;
                    return (
                      <div key={j} style={{
                        flex: 1, height: 12, borderRadius: 2,
                        background: v < 3 ? UN.d.sev.warm : v > 3 ? T.sage : T.surface2,
                        opacity: 0.35 + intensity * 0.55,
                      }}/>
                    );
                  })}
                </div>
              </div>
            ))}
          </div>

          {/* Event log */}
          <div style={{ padding: '0 22px' }}>
            <TimeGroup label="Tonight · 11pm – 2am" />
            <Event time="11:42 PM" who="G" tone="#d3a89a" icon="pill" tone2="trust"
                   title="2.5mL Tylenol" sub="children's liquid · stayed down ✓" />
            <Event time="10:15 PM" who="Y" tone="#c2b39a" icon="vomit" sev="warm"
                   title="Vomit · small" sub="~10 min after Pedialyte" voice />
            <Event time="9:30 PM"  who="Y" tone="#c2b39a" icon="thermo" sev="warm"
                   title="38.6°C · ear" sub="pre-Tylenol" />
            <Event time="9:18 PM"  who="Y" tone="#c2b39a" icon="alert"
                   title="Observation · seems weak" sub="Energy 2 · Mood 3 · Appetite 2"
                   tag="OBS" />
            <Event time="8:50 PM"  who="S" tone="#a5b8c9" icon="drop"
                   title="5oz Pedialyte" sub="drank ~3oz of it" />

            <TimeGroup label="Evening · 6pm – 9pm" />
            <Event time="7:18 PM"  who="Y" tone="#c2b39a" icon="food"
                   title="½ slice toast" sub="refused the second half" />
            <Event time="6:02 PM"  who="S" tone="#a5b8c9" icon="thermo" sev="hot"
                   title="39.1°C · ear · peak" sub="gave Motrin 5mL right after" />
            <Event time="5:45 PM"  who="S" tone="#a5b8c9" icon="pill" tone2="trust"
                   title="5mL Motrin" sub="for the 39.1° spike · stayed down ✓" />

            <div style={{ padding: '14px 0 8px', textAlign: 'center' }}>
              <button style={{
                fontSize: 12, color: T.sage, fontWeight: 600,
                padding: '8px 14px', borderRadius: 99,
                background: T.sageSoft, border: `1px solid ${T.sageEdge}`,
              }}>Load earlier · Days 1–2</button>
            </div>
          </div>
        </div>
        <TabBar mode="d" active="timeline"/>
        <HomeIndicator mode="d"/>
      </div>
    </Phone>
  );
}

function TimeGroup({ label }) {
  const T = UN.d;
  return (
    <div style={{
      padding: '14px 0 6px',
      display: 'flex', alignItems: 'center', gap: 10,
    }}>
      <span style={{ fontSize: 10.5, color: T.textMute, letterSpacing: 0.7, fontWeight: 700, textTransform: 'uppercase' }}>
        {label}
      </span>
      <div style={{ flex: 1, height: 1, background: UN.d.line }}/>
    </div>
  );
}

function Event({ time, who, tone, icon, sev, tone2, title, sub, voice, tag, edit }) {
  const T = UN.d;
  return (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 11, padding: '10px 0',
      borderBottom: `1px solid ${T.line}`,
      position: 'relative',
    }}>
      <div style={{
        width: 50, fontFamily: UN.font.num, fontSize: 11.5, color: T.textMute,
        fontVariantNumeric: 'tabular-nums', fontWeight: 500,
      }}>{time}</div>
      <div style={{
        width: 22, height: 22, borderRadius: 22, background: tone,
        color: '#fff', fontSize: 9.5, fontWeight: 700,
        display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
      }}>{who}</div>
      <div style={{
        width: 30, height: 30, borderRadius: 9,
        background: tone2 === 'trust' ? UN.d.trustSoft :
                    sev ? `${UN.d.sev[sev]}22` : T.surface2,
        display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
      }}>
        <Icon name={icon} size={14}
              color={tone2 === 'trust' ? UN.d.trust : sev ? UN.d.sev[sev] : T.textDim}
              strokeWidth={1.9}/>
      </div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{
          fontSize: 13.5, color: T.text, fontWeight: 600, letterSpacing: -0.1,
          display: 'flex', alignItems: 'center', gap: 6,
        }}>
          {title}
          {voice && <Icon name="mic" size={11} color={T.textMute} strokeWidth={2}/>}
          {tag && (
            <span style={{
              fontSize: 9, color: UN.d.trust, fontWeight: 700, letterSpacing: 0.4,
              padding: '1px 5px', borderRadius: 3, background: UN.d.trustSoft,
            }}>{tag}</span>
          )}
        </div>
        <div style={{ fontSize: 11.5, color: T.textMute, marginTop: 1 }}>{sub}</div>
      </div>
    </div>
  );
}

// ═══════════════════════════════════════════════════════════
// 3. EDIT ENTRY — retroactive edit modal
// ═══════════════════════════════════════════════════════════
function EditEntry() {
  const T = UN.d;
  return (
    <ModalShell
      mode="d"
      title="Edit temp"
      subtitle="38.4° · 9:30pm · you"
      cta={<><Icon name="check" size={16} color="#0E1A14" strokeWidth={2.4}/>Save</>}
      footer={(
        <button style={{
          marginBottom: 10, width: '100%', height: 40,
          background: 'transparent', border: 'none',
          color: UN.d.sev.hot, fontFamily: UN.font.body, fontSize: 13, fontWeight: 600,
        }}>
          Delete entry
        </button>
      )}
    >
      <Label>Temperature</Label>
      <div style={{ marginTop: 8, marginBottom: 14 }}>
        <Stepper value="38.6" unit="°C" sub={<span style={{ color: T.textMute, fontWeight: 500 }}>was 38.4 · changed</span>}/>
      </div>

      <Label>Method</Label>
      <div style={{ marginTop: 8, marginBottom: 14, display: 'flex', gap: 6 }}>
        {['Forehead', 'Ear', 'Underarm', 'Rectal'].map((m, i) => (
          <button key={m} style={{
            flex: 1, padding: '10px 4px', borderRadius: 99,
            background: i === 1 ? T.sageSoft : T.surface,
            border: `1.5px solid ${i === 1 ? T.sage : T.line2}`,
            color: i === 1 ? T.text : T.textDim,
            fontSize: 11.5, fontWeight: i === 1 ? 700 : 500,
          }}>{m}</button>
        ))}
      </div>

      <Label>When</Label>
      <div style={{
        marginTop: 8, marginBottom: 14,
        background: T.surface, borderRadius: 14, border: `1px solid ${T.line2}`,
        padding: '12px 14px',
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
      }}>
        <span style={{ fontSize: 13.5, color: T.text, fontWeight: 600 }}>Thu 9:30 PM</span>
        <span style={{ fontSize: 11.5, color: T.textMute }}>4h ago</span>
        <Icon name="chev" size={12} color={T.textMute} strokeWidth={2}/>
      </div>

      <div style={{
        marginTop: 6, padding: '8px 10px', borderRadius: 10,
        background: UN.d.trustSoft, border: `1px solid rgba(112,144,201,0.32)`,
        display: 'flex', gap: 8, alignItems: 'center',
        fontSize: 11, color: T.textDim, lineHeight: 1.4,
      }}>
        <Icon name="clock" size={13} color={UN.d.trust} strokeWidth={2}/>
        Will appear <strong style={{ color: T.text, fontWeight: 700 }}>edited</strong> in handoff
      </div>
    </ModalShell>
  );
}

// ═══════════════════════════════════════════════════════════
// 4. QUICK LOG GRID — every dimension at once. Big, tappable.
// ═══════════════════════════════════════════════════════════
function QuickLog() {
  const T = UN.d;
  const Tile = ({ icon, label, sub, tone, big }) => (
    <button style={{
      padding: big ? '20px 14px' : '14px 12px',
      background: T.surface, border: `1px solid ${T.line2}`,
      borderRadius: 16, textAlign: 'left',
      display: 'flex', flexDirection: 'column', gap: big ? 10 : 6,
      gridColumn: big ? 'span 2' : 'span 1',
    }}>
      <div style={{
        width: big ? 44 : 32, height: big ? 44 : 32, borderRadius: big ? 13 : 10,
        background: tone === 'sage' ? T.sageSoft :
                   tone === 'trust' ? UN.d.trustSoft :
                   tone === 'warm' ? `${UN.d.sev.warm}22` : T.surface2,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
      }}>
        <Icon name={icon} size={big ? 22 : 16}
              color={tone === 'sage' ? T.sage :
                     tone === 'trust' ? UN.d.trust :
                     tone === 'warm' ? UN.d.sev.warm : T.text}
              strokeWidth={1.9}/>
      </div>
      <div style={{ fontSize: big ? 16 : 13, fontWeight: 700, color: T.text, letterSpacing: -0.15 }}>{label}</div>
      {sub && <div style={{ fontSize: 11, color: T.textMute, marginTop: -2 }}>{sub}</div>}
    </button>
  );

  return (
    <ModalShell mode="d" title="Quick log" subtitle="Maeve">
      {/* Big voice tile */}
      <button style={{
        marginBottom: 10, width: '100%', padding: '20px 18px',
        background: `linear-gradient(135deg, ${T.sage}, ${T.sageDeep})`,
        border: 'none', borderRadius: 18, color: '#0E1A14',
        display: 'flex', alignItems: 'center', gap: 16,
        boxShadow: '0 10px 30px rgba(143,181,162,0.3)',
      }}>
        <div style={{
          width: 56, height: 56, borderRadius: 56,
          background: 'rgba(14,26,20,0.18)',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}>
          <Icon name="mic" size={26} color="#0E1A14" strokeWidth={2.2}/>
        </div>
        <div style={{ flex: 1, textAlign: 'left' }}>
          <div style={{ fontSize: 17, fontWeight: 700, letterSpacing: -0.3 }}>Hold to voice log</div>
          <div style={{ fontSize: 12.5, opacity: 0.7, marginTop: 2 }}>We'll parse it · usually fastest</div>
        </div>
      </button>

      <Label>Or tap what happened</Label>
      <div style={{
        marginTop: 8,
        display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 8,
      }}>
        <Tile icon="thermo" label="Temp"     tone="warm"   sub="38.6° last"/>
        <Tile icon="pill"   label="Dose"     tone="trust"  sub="Mot ready"/>
        <Tile icon="alert"  label="Observe"  tone="sage"   sub="Energy / mood"/>

        <Tile icon="drop"   label="Fluid"    sub="oz drank"/>
        <Tile icon="food"   label="Food"     sub="what / amt"/>
        <Tile icon="vomit"  label="Vomit"    tone="warm" sub="size"/>

        <Tile icon="diaper" label="Wet"      sub="diaper"/>
        <Tile icon="diaper" label="Stool"    sub="Bristol"/>
        <Tile icon="camera" label="Photo"    sub="rash / throat"/>

        <Tile icon="clock"  label="Sleep"    sub="duration"/>
        <Tile icon="mic"    label="Note"     sub="voice / text"/>
        <Tile icon="plus"   label="More…"    sub="add a track"/>
      </div>
    </ModalShell>
  );
}

// ═══════════════════════════════════════════════════════════
// 5. LOG SYMPTOM — rated physical complaints (1-5 each)
// ═══════════════════════════════════════════════════════════
function LogSymptom() {
  const T = UN.d;

  const SymRow = ({ icon, name, value, color = UN.d.sev.warm, pinned = false }) => (
    <div style={{
      padding: '12px 14px', borderRadius: 14,
      background: T.surface, border: `1px solid ${T.line2}`,
      marginBottom: 6,
    }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: value ? 10 : 0 }}>
        <div style={{
          width: 30, height: 30, borderRadius: 9, background: T.surface2,
          display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
        }}>
          <Icon name={icon} size={14} color={value ? color : T.textDim} strokeWidth={1.9}/>
        </div>
        <div style={{ flex: 1, fontSize: 14, color: T.text, fontWeight: 600, letterSpacing: -0.1 }}>{name}</div>
        {/* pin/unpin */}
        <button style={{
          width: 26, height: 26, borderRadius: 8,
          background: pinned ? T.sageSoft : 'transparent',
          border: `1px solid ${pinned ? T.sageEdge : T.line2}`,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          color: pinned ? T.sage : T.textMute,
          cursor: 'pointer',
        }} title={pinned ? "Unpin" : "Pin"}>
          <svg width="12" height="12" viewBox="0 0 24 24" fill={pinned ? 'currentColor' : 'none'} stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
            <path d="M12 17v4M5 9V3h14v6l-3 3v3H8v-3z"/>
          </svg>
        </button>
      </div>
      {value && <Scale5 value={value} color={color}/>}
    </div>
  );

  return (
    <ModalShell mode="d" title="Symptoms" subtitle="Maeve" cta="Log symptoms">
      {/* Pinned */}
      <div style={{
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        marginBottom: 8,
      }}>
        <Label>Pinned · stomach-flu template</Label>
        <button style={{
          fontSize: 11, color: T.textDim, fontWeight: 600,
          background: 'transparent', border: 'none', padding: 0,
          display: 'inline-flex', alignItems: 'center', gap: 4,
        }}>
          <Icon name="gear" size={11} color={T.textDim} strokeWidth={2}/>
          Manage
        </button>
      </div>
      <SymRow icon="vomit"  name="Nausea"     value={4} pinned/>
      <SymRow icon="alert"  name="Belly pain" value={3} pinned/>
      <SymRow icon="alert"  name="Body aches" value={2} pinned/>
      <SymRow icon="alert"  name="Headache"   pinned/>

      {/* Unpinned — tap pin icon to pin */}
      <Label>Other symptoms · tap pin to add</Label>
      <div style={{ marginTop: 8 }}>
        {[
          { i: 'alert', n: 'Sore throat' },
          { i: 'drop',  n: 'Cough' },
          { i: 'drop',  n: 'Congestion' },
          { i: 'alert', n: 'Ear pain' },
          { i: 'alert', n: 'Itch' },
        ].map((s,i) => (
          <SymRow key={i} icon={s.i} name={s.n}/>
        ))}
      </div>
    </ModalShell>
  );
}

Object.assign(window, { LogObservation, LogSymptom, TimelineFull, EditEntry, QuickLog });
