// Dashboard. All numbers and rows come from real user data — subjects, guides, events.

function HomeScreen() {
  const subjects = useSubjects();
  const userGuides = useGuides();
  const events = useEvents();

  const today = todayISO();
  const upcoming = upcomingEvents(events, 30);
  const next = upcoming[0];
  const inSevenDays = upcoming.filter((e) => daysBetween(today, e.date) <= 7);
  const totalCards = userGuides.reduce((n, g) => n + ((g.content?.flashcards || []).length), 0);

  return (
    <Page>
      <PageHeader
        breadcrumb={['Dashboard']}
        sub={prettyDateLong(today)}
        actions={
          <>
            <button className="btn ghost small" onClick={() => navigate('/calendar')}>{Icon.calendar} Calendar</button>
            <button className="btn blue small" onClick={() => {
              if (subjects.length === 0) { navigate('/'); /* sidebar opens dialog */ return; }
              navigate(`/subject/${subjects[0].id}/upload`);
            }}>{Icon.sparkle} Generate guide</button>
          </>
        }
      />

      <div style={{ flex: 1, display: 'grid', gridTemplateColumns: '1fr 320px', overflow: 'hidden' }}>
        <div style={{ overflowY: 'auto', padding: '16px 22px' }}>
          {/* KPIs */}
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 10, marginBottom: 14 }}>
            <Kpi label="Subjects" value={subjects.length} sub={subjects.length === 0 ? 'add one to begin' : 'tracked'} />
            <Kpi label="Guides" value={userGuides.length} sub="generated" tone={userGuides.length > 0 ? 'mint' : null} />
            <Kpi label="Cards" value={totalCards} sub="across all guides" />
            <Kpi label="This week" value={inSevenDays.length} sub="events ahead" tone={inSevenDays.length > 0 ? 'coral' : null} />
          </div>

          {/* Upcoming */}
          <SectionTitle title="Upcoming" sub={upcoming.length === 0 ? 'no events scheduled' : `next ${Math.min(upcoming.length, 5)} of ${upcoming.length}`}
            right={<button className="btn ghost small" onClick={() => navigate('/calendar')}>Open calendar</button>} />
          <div style={{ background: 'white', border: '1px solid var(--line)', borderRadius: 10, overflow: 'hidden', marginBottom: 18 }}>
            {upcoming.length === 0 ? (
              <EmptyRow>
                Nothing on the calendar. <a href="#" onClick={(e) => { e.preventDefault(); navigate('/calendar'); }} style={{ color: 'var(--blue-deep)' }}>Add an event</a>.
              </EmptyRow>
            ) : upcoming.slice(0, 5).map((ev, i, arr) => {
              const subject = subjects.find((s) => s.id === ev.subject_id);
              return <UpcomingRow key={ev.id} ev={ev} subject={subject} last={i === arr.length - 1} />;
            })}
          </div>

          {/* Guides + subjects */}
          <div style={{ display: 'grid', gridTemplateColumns: '1.2fr 1fr', gap: 14 }}>
            <div>
              <SectionTitle title="Recent guides" sub={userGuides.length === 0 ? 'none yet' : null}
                right={<button className="btn ghost small" onClick={() => navigate('/library')}>View all</button>} />
              <div style={{ background: 'white', border: '1px solid var(--line)', borderRadius: 10, overflow: 'hidden' }}>
                {userGuides.length === 0 ? (
                  <EmptyRow>
                    No guides yet. {subjects.length === 0
                      ? 'Add a subject from the sidebar to start.'
                      : <>Pick a subject and <a href="#" onClick={(e) => { e.preventDefault(); navigate(`/subject/${subjects[0].id}/upload`); }} style={{ color: 'var(--blue-deep)' }}>upload files</a>.</>}
                  </EmptyRow>
                ) : userGuides.slice(0, 6).map((g, i, arr) => {
                  const subject = subjects.find((s) => s.id === g.subjectId);
                  return <GuideRow key={g.id} guide={g} subject={subject} last={i === arr.length - 1} />;
                })}
              </div>
            </div>

            <div>
              <SectionTitle title="Your subjects" sub={subjects.length === 0 ? 'none yet' : null} />
              <div style={{ background: 'white', border: '1px solid var(--line)', borderRadius: 10, padding: 14 }}>
                {subjects.length === 0 ? (
                  <div style={{ fontSize: 11.5, color: 'var(--ink-mute)' }}>Add a subject from the sidebar (the + next to "Subjects").</div>
                ) : subjects.map((s) => {
                  const count = userGuides.filter((g) => g.subjectId === s.id).length;
                  return (
                    <div key={s.id}
                      onClick={() => navigate(`/subject/${s.id}`)}
                      style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '6px 0', cursor: 'pointer' }}>
                      <span style={{ width: 14, fontSize: 13 }}>{s.emoji}</span>
                      <span style={{ fontSize: 11.5, flex: 1, color: 'var(--ink-soft)' }}>{s.name}</span>
                      <span className="mono" style={{ fontSize: 10, color: 'var(--ink-mute)' }}>{count} {count === 1 ? 'guide' : 'guides'}</span>
                    </div>
                  );
                })}
              </div>
            </div>
          </div>
        </div>

        {/* Right rail */}
        <aside style={{ borderLeft: '1px solid var(--line)', overflowY: 'auto', padding: '16px 16px', background: 'var(--bg)' }}>
          {next ? (
            <NextEventCard ev={next} subject={subjects.find((s) => s.id === next.subject_id)} />
          ) : (
            <div style={{ background: 'white', border: '1px solid var(--line)', borderRadius: 10, padding: 14 }}>
              <div style={{ fontSize: 10, textTransform: 'uppercase', letterSpacing: '0.08em', color: 'var(--ink-mute)' }}>Up next</div>
              <div style={{ fontSize: 12.5, marginTop: 6, color: 'var(--ink-soft)' }}>No events scheduled.</div>
              <button className="btn small" style={{ marginTop: 10, width: '100%', justifyContent: 'center' }} onClick={() => navigate('/calendar')}>{Icon.calendar} Open calendar</button>
            </div>
          )}

          <div style={{ marginTop: 18 }}>
            <div style={{ fontSize: 10, textTransform: 'uppercase', letterSpacing: '0.08em', color: 'var(--ink-mute)', marginBottom: 8 }}>Quick actions</div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
              <button className="btn ghost small" style={{ justifyContent: 'flex-start' }} onClick={() => navigate('/calendar')}>{Icon.calendar} Add an event</button>
              <button className="btn ghost small" style={{ justifyContent: 'flex-start' }} onClick={() => navigate('/library')}>{Icon.book} Browse guides</button>
              {subjects[0] && (
                <button className="btn ghost small" style={{ justifyContent: 'flex-start' }} onClick={() => navigate(`/subject/${subjects[0].id}/upload`)}>{Icon.upload} Upload files</button>
              )}
            </div>
          </div>
        </aside>
      </div>
    </Page>
  );
}

function Kpi({ label, value, sub, tone }) {
  const accent = tone === 'coral' ? 'var(--coral)' : tone === 'mint' ? 'var(--mint)' : 'var(--ink)';
  return (
    <div style={{ background: 'white', border: '1px solid var(--line)', borderRadius: 10, padding: '12px 14px' }}>
      <div style={{ fontSize: 10.5, textTransform: 'uppercase', letterSpacing: '0.06em', color: 'var(--ink-mute)' }}>{label}</div>
      <div style={{ display: 'flex', alignItems: 'baseline', gap: 8, marginTop: 2 }}>
        <div style={{ fontSize: 22, fontWeight: 600, color: accent, letterSpacing: '-0.02em' }}>{value}</div>
        <div style={{ fontSize: 10.5, color: 'var(--ink-mute)' }}>{sub}</div>
      </div>
    </div>
  );
}

function SectionTitle({ title, sub, right }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 8 }}>
      <div style={{ display: 'flex', alignItems: 'baseline', gap: 8 }}>
        <h2 style={{ fontSize: 13, fontWeight: 600, margin: 0 }}>{title}</h2>
        {sub && <span style={{ fontSize: 11, color: 'var(--ink-mute)' }}>{sub}</span>}
      </div>
      {right}
    </div>
  );
}

function EmptyRow({ children }) {
  return <div style={{ padding: '14px 16px', fontSize: 12, color: 'var(--ink-mute)' }}>{children}</div>;
}

const KIND_LABEL = { exam: 'Exam', assignment: 'Assignment', study: 'Study', other: 'Event' };
const KIND_DOT = { exam: 'var(--coral)', assignment: 'var(--blue)', study: 'var(--mint)', other: 'var(--ink-whisper)' };

function UpcomingRow({ ev, subject, last }) {
  const today = todayISO();
  const days = daysBetween(today, ev.date);
  const dayLabel = days === 0 ? 'Today' : days === 1 ? 'Tomorrow' : `in ${days}d`;
  return (
    <div onClick={() => navigate('/calendar')} style={{
      display: 'flex', alignItems: 'center', gap: 12,
      padding: '10px 14px',
      borderBottom: last ? 'none' : '1px solid var(--line-soft)', cursor: 'pointer',
    }}>
      <div style={{ width: 6, height: 6, borderRadius: 3, background: KIND_DOT[ev.kind] || 'var(--ink-whisper)', flexShrink: 0 }} />
      <div style={{ width: 18, fontSize: 14, textAlign: 'center' }}>{subject?.emoji || '•'}</div>
      <div style={{ width: 96, fontSize: 11.5, color: 'var(--ink-mute)' }}>{subject?.name || '—'}</div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 12.5, fontWeight: 500 }}>{ev.title}</div>
        <div style={{ fontSize: 10.5, color: 'var(--ink-mute)', marginTop: 1 }}>{KIND_LABEL[ev.kind] || ev.kind} · {ev.date}</div>
      </div>
      <span className="mono" style={{ fontSize: 11, color: days <= 1 ? 'var(--coral)' : 'var(--ink-mute)' }}>{dayLabel}</span>
    </div>
  );
}

function GuideRow({ guide, subject, last }) {
  return (
    <div onClick={() => navigate(`/subject/${guide.subjectId}/guide/${guide.id}`)} style={{
      display: 'flex', alignItems: 'center', gap: 10,
      padding: '8px 14px',
      borderBottom: last ? 'none' : '1px solid var(--line-soft)',
      cursor: 'pointer',
    }}>
      <span style={{ width: 18, color: 'var(--ink-mute)', fontSize: 13, textAlign: 'center' }}>{subject?.emoji || '📄'}</span>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 12, fontWeight: 500, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{guide.title}</div>
        <div style={{ fontSize: 10.5, color: 'var(--ink-mute)' }}>
          {subject?.name || 'unknown subject'} · {(guide.content?.sections || []).length} sections · {(guide.content?.flashcards || []).length} cards
        </div>
      </div>
      <span className="mono" style={{ fontSize: 10, color: 'var(--ink-mute)' }}>{relativeShort(guide.generatedAt)}</span>
    </div>
  );
}

function NextEventCard({ ev, subject }) {
  const today = todayISO();
  const days = daysBetween(today, ev.date);
  const dayLabel = days === 0 ? 'Today' : days === 1 ? 'Tomorrow' : `${days}d`;
  return (
    <div style={{ background: 'var(--ink)', color: 'white', borderRadius: 10, padding: 14 }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
        <div style={{ fontSize: 10, textTransform: 'uppercase', letterSpacing: '0.08em', opacity: 0.55 }}>Up next</div>
        <div className="mono" style={{ fontSize: 10, color: 'var(--lemon)' }}>{ev.date}</div>
      </div>
      <div style={{ fontSize: 18, fontWeight: 600, fontFamily: 'var(--font-display)', lineHeight: 1.2, marginTop: 6 }}>{ev.title}</div>
      <div style={{ fontSize: 11, opacity: 0.7, marginTop: 2 }}>
        {KIND_LABEL[ev.kind] || ev.kind}{subject ? ` · ${subject.emoji} ${subject.name}` : ''}
      </div>
      <div style={{ display: 'flex', alignItems: 'baseline', gap: 6, marginTop: 10 }}>
        <div style={{ fontSize: 22, fontWeight: 600, fontFamily: 'var(--font-display)', lineHeight: 1 }}>{dayLabel}</div>
        <div style={{ fontSize: 11, opacity: 0.7 }}>{days === 0 ? '' : 'away'}</div>
      </div>
      <button className="btn small" style={{ marginTop: 10, width: '100%', background: 'white', color: 'var(--ink)', borderColor: 'white', justifyContent: 'center' }}
        onClick={() => navigate('/calendar')}>
        Open calendar
      </button>
    </div>
  );
}

function prettyDateLong(iso) {
  return new Date(iso + 'T00:00:00').toLocaleDateString(undefined, { weekday: 'long', month: 'short', day: 'numeric' });
}
function relativeShort(iso) {
  if (!iso) return '';
  const sec = Math.floor((Date.now() - new Date(iso).getTime()) / 1000);
  if (sec < 60) return 'now';
  if (sec < 3600) return Math.floor(sec / 60) + 'm';
  if (sec < 86400) return Math.floor(sec / 3600) + 'h';
  return Math.floor(sec / 86400) + 'd';
}

Object.assign(window, { HomeScreen });
