// Trends tab — five chart panels driven by /api/sleep-trends.

const { thirdsPhases, phaseAvg, eventsToAnnotations, fmtBedtime } = window.HC_DATA;

function Row({ label, value, color, theme }) {
  return (
    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginTop: 3 }}>
      <span style={{ fontFamily: 'DM Mono, monospace', fontSize: 9, color: theme.palette.text3 }}>{label}</span>
      <span style={{ fontFamily: 'DM Mono, monospace', fontSize: 13, color, fontWeight: 500 }}>{value}</span>
    </div>
  );
}

function PhaseStat({ name, color, sleep, hrv, ready, theme }) {
  const Card = window.HCCard;
  const p = theme.palette;
  return (
    <Card theme={theme} style={{ padding: 12, flex: 1 }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 8 }}>
        <div style={{ width: 6, height: 6, borderRadius: '50%', background: color }} />
        <div style={{ fontSize: 9, letterSpacing: 0.5, color: p.text2, textTransform: 'uppercase', fontFamily: 'DM Sans' }}>{name}</div>
      </div>
      <Row theme={theme} label="sleep" value={isFinite(sleep) ? sleep.toFixed(1) + 'h' : '—'} color={p.sleep} />
      <Row theme={theme} label="hrv" value={isFinite(hrv) ? Math.round(hrv) + 'ms' : '—'} color={p.hrv} />
      <Row theme={theme} label="ready" value={isFinite(ready) ? Math.round(ready) : '—'} color={p.ready} />
    </Card>
  );
}

function ChartPanel({ title, unit, children, theme }) {
  const Card = window.HCCard;
  const p = theme.palette;
  return (
    <Card theme={theme} style={{ padding: 14 }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 8 }}>
        <div style={{ fontSize: 10, letterSpacing: 0.6, color: p.text, textTransform: 'uppercase', fontFamily: 'DM Sans', fontWeight: 500 }}>{title}</div>
        <div style={{ fontFamily: 'DM Mono, monospace', fontSize: 10, color: p.text3 }}>{unit}</div>
      </div>
      {children}
    </Card>
  );
}

function TrendsTab({ trends, series }) {
  const theme = window.HC_THEME.useHCTheme();
  const p = theme.palette;
  const d = theme.density;
  const [range, setRange] = React.useState('full');

  if (!trends || !series) {
    return (
      <div style={{ padding: '40px 16px', textAlign: 'center', color: p.text3, fontFamily: 'DM Mono, monospace', fontSize: 12 }}>
        loading trends…
      </div>
    );
  }

  const days = trends.days || [];
  // Expose date array so DateTicks can label the x-axis with real dates.
  window.HC_TREND_DATES = days.map((d) => d.day);

  const phases = thirdsPhases(days);
  const sleepPhase = (i) => phaseAvg(series.sleep, phases[i]);
  const hrvPhase = (i) => phaseAvg(series.hrv, phases[i]);
  const readyPhase = (i) => phaseAvg(series.ready, phases[i]);

  const annotations = eventsToAnnotations(trends.events || [], days);
  const windowDays = days.length;

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

      <div style={{ display: 'flex', gap: 8 }}>
        <PhaseStat theme={theme} name={phases[0].name} color={p.training}
                   sleep={sleepPhase(0)} hrv={hrvPhase(0)} ready={readyPhase(0)} />
        <PhaseStat theme={theme} name={phases[1].name} color={p.warning}
                   sleep={sleepPhase(1)} hrv={hrvPhase(1)} ready={readyPhase(1)} />
        <PhaseStat theme={theme} name={phases[2].name} color={p.accent}
                   sleep={sleepPhase(2)} hrv={hrvPhase(2)} ready={readyPhase(2)} />
      </div>

      <div style={{ display: 'flex', gap: 6, padding: 3, background: p.tabRail, borderRadius: 10, alignSelf: 'flex-start' }}>
        {[['full', 'Full history'], ['4w', 'Last 4 weeks']].map(([k, label]) => (
          <button key={k} onClick={() => setRange(k)} style={{
            padding: '6px 12px', border: 'none', borderRadius: 8,
            fontFamily: 'DM Sans', fontSize: 12,
            background: range === k ? p.tabActive : 'transparent',
            color: range === k ? p.text : p.text2,
            boxShadow: range === k ? '0 1px 2px rgba(0,0,0,0.05)' : 'none',
            cursor: 'pointer', fontWeight: range === k ? 500 : 400,
          }}>{label}</button>
        ))}
      </div>

      <ChartPanel theme={theme} title="Sleep duration" unit="hours · target 6.5h">
        <window.TrendChart series="sleep" refLine={6.5} refLabel="6.5h"
                           phases={phases} annotations={annotations}
                           range={range} windowDays={windowDays} />
      </ChartPanel>

      <ChartPanel theme={theme} title="HRV" unit="ms · ref 25">
        <window.TrendChart series="hrv" refLine={25} refLabel="25ms"
                           phases={phases} annotations={annotations}
                           range={range} windowDays={windowDays} />
      </ChartPanel>

      <ChartPanel theme={theme} title="Avg heart rate" unit="bpm · lower = better">
        <window.TrendChart series="hr" invert
                           phases={phases} annotations={annotations}
                           range={range} windowDays={windowDays} />
      </ChartPanel>

      <ChartPanel theme={theme} title="Bedtime" unit="HH:MM · target 22:45">
        <window.TrendChart series="bedtime" refLine={22.75} refLabel="22:45" showVolBand
                           yFormat={(v) => fmtBedtime(v)}
                           phases={phases} annotations={annotations}
                           range={range} windowDays={windowDays} />
      </ChartPanel>

      <ChartPanel theme={theme} title="Readiness" unit="score · ref 70">
        <window.TrendChart series="ready" refLine={70} refLabel="70"
                           phases={phases} annotations={annotations}
                           range={range} windowDays={windowDays} />
      </ChartPanel>

      <ChartPanel theme={theme} title="Drinks" unit="units · ref 3u">
        <window.DrinksTrendChart phases={phases} annotations={annotations}
                                 range={range} windowDays={windowDays}
                                 threshold={3} />
      </ChartPanel>

      <div style={{
        textAlign: 'center', fontFamily: 'DM Mono, monospace', fontSize: 10,
        color: p.text3, marginTop: 4,
      }}>
        — raw · ewma · 14d ma · vol band on bedtime —
      </div>
    </div>
  );
}

window.TrendsTab = TrendsTab;
