// pages/preview.jsx — free preview listing + chapter viewer

const { useState: useS_P } = React;

function PreviewListPage({ go }) {
  const freeIcse10 = COURSE_DATA.icse10.chapters.filter(c => c.free);
  const freeIsc12  = COURSE_DATA.isc12.chapters.filter(c => c.free);

  return (
    <>
      <Navbar go={go} />
      <section style={{ padding: "80px 0 48px", background: "var(--white)" }}>
        <div className="container-narrow" style={{ textAlign: "center" }}>
          <div className="eyebrow">Free preview · No login needed</div>
          <h1 style={{ marginTop: 16, fontSize: "clamp(36px, 4.4vw, 64px)" }}>Try two full chapters.</h1>
          <p style={{ marginTop: 16, fontSize: 18, color: "var(--ink-2)", maxWidth: 620, margin: "16px auto 0" }}>
            One chapter from ICSE Class 10 Computer Applications. One from ISC Class 12 Computer Science. Same teacher, same recordings, same notes. If it clicks, enrol — if it doesn't, no harm done.
          </p>
        </div>
      </section>

      <section style={{ padding: "32px 0 96px", background: "var(--white)" }}>
        <div className="container">
          <PreviewBlock
            go={go}
            courseKey="icse10"
            courseLabel="ICSE Class 10"
            courseCode="ICSE-X"
            courseTitle="Computer Applications"
            courseTagline="The Java OOP foundation, taught the ICSE way."
            chapters={freeIcse10}
          />
          <div style={{ height: 48 }}/>
          <PreviewBlock
            go={go}
            courseKey="isc12"
            courseLabel="ISC Class 12"
            courseCode="ISC-XII"
            courseTitle="Computer Science"
            courseTagline="Advanced OOP, recursion & data structures — for the ISC board paper."
            chapters={freeIsc12}
          />
        </div>
      </section>

      <StickyEnrolBar go={go} />
      <Footer go={go} />
    </>
  );
}

const PreviewBlock = ({ go, courseKey, courseLabel, courseCode, courseTitle, courseTagline, chapters }) => (
  <div>
    <div className="row between" style={{ alignItems: "flex-end", marginBottom: 24, flexWrap: "wrap", gap: 16 }}>
      <div>
        <div className="row gap-12 center">
          <span className="pill pill-mono">{courseCode}</span>
          <span style={{ fontFamily: "var(--font-mono)", fontSize: 12, color: "var(--ink-3)" }}>1 chapter · free</span>
        </div>
        <h2 style={{ marginTop: 12, fontSize: 36 }}>{courseLabel} — {courseTitle}</h2>
        <p className="muted" style={{ marginTop: 6, fontSize: 16 }}>{courseTagline}</p>
      </div>
    </div>
    <div style={{ display: "grid", gridTemplateColumns: "1fr", gap: 16, maxWidth: 720 }}>
      {chapters.map((ch, i) => (
        <button key={ch.id} onClick={() => go(`/preview/${courseKey}/${ch.id}`)}
          style={{ all: "unset", cursor: "pointer", display: "block" }}>
          <div className="card" style={{ padding: 0, overflow: "hidden", transition: "box-shadow .15s, transform .15s", display: "grid", gridTemplateColumns: "300px 1fr" }}
               onMouseEnter={e => e.currentTarget.style.boxShadow = "var(--shadow-lg)"}
               onMouseLeave={e => e.currentTarget.style.boxShadow = ""}>
            <div className="video-frame" style={{ aspectRatio: "16/9", borderRadius: 0, height: "100%" }}>
              <button className="play-btn" tabIndex={-1}><Icon name="play" size={24} /></button>
              <div className="video-meta">
                <span style={{ background: "rgba(0,0,0,.6)", padding: "4px 8px", borderRadius: 4 }}>{ch.duration}</span>
              </div>
              <div style={{ position: "absolute", top: 16, left: 16 }}>
                <span className="pill" style={{ background: "rgba(255,255,255,.18)", color: "#fff", fontFamily: "var(--font-mono)" }}>Free</span>
              </div>
            </div>
            <div style={{ padding: 24 }}>
              <div style={{ fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--ink-3)", letterSpacing: "0.08em", textTransform: "uppercase", marginBottom: 8 }}>{courseCode} · Chapter {i + 1}</div>
              <h3 style={{ fontSize: 22 }}>{ch.title}</h3>
              <p className="muted" style={{ marginTop: 8, fontSize: 14 }}>{ch.desc}</p>
              <div className="row between center" style={{ marginTop: 16 }}>
                <span style={{ color: "var(--blue)", fontWeight: 600, fontSize: 14 }}>Watch chapter <Icon name="arrow-right" size={14} /></span>
                <span style={{ fontFamily: "var(--font-mono)", fontSize: 12, color: "var(--ink-3)" }}>{ch.duration}</span>
              </div>
            </div>
          </div>
        </button>
      ))}
    </div>
  </div>
);

// ───── Chapter viewer ───────────────────────────────────────
function PreviewViewerPage({ go, parts }) {
  // /preview/:c/:ch — parts = ["preview", "icse10", "ch1"]
  // Accept legacy "cs11" / "cs12" too in case of old links.
  let courseId = parts[1] || "isc12";
  if (courseId === "cs11") courseId = "icse10";
  if (courseId === "cs12") courseId = "isc12";
  const chapterId = parts[2] || "ch1";

  const course = COURSE_DATA[courseId] || COURSE_DATA.isc12;
  const idx = course.chapters.findIndex(c => c.id === chapterId);
  const chapter = course.chapters[idx >= 0 ? idx : 0];
  const realIdx = idx >= 0 ? idx : 0;

  const courseLabelMap = { icse10: "ICSE Class 10", isc12: "ISC Class 12" };

  // next free chapter across both courses
  const allFree = [
    ...COURSE_DATA.icse10.chapters.filter(c => c.free).map(c => ({ ...c, courseId: "icse10", courseLabel: "ICSE Class 10" })),
    ...COURSE_DATA.isc12.chapters.filter(c => c.free).map(c => ({ ...c, courseId: "isc12",  courseLabel: "ISC Class 12"  })),
  ];
  const flatIdx = allFree.findIndex(c => c.id === chapter.id && c.courseId === courseId);
  const nextFree = allFree[(flatIdx + 1) % allFree.length];

  return (
    <>
      <Navbar go={go} />
      <section style={{ padding: "32px 0", background: "var(--white)" }}>
        <div className="container">
          {/* Breadcrumb */}
          <div className="row center gap-8" style={{ marginBottom: 24, fontSize: 13, color: "var(--ink-3)" }}>
            <button className="btn btn-ghost btn-sm" style={{ height: 28, padding: "0 8px" }} onClick={() => go("/preview")}>
              <Icon name="arrow-left" size={14} /> Back to free preview
            </button>
            <span>·</span>
            <span>{course.name}</span>
            <span>·</span>
            <span style={{ color: "var(--ink-2)" }}>Chapter {realIdx + 1}</span>
          </div>

          <div style={{ display: "grid", gridTemplateColumns: "1fr 340px", gap: 32, alignItems: "flex-start" }}>
            <div>
              <div className="video-frame" style={{ aspectRatio: "16/9" }}>
                <image-slot id={`pv-${courseId}-${chapterId}`} placeholder="Video — drop a thumbnail or recording embed" shape="rect" style={{ position: "absolute", inset: 0, width: "100%", height: "100%" }}></image-slot>
                <div style={{ position: "absolute", inset: 0, background: "linear-gradient(180deg, rgba(0,0,0,.0) 60%, rgba(0,0,0,.5))", pointerEvents: "none" }}/>
                <button className="play-btn" style={{ position: "relative" }}><Icon name="play" size={28} /></button>
                <div style={{ position: "absolute", left: 24, bottom: 24, color: "#fff", display: "flex", alignItems: "center", gap: 12, fontFamily: "var(--font-mono)", fontSize: 13 }}>
                  <span>0:00</span>
                  <div style={{ width: 200, height: 4, background: "rgba(255,255,255,.2)", borderRadius: 2, position: "relative" }}>
                    <div style={{ position: "absolute", inset: 0, width: "12%", background: "#fff", borderRadius: 2 }}/>
                  </div>
                  <span>{chapter.duration}</span>
                </div>
              </div>

              <div style={{ marginTop: 32 }}>
                <div className="row gap-12 center" style={{ marginBottom: 12 }}>
                  <span className="pill pill-mono">{course.code}</span>
                  <span className="pill pill-mono pill-gray">{courseLabelMap[courseId]}</span>
                  <span className="pill pill-mono pill-gray">Chapter {realIdx + 1}</span>
                  <span className="pill pill-mono pill-gray">{chapter.duration}</span>
                  <span className="pill" style={{ background: "var(--green-100)", color: "#065F46" }}>Free preview</span>
                </div>
                <h1 style={{ fontSize: 42 }}>{chapter.title}</h1>
                <p style={{ marginTop: 16, fontSize: 18, color: "var(--ink-2)", maxWidth: 640 }}>{chapter.desc}</p>

                <div style={{ marginTop: 32, padding: 24, background: "var(--paper)", borderRadius: 16 }}>
                  <h4 style={{ marginBottom: 16 }}>What you'll learn</h4>
                  <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "10px 24px" }}>
                    {["Core concept walkthrough", "Worked examples in Java", `${courseId === "icse10" ? "ICSE" : "ISC"} board-pattern questions`, "Doubts & misconceptions", "Practice problem set", "Chapter recap"].map((f) => (
                      <div key={f} className="row gap-12 center" style={{ fontSize: 14, color: "var(--ink-2)" }}>
                        <span style={{ color: "var(--blue)" }}><Icon name="check" size={16} stroke={2.5}/></span> {f}
                      </div>
                    ))}
                  </div>
                </div>

                <div className="row between center" style={{ marginTop: 40, paddingTop: 24, borderTop: "1px solid var(--line)" }}>
                  <button className="btn btn-ghost" onClick={() => go("/preview")}>
                    <Icon name="arrow-left" size={16}/> All free chapters
                  </button>
                  <button className="btn btn-secondary" onClick={() => go(`/preview/${nextFree.courseId}/${nextFree.id}`)}>
                    Next free chapter <Icon name="arrow-right" size={16}/>
                  </button>
                </div>
              </div>
            </div>

            {/* Enrol sidebar */}
            <aside style={{ position: "sticky", top: 96 }}>
              <div className="card" style={{ padding: 24, background: "var(--blue)", color: "#fff", borderColor: "var(--blue)" }}>
                <div style={{ fontFamily: "var(--font-mono)", fontSize: 11, letterSpacing: "0.12em", textTransform: "uppercase", color: "rgba(255,255,255,.7)" }}>Want it all?</div>
                <h3 style={{ marginTop: 8, color: "#fff", fontSize: 22 }}>Enrol in {course.code} — ₹1800/mo</h3>
                <p style={{ marginTop: 8, color: "rgba(255,255,255,.7)", fontSize: 14 }}>Unlock every chapter of {courseLabelMap[courseId]}, live classes twice a week, and recordings of everything.</p>
                <button className="btn btn-block" style={{ background: "#fff", color: "var(--blue)", marginTop: 20 }} onClick={() => go("/signup")}>
                  Enrol now <Icon name="arrow-right" size={16}/>
                </button>
                <div style={{ marginTop: 24, paddingTop: 16, borderTop: "1px solid rgba(255,255,255,.15)" }}>
                  {["Full course access", "Live + recorded classes", "WhatsApp doubt channel", courseId === "isc12" ? "12 ISC mock practicals" : "ICSE project review"].map((f) => (
                    <div key={f} className="row gap-12 center" style={{ fontSize: 13, padding: "6px 0", color: "rgba(255,255,255,.9)" }}>
                      <Icon name="check" size={14} stroke={2.5}/> {f}
                    </div>
                  ))}
                </div>
              </div>

              <div style={{ marginTop: 16, padding: 20, border: "1px solid var(--line)", borderRadius: 16 }}>
                <div style={{ fontSize: 13, color: "var(--ink-3)", letterSpacing: "0.04em" }}>Other free chapter</div>
                <div style={{ marginTop: 12, display: "flex", flexDirection: "column", gap: 8 }}>
                  {allFree.filter(c => !(c.id === chapter.id && c.courseId === courseId)).map((c) => (
                    <button key={`${c.courseId}-${c.id}`} onClick={() => go(`/preview/${c.courseId}/${c.id}`)}
                      style={{ all: "unset", cursor: "pointer", display: "flex", alignItems: "center", gap: 12, padding: "8px 10px", borderRadius: 8 }}
                      onMouseEnter={e => e.currentTarget.style.background = "var(--paper)"}
                      onMouseLeave={e => e.currentTarget.style.background = ""}>
                      <span style={{ width: 32, height: 32, borderRadius: 6, background: "var(--blue-50)", color: "var(--blue)", display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}>
                        <Icon name="play" size={12}/>
                      </span>
                      <div style={{ flex: 1, minWidth: 0 }}>
                        <div style={{ fontSize: 13, fontWeight: 500, color: "var(--ink)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{c.title}</div>
                        <div style={{ fontSize: 11, color: "var(--ink-3)", fontFamily: "var(--font-mono)" }}>{c.courseLabel} · {c.duration}</div>
                      </div>
                    </button>
                  ))}
                </div>
              </div>
            </aside>
          </div>
        </div>
      </section>
      <StickyEnrolBar go={go} />
      <Footer go={go} />
    </>
  );
}

Object.assign(window, { PreviewListPage, PreviewViewerPage });
