// AFTER — Trend screen (4-week view). Same vocabulary as DashboardScreen.
const { useState: useStateTrend, useMemo: useMemoTrend } = React;

const TR = {
  cream: '#fafaf8', black: '#0f0f0f', green: '#3d6b4f',
  greenDark: '#2a4d39',
  gray: '#6b6b6b', border: '#e2e0db', greenLight: '#e8f0eb',
};

const trStyles = {
  screen: { background: TR.cream, height: '100%', display: 'flex', flexDirection: 'column' },
  scroll: { flex: 1, overflowY: 'auto', padding: '64px 20px 20px' },
  headerRow: { marginBottom: 24 },
  eyebrow: { fontFamily: '"DM Sans", system-ui', fontSize: 12, fontWeight: 600, color: TR.gray, letterSpacing: '.08em', textTransform: 'uppercase' },
  title: { fontFamily: '"DM Serif Display", Georgia, serif', fontSize: 30, color: TR.black, lineHeight: 1.15, marginTop: 6 },
  sub: { fontFamily: '"DM Sans", system-ui', fontSize: 14, color: TR.gray, marginTop: 6, lineHeight: 1.5 },
  card: { background: TR.cream, border: `1px solid ${TR.border}`, borderRadius: 16, padding: 20, marginBottom: 12 },
  cardLabel: { fontFamily: '"DM Sans", system-ui', fontSize: 12, fontWeight: 600, color: TR.gray, textTransform: 'uppercase', letterSpacing: '.05em', marginBottom: 12 },
  statsRow: { display: 'flex', gap: 24, marginTop: 12 },
  statLabel: { fontFamily: '"DM Sans", system-ui', fontSize: 12, color: TR.gray },
  statValue: { fontFamily: '"DM Sans", system-ui', fontSize: 18, fontWeight: 600, color: TR.black, marginTop: 2 },
  callout: {
    background: TR.greenLight,
    border: `1px solid ${TR.green}`,
    borderRadius: 14,
    padding: '14px 16px',
    marginBottom: 12,
  },
  calloutLabel: {
    fontFamily: '"DM Sans", system-ui', fontSize: 11, fontWeight: 600, color: TR.green,
    letterSpacing: '.1em', textTransform: 'uppercase', marginBottom: 6,
  },
  calloutBody: {
    fontFamily: '"DM Sans", system-ui', fontSize: 14, color: TR.greenDark, lineHeight: 1.5,
  },
  segRow: { display: 'flex', gap: 6, background: '#f0efed', padding: 4, borderRadius: 10, marginBottom: 14 },
  segBtn: (on) => ({
    flex: 1, padding: '8px 0', borderRadius: 8,
    fontFamily: '"DM Sans", system-ui', fontSize: 13, fontWeight: 600,
    background: on ? TR.cream : 'transparent',
    color: on ? TR.black : TR.gray,
    boxShadow: on ? '0 1px 2px rgba(0,0,0,0.06)' : 'none',
    border: 'none', cursor: 'pointer',
    textAlign: 'center',
  }),
};

function TrendChart() {
  // 30-day weight series — drifts within a 175 ± 3 lb maintenance band
  const W = 320, H = 130;
  const center = 175;
  const bandHi = 178, bandLo = 172;
  const pts = Array.from({ length: 30 }, (_, i) => {
    const drift = Math.sin(i * 0.32) * 1.4;
    const wobble = Math.sin(i * 1.7) * 0.4 + Math.sin(i * 2.9 + 1) * 0.3;
    return center + drift + wobble + (i < 4 ? 0.6 : 0);
  });
  const yMin = 170, yMax = 180;
  const yOf = v => H - 8 - ((v - yMin) / (yMax - yMin)) * (H - 16);
  const xOf = i => (i / (pts.length - 1)) * W;
  const xs = pts.map((_, i) => xOf(i));
  const ys = pts.map(yOf);
  const line = xs.map((x, i) => `${i === 0 ? 'M' : 'L'} ${x.toFixed(2)} ${ys[i].toFixed(2)}`).join(' ');
  const fill = line + ` L ${W} ${H} L 0 ${H} Z`;
  const yBandHi = yOf(bandHi), yBandLo = yOf(bandLo);
  return (
    <svg width="100%" height={H} viewBox={`0 0 ${W} ${H}`} preserveAspectRatio="none" style={{ display: 'block' }}>
      <defs>
        <linearGradient id="trch" x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor={TR.green} stopOpacity=".22"/>
          <stop offset="100%" stopColor={TR.green} stopOpacity="0"/>
        </linearGradient>
      </defs>
      <rect x="0" y={yBandHi} width={W} height={yBandLo - yBandHi} fill={TR.green} fillOpacity="0.08"/>
      <line x1="0" x2={W} y1={yBandHi} y2={yBandHi} stroke={TR.green} strokeOpacity="0.4" strokeDasharray="3 3" strokeWidth="1"/>
      <line x1="0" x2={W} y1={yBandLo} y2={yBandLo} stroke={TR.green} strokeOpacity="0.4" strokeDasharray="3 3" strokeWidth="1"/>
      <path d={fill} fill="url(#trch)"/>
      <path d={line} fill="none" stroke={TR.green} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
      <circle cx={xs[xs.length-1]} cy={ys[ys.length-1]} r="3.5" fill={TR.green}/>
      <circle cx={xs[xs.length-1]} cy={ys[ys.length-1]} r="7" fill={TR.green} fillOpacity="0.18"/>
    </svg>
  );
}

function NoiseBars() {
  // Per-day food noise score (0–10), 14 days, with a Sunday-evening spike pattern
  const days = [3, 4, 3, 5, 4, 6, 8, 3, 4, 3, 4, 5, 7, 9];
  const max = 10;
  return (
    <div style={{ display: 'flex', alignItems: 'flex-end', gap: 4, height: 64, marginTop: 6 }}>
      {days.map((d, i) => {
        const isSpike = d >= 7;
        return (
          <div key={i} style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4 }}>
            <div style={{
              width: '100%',
              height: `${(d / max) * 100}%`,
              background: isSpike ? TR.green : TR.border,
              borderRadius: 3,
            }} />
          </div>
        );
      })}
    </div>
  );
}

function TrendScreen() {
  const [range, setRange] = useStateTrend('30d');
  return (
    <div style={trStyles.screen}>
      <div style={trStyles.scroll}>
        <div style={trStyles.headerRow}>
          <div style={trStyles.eyebrow}>Last 30 days</div>
          <div style={trStyles.title}>Holding steady.</div>
          <div style={trStyles.sub}>You're within 1.4 lb of where you started maintenance. That's the goal — not down, just held.</div>
        </div>

        <div style={trStyles.segRow}>
          {[['7d','7 days'],['30d','30 days'],['90d','90 days']].map(([k, label]) => (
            <button key={k} style={trStyles.segBtn(range === k)} onClick={() => setRange(k)}>{label}</button>
          ))}
        </div>

        {/* Chart card */}
        <div style={trStyles.card}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 6 }}>
            <div style={trStyles.cardLabel}>Weight trend</div>
            <div style={{ fontFamily: '"DM Sans", system-ui', fontSize: 11, fontWeight: 500, color: TR.green }}>Maintenance band</div>
          </div>
          <TrendChart />
          <div style={trStyles.statsRow}>
            <div><div style={trStyles.statLabel}>Start</div><div style={trStyles.statValue}>175.8</div></div>
            <div><div style={trStyles.statLabel}>Now</div><div style={trStyles.statValue}>174.4</div></div>
            <div><div style={trStyles.statLabel}>Range</div><div style={{ ...trStyles.statValue, color: TR.green }}>±1.6 lb</div></div>
          </div>
        </div>

        {/* Mira's pattern callout */}
        <div style={trStyles.callout}>
          <div style={trStyles.calloutLabel}>Pattern Mira noticed</div>
          <div style={trStyles.calloutBody}>Food noise spikes Sunday evenings. Want to plan a Sunday ritual together?</div>
        </div>

        {/* Food noise card */}
        <div style={trStyles.card}>
          <div style={trStyles.cardLabel}>Food noise · 14 days</div>
          <NoiseBars />
          <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 8 }}>
            <span style={trStyles.statLabel}>Mon</span>
            <span style={trStyles.statLabel}>Sun</span>
            <span style={trStyles.statLabel}>Sat</span>
            <span style={trStyles.statLabel}>Fri</span>
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { TrendScreen });
