// Lessons Library + Lesson detail (full 10-section schema)

function LessonsLibrary() {
  const [filter, setFilter] = useState("All");
  const [query, setQuery] = useState("");

  const filtered = useMemo(() => {
    return LESSONS.filter((l) => {
      const cat = filterCategoryFor(l);
      const matchCat = filter === "All" || cat === filter;
      const q = query.trim().toLowerCase();
      const matchQ =
        !q ||
        l.title.toLowerCase().includes(q) ||
        l.summary.toLowerCase().includes(q) ||
        l.category.toLowerCase().includes(q) ||
        cat.toLowerCase().includes(q) ||
        l.story.toLowerCase().includes(q);
      return matchCat && matchQ;
    });
  }, [filter, query]);

  return (
    <Page className="library">
      <section className="page-hero">
        <div className="container">
          <div className="back-link mono">Library</div>
          <h1>{LIBRARY_PAGE.hero.headline.split(" facing now.")[0]} <em>facing now.</em></h1>
          <p>{LIBRARY_PAGE.hero.subheadline}</p>
        </div>
      </section>

      <div className="container">
        <div className="library-controls">
          <div className="library-search">
            <span className="library-search-icon" aria-hidden="true">⌕</span>
            <input
              type="text"
              placeholder={LIBRARY_PAGE.searchPlaceholder}
              value={query}
              onChange={(e) => setQuery(e.target.value)}
              aria-label="Search lessons"
            />
            {query && (
              <button className="btn btn-link" style={{ fontSize: 12, borderBottom: 0 }} onClick={() => setQuery("")}>Clear</button>
            )}
          </div>
          <div className="filter-row" role="tablist" aria-label="Categories">
            {["All", ...CATEGORIES].map((c) => (
              <button
                key={c}
                role="tab"
                aria-selected={filter === c}
                className={"filter-pill " + (filter === c ? "is-active" : "")}
                onClick={() => setFilter(c)}
              >
                {c}
              </button>
            ))}
          </div>
        </div>

        <div className="results-meta">
          {filtered.length} lesson{filtered.length === 1 ? "" : "s"}
          {filter !== "All" && <> · in <span style={{ color: "var(--ink)" }}>{filter}</span></>}
          {query && <> · matching <span style={{ color: "var(--ink)" }}>"{query}"</span></>}
        </div>

        {filtered.length === 0 ? (
          <div className="empty-state">
            <h3>Nothing matches yet.</h3>
            <p>Try a different search term or clear the filter to see every lesson.</p>
            <button className="btn btn-secondary" onClick={() => { setFilter("All"); setQuery(""); }}>Reset filters</button>
          </div>
        ) : (
          <div className="lessons-grid">
            {filtered.map((l) => <LessonCard key={l.slug} lesson={l} />)}
          </div>
        )}

        <div style={{ marginTop: 64, padding: "32px 0", borderTop: "1px solid var(--rule)", display: "flex", justifyContent: "space-between", alignItems: "center", flexWrap: "wrap", gap: 16 }}>
          <div>
            <div className="mono" style={{ marginBottom: 4 }}>Want the worksheets?</div>
            <div style={{ fontFamily: "var(--serif)", fontSize: 22, letterSpacing: "-0.01em" }}>Every lesson pairs with a downloadable tool.</div>
          </div>
          <Link to="/resources" className="btn btn-ghost">Browse resources →</Link>
        </div>
      </div>
    </Page>
  );
}

// Lesson detail — renders the full 10-section schema
const LESSON_SECTIONS = [
  { id: "story", num: "01", h: "Opening story" },
  { id: "lesson", num: "02", h: "The lesson", callout: true },
  { id: "whyItMatters", num: "03", h: "Why this matters" },
  { id: "practice", num: "04", h: "What this means in practice", list: true },
  { id: "hacks", num: "05", h: "Founder hacks", list: true },
  { id: "mistakes", num: "06", h: "Common mistakes", list: true },
  { id: "questions", num: "07", h: "Questions to ask yourself", list: true },
];

function LessonDetail({ slug }) {
  const lesson = lessonBySlug(slug);
  if (!lesson) return <NotFound />;
  const cat = filterCategoryFor(lesson);
  const resource = resourceBySlug(lesson.resource);
  const linkedChapters = chaptersForLesson(lesson);
  // Find the next lesson by number for sequential navigation
  const next = LESSONS.find((l) => l.n === lesson.n + 1) || LESSONS[0];

  return (
    <Page>
      <section className="chapter-hero">
        <div className="container">
          <Link to="/lessons" className="back-link">← All lessons</Link>
          <div className="chapter-hero-eyebrow">
            <span className="mono">Lesson {String(lesson.n).padStart(2, "0")} of {LESSONS.length}</span>
            <span style={{ width: 24, height: 1, background: "var(--rule-2)" }} />
            <Tag tone="accent" data-cat={cat}>{lesson.category}</Tag>
          </div>
          <h1>{lesson.title}</h1>
          <p className="chapter-hero-intro">{lesson.summary}</p>
        </div>
      </section>

      <div className="container">
        <div className="chapter-body">
          <aside className="chapter-toc">
            <div className="toc-h">In this lesson</div>
            {LESSON_SECTIONS.map((s) => (
              <a key={s.id} href={"#" + s.id} className="toc-link">{s.h}</a>
            ))}
            {resource && <a href="#resource" className="toc-link">Related resource</a>}
            <a href="#quote" className="toc-link">Quote</a>
          </aside>

          <div>
            {LESSON_SECTIONS.map((s) => (
              <section key={s.id} id={s.id} className={"chapter-sec" + (s.callout ? " callout" : "")}>
                <h2><span className="num">{s.num}</span>{s.h}</h2>
                <div className="body">
                  {s.list ? (
                    <ul>{lesson[s.id].map((x, i) => <li key={i}>{x}</li>)}</ul>
                  ) : (
                    <p>{lesson[s.id]}</p>
                  )}
                </div>
              </section>
            ))}

            {/* Related resource */}
            {resource && (
              <section id="resource" className="chapter-sec">
                <h2><span className="num">08</span>Related resource</h2>
                <div className="body">
                  <p style={{ marginBottom: 16 }}>This lesson pairs with a practical worksheet you can use this week.</p>
                  <div className="resources-grid" style={{ gridTemplateColumns: "1fr" }}>
                    <ResourceCard resource={resource} />
                  </div>
                </div>
              </section>
            )}

            {/* Anonymous quote slot — placeholder until verified */}
            <section id="quote" className="chapter-sec">
              <h2><span className="num">09</span>From the conversations</h2>
              <div className="body">
                <div className="lesson-quote-slot">
                  <div className="quote-mark" aria-hidden="true">“</div>
                  <p className="lesson-quote-text">
                    A verified anonymous founder quote will appear here once transcript review is complete.
                  </p>
                  <div className="mono" style={{ color: "var(--ink-3)", fontSize: 12 }}>Anonymous founder interview</div>
                </div>
              </div>
            </section>

            {/* Linked chapters */}
            {linkedChapters.length > 0 && (
              <section style={{ paddingTop: 48, borderTop: "1px solid var(--rule)", marginTop: 24 }}>
                <div className="eyebrow mono">Read in context</div>
                <h3 style={{ fontFamily: "var(--serif)", fontSize: 28, letterSpacing: "-0.01em", margin: "0 0 24px", fontWeight: 500 }}>
                  This lesson sits inside {linkedChapters.length === 1 ? "a chapter" : "these chapters"}.
                </h3>
                <div className="chapters" style={{ marginTop: 0 }}>
                  {linkedChapters.map((c) => (
                    <Link key={c.n} to={"/chapters/" + c.n} className="chapter-row">
                      <span className="ch-n">CH · {String(c.n).padStart(2, "0")}</span>
                      <span className="ch-title">{c.title}</span>
                      <span className="ch-sum">{c.headline}</span>
                      <span className="ch-cta">Read chapter <span className="arrow">→</span></span>
                    </Link>
                  ))}
                </div>
              </section>
            )}

            <div className="chapter-next">
              <div>
                <div className="next-eyebrow">Up next · Lesson {String(next.n).padStart(2, "0")}</div>
                <div className="next-title">{next.title}</div>
              </div>
              <Link to={"/lessons/" + next.slug} className="btn btn-ghost">
                Read lesson <span className="arrow">→</span>
              </Link>
            </div>
          </div>
        </div>
      </div>
    </Page>
  );
}

function NotFound() {
  return (
    <Page>
      <section className="page-hero">
        <div className="container">
          <div className="back-link">404</div>
          <h1>{NOT_FOUND_PAGE.headline}</h1>
          <p>{NOT_FOUND_PAGE.body}</p>
          <div style={{ display: "flex", gap: 12, marginTop: 24, flexWrap: "wrap" }}>
            <Link to="/" className="btn btn-primary">Homepage</Link>
            <Link to="/lessons" className="btn btn-secondary">Lessons</Link>
            <Link to="/start" className="btn btn-ghost">Start Here</Link>
          </div>
        </div>
      </section>
    </Page>
  );
}

Object.assign(window, { LessonsLibrary, LessonDetail, LESSON_SECTIONS, NotFound });
