// Interactive quiz — content generated from NotebookLM source materials.
// Mounts to #quiz-root

(function() {
  const { useState, useMemo, useEffect } = React;

  function useLang() {
    const [lang, setLang] = useState(window.PilatesI18n?.getLang() || "en");
    useEffect(() => window.PilatesI18n?.subscribe(setLang), []);
    return lang;
  }
  function pick(obj, lang) { return obj && typeof obj === "object" && obj[lang] !== undefined ? obj[lang] : obj?.en ?? obj; }

  /* ════════════════════════════════════════════════════
     QUIZ DATA — sourced from NotebookLM, written as multiple-choice
     ════════════════════════════════════════════════════ */
  const QUESTIONS = [
    // ── Notebook 1: Pilates / Anatomy / Posture / Scoliosis (10) ──
    {
      cat: "physiology",
      q: {
        en: "What type of muscle contraction occurs when the muscle lengthens while actively producing tension?",
        th: "การหดตัวของกล้ามเนื้อแบบใดเกิดขึ้นเมื่อกล้ามเนื้อยืดยาวออกขณะที่ยังสร้างแรงตึง?",
      },
      opts: {
        en: ["Concentric contraction", "Eccentric contraction", "Isometric contraction", "Isokinetic contraction"],
        th: ["Concentric (หดสั้น)", "Eccentric (ยืดยาว)", "Isometric (คงที่)", "Isokinetic (ความเร็วคงที่)"],
      },
      a: 1,
      e: {
        en: "An eccentric contraction happens when the muscle lengthens while under tension — the body's braking system against gravity or resistance, critical for injury prevention and strength.",
        th: "Eccentric contraction เกิดขึ้นเมื่อกล้ามเนื้อยืดยาวขณะมีแรงตึง — เป็นระบบเบรกของร่างกายต้านแรงโน้มถ่วงหรือแรงต้าน สำคัญต่อการป้องกันการบาดเจ็บและการสร้างความแข็งแรง",
      },
    },
    {
      cat: "biomechanics",
      q: {
        en: "Which lever system is most common in the human body, with the effort applied between the fulcrum and the load?",
        th: "ระบบคานชนิดใดพบมากที่สุดในร่างกายมนุษย์ โดยมีจุดออกแรงอยู่ระหว่างจุดหมุนและน้ำหนัก?",
      },
      opts: {
        en: ["First-class lever", "Second-class lever", "Third-class lever", "Fourth-class lever"],
        th: ["คานชั้นที่ 1", "คานชั้นที่ 2", "คานชั้นที่ 3", "คานชั้นที่ 4"],
      },
      a: 2,
      e: {
        en: "The body is dominated by third-class levers (e.g. biceps at the elbow). They trade mechanical disadvantage for speed and range of motion.",
        th: "ร่างกายส่วนใหญ่ใช้คานชั้นที่ 3 (เช่น Biceps ที่ข้อศอก) แลกข้อเสียเปรียบเชิงกลกับความเร็วและช่วงการเคลื่อนไหวที่กว้าง",
      },
    },
    {
      cat: "posture",
      q: {
        en: "Which postural archetype features forward head, thoracic hyper-kyphosis, hyper-lordosis, and anterior pelvic tilt?",
        th: "ท่าทางต้นแบบแบบใดมีลักษณะ ศีรษะยื่นหน้า หลังบนค่อมมาก เอวแอ่นมาก และเชิงกรานเอียงไปหน้า?",
      },
      opts: {
        en: ["Flat Back Posture", "Sway Back Posture", "Ideal Posture", "Kypho-Lordosis Posture"],
        th: ["Flat Back (หลังแบน)", "Sway Back (สะโพกยื่นหน้า)", "Ideal (ในอุดมคติ)", "Kypho-Lordosis (หลังค่อม-แอ่นเอว)"],
      },
      a: 3,
      e: {
        en: "Kypho-Lordosis presents with a forward head, exaggerated upper-back curve, excessive lumbar arch, and anterior pelvic tilt.",
        th: "Kypho-Lordosis แสดงด้วยศีรษะยื่นหน้า โค้งหลังบนมากเกิน เอวแอ่นมากเกิน และเชิงกรานเอียงไปหน้า",
      },
    },
    {
      cat: "pilates",
      q: {
        en: "In STOTT PILATES, what is the primary purpose of Lateral Rib Cage Breathing?",
        th: "ในระบบ STOTT PILATES จุดประสงค์หลักของการหายใจขยายซี่โครงด้านข้าง (Lateral Rib Cage Breathing) คืออะไร?",
      },
      opts: {
        en: [
          "Expand the abdomen forward and relax the core entirely",
          "Expand the ribs anteriorly, laterally, and posteriorly while keeping TVA engaged",
          "Elevate the shoulders and lift the rib cage toward the ears",
          "Flatten the lumbar spine into the mat",
        ],
        th: [
          "ขยายหน้าท้องไปข้างหน้าและคลายแกนกลางทั้งหมด",
          "ขยายซี่โครงไปด้านหน้า ด้านข้าง และด้านหลัง โดย TVA ยังคงทำงาน",
          "ยกไหล่และดันซี่โครงขึ้นไปทางหู",
          "กดเอวให้แบนราบกับเสื่อ",
        ],
      },
      a: 1,
      e: {
        en: "Lateral rib cage breathing draws breath into the sides and back of the ribcage while the transversus abdominis stays engaged — stabilizing the lumbo-pelvic region under load.",
        th: "การหายใจด้านข้างนำลมหายใจไปยังด้านข้างและด้านหลังของซี่โครง โดย Transversus abdominis ยังคงทำงาน — ค้ำยันแกน Lumbo-pelvic ภายใต้แรงโหลด",
      },
    },
    {
      cat: "pilates",
      q: {
        en: "What is the standard breathing pattern for the Hundred on the Reformer?",
        th: "รูปแบบการหายใจมาตรฐานของท่า Hundred บน Reformer คืออะไร?",
      },
      opts: {
        en: [
          "Inhale 5 counts, Exhale 5 counts",
          "Inhale 10 counts, Exhale 10 counts",
          "Inhale 3 counts, Exhale 7 counts",
          "Continuous breath, no count",
        ],
        th: [
          "หายใจเข้า 5 จังหวะ ออก 5 จังหวะ",
          "หายใจเข้า 10 จังหวะ ออก 10 จังหวะ",
          "หายใจเข้า 3 จังหวะ ออก 7 จังหวะ",
          "หายใจต่อเนื่อง ไม่นับจังหวะ",
        ],
      },
      a: 0,
      e: {
        en: "The Hundred uses 5-count inhales and 5-count exhales paired with small arm pulses — 10 sets = 100 counts.",
        th: "ท่า Hundred ใช้การหายใจเข้า 5 จังหวะ ออก 5 จังหวะ พร้อมกับการปั๊มแขนเล็กๆ — 10 รอบ รวม 100 จังหวะ",
      },
    },
    {
      cat: "scoliosis",
      q: {
        en: "In the Augmented Lehnert-Schroth (ALS) classification, what does the 3CH pattern indicate?",
        th: "ในการจำแนกแบบ Augmented Lehnert-Schroth (ALS) รูปแบบ 3CH บ่งบอกถึงอะไร?",
      },
      opts: {
        en: [
          "3-curve functional scoliosis with a balanced pelvis and no hip prominence",
          "4-curve functional scoliosis with a major lumbar curvature",
          "3-curve functional scoliosis with significant hip prominence on the thoracic concave side",
          "4-curve functional scoliosis with a major thoracolumbar curvature",
        ],
        th: [
          "Scoliosis 3 ความโค้งโดยเชิงกรานสมดุล ไม่มีสะโพกยื่น",
          "Scoliosis 4 ความโค้งที่มีความโค้งหลักที่เอว",
          "Scoliosis 3 ความโค้งโดยมีสะโพกยื่นชัดเจนในด้านเว้าของทรวงอก",
          "Scoliosis 4 ความโค้งที่มีความโค้งหลักที่ Thoracolumbar",
        ],
      },
      a: 2,
      e: {
        en: "3CH = 3-curve functional scoliosis with Hip prominence. A long thoracic curve plus significant hip prominence on the thoracic concave side.",
        th: "3CH = Scoliosis 3 ความโค้งที่มี Hip prominence (สะโพกยื่น) ความโค้งทรวงอกยาว ร่วมกับสะโพกยื่นชัดเจนในด้านเว้าของทรวงอก",
      },
    },
    {
      cat: "posture",
      q: {
        en: "Which biomechanical pattern is most directly associated with Dynamic Valgus during loaded movements like squats?",
        th: "รูปแบบทางชีวกลศาสตร์ใดสัมพันธ์โดยตรงที่สุดกับ Dynamic Valgus ขณะรับแรงโหลด เช่น การ Squat?",
      },
      opts: {
        en: [
          "Femur external rotation with supinated feet",
          "Femur adduction and internal rotation, often from a weak gluteus medius",
          "Femur internal rotation with hyperextended elbows",
          "Hyperextended knees with extremely tight hamstrings",
        ],
        th: [
          "ต้นขาหมุนออกพร้อมเท้าหงาย",
          "ต้นขาหุบและหมุนเข้า มักเกิดจาก Gluteus medius อ่อนแรง",
          "ต้นขาหมุนเข้าพร้อมข้อศอกเหยียดแอ่น",
          "เข่าเหยียดแอ่นพร้อม Hamstrings ตึงมาก",
        ],
      },
      a: 1,
      e: {
        en: "Dynamic valgus is femur adduction + internal rotation during movement, driven by weakness in the gluteus medius and hip external rotators.",
        th: "Dynamic valgus คือต้นขาหุบและหมุนเข้าขณะเคลื่อนไหว เกิดจาก Gluteus medius และกล้ามเนื้อหมุนสะโพกออกอ่อนแรง",
      },
    },
    {
      cat: "physiology",
      q: {
        en: "In the sliding filament theory, which mineral binds to troponin to expose myosin-binding sites on actin?",
        th: "ในทฤษฎี Sliding Filament แร่ธาตุใดจับกับ Troponin เพื่อเปิดจุดเชื่อมของ Myosin บน Actin?",
      },
      opts: {
        en: ["Potassium", "Sodium", "Magnesium", "Calcium"],
        th: ["Potassium (โพแทสเซียม)", "Sodium (โซเดียม)", "Magnesium (แมกนีเซียม)", "Calcium (แคลเซียม)"],
      },
      a: 3,
      e: {
        en: "Calcium binds troponin (specifically troponin-C), shifting tropomyosin and exposing actin's myosin-binding sites — initiating the power stroke.",
        th: "Calcium จับกับ Troponin (Troponin-C) ทำให้ Tropomyosin เลื่อนและเปิดจุดเชื่อมของ Myosin บน Actin — เริ่มต้น Power-stroke",
      },
    },
    {
      cat: "anatomy",
      q: {
        en: "Which shoulder condition presents with a 'Painful Arc' specifically between 60° and 120° of abduction?",
        th: "ภาวะของหัวไหล่ใดที่แสดงอาการ 'Painful Arc' ในช่วงการกางแขน 60° ถึง 120° โดยเฉพาะ?",
      },
      opts: {
        en: ["Subacromial Impingement Syndrome", "Rotator Cuff Tear", "Anterior Shoulder Dislocation", "Scapular Winging"],
        th: ["Subacromial Impingement (เอ็นถูกหนีบใต้กระดูกไหปลาร้า)", "Rotator Cuff Tear (เอ็นข้อมือหมุนฉีก)", "Anterior Shoulder Dislocation (ไหล่หลุดด้านหน้า)", "Scapular Winging (สะบักยื่น)"],
      },
      a: 0,
      e: {
        en: "Subacromial impingement produces pain in the 60–120° abduction range as the rotator cuff is pinched under the acromion.",
        th: "Subacromial Impingement ทำให้เกิดอาการเจ็บในช่วงกางแขน 60–120° เนื่องจาก Rotator Cuff ถูกหนีบใต้กระดูก Acromion",
      },
    },
    {
      cat: "posture",
      q: {
        en: "What is the primary focus of the Standing Roll Down movement assessment?",
        th: "จุดโฟกัสหลักของการประเมินการเคลื่อนไหวด้วยท่า Standing Roll Down คืออะไร?",
      },
      opts: {
        en: [
          "Maximum cardiovascular endurance",
          "Range of motion strictly in the glenohumeral joint",
          "Spinal segmentation ability and compensation patterns",
          "Concentric strength of the quadriceps",
        ],
        th: [
          "ความทนทานของระบบหัวใจและหลอดเลือดสูงสุด",
          "ช่วงการเคลื่อนไหวเฉพาะข้อต่อ Glenohumeral",
          "ความสามารถในการขยับกระดูกสันหลังทีละข้อและรูปแบบการชดเชย",
          "ความแข็งแรงแบบ Concentric ของกล้ามเนื้อต้นขาด้านหน้า",
        ],
      },
      a: 2,
      e: {
        en: "Standing Roll Down evaluates the ability to articulate the spine vertebra by vertebra and reveals muscular tension or compensation patterns.",
        th: "Standing Roll Down ประเมินความสามารถในการขยับกระดูกสันหลังทีละข้อ และเผยให้เห็นความตึงของกล้ามเนื้อหรือรูปแบบการชดเชย",
      },
    },

    // ── Notebook 2: Biomechanics / Physiology / Nervous system / Sport science (10) ──
    {
      cat: "biomechanics",
      q: {
        en: "What class of lever is a playground seesaw?",
        th: "ไม้กระดกในสนามเด็กเล่นเป็นคานชั้นที่เท่าไร?",
      },
      opts: {
        en: ["First-class lever", "Second-class lever", "Third-class lever", "Fourth-class lever"],
        th: ["คานชั้นที่ 1", "คานชั้นที่ 2", "คานชั้นที่ 3", "คานชั้นที่ 4"],
      },
      a: 0,
      e: {
        en: "A seesaw is a first-class lever — the axis (fulcrum) sits between the force and the resistance.",
        th: "ไม้กระดกเป็นคานชั้นที่ 1 — จุดหมุนอยู่ระหว่างจุดออกแรงและน้ำหนัก",
      },
    },
    {
      cat: "biomechanics",
      q: {
        en: "How do second-class and third-class levers differ?",
        th: "คานชั้นที่ 2 และคานชั้นที่ 3 แตกต่างกันอย่างไร?",
      },
      opts: {
        en: [
          "Second-class has the axis in the middle; third-class has the resistance in the middle",
          "Second-class favors force (resistance in middle); third-class favors distance/speed (force in middle)",
          "Second-class is for fine motor; third-class is for gross motor",
          "They are functionally identical and only the naming differs",
        ],
        th: [
          "ชั้นที่ 2 มีจุดหมุนตรงกลาง; ชั้นที่ 3 มีน้ำหนักตรงกลาง",
          "ชั้นที่ 2 ได้เปรียบเรื่องแรง (น้ำหนักตรงกลาง); ชั้นที่ 3 ได้เปรียบเรื่องระยะ/ความเร็ว (แรงตรงกลาง)",
          "ชั้นที่ 2 ใช้กล้ามเนื้อมัดเล็ก; ชั้นที่ 3 ใช้กล้ามเนื้อมัดใหญ่",
          "ทำงานเหมือนกัน ต่างเพียงชื่อเรียก",
        ],
      },
      a: 1,
      e: {
        en: "Second-class levers (resistance in the middle, like a wheelbarrow) favor force production. Third-class levers (force in the middle, like the biceps) favor speed and range.",
        th: "คานชั้นที่ 2 (น้ำหนักตรงกลาง เช่นรถเข็นปูน) ได้เปรียบเรื่องแรง คานชั้นที่ 3 (แรงตรงกลาง เช่น Biceps) ได้เปรียบเรื่องความเร็วและช่วงการเคลื่อนไหว",
      },
    },
    {
      cat: "biomechanics",
      q: {
        en: "What does a muscle's 'angle of pull' primarily determine?",
        th: "'มุมการดึง' ของกล้ามเนื้อ (Angle of pull) กำหนดอะไรเป็นหลัก?",
      },
      opts: {
        en: [
          "The maximum weight a muscle can lift",
          "The muscle's action — vertical pull elevates/depresses, horizontal pull retracts/protracts a segment",
          "The metabolic cost of the contraction",
          "Whether the contraction is concentric or eccentric",
        ],
        th: [
          "น้ำหนักสูงสุดที่กล้ามเนื้อยกได้",
          "การทำงานของกล้ามเนื้อ — แนวดิ่งทำให้ยก/กด แนวนอนทำให้ดึง/ดัน",
          "ต้นทุนพลังงานของการหดตัว",
          "การหดตัวเป็น Concentric หรือ Eccentric",
        ],
      },
      a: 1,
      e: {
        en: "A muscle's line of pull relative to the joint determines its action — a vertical line elevates/depresses, a horizontal line retracts/protracts.",
        th: "แนวการดึงของกล้ามเนื้อเทียบกับข้อต่อจะกำหนดการทำงาน — แนวดิ่งทำให้ยก/กด แนวนอนทำให้ดึง/ดัน",
      },
    },
    {
      cat: "physiology",
      q: {
        en: "What are the three types of muscle tissue in the human body?",
        th: "เนื้อเยื่อกล้ามเนื้อ 3 ประเภทในร่างกายมนุษย์มีอะไรบ้าง?",
      },
      opts: {
        en: [
          "Skeletal, cardiac, smooth",
          "Fast-twitch, slow-twitch, mixed",
          "Voluntary, involuntary, autonomic",
          "Type I, Type II, Type III",
        ],
        th: [
          "Skeletal (โครงร่าง), Cardiac (หัวใจ), Smooth (เรียบ)",
          "Fast-twitch (กระตุกเร็ว), Slow-twitch (กระตุกช้า), แบบผสม",
          "ภายใต้คำสั่ง, นอกคำสั่ง, อัตโนมัติ",
          "Type I, Type II, Type III",
        ],
      },
      a: 0,
      e: {
        en: "The three muscle tissues are skeletal (voluntary), cardiac (heart), and smooth (involuntary organ walls).",
        th: "เนื้อเยื่อกล้ามเนื้อ 3 ประเภทคือ Skeletal (โครงร่าง · ภายใต้คำสั่ง), Cardiac (หัวใจ), และ Smooth (ผนังอวัยวะ · นอกคำสั่ง)",
      },
    },
    {
      cat: "sport-science",
      q: {
        en: "What are the four classic domains of physical activity?",
        th: "โดเมนคลาสสิก 4 ประการของกิจกรรมทางกายมีอะไรบ้าง?",
      },
      opts: {
        en: [
          "Cardio, strength, flexibility, balance",
          "Domestic/household, transportation, occupational, leisure-time",
          "Aerobic, anaerobic, isometric, plyometric",
          "Walking, running, lifting, stretching",
        ],
        th: [
          "Cardio, ความแข็งแรง, ความยืดหยุ่น, การทรงตัว",
          "กิจกรรมในบ้าน, การเดินทาง, งานอาชีพ, เวลาว่าง",
          "Aerobic, Anaerobic, Isometric, Plyometric",
          "เดิน, วิ่ง, ยก, ยืด",
        ],
      },
      a: 1,
      e: {
        en: "Physical activity is classified into four domains: domestic, transportation, occupational, and leisure-time.",
        th: "กิจกรรมทางกายแบ่งเป็น 4 โดเมน: กิจกรรมในบ้าน การเดินทาง งานอาชีพ และเวลาว่าง",
      },
    },
    {
      cat: "physiology",
      q: {
        en: "What distinguishes active from passive muscle insufficiency?",
        th: "อะไรคือความแตกต่างระหว่าง Active กับ Passive muscle insufficiency?",
      },
      opts: {
        en: [
          "Active is voluntary; passive is involuntary",
          "Active happens during contraction; passive happens during rest",
          "Active = a muscle shortened over all its joints loses tension; Passive = a muscle stretched over all its joints can't lengthen further",
          "Active is concentric only; passive is eccentric only",
        ],
        th: [
          "Active คือภายใต้คำสั่ง; Passive คือนอกคำสั่ง",
          "Active เกิดขณะหดตัว; Passive เกิดขณะพัก",
          "Active = กล้ามเนื้อหดสั้นข้ามทุกข้อต่อแล้วเสียแรงตึง; Passive = กล้ามเนื้อยืดยาวข้ามทุกข้อต่อแล้วยืดต่อไม่ได้",
          "Active เป็น Concentric เท่านั้น; Passive เป็น Eccentric เท่านั้น",
        ],
      },
      a: 2,
      e: {
        en: "Active insufficiency: a multi-joint muscle contracts maximally over all its joints and loses tension. Passive insufficiency: it can't be stretched further over all its joints.",
        th: "Active insufficiency: กล้ามเนื้อข้ามหลายข้อต่อหดตัวสุดทุกข้อแล้วเสียแรงตึง · Passive insufficiency: ยืดต่อไม่ได้เพราะถูกยืดสุดทุกข้อต่อแล้ว",
      },
    },
    {
      cat: "nervous-system",
      q: {
        en: "What are the two main components of the central nervous system?",
        th: "ส่วนประกอบหลัก 2 อย่างของระบบประสาทส่วนกลาง (CNS) คืออะไร?",
      },
      opts: {
        en: [
          "Brain and spinal cord",
          "Cerebrum and cerebellum",
          "Sympathetic and parasympathetic",
          "Sensory and motor pathways",
        ],
        th: [
          "สมองและไขสันหลัง",
          "Cerebrum และ Cerebellum",
          "Sympathetic และ Parasympathetic",
          "เส้นทางรับความรู้สึกและเส้นทางสั่งการ",
        ],
      },
      a: 0,
      e: {
        en: "The central nervous system (CNS) comprises the brain and the spinal cord. Everything else is peripheral.",
        th: "ระบบประสาทส่วนกลาง (CNS) ประกอบด้วยสมองและไขสันหลัง ส่วนอื่นๆ ทั้งหมดเป็นระบบประสาทส่วนปลาย",
      },
    },
    {
      cat: "nervous-system",
      q: {
        en: "What is the clinical reflex pattern of upper vs lower motor neuron lesions?",
        th: "รูปแบบทางคลินิกของรีเฟล็กซ์ในรอยโรค Upper vs Lower motor neuron เป็นอย่างไร?",
      },
      opts: {
        en: [
          "Upper = hyperreflexia; Lower = hyporeflexia",
          "Upper = hyporeflexia; Lower = hyperreflexia",
          "Both present with hyperreflexia",
          "Both present with hyporeflexia",
        ],
        th: [
          "Upper = Hyperreflexia (มากเกิน); Lower = Hyporeflexia (น้อยเกิน)",
          "Upper = Hyporeflexia (น้อยเกิน); Lower = Hyperreflexia (มากเกิน)",
          "ทั้งคู่เป็น Hyperreflexia",
          "ทั้งคู่เป็น Hyporeflexia",
        ],
      },
      a: 0,
      e: {
        en: "Upper motor neuron lesions typically cause hyperreflexia (overactive reflexes). Lower motor neuron lesions cause hyporeflexia (underactive or absent reflexes).",
        th: "รอยโรค Upper motor neuron มักทำให้เกิด Hyperreflexia (รีเฟล็กซ์มากเกิน) · รอยโรค Lower motor neuron ทำให้เกิด Hyporeflexia (รีเฟล็กซ์น้อยหรือไม่มี)",
      },
    },
    {
      cat: "nervous-system",
      q: {
        en: "What distinguishes a withdrawal reflex from a crossed extensor reflex?",
        th: "อะไรคือความแตกต่างระหว่าง Withdrawal reflex กับ Crossed extensor reflex?",
      },
      opts: {
        en: [
          "Withdrawal occurs in adults only; crossed extensor in infants only",
          "Withdrawal is a 3-neuron arc, flexor contracts to withdraw the limb; Crossed extensor adds extension on the opposite side to support body weight",
          "They are the same reflex with different names",
          "Both reflexes involve all four limbs",
        ],
        th: [
          "Withdrawal เกิดในผู้ใหญ่เท่านั้น; Crossed extensor เกิดในทารกเท่านั้น",
          "Withdrawal เป็น 3-neuron arc กล้ามเนื้องอหดตัวดึงแขนขาออก · Crossed extensor เพิ่มการเหยียดของฝั่งตรงข้ามเพื่อพยุงน้ำหนักตัว",
          "เป็นรีเฟล็กซ์เดียวกัน แค่ชื่อต่าง",
          "ทั้งสองรีเฟล็กซ์เกี่ยวข้องกับแขนขาทั้ง 4 ข้าง",
        ],
      },
      a: 1,
      e: {
        en: "Withdrawal pulls the stimulated limb away via flexor contraction (3-neuron arc). Crossed extensor adds extension on the contralateral side so the body stays supported.",
        th: "Withdrawal ดึงแขนขาฝั่งที่ถูกกระตุ้นออกด้วยการหดของกล้ามเนื้องอ (3-neuron arc) · Crossed extensor เพิ่มการเหยียดของฝั่งตรงข้ามเพื่อพยุงร่างกาย",
      },
    },
    {
      cat: "sport-science",
      q: {
        en: "What was the impact of Title IX in the United States?",
        th: "Title IX มีผลกระทบอย่างไรในสหรัฐอเมริกา?",
      },
      opts: {
        en: [
          "Banned doping in college sports",
          "Prohibited sex-based discrimination in educational programs and significantly increased female participation in sports",
          "Required all schools to fund football programs",
          "Standardized the Olympic qualification process",
        ],
        th: [
          "ห้ามใช้สารกระตุ้นในกีฬาระดับมหาวิทยาลัย",
          "ห้ามการเลือกปฏิบัติทางเพศในโปรแกรมการศึกษา และเพิ่มการมีส่วนร่วมของผู้หญิงในกีฬาอย่างมาก",
          "บังคับให้ทุกโรงเรียนให้ทุนโปรแกรมฟุตบอล",
          "วางมาตรฐานกระบวนการคัดเลือกโอลิมปิก",
        ],
      },
      a: 1,
      e: {
        en: "Title IX (1972) prohibited sex-based discrimination in educational programs receiving federal funding — a turning point for female participation in sports.",
        th: "Title IX (1972) ห้ามการเลือกปฏิบัติทางเพศในโปรแกรมการศึกษาที่ได้รับทุนรัฐบาลกลาง — เป็นจุดเปลี่ยนสำคัญสำหรับการมีส่วนร่วมของผู้หญิงในวงการกีฬา",
      },
    },
  ];

  /* ════════════════════════════════════════════════════
     UI TEXT (small i18n surface)
     ════════════════════════════════════════════════════ */
  const TXT = {
    en: {
      lede: <>An <em>interactive quiz</em> drawn from the source materials. Pick a category and a length; answer one question at a time; review your score at the end.</>,
      questions: "Questions",
      categories: "Categories",
      questionsAvail: "available",
      catsAvail: "topics",
      filterCat: "// category",
      filterLen: "// length",
      all: "All",
      start: "Start Quiz →",
      questionOf: (n, t) => `Question ${n} of ${t}`,
      scoreSoFar: (s, t) => `${s} / ${t} correct`,
      explanation: "// Explanation",
      explanationWrong: "// Not quite",
      next: "Next →",
      finish: "Finish →",
      submit: "Submit",
      tryAgain: "↻ Try again",
      newQuiz: "← New quiz",
      result: "Quiz complete",
      yourScore: "Your score",
      out: "of",
      rank: { master: "Master · clinical fluency", practitioner: "Practitioner · solid foundation", apprentice: "Apprentice · keep building", learner: "Learner · the journey begins" },
      ranktext: {
        master: "Excellent. You're operating at a clinical level — keep refining the edges.",
        practitioner: "Solid. You've internalized the core concepts; the rest is sharpening detail.",
        apprentice: "Good start. Review the topics you missed and circle back.",
        learner: "Welcome to the practice. The deeper the dive, the clearer the picture.",
      },
      breakdown: "Topic breakdown",
      cats: {
        biomechanics: "Biomechanics",
        physiology: "Physiology",
        anatomy: "Anatomy",
        posture: "Posture",
        pilates: "Pilates Method",
        scoliosis: "Scoliosis",
        "nervous-system": "Nervous System",
        "sport-science": "Sport Science",
      },
    },
    th: {
      lede: <><em>แบบทดสอบลองวิชา</em> มาลองดูว่าเราเข้าใจร่างกายตัวเองดีแค่ไหน เลือกหัวข้อที่อยากลอง แล้วตอบทีละข้อ จบแล้วมาดูคะแนนกัน!</>,
      questions: "ข้อ",
      categories: "หัวข้อ",
      questionsAvail: "ทั้งหมด",
      catsAvail: "หัวข้อ",
      filterCat: "// หัวข้อ",
      filterLen: "// จำนวนข้อ",
      all: "ทั้งหมด",
      start: "เริ่มเลย →",
      questionOf: (n, t) => `ข้อ ${n} จาก ${t}`,
      scoreSoFar: (s, t) => `ถูก ${s} / ${t} ข้อ`,
      explanation: "// คำอธิบาย",
      explanationWrong: "// ยังไม่ถูกนะ",
      next: "ถัดไป →",
      finish: "เสร็จแล้ว →",
      submit: "ส่งคำตอบ",
      tryAgain: "↻ ทำใหม่",
      newQuiz: "← เริ่มชุดใหม่",
      result: "ทำเสร็จแล้ว!",
      yourScore: "คะแนนของคุณ",
      out: "จาก",
      rank: { master: "เซียนเลย · ระดับคลินิก", practitioner: "พื้นฐานแน่น", apprentice: "เริ่มเข้าทาง · ฝึกต่อไปนะ", learner: "เริ่มต้นได้ดีเลย" },
      ranktext: {
        master: "เก่งมากเลย! เข้าใจในระดับคลินิกเลยล่ะ มาขัดเกลารายละเอียดเล็กๆ กันต่อ",
        practitioner: "แน่นแล้วนะ แนวคิดหลักจับมือถือมือเลย เหลือแค่ลงรายละเอียด",
        apprentice: "เริ่มได้ดีเลย ทบทวนหัวข้อที่พลาดแล้วลองใหม่อีกทีนะ",
        learner: "ยินดีต้อนรับเข้าสู่การฝึก! ยิ่งลงลึก ภาพจะยิ่งชัดขึ้นนะ",
      },
      breakdown: "สรุปตามหัวข้อ",
      cats: {
        biomechanics: "ชีวกลศาสตร์",
        physiology: "สรีรวิทยา",
        anatomy: "กายวิภาค",
        posture: "ท่าทาง",
        pilates: "หลักพิลาทิส",
        scoliosis: "หลังคด",
        "nervous-system": "ระบบประสาท",
        "sport-science": "วิทยาศาสตร์การกีฬา",
      },
    },
  };
  function T(lang) { return TXT[lang] || TXT.en; }

  /* ════════════════════════════════════════════════════
     MAIN COMPONENT
     ════════════════════════════════════════════════════ */
  function shuffle(arr) {
    const a = arr.slice();
    for (let i = a.length - 1; i > 0; i--) {
      const j = Math.floor(Math.random() * (i + 1));
      [a[i], a[j]] = [a[j], a[i]];
    }
    return a;
  }

  function QuizSection() {
    const lang = useLang();
    const t = T(lang);
    const [phase, setPhase] = useState("start"); // 'start' | 'quiz' | 'result'
    const [catFilter, setCatFilter] = useState("all");
    const [lengthChoice, setLengthChoice] = useState(10);
    const [questions, setQuestions] = useState([]);
    const [idx, setIdx] = useState(0);
    const [selected, setSelected] = useState(null);
    const [answers, setAnswers] = useState([]); // [{qid, correct: bool, cat}]

    const cats = useMemo(() => Array.from(new Set(QUESTIONS.map(q => q.cat))), []);
    const filteredPool = useMemo(() =>
      catFilter === "all" ? QUESTIONS : QUESTIONS.filter(q => q.cat === catFilter),
    [catFilter]);

    function start() {
      const pool = shuffle(filteredPool);
      const take = lengthChoice === "all" ? pool : pool.slice(0, Math.min(lengthChoice, pool.length));
      setQuestions(take);
      setIdx(0); setSelected(null); setAnswers([]);
      setPhase("quiz");
    }
    function pickAnswer(i) {
      if (selected !== null) return;
      setSelected(i);
      const q = questions[idx];
      setAnswers(prev => [...prev, { cat: q.cat, correct: i === q.a }]);
    }
    function next() {
      if (idx + 1 >= questions.length) { setPhase("result"); return; }
      setIdx(idx + 1); setSelected(null);
    }
    function reset() { setPhase("start"); setIdx(0); setSelected(null); setAnswers([]); }
    function restart() {
      const pool = shuffle(questions);
      setQuestions(pool); setIdx(0); setSelected(null); setAnswers([]);
      setPhase("quiz");
    }

    /* ── START SCREEN ── */
    if (phase === "start") {
      return (
        <div className="quiz-wrap">
          <p className="quiz-lede">{t.lede}</p>
          <div className="quiz-start">
            <div>
              <div className="quiz-start-head">// {lang === "th" ? "แบบทดสอบ" : "the quiz"}</div>
              <div className="quiz-start-title">
                {lang === "th" ? <>มาลอง <em>วิชา</em> กัน</> : <>Test your <em>knowledge</em></>}
              </div>
              <p className="quiz-start-text">
                {lang === "th"
                  ? "แบบทดสอบลองวิชา — เลือกหัวข้อที่อยากลอง แล้วมาตอบดูว่าเราเข้าใจร่างกายตัวเองดีแค่ไหน ครอบคลุมชีวกลศาสตร์ สรีรวิทยา การวิเคราะห์ท่าทาง หลังคด หลักพิลาทิส และวิทยาศาสตร์การกีฬา"
                  : "An interactive quiz drawn from the curriculum — biomechanics, physiology, postural analysis, scoliosis, the Pilates method, and sport science."}
              </p>
              <div className="quiz-stats">
                <div>
                  <div className="quiz-stat-num">{QUESTIONS.length}</div>
                  <div className="quiz-stat-label">{t.questions} {t.questionsAvail}</div>
                </div>
                <div>
                  <div className="quiz-stat-num">{cats.length}</div>
                  <div className="quiz-stat-label">{t.catsAvail}</div>
                </div>
              </div>
            </div>
            <div className="quiz-options">
              <div className="quiz-opt-group">
                <div className="quiz-opt-label">{t.filterCat}</div>
                <div className="quiz-pills">
                  <button className="quiz-pill" data-active={catFilter === "all"} onClick={() => setCatFilter("all")}>{t.all}</button>
                  {cats.map(c => (
                    <button key={c} className="quiz-pill" data-active={catFilter === c} onClick={() => setCatFilter(c)}>
                      {t.cats[c] || c}
                    </button>
                  ))}
                </div>
              </div>
              <div className="quiz-opt-group">
                <div className="quiz-opt-label">{t.filterLen}</div>
                <div className="quiz-pills">
                  {[5, 10, 20, "all"].map(n => (
                    <button key={n} className="quiz-pill" data-active={lengthChoice === n} onClick={() => setLengthChoice(n)}>
                      {n === "all" ? (lang === "th" ? "ทั้งหมด" : "All") : n}
                    </button>
                  ))}
                </div>
              </div>
              <button className="quiz-start-cta" onClick={start} disabled={filteredPool.length === 0}>
                {t.start}
              </button>
            </div>
          </div>
        </div>
      );
    }

    /* ── QUESTION SCREEN ── */
    if (phase === "quiz") {
      const q = questions[idx];
      const scoreSoFar = answers.filter(a => a.correct).length;
      const isAnswered = selected !== null;
      const isCorrect = selected === q.a;
      return (
        <div className="quiz-wrap">
          <div className="quiz-question-wrap">
            <div className="quiz-progress">
              <div className="quiz-progress-bar">
                <div className="quiz-progress-fill" style={{width: `${((idx) / questions.length) * 100}%`}}/>
              </div>
              <div className="quiz-progress-text">{t.questionOf(idx + 1, questions.length)}</div>
              <div className="quiz-score-mini">{t.scoreSoFar(scoreSoFar, idx + (isAnswered ? 1 : 0))}</div>
            </div>

            <div className="quiz-q-meta">
              <div className="quiz-q-num">Q{String(idx + 1).padStart(2, "0")}</div>
              <div className="quiz-q-category">// {t.cats[q.cat] || q.cat}</div>
            </div>
            <div className="quiz-q-text">{pick(q.q, lang)}</div>

            <div className="quiz-answers">
              {pick(q.opts, lang).map((opt, i) => {
                let state;
                if (isAnswered) {
                  if (i === q.a) state = "correct";
                  else if (i === selected) state = "wrong";
                  else state = "dim";
                }
                return (
                  <button
                    key={i}
                    className="quiz-answer"
                    data-state={state}
                    disabled={isAnswered}
                    onClick={() => pickAnswer(i)}
                  >
                    <span className="quiz-answer-letter">{String.fromCharCode(65 + i)})</span>
                    <span className="quiz-answer-text">{opt}</span>
                  </button>
                );
              })}
            </div>

            {isAnswered && (
              <div className={"quiz-feedback" + (isCorrect ? "" : " wrong")}>
                <span className="quiz-feedback-label">{isCorrect ? t.explanation : t.explanationWrong}</span>
                {pick(q.e, lang)}
              </div>
            )}

            <div className="quiz-actions">
              <button className="quiz-btn ghost" onClick={reset}>{t.newQuiz}</button>
              {isAnswered && (
                <button className="quiz-btn accent" onClick={next}>
                  {idx + 1 >= questions.length ? t.finish : t.next}
                </button>
              )}
            </div>
          </div>
        </div>
      );
    }

    /* ── RESULT SCREEN ── */
    const total = answers.length;
    const correct = answers.filter(a => a.correct).length;
    const pct = total > 0 ? Math.round((correct / total) * 100) : 0;
    const rank = pct >= 90 ? "master" : pct >= 70 ? "practitioner" : pct >= 50 ? "apprentice" : "learner";
    const byCat = {};
    answers.forEach(a => {
      if (!byCat[a.cat]) byCat[a.cat] = { c: 0, n: 0 };
      byCat[a.cat].n++;
      if (a.correct) byCat[a.cat].c++;
    });
    return (
      <div className="quiz-wrap">
        <div className="quiz-result">
          <div className="quiz-result-score">
            <div className="quiz-result-score-num">{pct}<em>%</em></div>
            <div className="quiz-result-score-label">{t.yourScore} · {correct} {t.out} {total}</div>
            <div className="quiz-result-rank">{t.rank[rank]}</div>
          </div>
          <div className="quiz-result-details">
            <div className="quiz-result-eyebrow">// {t.result}</div>
            <div className="quiz-result-title">{t.rank[rank]}</div>
            <p className="quiz-result-text">{t.ranktext[rank]}</p>
            <div className="quiz-result-breakdown">
              <div className="quiz-breakdown-row" style={{borderBottom: "1px solid var(--rule-2)", paddingBottom: "8px", marginBottom: "4px"}}>
                <div className="quiz-breakdown-cat" style={{color: "var(--ink-3)", fontSize: "9px", letterSpacing: "0.16em", textTransform: "uppercase"}}>{t.breakdown}</div>
                <div className="quiz-breakdown-score" style={{color: "var(--ink-3)", fontSize: "9px", letterSpacing: "0.06em"}}>{lang === "th" ? "ถูก / ทั้งหมด" : "correct / total"}</div>
              </div>
              {Object.entries(byCat).map(([cat, s]) => (
                <div key={cat} className="quiz-breakdown-row">
                  <div className="quiz-breakdown-cat">{t.cats[cat] || cat}</div>
                  <div className="quiz-breakdown-score">{s.c} / {s.n}</div>
                </div>
              ))}
            </div>
            <div className="quiz-result-actions">
              <button className="quiz-btn accent" onClick={restart}>{t.tryAgain}</button>
              <button className="quiz-btn" onClick={reset}>{t.newQuiz}</button>
            </div>
          </div>
        </div>
      </div>
    );
  }

  const root = document.getElementById("quiz-root");
  if (root) ReactDOM.createRoot(root).render(<QuizSection />);
})();
