// Parent dashboard — wired to real store.

function Dashboard({ onOpenKid }) {
  const s = window.useStore();
  const kids = s.kids;
  const total = kids.reduce((acc, k) => acc + (k.points || 0), 0);

  // Compute today's delta + week delta + longest streak from history
  const now = Date.now();
  const dayMs = 24 * 60 * 60 * 1000;
  const startToday = startOfDay(new Date()).getTime();
  const startWeek  = now - 7 * dayMs;

  const todayDelta = s.history.filter(h => h.ts >= startToday).reduce((a, h) => a + h.delta, 0);
  const weekDelta  = s.history.filter(h => h.ts >= startWeek ).reduce((a, h) => a + h.delta, 0);
  const longestStreak = Math.max(0, ...kids.map(k => k.bestDaily || k.streak || 0));

  // MVP = kid with highest 7-day delta
  const weekByKid = {};
  s.history.forEach(h => {
    if (h.ts < startWeek) return;
    weekByKid[h.kid_id] = (weekByKid[h.kid_id] || 0) + h.delta;
  });
  let mvpKid = null, mvpDelta = 0;
  kids.forEach(k => {
    const d = weekByKid[k.id] || 0;
    if (d > mvpDelta) { mvpDelta = d; mvpKid = k; }
  });
  if (!mvpKid) mvpKid = kids[0];

  const meta = (s.user && s.user.user_metadata) || {};
  const firstName = (meta.full_name || meta.name || s.user?.email || '').split(/[\s@]/)[0] || 'friend';

  const todayLabel = new Date().toLocaleDateString([], { weekday: 'long', day: 'numeric', month: 'short' });

  return (
    <div style={{ background: 'var(--paper)', minHeight: 'calc(100vh - 73px)' }}>
      <DashboardStyles />

      <header className="dash-hero">
        <div className="dash-hero-dots" />
        <div className="dash-hero-inner">
          <div style={{ display: 'flex', alignItems: 'center', gap: 22, marginBottom: 28, flexWrap: 'wrap' }}>
            <window.Suri mood="wave" wave size={92} color="#FFD23F" className="mascot-idle" />
            <div>
              <div className="eyebrow" style={{ color: 'rgba(251,246,235,0.55)' }}>{todayLabel}</div>
              <div className="h-display" style={{ fontSize: 'clamp(36px, 6vw, 64px)', fontWeight: 700, color: 'var(--paper)', letterSpacing: '-0.04em', lineHeight: 1, marginTop: 8 }}>
                {greetingFor(new Date())}, <em style={{ fontStyle: 'normal', color: 'var(--mango)' }}>{firstName}</em>.
              </div>
              <div style={{ marginTop: 14, fontSize: 17, color: 'rgba(251,246,235,0.7)', maxWidth: 540, lineHeight: 1.5 }}>
                {kids.length} {kids.length === 1 ? 'kid' : 'kids'}. {total} stars in the family. {' '}
                <em style={{ color: 'rgba(251,246,235,0.95)', fontStyle: 'normal' }}>
                  {todayDelta >= 0 ? `+${todayDelta}` : todayDelta} today.
                </em>
              </div>
            </div>
          </div>

          <div className="dash-stats">
            <DashStat label="Family total"     value={total}                                       suffix="★"    color="#FFD23F" />
            <DashStat label="Today"            value={(todayDelta >= 0 ? '+' : '') + todayDelta}   color="#00C896" />
            <DashStat label="This week"        value={(weekDelta  >= 0 ? '+' : '') + weekDelta}    color="#FFB7C8" />
            <DashStat label="Longest streak"   value={longestStreak}                              suffix="days"  color="#6979F8" />
          </div>
        </div>
      </header>

      <section className="dash-section">
        <div className="dash-section-head">
          <div>
            <div className="eyebrow">Your kids</div>
            <h2 className="h-display" style={{ fontSize: 'clamp(28px, 4vw, 44px)', marginTop: 8 }}>Today across the family.</h2>
          </div>
          <button className="btn btn-primary" onClick={() => { window.location.hash = '#/add-kid'; }}>
            ＋ Add kid
          </button>
        </div>

        <div className="dash-kids">
          {kids.map((kid) => <KidCard key={kid.id} kid={kid} onOpen={() => onOpenKid?.(kid.id)} />)}
        </div>
      </section>

      <section className="dash-section" style={{ paddingBottom: 100 }}>
        <div className="dash-bottom">
          <div className="card" style={{ padding: 32 }}>
            <div className="dash-section-head" style={{ marginBottom: 18 }}>
              <h3 className="h-display" style={{ fontSize: 28 }}>Recent activity</h3>
            </div>
            <ActivityList history={s.history.slice(0, 8)} kids={kids} onUndo={s.undoHistory} />
          </div>

          {mvpKid && <MvpCard kid={mvpKid} delta={mvpDelta} />}
        </div>
      </section>
    </div>
  );
}

function startOfDay(d) {
  const x = new Date(d); x.setHours(0,0,0,0); return x;
}

function greetingFor(d) {
  const h = d.getHours();
  if (h < 12) return 'Good morning';
  if (h < 18) return 'Good afternoon';
  return 'Good evening';
}

function DashStat({ label, value, suffix, color }) {
  return (
    <div className="dash-stat">
      <div style={{
        fontFamily: 'var(--font-body)', fontSize: 11, fontWeight: 500,
        textTransform: 'uppercase', letterSpacing: '0.16em',
        color: 'rgba(251,246,235,0.5)',
      }}>{label}</div>
      <div style={{
        fontFamily: 'var(--font-chunky)',
        fontSize: 'clamp(36px, 5vw, 56px)', letterSpacing: '-0.02em',
        marginTop: 8, color: color || 'white',
        display: 'flex', alignItems: 'baseline', gap: 8, lineHeight: 0.9,
      }}>
        {value}
        {suffix && <span style={{ fontSize: 20, fontFamily: 'var(--font-display)', fontWeight: 500, color: 'rgba(251,246,235,0.5)' }}>{suffix}</span>}
      </div>
    </div>
  );
}

function KidCard({ kid, onOpen }) {
  const c = window.KID_COLORS_V3[kid.color] || window.KID_COLORS_V3.mango;
  const goal = kid.goalAt || kid.goal || 50;
  const progress = Math.min(100, Math.round((kid.points / goal) * 100));

  return (
    <div className="card dash-kid-card" onClick={onOpen} style={{ cursor: 'pointer' }}>
      <div className="dash-kid-tape" style={{ background: c.hex }} />
      <div style={{ display: 'flex', alignItems: 'flex-start', gap: 16 }}>
        <window.KidAvatar kid={kid} size="lg" />
        <div style={{ flex: 1, minWidth: 0 }}>
          <div className="h-display" style={{ fontSize: 28, fontWeight: 700, letterSpacing: '-0.02em' }}>{kid.name}</div>
          {kid.streak > 0 && (
            <div style={{ marginTop: 8 }}>
              <span className="chip warm">🔥 {kid.streak} day streak</span>
            </div>
          )}
        </div>
      </div>

      <div style={{ marginTop: 22 }}>
        <div className="eyebrow" style={{ marginBottom: 8 }}>Stars earned</div>
        <div style={{ display: 'flex', alignItems: 'baseline', gap: 10 }}>
          <div className="h-chunky" style={{ fontSize: 56, color: c.hex }}>{kid.points}</div>
          <div style={{ fontSize: 14, color: 'var(--ink-faint)' }}>of {goal} for next reward</div>
        </div>
        <div className="prog" style={{ marginTop: 12 }}>
          <div className="prog-fill" style={{ width: `${progress}%`, background: c.hex }} />
        </div>
        <div style={{ marginTop: 6, fontSize: 12, color: 'var(--ink-faint)' }}>
          {Math.max(0, goal - kid.points)} stars to go
        </div>
      </div>

      <div style={{ display: 'flex', gap: 8, marginTop: 18 }}>
        <button className="btn btn-ghost" style={{ flex: 1, fontSize: 14, padding: '10px 14px' }}
          onClick={(e) => { e.stopPropagation(); onOpen?.(); }}>
          View detail
        </button>
        <button className="btn btn-dark" style={{ flex: 1, fontSize: 14, padding: '10px 14px' }}
          onClick={(e) => { e.stopPropagation(); window.location.hash = '#/kidview'; }}>
          ＋ Mark task
        </button>
      </div>
    </div>
  );
}

function MvpCard({ kid, delta }) {
  const c = window.KID_COLORS_V3[kid.color] || window.KID_COLORS_V3.mango;
  return (
    <div className="card-dusk" style={{ padding: 36, position: 'relative', overflow: 'hidden' }}>
      <div style={{ position: 'absolute', top: -30, right: -30, opacity: 0.7 }}>
        <window.Suri mood="proud" size={180} color="#FFD23F" />
      </div>
      <div style={{ position: 'relative' }}>
        <div className="eyebrow" style={{ color: 'var(--butter)' }}>🏆 Week's MVP</div>
        <div className="h-display" style={{ fontSize: 60, color: 'white', marginTop: 14, fontWeight: 700, letterSpacing: '-0.04em', lineHeight: 0.95 }}>
          {kid.name}.
        </div>
        <div style={{ marginTop: 14, fontSize: 15, color: 'rgba(251,246,235,0.7)', lineHeight: 1.5, maxWidth: 320 }}>
          {delta > 0 ? `Leading the family this week with ${delta} stars earned.` : 'No big movers this week yet — early days!'}
        </div>
        <div style={{
          marginTop: 28, display: 'flex', alignItems: 'baseline', gap: 14, paddingTop: 22,
          borderTop: '1px solid rgba(251,246,235,0.12)',
        }}>
          <div className="h-chunky" style={{ fontSize: 48, color: c.hex }}>{delta >= 0 ? `+${delta}` : delta}</div>
          <div style={{ fontSize: 14, color: 'rgba(251,246,235,0.6)', textTransform: 'uppercase', letterSpacing: '0.12em', fontWeight: 500 }}>this week</div>
        </div>
      </div>
    </div>
  );
}

function ActivityList({ history, kids, onUndo }) {
  if (!history.length) {
    return (
      <div style={{ padding: '30px 6px', color: 'var(--ink-faint)', fontStyle: 'italic' }}>
        No activity yet — mark a task to get started.
      </div>
    );
  }
  return (
    <div style={{ display: 'grid' }}>
      {history.map((it, i) => {
        const kid = kids.find(k => k.id === it.kid_id);
        if (!kid) return null;
        return (
          <div key={it.id || i} style={{
            display: 'grid',
            gridTemplateColumns: 'auto auto 1fr auto auto',
            gap: 16, alignItems: 'center',
            padding: '14px 0',
            borderBottom: i < history.length - 1 ? '1px solid var(--rule)' : 'none',
          }}>
            <window.KidAvatar kid={kid} />
            <div style={{ fontSize: 24 }}>{it.emoji}</div>
            <div>
              <div style={{ fontFamily: 'var(--font-display)', fontWeight: 500, fontSize: 15, letterSpacing: '-0.01em' }}>
                <span style={{ color: 'var(--ink)' }}>{kid.name}</span>
                <span style={{ color: 'var(--ink-soft)' }}> · {it.task}</span>
              </div>
              <div style={{ fontSize: 12, color: 'var(--ink-faint)', marginTop: 2 }}>{it.day} · {it.when}</div>
            </div>
            <div className="h-chunky" style={{
              fontSize: 28,
              color: it.delta > 0 ? 'var(--success)' : 'var(--alert)',
            }}>{it.delta > 0 ? `+${it.delta}` : it.delta}</div>
            <button onClick={() => onUndo?.(it.id)} title="Undo"
              style={{
                background: 'transparent', color: 'var(--ink-faint)',
                fontSize: 13, padding: '6px 10px', borderRadius: 8,
                fontFamily: 'var(--font-display)',
              }}>↺</button>
          </div>
        );
      })}
    </div>
  );
}

function DashboardStyles() {
  return <style>{`
    .dash-hero {
      background: var(--dusk);
      color: var(--paper);
      padding: 56px 64px 100px;
      position: relative; overflow: hidden;
    }
    .dash-hero::after {
      content: ''; position: absolute; bottom: -40px; left: 0; right: 0; height: 80px;
      background: var(--paper);
      border-radius: 50% 50% 0 0 / 100% 100% 0 0;
    }
    .dash-hero-dots {
      position: absolute; inset: 0;
      background-image: radial-gradient(circle, rgba(255,210,63,0.3) 1px, transparent 1px);
      background-size: 32px 32px; opacity: 0.6;
    }
    .dash-hero-inner { position: relative; z-index: 2; max-width: 1480px; margin: 0 auto; }
    .dash-stats {
      display: grid; grid-template-columns: repeat(4, 1fr); gap: 24px;
      margin-top: 40px; padding: 28px 32px;
      background: rgba(251,246,235,0.04);
      border-radius: 28px;
      border: 1px solid rgba(251,246,235,0.08);
    }
    .dash-section { max-width: 1480px; margin: 0 auto; padding: 60px 64px 40px; }
    .dash-section-head {
      display: flex; align-items: flex-end; justify-content: space-between;
      margin-bottom: 32px; flex-wrap: wrap; gap: 16px;
    }
    .dash-kids {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
      gap: 22px;
    }
    .dash-kid-card { padding: 28px; position: relative; overflow: hidden;
      transition: transform 240ms cubic-bezier(.4,1.4,.5,1), box-shadow 240ms ease;
    }
    .dash-kid-card:hover { transform: translateY(-4px); box-shadow: var(--shadow-2); }
    .dash-kid-tape { position: absolute; top: 0; left: 0; right: 0; height: 6px; }
    .dash-bottom { display: grid; grid-template-columns: 1.6fr 1fr; gap: 24px; }

    @media (max-width: 1000px) {
      .dash-hero { padding: 32px 22px 100px; }
      .dash-section { padding: 40px 22px; }
      .dash-stats { grid-template-columns: repeat(2, 1fr); gap: 16px; padding: 18px; }
      .dash-bottom { grid-template-columns: 1fr; }
    }
  `}</style>;
}

window.Dashboard = Dashboard;
