// Per-kid detail page — wired to real store.

function KidDetail({ kidId, onBack }) {
  const s = window.useStore();
  const kid = s.kids.find(k => k.id === kidId) || s.kids[0];
  if (!kid) {
    return (
      <div className="screen">
        <p>Kid not found. <a href="#/dashboard">Back to dashboard</a></p>
      </div>
    );
  }
  const c = window.KID_COLORS_V3[kid.color] || window.KID_COLORS_V3.mango;
  const tasks = s.tasks.filter(t => t.kid_id === kid.id);
  const history = s.history.filter(h => h.kid_id === kid.id);

  const now = Date.now();
  const dayMs = 24 * 60 * 60 * 1000;
  const startWeek = now - 7 * dayMs;
  const weekHist  = history.filter(h => h.ts >= startWeek);
  const earned = weekHist.filter(h => h.delta > 0).reduce((a, h) => a + h.delta, 0);
  const lost   = weekHist.filter(h => h.delta < 0).reduce((a, h) => a + h.delta, 0);
  const tasksDone = weekHist.length;

  // Best day this week
  const byDay = {};
  weekHist.forEach(h => {
    const d = new Date(h.ts);
    const k = d.toLocaleDateString();
    byDay[k] = (byDay[k] || 0) + h.delta;
  });
  let bestDayLabel = '—';
  let bestDelta = 0;
  Object.entries(byDay).forEach(([k, v]) => {
    if (v > bestDelta) {
      bestDelta = v;
      bestDayLabel = new Date(k).toLocaleDateString([], { weekday: 'short' }) + ` · +${v}`;
    }
  });

  // 14-day chart data (sum delta per day, newest on right)
  const days = Array.from({ length: 14 }, (_, i) => {
    const d = new Date(); d.setHours(0,0,0,0);
    d.setDate(d.getDate() - (13 - i));
    return d;
  });
  const chartData = days.map(d => {
    const start = d.getTime();
    const end = start + dayMs;
    return history.filter(h => h.ts >= start && h.ts < end).reduce((a, h) => a + h.delta, 0);
  });

  const goal = kid.goalAt || kid.goal || 50;

  const [historyFilter, setHistoryFilter] = React.useState('all');
  const filteredHistory = history.filter(h =>
    historyFilter === 'all' ? true :
    historyFilter === 'earned' ? h.delta > 0 :
    h.delta < 0
  );

  return (
    <div className="screen">
      <button onClick={onBack} className="btn btn-ghost" style={{ marginBottom: 16, fontSize: 13 }}>
        ← Back
      </button>

      <div className="card" style={{ padding: 0, overflow: 'hidden', marginBottom: 24 }}>
        <div style={{
          background: c.soft, padding: '36px 40px',
          display: 'flex', alignItems: 'center', gap: 28, position: 'relative', flexWrap: 'wrap',
        }}>
          <window.KidAvatar kid={kid} size="xl" />
          <div style={{ flex: 1, minWidth: 200 }}>
            <window.Eyebrow color="rgba(33,26,46,0.6)">Kid</window.Eyebrow>
            <h1 className="h-display h1" style={{ marginTop: 6 }}>{kid.name}</h1>
            <div style={{ display: 'flex', gap: 10, marginTop: 12, flexWrap: 'wrap' }}>
              {kid.streak > 0 && <span className="chip">🔥 {kid.streak} day streak</span>}
              <span className="chip">🎯 Goal: {goal} stars</span>
            </div>
          </div>
          <div style={{ textAlign: 'right' }}>
            <div style={{ fontFamily: 'var(--font-chunky)', fontSize: 64, letterSpacing: '-0.04em', lineHeight: 1, color: c.hex }}>
              {kid.points} <span style={{ fontSize: 28, color: 'rgba(33,26,46,0.6)' }}>★</span>
            </div>
            <div style={{ fontSize: 13, marginTop: 4 }}>{Math.max(0, goal - kid.points)} to go</div>
          </div>
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(180px, 1fr))', gap: 16, marginBottom: 24 }}>
        <div className="card"><window.Stat label="This week" value={earned >= 0 ? `+${earned}` : earned} color="var(--success)" /></div>
        <div className="card"><window.Stat label="Lost this week" value={lost} color="var(--alert)" /></div>
        <div className="card"><window.Stat label="Tasks done" value={tasksDone} /></div>
        <div className="card"><window.Stat label="Best day" value={bestDayLabel} /></div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: 20, marginBottom: 24 }}>
        <div className="card">
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 18 }}>
            <h3 className="h-display h3">Last 14 days</h3>
          </div>
          <Chart data={chartData} color={c.hex} />
        </div>

        <div className="card">
          <h3 className="h-display h3" style={{ marginBottom: 16 }}>Tasks for {kid.name}</h3>
          <div style={{ display: 'grid', gap: 8 }}>
            {tasks.length === 0 && (
              <div style={{ color: 'var(--ink-soft)', fontSize: 14, fontStyle: 'italic', padding: '8px 4px' }}>
                No tasks yet. <a href="#/tasks">Add some →</a>
              </div>
            )}
            {tasks.map(t => (
              <div key={t.id} style={{
                display: 'flex', alignItems: 'center', gap: 10,
                padding: '8px 12px', borderRadius: 999,
                background: t.kind === 'good' ? 'var(--mint-soft)' : 'var(--blush-soft)',
                border: '1px solid ' + (t.kind === 'good' ? 'var(--mint)' : 'var(--blush)'),
              }}>
                <div style={{ fontSize: 18 }}>{t.emoji}</div>
                <div style={{ flex: 1, fontSize: 13, fontWeight: 600 }}>{t.label}</div>
                <div style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 14,
                  color: t.kind === 'good' ? 'var(--success)' : 'var(--alert)' }}>
                  {t.points > 0 ? `+${t.points}` : t.points}
                </div>
              </div>
            ))}
            <div style={{ marginTop: 12, fontSize: 13 }}>
              <a href="#/tasks" style={{ color: 'var(--mango-deep)', fontWeight: 600 }}>Manage tasks & jars →</a>
            </div>
          </div>
        </div>
      </div>

      <div className="card">
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 12, flexWrap: 'wrap', gap: 8 }}>
          <h3 className="h-display h3">{kid.name}'s history</h3>
          <div style={{ display: 'flex', gap: 6 }}>
            {['all', 'earned', 'lost'].map(f => (
              <button key={f} onClick={() => setHistoryFilter(f)} className="chip"
                style={{
                  background: historyFilter === f ? 'var(--ink)' : 'var(--paper)',
                  color: historyFilter === f ? 'white' : 'var(--ink)',
                  cursor: 'pointer', textTransform: 'capitalize',
                }}>{f}</button>
            ))}
          </div>
        </div>
        {filteredHistory.length === 0 ? (
          <div style={{ padding: 24, color: 'var(--ink-soft)', fontStyle: 'italic', textAlign: 'center' }}>
            No history yet.
          </div>
        ) : (
          <table className="tbl">
            <thead><tr>
              <th>When</th><th>Task</th><th style={{ textAlign: 'right' }}>Δ</th>
            </tr></thead>
            <tbody>
              {filteredHistory.slice(0, 50).map((h) => (
                <tr key={h.id}>
                  <td style={{ color: 'var(--ink-soft)' }}>{h.day} · {h.when}</td>
                  <td>
                    <span style={{ marginRight: 8, fontSize: 18 }}>{h.emoji}</span>
                    {h.task}
                  </td>
                  <td style={{
                    textAlign: 'right',
                    fontFamily: 'var(--font-display)', fontWeight: 800, fontSize: 17,
                    color: h.delta > 0 ? 'var(--success)' : 'var(--alert)',
                  }}>{h.delta > 0 ? `+${h.delta}` : h.delta}</td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
      </div>
    </div>
  );
}


function Chart({ data, color }) {
  const max = Math.max(8, ...data.map(v => Math.abs(v)));
  return (
    <div style={{ display: 'flex', alignItems: 'flex-end', gap: 6, height: 180, padding: '20px 0', borderTop: '1px solid var(--rule)', borderBottom: '1px solid var(--rule)', position: 'relative' }}>
      <div style={{ position: 'absolute', left: 0, right: 0, top: '50%', height: 1, background: 'var(--rule-strong)' }} />
      {data.map((v, i) => {
        const h = max === 0 ? 0 : Math.abs(v) / max * 70;
        const isPos = v >= 0;
        return (
          <div key={i} style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', height: '100%', justifyContent: 'center', position: 'relative' }}>
            {v !== 0 && isPos && <div style={{ height: `${h}%`, width: '70%', background: color, borderRadius: '6px 6px 2px 2px', alignSelf: 'flex-end', marginBottom: '50%' }} />}
            {v !== 0 && !isPos && <div style={{ height: `${h}%`, width: '70%', background: 'var(--alert)', borderRadius: '2px 2px 6px 6px', alignSelf: 'flex-start', marginTop: '50%' }} />}
          </div>
        );
      })}
    </div>
  );
}

window.KidDetail = KidDetail;
