// Guide reading view. If a generated guide exists with this ID, render it
// from the structured JSON. Otherwise fall back to the static demo content
// (used for the fixture guides shown on Library/SubjectDetail).

function GuideScreen({ subjectId, guideId }) {
  const subjects = useSubjects();
  const subject = subjects.find((s) => s.id === subjectId) || { id: subjectId, name: '(unknown subject)', emoji: '📄' };
  const [generated, setGenerated] = React.useState(() => findGuideSync(guideId));
  const [tried, setTried] = React.useState(!!findGuideSync(guideId));

  React.useEffect(() => {
    if (tried) return;
    let cancelled = false;
    findGuide(guideId).then((g) => {
      if (cancelled) return;
      setGenerated(g);
      setTried(true);
    });
    return () => { cancelled = true; };
  }, [guideId, tried]);

  const guidePath = `/subject/${subjectId}/guide/${guideId}`;

  if (!tried) {
    return (
      <Page>
        <PageHeader breadcrumb={[{ label: 'Dashboard', to: '/' }, 'Loading…']} />
        <div style={{ flex: 1, display: 'grid', placeItems: 'center', color: 'var(--ink-mute)', fontSize: 12 }}>
          <span className="pulse">Loading guide…</span>
        </div>
      </Page>
    );
  }

  if (!generated) {
    return (
      <Page>
        <PageHeader breadcrumb={[{ label: 'Dashboard', to: '/' }, 'Not found']} />
        <div style={{ padding: 22 }}>
          <div style={{ fontSize: 13 }}>Guide not found.</div>
          <button className="btn small" style={{ marginTop: 10 }} onClick={() => navigate('/library')}>Browse all guides</button>
        </div>
      </Page>
    );
  }

  return (
    <Page>
      <PageHeader
        breadcrumb={[
          { label: 'Dashboard', to: '/' },
          { label: subject.name, to: `/subject/${subject.id}` },
          generated.title,
        ]}
        actions={
          <>
            <button className="btn ghost small" onClick={() => navigate(`/subject/${subject.id}/upload`)}>{Icon.upload} Add files</button>
            <button className="btn blue small" onClick={() => navigate(`${guidePath}/flashcards`)}>Study now</button>
          </>
        }
      />

      <div style={{ flex: 1, display: 'grid', gridTemplateColumns: '180px 1fr 220px', overflow: 'hidden' }}>
        <GeneratedGuideBody subject={subject} guide={generated} guidePath={guidePath} />
      </div>
    </Page>
  );
}

// ─── Generated guide ────────────────────────────────────────────────────────
function GeneratedGuideBody({ subject, guide, guidePath }) {
  const c = guide.content;
  const sections = c.sections || [];
  const firstQuiz = (c.quiz || [])[0];

  return (
    <>
      <div style={{ borderRight: '1px solid var(--line)', padding: '14px 10px', overflowY: 'auto', background: 'var(--bg)' }}>
        <div style={{ fontSize: 10, textTransform: 'uppercase', letterSpacing: '0.08em', color: 'var(--ink-mute)', padding: '0 8px 8px' }}>Contents</div>
        {sections.map((s) => (
          <div key={s.number} style={{
            display: 'flex', gap: 8,
            padding: '5px 10px', borderRadius: 5, fontSize: 12,
            color: 'var(--ink-soft)',
          }}>
            <span className="mono" style={{ fontSize: 10, color: 'var(--ink-whisper)', width: 14 }}>{s.number}</span>
            <span style={{ overflow: 'hidden', textOverflow: 'ellipsis' }}>{s.title}</span>
          </div>
        ))}
        {(c.flashcards || []).length > 0 && (
          <div onClick={() => navigate(`${guidePath}/flashcards`)} style={{ display: 'flex', gap: 8, padding: '5px 10px', borderRadius: 5, fontSize: 12, color: 'var(--ink-soft)', cursor: 'pointer', marginTop: 6, borderTop: '1px solid var(--line-soft)', paddingTop: 9 }}>
            <span className="mono" style={{ fontSize: 10, color: 'var(--ink-whisper)', width: 14 }}>★</span>
            <span>Flashcards · {c.flashcards.length}</span>
          </div>
        )}
        {(c.quiz || []).length > 0 && (
          <div onClick={() => navigate(`${guidePath}/quiz`)} style={{ display: 'flex', gap: 8, padding: '5px 10px', borderRadius: 5, fontSize: 12, color: 'var(--ink-soft)', cursor: 'pointer' }}>
            <span className="mono" style={{ fontSize: 10, color: 'var(--ink-whisper)', width: 14 }}>?</span>
            <span>Practice quiz · {c.quiz.length}</span>
          </div>
        )}
      </div>

      <main style={{ overflowY: 'auto', padding: '24px 36px', background: 'white' }}>
        <div style={{ maxWidth: 640, margin: '0 auto' }}>
          <div style={{ fontSize: 10.5, textTransform: 'uppercase', letterSpacing: '0.1em', color: 'var(--ink-mute)' }}>{subject.name}{c.subjectHint ? ` · ${c.subjectHint}` : ''}</div>
          <h1 className="display" style={{ fontSize: 30, margin: '6px 0 4px', letterSpacing: '-0.02em', lineHeight: 1.1 }}>{c.title}</h1>
          <div style={{ color: 'var(--ink-mute)', fontSize: 11.5, display: 'flex', gap: 8, alignItems: 'center' }}>
            <span>{guide.sources} source{guide.sources === 1 ? '' : 's'} · generated {timeAgo(guide.generatedAt)}</span>
            <span className="chip mint" style={{ fontSize: 9.5 }}>generated</span>
          </div>

          {c.bigIdea && (
            <div style={{ marginTop: 16, padding: 14, background: 'var(--paper)', borderRadius: 8, border: '1px solid var(--line)' }}>
              <div style={{ fontSize: 10, textTransform: 'uppercase', letterSpacing: '0.1em', color: 'var(--ink-mute)', marginBottom: 4 }}>★ The big idea</div>
              <p style={{ margin: 0, fontSize: 13.5, lineHeight: 1.55, fontFamily: 'var(--font-display)' }}>{c.bigIdea}</p>
            </div>
          )}

          {sections.map((s) => (
            <section key={s.number}>
              <h2 className="display" style={{ fontSize: 20, marginTop: 24, marginBottom: 4 }}>{s.number}. {s.title}</h2>
              <p style={{ fontSize: 13, lineHeight: 1.65, margin: '0 0 10px', whiteSpace: 'pre-wrap' }}>{s.body}</p>
              {(s.terms || []).length > 0 && (
                <>
                  <h3 className="display" style={{ fontSize: 15, marginTop: 14, marginBottom: 8 }}>Key terms</h3>
                  {s.terms.map((t, i) => <Term key={i} term={t.term} def={t.def} />)}
                </>
              )}
            </section>
          ))}

          {sections.length === 0 && (c.flashcards || []).length > 0 && (
            <section>
              <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginTop: 24, marginBottom: 10 }}>
                <h2 className="display" style={{ fontSize: 20, margin: 0 }}>Flashcards <span className="mono" style={{ fontSize: 12, color: 'var(--ink-mute)', fontWeight: 400 }}>· {c.flashcards.length}</span></h2>
                <button className="btn blue small" onClick={() => navigate(`${guidePath}/flashcards`)}>{Icon.sparkle} Study now</button>
              </div>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr', gap: 6 }}>
                {c.flashcards.map((card, i) => (
                  <div key={i} style={{ display: 'grid', gridTemplateColumns: '24px 1fr 1fr', gap: 10, padding: '8px 10px', background: 'var(--paper)', border: '1px solid var(--line)', borderRadius: 6, alignItems: 'baseline' }}>
                    <span className="mono" style={{ fontSize: 10, color: 'var(--ink-mute)' }}>{i + 1}</span>
                    <span style={{ fontSize: 12.5, fontWeight: 500 }}>{card.front}</span>
                    <span style={{ fontSize: 12, color: 'var(--ink-soft)' }}>{card.back}</span>
                  </div>
                ))}
              </div>
            </section>
          )}

          {firstQuiz && (
            <div style={{ marginTop: 24, padding: 12, border: '1.5px solid var(--blue)', borderRadius: 8, background: 'var(--blue-wash)' }}>
              <div style={{ fontSize: 10, textTransform: 'uppercase', letterSpacing: '0.08em', color: 'var(--blue-deep)', fontWeight: 600, marginBottom: 6 }}>? Quick check</div>
              <div style={{ fontSize: 13, fontWeight: 500, marginBottom: 8 }}>{firstQuiz.question}</div>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
                {(firstQuiz.options || []).map((opt, i) => (
                  <div key={i} style={{ padding: '7px 10px', background: 'white', border: '1px solid var(--line)', borderRadius: 6, fontSize: 12, display: 'flex', gap: 8 }}>
                    <span className="mono" style={{ fontSize: 10, color: 'var(--ink-mute)', width: 12 }}>{String.fromCharCode(65 + i)}</span>{opt}
                  </div>
                ))}
              </div>
              <div style={{ marginTop: 10, textAlign: 'right' }}>
                <button className="btn ghost small" onClick={() => navigate(`${guidePath}/quiz`)}>Open full quiz →</button>
              </div>
            </div>
          )}
        </div>
      </main>

      <aside style={{ borderLeft: '1px solid var(--line)', padding: '14px 14px', overflowY: 'auto', background: 'var(--bg)' }}>
        <div style={{ fontSize: 10, textTransform: 'uppercase', letterSpacing: '0.08em', color: 'var(--ink-mute)', marginBottom: 8 }}>About</div>
        <div style={{ background: 'white', border: '1px solid var(--line)', borderRadius: 6, padding: 10, fontSize: 11.5, color: 'var(--ink-soft)' }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', padding: '2px 0' }}><span>Sources</span><span className="mono">{guide.sources}</span></div>
          <div style={{ display: 'flex', justifyContent: 'space-between', padding: '2px 0' }}><span>Sections</span><span className="mono">{sections.length}</span></div>
          <div style={{ display: 'flex', justifyContent: 'space-between', padding: '2px 0' }}><span>Flashcards</span><span className="mono">{(c.flashcards || []).length}</span></div>
          <div style={{ display: 'flex', justifyContent: 'space-between', padding: '2px 0' }}><span>Quiz items</span><span className="mono">{(c.quiz || []).length}</span></div>
        </div>
        <div style={{ display: 'flex', gap: 6, marginTop: 12 }}>
          {(c.flashcards || []).length > 0 && (
            <button className="btn ghost small" style={{ flex: 1, justifyContent: 'center' }} onClick={() => navigate(`${guidePath}/flashcards`)}>Cards</button>
          )}
          {(c.quiz || []).length > 0 && (
            <button className="btn ghost small" style={{ flex: 1, justifyContent: 'center' }} onClick={() => navigate(`${guidePath}/quiz`)}>Quiz</button>
          )}
        </div>
        <button className="btn ghost small" style={{ width: '100%', justifyContent: 'center', marginTop: 8, color: 'var(--coral)', borderColor: 'var(--coral-soft)' }}
          onClick={async () => {
            if (!confirm('Delete this generated guide?')) return;
            try { await deleteGuide(guide.id); navigate(`/subject/${subject.id}`); }
            catch (e) { alert('Delete failed: ' + e.message); }
          }}>
          Delete guide
        </button>
      </aside>
    </>
  );
}

function Term({ term, def }) {
  return (
    <div style={{ padding: '8px 10px', background: 'var(--paper)', borderRadius: 6, border: '1px solid var(--line)', marginBottom: 5 }}>
      <div style={{ fontWeight: 600, fontSize: 12 }}>{term}</div>
      <div style={{ fontSize: 11.5, color: 'var(--ink-soft)', marginTop: 1 }}>{def}</div>
    </div>
  );
}

function timeAgo(iso) {
  if (!iso) return 'just now';
  const t = new Date(iso).getTime();
  const sec = Math.floor((Date.now() - t) / 1000);
  if (sec < 60) return 'just now';
  if (sec < 3600) return Math.floor(sec / 60) + 'm ago';
  if (sec < 86400) return Math.floor(sec / 3600) + 'h ago';
  return Math.floor(sec / 86400) + 'd ago';
}

Object.assign(window, { GuideScreen });
