/* Nutri Analyses Screen
   Ported from Calories Analysis.html — Section 3 ("Analyses").
   - 6 summary cards: avg calories, avg protein, avg carbs, avg fat, highest day, lowest day
   - Daily Calories bar chart
   - Daily Macros chart (stacked bars)
   - Daily Calories Breakdown table (Breakfast / Lunch / Dinner / Snacks / Total per date)
   Uses Chart.js (loaded via CDN in index.html).
*/

function AnalysesScreen() {
  const Store = window.Store;
  const useStore = window.useStore;
  useStore();
  const [range, setRange] = React.useState('1w'); // 1d | 1w | 1m | max
  // Adapt the flat Store into the project-shape this screen was written against.
  const project = {
    entries: Store.meals(),
    goals: Store.macroGoals() || {},
  };

  // ── Build per-day aggregation with item-level macro fallback ──
  const days = byDay(project);
  const filtered = inRange(days, range);

  // ── Compute summary stats ──
  const stat = summarize(filtered);

  // ── Chart refs ──
  const caloriesChartRef = React.useRef(null);
  const macrosChartRef = React.useRef(null);
  const caloriesChartInstance = React.useRef(null);
  const macrosChartInstance = React.useRef(null);

  React.useEffect(() => {
    if (!window.Chart) return; // Chart.js not loaded yet
    drawCaloriesChart();
    drawMacrosChart();
    return () => {
      if (caloriesChartInstance.current) caloriesChartInstance.current.destroy();
      if (macrosChartInstance.current) macrosChartInstance.current.destroy();
    };
  }, [filtered]);

  function drawCaloriesChart() {
    const ctx = caloriesChartRef.current;
    if (!ctx) return;
    if (caloriesChartInstance.current) caloriesChartInstance.current.destroy();
    const goal = +(project.goals && project.goals.calories) || 0;
    caloriesChartInstance.current = new window.Chart(ctx, {
      type: 'bar',
      data: {
        labels: filtered.map(d => d.date),
        datasets: [
          { label: 'Calories', data: filtered.map(d => d.calories), backgroundColor: '#E89B3C', borderRadius: 6 },
          ...(goal ? [{ label: `Goal ${goal}`, type: 'line', data: filtered.map(() => goal), borderColor: '#7A766C', borderDash: [4,4], borderWidth: 1.5, pointRadius: 0, fill: false }] : []),
        ],
      },
      options: chartOpts(),
    });
  }

  function drawMacrosChart() {
    const ctx = macrosChartRef.current;
    if (!ctx) return;
    if (macrosChartInstance.current) macrosChartInstance.current.destroy();
    macrosChartInstance.current = new window.Chart(ctx, {
      type: 'bar',
      data: {
        labels: filtered.map(d => d.date),
        datasets: [
          { label: 'Carbs (g)',   data: filtered.map(d => d.carbs_g),   backgroundColor: '#E89B3C', stack: 'm' },
          { label: 'Protein (g)', data: filtered.map(d => d.protein_g), backgroundColor: '#4FA862', stack: 'm' },
          { label: 'Fat (g)',     data: filtered.map(d => d.fat_g),     backgroundColor: '#5784D8', stack: 'm' },
        ],
      },
      options: chartOpts(true),
    });
  }

  // ── breakdown table rows ──
  const breakdownRows = buildBreakdown(project, range);

  // ── styles ──
  const card = {
    background: 'var(--surface)', border: '1px solid var(--border)',
    borderRadius: 16, padding: 16, marginBottom: 12,
    boxShadow: 'var(--shadow-sm)',
  };
  const statCard = { ...card, padding: '14px 16px' };

  return (
    <div style={{ padding: 16, paddingBottom: 100 }}>
      {/* Header */}
      <div style={{ marginBottom: 16, display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12 }}>
        <div>
          <h1 style={{ fontSize: 22, fontWeight: 700, letterSpacing: '-0.02em', margin: '0 0 4px' }}>Analyses</h1>
          <p style={{ fontSize: 13, color: 'var(--muted)', margin: 0 }}>{filtered.length} day{filtered.length===1?'':'s'} shown</p>
        </div>
        <RangeToggle value={range} onChange={setRange}/>
      </div>

      {/* Stat grid */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 8, marginBottom: 16 }}>
        <Stat label="Avg Calories" value={fmt(stat.avgCal)} unit="kcal" color="#E89B3C"/>
        <Stat label="Avg Protein"  value={fmt(stat.avgProt)} unit="g" color="#4FA862"/>
        <Stat label="Avg Carbs"    value={fmt(stat.avgCarb)} unit="g" color="#E89B3C"/>
        <Stat label="Avg Fat"      value={fmt(stat.avgFat)} unit="g" color="#5784D8"/>
        <Stat label="Highest Day"  value={fmt(stat.max)} unit="kcal"/>
        <Stat label="Lowest Day"   value={fmt(stat.min)} unit="kcal"/>
      </div>

      {/* Daily Calories chart */}
      <div style={card}>
        <h3 style={chartTitle}>Daily Calories</h3>
        <div style={{ position: 'relative', height: 220 }}>
          <canvas ref={caloriesChartRef}/>
        </div>
      </div>

      {/* Daily Macros chart */}
      <div style={card}>
        <h3 style={chartTitle}>Daily Macros</h3>
        <div style={{ position: 'relative', height: 220 }}>
          <canvas ref={macrosChartRef}/>
        </div>
      </div>

      {/* Daily Calories Breakdown table */}
      <div style={card}>
        <h3 style={chartTitle}>Daily Calories Breakdown</h3>
        <div style={{ overflowX: 'auto', marginTop: 8 }}>
          <table style={{
            width: '100%', borderCollapse: 'collapse',
            fontSize: 12.5, minWidth: 480,
          }}>
            <thead>
              <tr style={{ borderBottom: '1px solid var(--border)' }}>
                <Th style={{ textAlign: 'left' }}>Date</Th>
                <Th>Breakfast</Th><Th>Lunch</Th><Th>Dinner</Th><Th>Snacks</Th>
                <Th>Total</Th>
              </tr>
            </thead>
            <tbody>
              {breakdownRows.length === 0
                ? <tr><Td colSpan={6} style={{ color: 'var(--muted)', textAlign: 'center', padding: 16 }}>No entries.</Td></tr>
                : breakdownRows.map(r => (
                    <tr key={r.date} style={{ borderBottom: '1px solid var(--border)' }}>
                      <Td style={{ textAlign: 'left' }}>{r.date}</Td>
                      <Td>{r.bCal || '—'}</Td><Td>{r.lCal || '—'}</Td><Td>{r.dCal || '—'}</Td><Td>{r.sCal || '—'}</Td>
                      <Td style={{ color: 'var(--accent)', fontWeight: 700 }}>{r.calories || '—'}</Td>
                    </tr>
                  ))
              }
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}

// ── Helpers ──────────────────────────────────────────────────────────

const chartTitle = { fontSize: 13, fontWeight: 600, margin: '0 0 8px', color: 'var(--text)' };

function chartOpts(stacked = false) {
  return {
    responsive: true, maintainAspectRatio: false,
    plugins: { legend: { display: stacked, position: 'bottom', labels: { font: { size: 11 }, color: 'var(--muted)' } } },
    scales: {
      x: { stacked, grid: { display: false }, ticks: { font: { size: 10 }, color: 'var(--muted)' } },
      y: { stacked, beginAtZero: true, grid: { color: 'var(--border)' }, ticks: { font: { size: 10 }, color: 'var(--muted)' } },
    },
  };
}

function fmt(n) {
  if (n == null || isNaN(n)) return '—';
  return Math.round(n).toLocaleString();
}

// Aggregate entries by date with item-level macro fallback
function byDay(project) {
  const m = {};
  const _bdM = (e, key) => (e[key] !== '' && e[key] != null && !isNaN(+e[key]))
    ? +e[key]
    : (e.items || []).reduce((s, it) => s + (it[key] != null && !isNaN(+it[key]) ? +it[key] : 0), 0);
  (project.entries || []).forEach(e => {
    const k = e.date || '(no date)';
    if (!m[k]) m[k] = { date: k, calories: 0, carbs_g: 0, protein_g: 0, fat_g: 0, bCal: 0, lCal: 0, dCal: 0, sCal: 0 };
    m[k].calories  += +e.calories || 0;
    m[k].carbs_g   += _bdM(e, 'carbs_g');
    m[k].protein_g += _bdM(e, 'protein_g');
    m[k].fat_g     += _bdM(e, 'fat_g');
    const ml = (e.meal || '').toLowerCase(), c = +e.calories || 0;
    if (ml.includes('breakfast'))    m[k].bCal += c;
    else if (ml.includes('lunch'))   m[k].lCal += c;
    else if (ml.includes('dinner'))  m[k].dCal += c;
    else if (ml.includes('snack'))   m[k].sCal += c;
  });
  return Object.values(m).sort((a, b) => a.date < b.date ? 1 : -1);
}

function inRange(days, range) {
  const iso = days.filter(d => /^\d{4}-\d{2}-\d{2}$/.test(d.date));
  if (!iso.length || range === 'max') return days;
  const anchor = iso[0].date;
  const a = new Date(anchor + 'T00:00:00');
  const cutoff = new Date(a);
  if (range === '1d') cutoff.setDate(a.getDate());
  else if (range === '1w') cutoff.setDate(a.getDate() - 6);
  else if (range === '1m') cutoff.setMonth(a.getMonth() - 1);
  else return days;
  const cutoffIso = isoOf(cutoff); // local date — toISOString() shifts in UTC+N timezones
  return days.filter(d => d.date >= cutoffIso && d.date <= anchor);
}

function summarize(filtered) {
  const cals = filtered.map(d => d.calories).filter(c => c > 0);
  const avg = arr => arr.length ? arr.reduce((s, v) => s + v, 0) / arr.length : 0;
  return {
    avgCal:  cals.length ? avg(cals) : null,
    avgProt: cals.length ? avg(filtered.map(d => d.protein_g)) : null,
    avgCarb: cals.length ? avg(filtered.map(d => d.carbs_g))   : null,
    avgFat:  cals.length ? avg(filtered.map(d => d.fat_g))     : null,
    max: cals.length ? Math.max(...cals) : null,
    min: cals.length ? Math.min(...cals) : null,
  };
}

function buildBreakdown(project, range) {
  return inRange(byDay(project), range);
}

function Stat({ label, value, unit, color }) {
  return (
    <div style={{
      background: 'var(--surface)', border: '1px solid var(--border)',
      borderRadius: 12, padding: '12px 14px', boxShadow: 'var(--shadow-sm)',
    }}>
      <div style={{
        fontSize: 10.5, color: 'var(--muted)',
        fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.05em',
        marginBottom: 4,
      }}>{label}</div>
      <div style={{ display: 'flex', alignItems: 'baseline', gap: 4 }}>
        <span style={{ fontSize: 20, fontWeight: 700, color: color || 'var(--text)', letterSpacing: '-0.02em' }}>{value}</span>
        {unit && <span style={{ fontSize: 11, color: 'var(--muted)' }}>{unit}</span>}
      </div>
    </div>
  );
}

function RangeToggle({ value, onChange }) {
  const opts = [
    { id: '1d', label: '1D' },
    { id: '1w', label: '1W' },
    { id: '1m', label: '1M' },
    { id: 'max', label: 'Max' },
  ];
  return (
    <div style={{
      display: 'inline-flex', background: 'var(--surface-2)',
      border: '1px solid var(--border)', borderRadius: 999, padding: 3,
    }}>
      {opts.map(o => (
        <button key={o.id} onClick={() => onChange(o.id)} style={{
          font: 'inherit', fontSize: 11, fontWeight: 600,
          padding: '4px 10px', borderRadius: 999, border: 0,
          background: value === o.id ? 'var(--text)' : 'transparent',
          color: value === o.id ? 'var(--bg)' : 'var(--muted)',
          cursor: 'pointer',
        }}>{o.label}</button>
      ))}
    </div>
  );
}

const Th = ({ children, style }) => (
  <th style={{
    padding: '8px 6px', fontWeight: 600, fontSize: 10.5,
    textTransform: 'uppercase', letterSpacing: '0.05em',
    color: 'var(--muted)', textAlign: 'right',
    ...style,
  }}>{children}</th>
);
const Td = ({ children, style, colSpan }) => (
  <td colSpan={colSpan} style={{ padding: '8px 6px', textAlign: 'right', ...style }}>{children}</td>
);

window.AnalysesScreen = AnalysesScreen;
