import type { Metadata } from "next";
import Link from "next/link";
import {
  BookOpen,
  Layers,
  ListChecks,
  Timer,
  Shuffle,
  PlayCircle,
  ChevronRight,
  User,
  BarChart3,
} from "lucide-react";

import { Container } from "@/components/Container";
import { PartBrowserCard } from "@/components/orthoprep/PartBrowserCard";
import {
  getAllPartsWithCounts,
  getFrcsBank,
  slugifyFrcs,
} from "@/lib/frcs";

export const metadata: Metadata = {
  title: "FRCS Basic Sciences question bank",
  description:
    "The OrthoPrep FRCS (Tr & Orth) SBA question bank — 1,575 single-best-answer questions across 22 parts (basic sciences + clinical sub-specialties), authored by Prof Mohamed A. Imam.",
};

const PREVIEW_PER_CHAPTER = 5;
// Rough study time per SBA: ~2 minutes reading + 1 minute answering.
const MINUTES_PER_QUESTION = 3;

export const dynamic = "force-dynamic";

export default async function QuestionBankPage() {
  // Access gating is handled in middleware.ts — see matcher for /products/orthoprep/*.
  const bank = await getFrcsBank();
  const parts = await getAllPartsWithCounts();
  const totalQuestions = parts.reduce((s, p) => s + p.questionCount, 0);
  const totalChapters = parts.reduce((s, p) => s + p.chapterCount, 0);
  const estimatedStudyHours = Math.round(
    (totalQuestions * MINUTES_PER_QUESTION) / 60,
  );
  const avgPerPart = parts.length
    ? Math.round(totalQuestions / parts.length)
    : 0;
  const maxQuestionsPerPart = Math.max(...parts.map((p) => p.questionCount), 1);

  const stats = [
    {
      label: "Questions",
      value: totalQuestions.toLocaleString("en-GB"),
      Icon: BookOpen,
    },
    {
      label: "Parts",
      value: parts.length.toString(),
      Icon: Layers,
    },
    {
      label: "Avg / part",
      value: avgPerPart.toString(),
      Icon: ListChecks,
    },
    {
      label: "Est. study",
      value: `${estimatedStudyHours}h`,
      Icon: Timer,
    },
  ];

  return (
    <>
      {/* HERO — contained brand-blue card on a white background, matching the
          StatStrip and admin dashboard visual language. */}
      <section className="bg-white pb-6 pt-6 md:pt-10">
        <Container>
          <div className="relative overflow-hidden rounded-3xl bg-[var(--color-blue)] text-white shadow-[0_28px_64px_-28px_rgba(30,64,255,0.55)]">
            <div
              aria-hidden
              className="pointer-events-none absolute inset-0 bg-[radial-gradient(ellipse_at_top_right,rgba(255,255,255,0.2),transparent_58%),radial-gradient(ellipse_at_bottom_left,rgba(255,255,255,0.08),transparent_55%)]"
            />
            <div
              aria-hidden
              className="pointer-events-none absolute inset-0 opacity-[0.07]"
              style={{
                backgroundImage:
                  "linear-gradient(to right, white 1px, transparent 1px), linear-gradient(to bottom, white 1px, transparent 1px)",
                backgroundSize: "40px 40px",
              }}
            />

            <div className="relative flex flex-col gap-8 px-6 pt-8 pb-0 md:px-10 md:pt-12">
              <div className="flex items-center gap-2 text-[10px] font-bold uppercase tracking-[0.22em] text-white/85">
                <span
                  aria-hidden
                  className="inline-block h-1.5 w-1.5 rounded-full bg-white/85"
                />
                OrthoPrep · FRCS SBA · Basic Sciences
              </div>

              <div className="grid items-end gap-6 md:grid-cols-[minmax(0,1.7fr)_minmax(0,1fr)]">
                <div>
                  <h1 className="font-display text-[38px] font-extrabold leading-[1.05] tracking-[-0.025em] md:text-[52px]">
                    1,575 single-best-answer questions.
                  </h1>
                  <p className="mt-5 max-w-2xl text-[16px] leading-relaxed text-white/90 md:text-[18px]">
                    Authored by Prof Mohamed A. Imam from his FRCS Basic Sciences:
                    The Detailed Edition. Bone, musculoskeletal tissues,
                    biomechanics, biomaterials, anatomy — {parts.length} parts,{" "}
                    {totalChapters} chapters.
                  </p>
                </div>

                <div className="flex flex-col gap-3 md:items-end">
                  <Link
                    href="/products/orthoprep/quiz?mode=random&count=10"
                    className="inline-flex items-center justify-center gap-2 rounded-lg bg-white px-5 py-3 text-[14px] font-semibold text-[var(--color-blue)] shadow-[0_8px_24px_rgba(10,15,46,0.2)] transition-transform hover:scale-[1.02]"
                  >
                    <Shuffle className="h-4 w-4" aria-hidden />
                    Quick 10 — random sample
                  </Link>
                  <Link
                    href="/products/orthoprep/quiz"
                    className="inline-flex items-center justify-center gap-2 rounded-lg border border-white/25 bg-white/10 px-5 py-3 text-[14px] font-semibold text-white transition-colors hover:bg-white/15"
                  >
                    <PlayCircle className="h-4 w-4" aria-hidden />
                    All quiz modes
                  </Link>
                </div>
              </div>

              {/* Inline sub-links that sit inside the hero rather than floating above it */}
              <div className="-mx-6 flex flex-wrap items-center gap-x-6 gap-y-2 border-t border-white/15 px-6 py-3 text-[12px] font-semibold text-white/80 md:-mx-10 md:px-10">
                <Link
                  href="/products/orthoprep"
                  className="inline-flex items-center gap-1 hover:text-white"
                >
                  <ChevronRight className="h-3 w-3 rotate-180" aria-hidden />
                  Back to OrthoPrep
                </Link>
                <Link
                  href="/products/orthoprep/stats"
                  className="inline-flex items-center gap-1 hover:text-white"
                >
                  <BarChart3 className="h-3 w-3" aria-hidden />
                  Your progress
                </Link>
                <span className="inline-flex items-center gap-1.5 text-white/70">
                  <User className="h-3 w-3" aria-hidden />
                  {bank.author}
                </span>
              </div>
            </div>

            {/* KPI strip at the bottom of the hero card, dashboard-style. */}
            <div className="relative grid grid-cols-2 gap-px bg-white/15 md:grid-cols-4">
              {stats.map((s) => (
                <div
                  key={s.label}
                  className="flex flex-col gap-3 bg-[var(--color-blue)] px-5 py-5 md:px-8 md:py-7"
                >
                  <div className="flex items-center gap-2">
                    <span className="flex h-7 w-7 items-center justify-center rounded-md bg-white/15 text-white ring-1 ring-inset ring-white/20">
                      <s.Icon className="h-[14px] w-[14px]" aria-hidden />
                    </span>
                    <span className="text-[10px] font-bold uppercase tracking-[0.2em] text-white/85">
                      {s.label}
                    </span>
                  </div>
                  <div className="font-display text-[36px] font-extrabold leading-none tracking-[-0.02em] text-white tabular-nums md:text-[40px]">
                    {s.value}
                  </div>
                </div>
              ))}
            </div>
          </div>
        </Container>
      </section>

      {/* Anchor nav — horizontal pill strip, sticky on scroll so readers can jump
          across the full set of parts without scrolling back to the top. */}
      <div className="sticky top-0 z-20 border-y border-[var(--color-line)] bg-white/90 backdrop-blur supports-[backdrop-filter]:bg-white/75">
        <Container>
          <nav
            aria-label="Part navigation"
            className="-mx-4 flex snap-x snap-mandatory overflow-x-auto scroll-smooth px-4 py-3 sm:-mx-6 sm:px-6 lg:-mx-8 lg:px-8"
          >
            <div className="flex items-center gap-1.5 text-[11px] font-bold uppercase tracking-[0.15em] text-[var(--color-slate)]">
              <span className="shrink-0 pr-2">Jump to</span>
            </div>
            <div className="flex flex-nowrap items-center gap-1.5">
              {parts.map((part, idx) => (
                <a
                  key={part.slug}
                  href={`#${part.slug}`}
                  className="snap-start inline-flex shrink-0 items-center gap-2 rounded-full border border-[var(--color-line)] bg-white px-3 py-1.5 text-[12px] font-semibold text-[var(--color-ink)] transition-colors hover:border-[var(--color-blue)] hover:bg-[var(--color-mist)] hover:text-[var(--color-blue)]"
                >
                  <span className="inline-flex h-5 min-w-[20px] items-center justify-center rounded-full bg-[var(--color-mist)] px-1.5 text-[10px] font-bold text-[var(--color-blue)]">
                    {String(idx + 1).padStart(2, "0")}
                  </span>
                  <span className="truncate">{part.title.replace(/^Part\s+\w+:\s*/i, "")}</span>
                  <span className="text-[11px] text-[var(--color-slate)]">
                    {part.questionCount}
                  </span>
                </a>
              ))}
            </div>
          </nav>
        </Container>
      </div>

      <Container className="py-10 md:py-14">
        {/* Part browser — richer cards with a quantity bar so readers can see at a
            glance which parts are the heaviest. */}
        <section className="mb-14">
          <div className="flex flex-wrap items-end justify-between gap-4">
            <div>
              <div className="text-[11px] font-bold uppercase tracking-[0.18em] text-[var(--color-blue)]">
                Part browser
              </div>
              <h2 className="mt-2 font-display text-[28px] font-extrabold leading-tight tracking-[-0.02em] text-[var(--color-ink)] md:text-[34px]">
                {parts.length} parts · {totalChapters} chapters
              </h2>
              <p className="mt-2 max-w-2xl text-[15px] leading-relaxed text-[var(--color-slate)]">
                Expand any card to see its chapters. Start a quiz directly, or
                jump to the part's question previews below.
              </p>
            </div>
            <Link
              href="/products/orthoprep/quiz"
              className="hidden shrink-0 items-center gap-1 rounded-lg border border-[var(--color-line)] bg-white px-4 py-2 text-[13px] font-semibold text-[var(--color-ink)] transition-colors hover:border-[var(--color-blue)] hover:text-[var(--color-blue)] md:inline-flex"
            >
              Quiz modes
              <ChevronRight className="h-3.5 w-3.5" aria-hidden />
            </Link>
          </div>

          <div className="mt-6 grid gap-4 md:grid-cols-2">
            {parts.map((part, i) => (
              <div key={part.slug} className="relative">
                {/* Progress-bar style fill indicating relative size of this part */}
                <div
                  aria-hidden
                  className="absolute inset-x-0 bottom-0 h-1 overflow-hidden rounded-b-xl bg-[var(--color-line)]"
                >
                  <div
                    className="h-full bg-[var(--color-blue)] transition-all"
                    style={{
                      width: `${(part.questionCount / maxQuestionsPerPart) * 100}%`,
                    }}
                  />
                </div>
                <PartBrowserCard part={part} index={i} />
              </div>
            ))}
          </div>
        </section>

        {/* Question previews — all parts as collapsible <details> to keep the
            page navigable. Each part opens to reveal its chapters and a handful
            of preview questions per chapter. */}
        <section>
          <div className="text-[11px] font-bold uppercase tracking-[0.18em] text-[var(--color-blue)]">
            Question previews
          </div>
          <h2 className="mt-2 font-display text-[28px] font-extrabold leading-tight tracking-[-0.02em] text-[var(--color-ink)] md:text-[34px]">
            First {PREVIEW_PER_CHAPTER} questions from every chapter
          </h2>
          <p className="mt-2 max-w-2xl text-[15px] leading-relaxed text-[var(--color-slate)]">
            The full bank is available in quiz mode. Each part is collapsed by
            default — expand the ones you want to preview.
          </p>

          <div className="mt-8 space-y-3">
            {bank.parts.map((part, partIdx) => {
              const partSlug = slugifyFrcs(part.title);
              const partSummary = parts[partIdx];
              return (
                <details
                  key={part.title}
                  id={partSlug}
                  className="group scroll-mt-24 overflow-hidden rounded-2xl border border-[var(--color-line)] bg-white open:shadow-[0_16px_40px_rgba(10,15,46,0.06)]"
                >
                  <summary className="flex cursor-pointer list-none items-center justify-between gap-4 px-6 py-5 transition-colors hover:bg-[var(--color-mist)]/40 [&::-webkit-details-marker]:hidden">
                    <div className="flex min-w-0 items-center gap-4">
                      <span className="inline-flex h-10 w-10 shrink-0 items-center justify-center rounded-lg bg-[var(--color-mist)] font-display text-[13px] font-extrabold text-[var(--color-blue)]">
                        {String(partIdx + 1).padStart(2, "0")}
                      </span>
                      <div className="min-w-0">
                        <div className="truncate font-display text-[18px] font-extrabold tracking-tight text-[var(--color-ink)] md:text-[20px]">
                          {part.title}
                        </div>
                        <div className="mt-0.5 text-[12px] font-semibold uppercase tracking-wider text-[var(--color-slate)]">
                          {partSummary.chapterCount} chapters ·{" "}
                          {partSummary.questionCount} questions
                        </div>
                      </div>
                    </div>
                    <div className="flex shrink-0 items-center gap-3">
                      <Link
                        href={`/products/orthoprep/quiz/session?mode=part&part=${partSlug}`}
                        className="hidden items-center gap-1 rounded-lg bg-[var(--color-blue)] px-3 py-1.5 text-[12px] font-semibold text-white transition-colors hover:bg-[var(--color-blue-deep)] sm:inline-flex"
                      >
                        Quiz this part →
                      </Link>
                      <ChevronRight
                        className="h-5 w-5 text-[var(--color-slate)] transition-transform group-open:rotate-90"
                        aria-hidden
                      />
                    </div>
                  </summary>

                  <div className="border-t border-[var(--color-line)] bg-[var(--color-line)]/10 px-6 pb-8 pt-4">
                    {part.chapters.map((chapter) => {
                      const chapterSlug = slugifyFrcs(chapter.title);
                      const previewed = chapter.questions.slice(
                        0,
                        PREVIEW_PER_CHAPTER,
                      );
                      const remaining =
                        chapter.questions.length - previewed.length;
                      return (
                        <div
                          key={chapter.title}
                          id={chapterSlug}
                          className="mt-8 scroll-mt-24 first:mt-4"
                        >
                          <div className="flex flex-wrap items-baseline justify-between gap-2">
                            <h3 className="font-display text-[18px] font-extrabold tracking-tight text-[var(--color-ink)]">
                              {chapter.title}
                            </h3>
                            <span className="text-[11px] font-bold uppercase tracking-wider text-[var(--color-blue)]">
                              {chapter.range} · {chapter.questions.length}{" "}
                              questions
                            </span>
                          </div>

                          <div className="mt-4 space-y-3">
                            {previewed.map((q) => (
                              <article
                                key={q.number}
                                className="overflow-hidden rounded-xl border border-[var(--color-line)] bg-white transition-[border-color,box-shadow] hover:border-[var(--color-blue)]/40"
                              >
                                <div className="flex items-start gap-4 border-l-[3px] border-[var(--color-blue)] p-5">
                                  <span className="inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-[var(--color-mist)] font-display text-[12px] font-extrabold text-[var(--color-blue)]">
                                    {q.number}
                                  </span>
                                  <div className="min-w-0 flex-1">
                                    <p className="text-[15.5px] leading-relaxed text-[var(--color-ink)]">
                                      {q.stem}
                                    </p>
                                    {q.options.length > 0 && (
                                      <ol
                                        className="mt-4 space-y-1.5 pl-6 text-[14.5px] leading-relaxed text-[var(--color-slate)] marker:font-semibold marker:text-[var(--color-blue)]"
                                        style={{ listStyleType: "upper-alpha" }}
                                      >
                                        {q.options.map((opt, oi) => {
                                          const stripped = opt.replace(
                                            /^[A-E][\.\)]\s*/,
                                            "",
                                          );
                                          return <li key={oi}>{stripped}</li>;
                                        })}
                                      </ol>
                                    )}
                                    {(q.answer || q.explanation) && (
                                      <details className="group/answer mt-4 border-t border-[var(--color-line)] pt-4">
                                        <summary className="flex cursor-pointer list-none items-center gap-2 text-[13px] font-semibold text-[var(--color-blue)] [&::-webkit-details-marker]:hidden">
                                          <svg
                                            viewBox="0 0 24 24"
                                            fill="none"
                                            stroke="currentColor"
                                            strokeWidth="2"
                                            strokeLinecap="round"
                                            className="h-4 w-4 transition-transform group-open/answer:rotate-45"
                                          >
                                            <path d="M12 5v14M5 12h14" />
                                          </svg>
                                          Reveal answer &amp; explanation
                                        </summary>
                                        {q.answer && (
                                          <p className="mt-3 inline-flex items-center gap-2 rounded-md bg-emerald-50 px-3 py-1.5 text-[13px] font-bold text-emerald-700 ring-1 ring-emerald-200">
                                            Answer · {q.answer}
                                          </p>
                                        )}
                                        {q.explanation && (
                                          <p className="mt-3 text-[14px] leading-relaxed text-[var(--color-ink)]/85">
                                            {q.explanation}
                                          </p>
                                        )}
                                        {q.takeHome && (
                                          <p className="mt-3 rounded-md border border-[var(--color-line)] bg-[var(--color-mist)]/40 px-3 py-2 text-[13px] leading-relaxed text-[var(--color-ink)]">
                                            <strong className="font-bold">Take-home:</strong>{" "}
                                            {q.takeHome}
                                          </p>
                                        )}
                                      </details>
                                    )}
                                  </div>
                                </div>
                              </article>
                            ))}

                            {remaining > 0 && (
                              <div className="flex flex-wrap items-center justify-between gap-3 rounded-xl border border-dashed border-[var(--color-line)] bg-white px-4 py-3 text-[13px] text-[var(--color-slate)]">
                                <span>
                                  + {remaining} more question
                                  {remaining === 1 ? "" : "s"} in this chapter
                                </span>
                                <Link
                                  href={`/products/orthoprep/quiz/session?mode=part&part=${partSlug}`}
                                  className="inline-flex items-center gap-1 font-semibold text-[var(--color-blue)] hover:underline"
                                >
                                  Start quiz
                                  <ChevronRight className="h-3.5 w-3.5" aria-hidden />
                                </Link>
                              </div>
                            )}
                          </div>
                        </div>
                      );
                    })}
                  </div>
                </details>
              );
            })}
          </div>
        </section>
      </Container>
    </>
  );
}
