// Today — the morning briefing home screen
// Synthesizes: weather + sleep + calendar + bills + approvals + recovery

function TodayScreen({ go, openCapture, pullProgress = 0 }) {
  const d = LifeData;
  const w = d.weather;
  const h = d.health.today;
  const baseline = d.health.baseline;
  const sleepDelta = (h.sleep_hours - baseline.sleep_hours).toFixed(1);
  const sleepBelow = h.sleep_hours < baseline.sleep_hours;
  const today = d.today instanceof Date ? d.today : new Date(d.today);
  const dateStr = today.toLocaleDateString('en-US', { weekday: 'long', day: 'numeric', month: 'long' });

  // Next event
  const nowMin = today.getHours() * 60 + today.getMinutes();
  const toMin = (s) => parseInt(s.slice(0,2)) * 60 + parseInt(s.slice(3,5));
  const next = d.calendar.find(e => toMin(e.time) >= nowMin) || d.calendar[0];
  const minsToNext = next ? toMin(next.time) - nowMin : 0;

  const haveSleep = h.sleep_hours > 0;
  const haveHRV = h.hrv_ms > 0;
  const haveHealth = haveSleep || haveHRV;

  return (
    <div style={{ paddingBottom: 110, opacity: 1 - pullProgress * 0.25 }}>
      {/* Greeting */}
      <div style={{ padding: '64px 20px 14px' }}>
        <div style={{ fontSize: 13, fontWeight: 600, color: T.label2, letterSpacing: 0.4, textTransform: 'uppercase' }}>
          {dateStr}
        </div>
        <div style={{ fontSize: 32, fontWeight: 700, letterSpacing: -0.6, lineHeight: '38px', marginTop: 4 }}>
          <Bi>שלום,</Bi> {d.user === 'shay' ? 'Shay' : 'Gili'}
        </div>
        <div style={{ fontSize: 15, color: T.label2, marginTop: 4 }}>
          {w.location} · {w.temp_c}° · {w.summary}
        </div>
      </div>

      {/* Hero — Morning Read */}
      <div style={{ padding: '0 16px 14px' }}>
        <div style={{
          background: grad('#1C1C1E', '#2C2C2E'),
          borderRadius: 22,
          padding: '18px 18px 16px',
          color: '#fff',
          position: 'relative', overflow: 'hidden',
          boxShadow: '0 1px 0 rgba(0,0,0,0.04), 0 8px 24px rgba(0,0,0,0.10)',
        }}>
          <div style={{
            position: 'absolute', top: -30, right: -30, width: 160, height: 160, borderRadius: 999,
            background: grad('rgba(255,149,0,0.35)', 'rgba(175,82,222,0.1)'),
            filter: 'blur(20px)',
          }} />
          <div style={{ display: 'flex', alignItems: 'center', gap: 6, position: 'relative' }}>
            <IconSparkle size={14} color="#FFCC00" fill="#FFCC00" sw={0} />
            <span style={{ fontSize: 12, fontWeight: 600, letterSpacing: 0.6, color: '#FFCC00', textTransform: 'uppercase' }}>The Morning Read</span>
          </div>
          <div style={{ marginTop: 12, fontSize: 19, lineHeight: '26px', letterSpacing: -0.2, position: 'relative' }}>
            {haveHealth ? (
              <>
                {haveSleep && <>You slept <b>{Math.floor(h.sleep_hours)}h{Math.round((h.sleep_hours % 1) * 60).toString().padStart(2,'0')}m</b> — {Math.abs(sleepDelta)}h {sleepBelow ? 'below' : 'above'} your baseline. </>}
                {haveHRV && <>HRV is at <b>{Math.round(h.hrv_ms)}ms</b>{baseline.hrv_ms ? ` (${h.hrv_ms < baseline.hrv_ms ? '–' : '+'}${Math.round(Math.abs(h.hrv_ms - baseline.hrv_ms))} from avg)` : ''}.</>}
              </>
            ) : (
              <>Good morning. No health data yet — sync Apple Health to see your recovery.</>
            )}
            {next && (
              <><br /><br />Next up: <b>{next.time}</b> — <Bi>{next.summary}</Bi>.</>
            )}
          </div>
          <div style={{ display: 'flex', gap: 8, marginTop: 14, position: 'relative' }}>
            <button onClick={() => go('chat')} style={{
              flex: 1, height: 38, borderRadius: 12, border: 'none', cursor: 'pointer',
              background: 'rgba(255,255,255,0.18)', color: '#fff', fontSize: 14, fontWeight: 600,
              backdropFilter: 'blur(20px)', WebkitBackdropFilter: 'blur(20px)',
            }}>Ask follow-up</button>
            <button onClick={() => go('inbox')} style={{
              flex: 1, height: 38, borderRadius: 12, border: 'none', cursor: 'pointer',
              background: '#fff', color: '#000', fontSize: 14, fontWeight: 600,
            }}>{d.approvals.length > 0 ? `${d.approvals.length} actions →` : 'Inbox →'}</button>
          </div>
        </div>
      </div>

      {/* Next event banner */}
      {next && (
        <div style={{ padding: '0 16px 14px' }}>
          <Card style={{ display: 'flex', alignItems: 'center', gap: 12, padding: 14 }}>
            <div style={{
              width: 44, height: 44, borderRadius: 12,
              background: grad('#5AC8FA','#007AFF'),
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              flexShrink: 0,
            }}>
              <IconCal size={22} color="#fff" />
            </div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 12, fontWeight: 600, color: T.blue, letterSpacing: 0.3 }}>
                {minsToNext > 0 ? `IN ${minsToNext} MIN · ` : ''}{next.time}
              </div>
              <div style={{ fontSize: 16, fontWeight: 600, marginTop: 2, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                <Bi>{next.summary}</Bi>
              </div>
              {next.location && (
                <div style={{ fontSize: 13, color: T.label2, marginTop: 1 }}>
                  <Bi>{next.location}</Bi>
                </div>
              )}
            </div>
            <IconChevR size={18} color={T.label4} />
          </Card>
        </div>
      )}

      {/* Schedule strip */}
      {d.calendar.length > 0 && (
        <Section title="Schedule">
          <Card padded={false}>
            {d.calendar.map((e, i) => {
              const done = toMin(e.time) < nowMin;
              const isNext = next && e.id === next.id;
              const color = e.type === 'work' ? T.blue : e.type === 'family' ? T.orange : e.type === 'health' ? T.green : T.pink;
              return (
                <div key={e.id} style={{
                  display: 'flex', alignItems: 'center', minHeight: 56,
                  padding: '8px 16px',
                  borderBottom: i < d.calendar.length - 1 ? `0.5px solid ${T.sep}` : 'none',
                  opacity: done ? 0.42 : 1,
                }}>
                  <div style={{ width: 56, fontSize: 13, fontWeight: 600, color: isNext ? T.blue : T.label2, fontVariantNumeric: 'tabular-nums' }}>
                    {e.time}
                  </div>
                  <div style={{ width: 4, height: 32, background: color, borderRadius: 2, marginRight: 12, flexShrink: 0 }} />
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontSize: 15, fontWeight: done ? 400 : 500, textDecoration: done ? 'line-through' : 'none', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                      <Bi>{e.summary}</Bi>
                    </div>
                    {e.location && (
                      <div style={{ fontSize: 12, color: T.label2, marginTop: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                        <Bi>{e.location}</Bi>
                      </div>
                    )}
                  </div>
                </div>
              );
            })}
          </Card>
        </Section>
      )}

      {/* Body glance — only show if we have data */}
      {haveHealth && (
        <Section title="Body" style={{ marginTop: 22 }} action={
          <span onClick={() => go('body')} style={{ fontSize: 14, color: T.blue, fontWeight: 500, cursor: 'pointer' }}>Open →</span>
        }>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 10 }}>
            <MiniStat label="Sleep" value={`${Math.floor(h.sleep_hours)}h${Math.round((h.sleep_hours%1)*60).toString().padStart(2,'0')}`} detail={`${sleepDelta}h vs avg`} bad={sleepBelow} icon={<IconBed size={16} color={T.indigo} />} />
            {haveHRV && <MiniStat label="HRV" value={`${Math.round(h.hrv_ms)}`} unit="ms" detail={baseline.hrv_ms ? `${h.hrv_ms < baseline.hrv_ms ? '–' : '+'}${Math.round(Math.abs(h.hrv_ms - baseline.hrv_ms))} from avg` : 'no baseline'} bad={baseline.hrv_ms && h.hrv_ms < baseline.hrv_ms} icon={<IconPulse size={16} color={T.red} />} />}
            {h.readiness > 0 && <MiniStat label="Readiness" value={`${Math.round(h.readiness)}`} unit="%" detail={h.readiness >= 80 ? 'Good' : h.readiness >= 60 ? 'Moderate' : 'Low'} icon={<IconBolt size={16} color={T.green} />} />}
          </div>
        </Section>
      )}

      {/* Bills */}
      {d.bills.length > 0 && (
        <Section title="Bills due" style={{ marginTop: 22 }} action={
          <span style={{ fontSize: 14, color: T.label2 }}>₪{d.bills.reduce((s, b) => s + (b.amount_nis || 0), 0).toFixed(0)} total</span>
        }>
          <Card padded={false}>
            {d.bills.slice(0, 3).map((b, i) => (
              <div key={b.id} style={{
                display: 'flex', alignItems: 'center', minHeight: 52, padding: '10px 14px',
                borderBottom: i < Math.min(d.bills.length, 3) - 1 ? `0.5px solid ${T.sep}` : 'none',
              }}>
                <div style={{
                  width: 32, height: 32, borderRadius: 8,
                  background: b.category === 'electric' ? T.yellow : b.category === 'gov' ? T.indigo : b.category === 'phone' ? T.green : T.blue,
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  marginRight: 12, color: '#fff', fontSize: 14, fontWeight: 700,
                }}>{(b.provider || '?')[0]}</div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 15, fontWeight: 500 }}>
                    {b.provider}
                    {b.provider_he ? <span style={{ color: T.label3, fontWeight: 400 }}> · <Bi>{b.provider_he}</Bi></span> : null}
                  </div>
                  <div style={{ fontSize: 12, color: T.label2 }}>Due {b.due_date ? new Date(b.due_date).toLocaleDateString('en-US', { day: 'numeric', month: 'short' }) : '—'}</div>
                </div>
                <div style={{ fontSize: 16, fontWeight: 600, fontVariantNumeric: 'tabular-nums' }}>₪{(b.amount_nis || 0).toFixed(0)}</div>
              </div>
            ))}
          </Card>
        </Section>
      )}

      {/* Drift teaser — only if we have people data */}
      {d.people.length > 0 && (
        <Section title="Relationship pulse" style={{ marginTop: 22 }} action={
          <span onClick={() => go('radar')} style={{ fontSize: 14, color: T.blue, fontWeight: 500, cursor: 'pointer' }}>Radar →</span>
        }>
          <Card onClick={() => go('radar')} style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
            <div style={{
              width: 44, height: 44, borderRadius: 12,
              background: grad('#FF2D55','#FF9500'),
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              flexShrink: 0,
            }}>
              <IconGhost size={22} color="#fff" />
            </div>
            <div style={{ flex: 1 }}>
              {(() => {
                const ghosts = d.people.filter(p => p.ghost);
                const drifting = d.people.filter(p => p.days_since > 7);
                return (
                  <>
                    <div style={{ fontSize: 15, fontWeight: 600 }}>
                      {drifting.length} drifting{ghosts.length > 0 ? `, ${ghosts.length} waiting` : ''}
                    </div>
                    <div style={{ fontSize: 13, color: T.label2 }}>
                      <Bi>{drifting.slice(0,3).map(p => p.name).join(', ')}</Bi>
                    </div>
                  </>
                );
              })()}
            </div>
            <IconChevR size={18} color={T.label4} />
          </Card>
        </Section>
      )}

      {/* Pull hint */}
      <div style={{ textAlign: 'center', padding: '24px 0 8px', color: T.label4, fontSize: 12 }}>
        ↓ pull down to capture
      </div>
    </div>
  );
}

function MiniStat({ label, value, unit, detail, icon, bad }) {
  return (
    <Card style={{ padding: 12 }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
        {icon}
        <span style={{ fontSize: 11, fontWeight: 600, color: T.label2, letterSpacing: 0.2, textTransform: 'uppercase' }}>{label}</span>
      </div>
      <div style={{ fontSize: 22, fontWeight: 700, letterSpacing: -0.4, marginTop: 6, fontVariantNumeric: 'tabular-nums' }}>
        {value}
        {unit && <span style={{ fontSize: 12, fontWeight: 500, color: T.label2, marginLeft: 2 }}>{unit}</span>}
      </div>
      <div style={{ fontSize: 11, color: bad ? T.red : T.label2, marginTop: 1 }}>{detail}</div>
    </Card>
  );
}

window.TodayScreen = TodayScreen;
