// Today tab — wired to /api/today + the last-14d slice of /api/sleep-trends.

const { fmtBedtime, fmtDelta, fmtHoursMinutes } = window.HC_DATA;

function Card({ children, style = {}, theme }) {
  const p = theme.palette;
  return (
    <div style={{
      background: p.card, border: `1px solid ${p.border}`, borderRadius: 14,
      padding: theme.density.cardPad, ...style,
    }}>{children}</div>
  );
}

function MetricMini({ label, value, unit, color, delta, deltaGood, sparkSeries, target, targetLabel, theme }) {
  const p = theme.palette;
  const deltaColor = deltaGood == null ? p.text3 : (deltaGood ? p.positive : p.warning);
  return (
    <Card theme={theme} style={{ padding: theme.density.miniPad, display: 'flex', flexDirection: 'column', gap: 8 }}>
      <div style={{ fontSize: 10, letterSpacing: 0.6, color: p.text2, textTransform: 'uppercase', fontFamily: 'DM Sans' }}>{label}</div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
        <div style={{ fontFamily: 'DM Mono, monospace', fontSize: theme.density.metricSize, fontWeight: 500, color, lineHeight: 1 }}>
          {value}<span style={{ fontSize: 12, color: p.text2, marginLeft: 2 }}>{unit}</span>
        </div>
        <div style={{ fontFamily: 'DM Mono, monospace', fontSize: 11, color: deltaColor }}>{delta}</div>
      </div>
      <window.Sparkline series={sparkSeries} width={158} height={theme.density.miniSparkH} days={14}
                        showTarget={target} targetLabel={targetLabel} padY={4} fullWidth />
    </Card>
  );
}

function DetailItem({ label, main, sub, stale, theme }) {
  const p = theme.palette;
  return (
    <div>
      <div style={{ fontSize: 9, letterSpacing: 0.5, color: p.text3, textTransform: 'uppercase', fontFamily: 'DM Sans' }}>{label}</div>
      <div style={{ fontFamily: 'DM Mono, monospace', fontSize: 13, color: p.text, marginTop: 4, lineHeight: 1.25 }}>{main}</div>
      <div style={{ fontFamily: 'DM Mono, monospace', fontSize: 10, color: stale ? p.amber : p.text2, marginTop: 3 }}>{sub}</div>
    </div>
  );
}

function ThisWeekRow({ label, filled, total, theme }) {
  const p = theme.palette;
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
      <span style={{ fontFamily: 'DM Mono, monospace', fontSize: 11, color: p.text2, width: 28 }}>{label}</span>
      <div style={{ display: 'flex', gap: 4 }}>
        {Array.from({ length: total }).map((_, i) => (
          <div key={i} style={{
            width: 14, height: 14, borderRadius: 3,
            background: i < filled ? p.training : 'transparent',
            border: `1px solid ${i < filled ? p.training : p.border}`,
          }} />
        ))}
      </div>
    </div>
  );
}

function daysAgoStr(iso) {
  if (!iso) return '—';
  const today = new Date(); today.setHours(0,0,0,0);
  const d = new Date(iso + 'T00:00:00');
  const diff = Math.round((today - d) / 86400000);
  if (diff <= 0) return 'today';
  if (diff === 1) return '1d ago';
  return `${diff}d ago`;
}

function fmtShortDate(iso) {
  if (!iso) return '';
  const d = new Date(iso + 'T00:00:00');
  return `${['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'][d.getMonth()]} ${d.getDate()}`;
}

function TodayTab({ today }) {
  const theme = window.HC_THEME.useHCTheme();
  const p = theme.palette;
  const d = theme.density;

  const sleep = today.sleep || {};
  const training = today.training || {};
  const readiness = today.readiness || {};

  const sleepH = sleep.duration_h;
  const avg10 = today.sleep_10d_avg;
  const delta = (sleepH != null && avg10 != null) ? (sleepH - avg10) : null;
  const deltaPositive = delta != null && delta >= 0;
  const deltaStr = delta != null ? `${delta >= 0 ? '↑' : '↓'} ${Math.abs(delta).toFixed(1)}h vs 10d avg` : '';

  const hrv = sleep.hrv;
  const rhr = sleep.lowest_hr;
  const readScore = readiness.score;
  const bedtime = sleep.bedtime;
  const efficiency = sleep.efficiency;

  // Sessions/wk (this week, Mon-Sun count via days_since_training only gives
  // gap, not weekly count). Use training summary: days_since_training is real.
  const daysSince = training.days_since_training;
  const isStale = daysSince != null && daysSince > 7;

  // Strength/run "this week" boxes — best-effort estimate from days_since.
  // The Trends data array would give the exact number, but we don't want a
  // second fetch on the Today path. Render based on days_since heuristic.
  // (When TrendsData is loaded after first viewing trends, the page does
  // refresh from /api/today, so this stays a snapshot.)

  return (
    <div style={{ padding: `0 16px 24px`, display: 'flex', flexDirection: 'column', gap: d.pageGap }}>

      {/* Sleep card */}
      <Card theme={theme} style={{ padding: d.cardPad }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
          <div>
            <div style={{ fontFamily: 'DM Mono, monospace', fontSize: d.heroSize, fontWeight: 500, color: p.sleep, lineHeight: 1, letterSpacing: -0.5 }}>
              {fmtHoursMinutes(sleepH)}
            </div>
            <div style={{ marginTop: 8, fontFamily: 'DM Mono, monospace', fontSize: 12,
                          color: delta == null ? p.text3 : (deltaPositive ? p.positive : p.warning) }}>
              {deltaStr}
            </div>
          </div>
          <div style={{ textAlign: 'right' }}>
            <div style={{ fontFamily: 'DM Mono, monospace', fontSize: d.scoreSize, color: p.text, fontWeight: 500, lineHeight: 1 }}>
              {today.sleep_score ?? '—'}
            </div>
            <div style={{ fontSize: 10, letterSpacing: 0.6, color: p.text2, textTransform: 'uppercase', marginTop: 6, fontFamily: 'DM Sans' }}>sleep score</div>
          </div>
        </div>
        <div style={{ marginTop: 14 }}>
          <window.Sparkline series="sleep" width={320} height={d.sparkH} days={14}
                            showTarget showLast lastLabel={sleepH != null ? sleepH.toFixed(1) : ''} targetLabel="6.5h"
                            padY={10} fullWidth />
        </div>
      </Card>

      {/* Metrics grid 2×2 */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: d.gridGap }}>
        <MetricMini theme={theme} label="HRV"
                    value={hrv != null ? Math.round(hrv) : '—'} unit="ms" color={p.hrv}
                    delta={null} deltaGood={null} sparkSeries="hrv" />
        <MetricMini theme={theme} label="Resting HR"
                    value={rhr != null ? Math.round(rhr) : '—'} unit="bpm" color={p.hr}
                    delta={null} deltaGood={null} sparkSeries="hr" />
        <MetricMini theme={theme} label="Readiness"
                    value={readScore != null ? readScore : '—'} unit="" color={p.ready}
                    delta={today.readiness_10d_avg != null && readScore != null
                      ? fmtDelta(readScore - today.readiness_10d_avg, 0) : null}
                    deltaGood={today.readiness_10d_avg != null && readScore != null
                      ? readScore >= today.readiness_10d_avg : null}
                    sparkSeries="ready" />
        <MetricMini theme={theme} label="Bedtime"
                    value={bedtime || '—'} unit="" color={p.text}
                    delta={null} deltaGood={null} sparkSeries="bedtime"
                    target targetLabel="22:45" />
      </div>

      {/* Drinks card — yesterday's intake, contextualizes last night's sleep */}
      {(() => {
        const yd = today.drinks_yesterday || {};
        const ydUnits = yd.units || 0;
        const history14 = (today.drinks_14d || []).map((d) => d.units);
        const valueColor = ydUnits >= 3 ? p.warning : ydUnits > 0 ? p.text : p.text3;
        return (
          <Card theme={theme} style={{ padding: d.miniPad, display: 'flex', flexDirection: 'column', gap: 8 }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
              <div style={{ fontSize: 10, letterSpacing: 0.6, color: p.text2, textTransform: 'uppercase', fontFamily: 'DM Sans' }}>
                Drinks <span style={{ color: p.text3, letterSpacing: 0.3 }}>· yesterday</span>
              </div>
              <div style={{ fontFamily: 'DM Mono, monospace', fontSize: 11, color: p.text3 }}>14d</div>
            </div>
            <div style={{ display: 'flex', alignItems: 'baseline', gap: 10 }}>
              <div style={{
                fontFamily: 'DM Mono, monospace', fontSize: d.metricSize, fontWeight: 500,
                color: valueColor, lineHeight: 1,
              }}>
                {ydUnits > 0 ? (
                  <>{ydUnits}<span style={{ fontSize: 12, color: p.text2, marginLeft: 2 }}>u</span></>
                ) : (
                  <span style={{ fontSize: 18 }}>—</span>
                )}
              </div>
              {yd.text && (
                <div style={{
                  fontFamily: 'DM Mono, monospace', fontSize: 11, color: p.text2,
                  lineHeight: 1.2, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
                  minWidth: 0, flex: 1,
                }}>{yd.text}</div>
              )}
            </div>
            <window.DrinksBars data={history14} width={320} height={36} fullWidth
                               threshold={3} mutedColor={p.text3} dangerColor={p.warning} />
          </Card>
        );
      })()}

      {/* Training card */}
      <Card theme={theme} style={{ padding: d.cardPad }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
          <div>
            <div style={{ fontSize: 10, letterSpacing: 0.6, color: p.text2, textTransform: 'uppercase', fontFamily: 'DM Sans' }}>Training</div>
            <div style={{ marginTop: 6, display: 'flex', alignItems: 'baseline', gap: 6 }}>
              <span style={{ fontFamily: 'DM Mono, monospace', fontSize: d.scoreSize,
                             color: isStale ? p.warning : p.text, fontWeight: 500, lineHeight: 1 }}>
                {daysSince != null ? daysSince : '—'}
              </span>
              <span style={{ fontFamily: 'DM Sans', fontSize: 12, color: p.text2 }}>
                days since last
              </span>
            </div>
            {training.comeback_mode && (
              <div style={{ marginTop: 6, fontFamily: 'DM Mono, monospace', fontSize: 11, color: p.amber }}>
                comeback mode · re-entry when ready
              </div>
            )}
          </div>
          <div style={{ textAlign: 'right' }}>
            <div style={{ fontFamily: 'DM Mono, monospace', fontSize: 26, color: p.text, fontWeight: 500, lineHeight: 1 }}>
              {training.vo2max != null ? Math.round(training.vo2max) : '—'}
            </div>
            <div style={{ fontSize: 10, letterSpacing: 0.6, color: p.text2, textTransform: 'uppercase', marginTop: 4, fontFamily: 'DM Sans' }}>vo₂max</div>
          </div>
        </div>

        <div style={{ marginTop: 14 }}>
          <window.Sparkline series="training" width={320} height={d.trainSparkH} days={30}
                            color={p.training} padY={8} fullWidth />
        </div>

        <div style={{ height: 1, background: p.divider, margin: `14px -${d.cardPad}px` }} />

        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16, rowGap: 14 }}>
          <DetailItem theme={theme} label="Longest run"
                      main={training.longest_run_km != null ? `${training.longest_run_km}km` : '—'}
                      sub={training.longest_run_date
                        ? `${fmtShortDate(training.longest_run_date)}${training.longest_run_min != null ? ` · ${training.longest_run_min}min` : ''}`
                        : ''}
                      stale={false} />
          <DetailItem theme={theme} label="Last core"
                      main={training.last_core_exercise || '—'}
                      sub={training.last_core_date
                        ? `${fmtShortDate(training.last_core_date)} · ${daysAgoStr(training.last_core_date)}`
                        : ''}
                      stale={training.last_core_date
                        ? (Date.now() - new Date(training.last_core_date + 'T00:00:00')) / 86400000 > 10
                        : false} />
          <DetailItem theme={theme} label="Last strength"
                      main={training.last_gym_title || '—'}
                      sub={training.last_gym
                        ? `${fmtShortDate(training.last_gym)} · ${daysAgoStr(training.last_gym)}`
                        : ''}
                      stale={training.last_gym
                        ? (Date.now() - new Date(training.last_gym + 'T00:00:00')) / 86400000 > 7
                        : false} />
          <DetailItem theme={theme} label="Last run"
                      main={training.last_run ? `${daysAgoStr(training.last_run)}` : '—'}
                      sub={training.last_run ? fmtShortDate(training.last_run) : ''}
                      stale={training.last_run
                        ? (Date.now() - new Date(training.last_run + 'T00:00:00')) / 86400000 > 7
                        : false} />
        </div>
      </Card>

      {/* Context strip */}
      <div style={{
        textAlign: 'center', fontFamily: 'DM Mono, monospace', fontSize: 11,
        color: p.text2, padding: '10px 4px', border: `1px solid ${p.border}`,
        borderRadius: 10, background: p.stripBg,
      }}>
        {efficiency != null ? `Eff ${Math.round(efficiency)}%` : ''}
        {efficiency != null && today.resilience ? ' · ' : ''}
        {today.resilience ? today.resilience.charAt(0).toUpperCase() + today.resilience.slice(1) : ''}
        {(efficiency != null || today.resilience) && daysSince != null ? ' · ' : ''}
        {daysSince != null ? `Last training ${daysSince}d ago` : ''}
      </div>
    </div>
  );
}

window.TodayTab = TodayTab;
window.HCCard = Card;
