// Subject detail — header + list of generated guides for this subject.

function SubjectDetailScreen({ subjectId }) {
  const subjects = useSubjects();
  const subject = subjects.find((s) => s.id === subjectId);
  if (!subject) {
    const loading = !subjectsLoaded();
    return (
      <Page>
        <PageHeader breadcrumb={[{ label: 'Dashboard', to: '/' }, loading ? 'Loading…' : 'Not found']} />
        {loading ? (
          <div style={{ flex: 1, display: 'grid', placeItems: 'center', color: 'var(--ink-mute)', fontSize: 12 }}>
            <span className="pulse">Loading subject…</span>
          </div>
        ) : (
          <div style={{ padding: 22 }}>
            <div style={{ fontSize: 13 }}>Subject not found.</div>
            <button className="btn small" style={{ marginTop: 10 }} onClick={() => navigate('/')}>Back to dashboard</button>
          </div>
        )}
      </Page>
    );
  }
  return <SubjectDetailBody subject={subject} />;
}

function SubjectDetailBody({ subject }) {
  const userGuides = useGuides();
  const events = useEvents();
  const [showEdit, setShowEdit] = React.useState(false);

  const guides = userGuides.filter((g) => g.subjectId === subject.id);
  const subjectEvents = events.filter((e) => e.subject_id === subject.id);
  const upcoming = subjectEvents.filter((e) => e.date >= todayISO());
  const totalCards = guides.reduce((n, g) => n + ((g.content?.flashcards || []).length), 0);
  const uploadTo = `/subject/${subject.id}/upload`;

  return (
    <Page>
      <PageHeader
        breadcrumb={[{ label: 'Dashboard', to: '/' }, subject.name]}
        actions={
          <>
            <button className="btn ghost small" onClick={() => navigate(uploadTo)}>{Icon.upload} Add files</button>
            <button className="btn ghost small" onClick={() => setShowEdit(true)}>Edit</button>
            <button className="btn blue small" onClick={() => navigate(uploadTo)}>{Icon.sparkle} Generate guide</button>
          </>
        }
      />

      <div style={{ flex: 1, overflowY: 'auto', padding: '16px 22px' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 14, marginBottom: 14 }}>
          <div style={{ fontSize: 28 }}>{subject.emoji}</div>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 16, fontWeight: 600 }}>{subject.name}</div>
            <div style={{ fontSize: 11.5, color: 'var(--ink-mute)' }}>
              Created {relativeShort(subject.created_at)} ago
            </div>
          </div>
          <div style={{ display: 'flex', gap: 8 }}>
            <Stat label="Guides" value={guides.length} />
            <Stat label="Cards" value={totalCards} />
            <Stat label="Events" value={subjectEvents.length} />
            <Stat label="Upcoming" value={upcoming.length} tone={upcoming.length > 0 ? 'coral' : null} />
          </div>
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: 14 }}>
          <div>
            <h2 style={{ fontSize: 13, fontWeight: 600, margin: '0 0 8px' }}>
              Study guides <span className="mono" style={{ fontSize: 11, color: 'var(--ink-mute)', fontWeight: 400 }}>· {guides.length}</span>
            </h2>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
              {guides.length === 0 ? (
                <div style={{ background: 'white', border: '1px dashed var(--line)', borderRadius: 8, padding: 18, textAlign: 'center' }}>
                  <div style={{ fontSize: 12.5, fontWeight: 500 }}>No guides for this subject yet</div>
                  <div style={{ fontSize: 11, color: 'var(--ink-mute)', marginTop: 4 }}>Upload files to generate your first one.</div>
                  <button className="btn blue small" style={{ marginTop: 10 }} onClick={() => navigate(uploadTo)}>{Icon.upload} Upload files</button>
                </div>
              ) : guides.map((g) => (
                <GuideRow key={g.id} guide={g}
                  onOpen={() => navigate(`/subject/${subject.id}/guide/${g.id}`)} />
              ))}
              {guides.length > 0 && (
                <button onClick={() => navigate(uploadTo)}
                  style={{
                    border: '1px dashed var(--line)', borderRadius: 8, padding: '12px',
                    display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6,
                    color: 'var(--ink-mute)', background: 'transparent', cursor: 'pointer', fontSize: 12,
                  }}>
                  {Icon.plus} New guide
                </button>
              )}
            </div>
          </div>

          <div>
            <h2 style={{ fontSize: 13, fontWeight: 600, margin: '0 0 8px' }}>
              Upcoming events <span className="mono" style={{ fontSize: 11, color: 'var(--ink-mute)', fontWeight: 400 }}>· {upcoming.length}</span>
            </h2>
            <div style={{ background: 'white', border: '1px solid var(--line)', borderRadius: 8, overflow: 'hidden' }}>
              {upcoming.length === 0 ? (
                <div style={{ padding: '14px 16px', fontSize: 11.5, color: 'var(--ink-mute)' }}>
                  No upcoming events. <a href="#" onClick={(e) => { e.preventDefault(); navigate('/calendar'); }} style={{ color: 'var(--blue-deep)' }}>Add one</a>.
                </div>
              ) : upcoming.slice(0, 6).map((ev, i, arr) => (
                <div key={ev.id} onClick={() => navigate('/calendar')} style={{
                  display: 'flex', alignItems: 'center', gap: 10, padding: '8px 12px',
                  borderBottom: i === arr.length - 1 ? 'none' : '1px solid var(--line-soft)', cursor: 'pointer',
                }}>
                  <span style={{ width: 6, height: 6, borderRadius: 3, background: KIND_DOT[ev.kind], flexShrink: 0 }} />
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontSize: 12, fontWeight: 500, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{ev.title}</div>
                    <div style={{ fontSize: 10.5, color: 'var(--ink-mute)' }}>{ev.date}</div>
                  </div>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>

      {showEdit && <SubjectDialog existing={subject} onClose={(opts) => {
        setShowEdit(false);
        if (opts?.deleted) navigate('/');
      }} />}
    </Page>
  );
}

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

function Stat({ label, value, tone }) {
  const c = tone === 'mint' ? 'var(--mint)' : tone === 'coral' ? 'var(--coral)' : 'var(--ink)';
  return (
    <div style={{ padding: '6px 12px', background: 'white', border: '1px solid var(--line)', borderRadius: 6, textAlign: 'center', minWidth: 60 }}>
      <div style={{ fontSize: 14, fontWeight: 600, color: c, lineHeight: 1.1 }}>{value}</div>
      <div style={{ fontSize: 9.5, textTransform: 'uppercase', letterSpacing: '0.06em', color: 'var(--ink-mute)' }}>{label}</div>
    </div>
  );
}

function GuideRow({ guide, onOpen }) {
  const cards = (guide.content?.flashcards || []).length;
  const sections = (guide.content?.sections || []).length;
  return (
    <div onClick={onOpen} style={{
      background: 'white',
      border: '1px solid var(--line)', borderRadius: 8, padding: '10px 12px', cursor: 'pointer',
    }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
        <div style={{ fontSize: 12.5, fontWeight: 600 }}>{guide.title}</div>
        <span className="mono" style={{ fontSize: 10, color: 'var(--ink-mute)' }}>{relativeShort(guide.generatedAt)} ago</span>
      </div>
      <div style={{ fontSize: 10.5, color: 'var(--ink-mute)', marginTop: 2 }}>
        {sections} sections · {cards} cards · {guide.sources || 0} sources
      </div>
    </div>
  );
}

function relativeShort(iso) {
  if (!iso) return 'just now';
  const sec = Math.floor((Date.now() - new Date(iso).getTime()) / 1000);
  if (sec < 60) return 'just 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, { SubjectDetailScreen });
