// Scoliosis section — Schroth-informed Pilates protocol
// Exposes window.ScoliosisSection. Mounted by the member gate in index.html.
// Content data (concepts, LS patterns, 5-phase protocol) is member-gated — it
// is fetched from /api/scoliosis and passed in as the `data` prop.

(function() {
  const { useState, 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; }

  /* SVG: 3C — three blocks (shoulders, thorax, pelvis) with thoracic-only curve */
  function Pattern3C() {
    return (
      <svg viewBox="0 0 100 160" preserveAspectRatio="xMidYMid meet">
        <line x1="50" y1="6" x2="50" y2="156" className="scoli-svg-axis"/>
        {/* Head */}
        <circle cx="48" cy="14" r="6" className="scoli-svg-block-l"/>
        {/* Block 1: shoulders */}
        <rect x="32" y="22" width="36" height="18" rx="2" className="scoli-svg-block-l"/>
        {/* Block 2: thorax — offset to RIGHT (convex side) */}
        <rect x="42" y="44" width="38" height="44" rx="2" className="scoli-svg-block-r"/>
        {/* Block 3: pelvis — offset to LEFT */}
        <rect x="28" y="94" width="38" height="22" rx="2" className="scoli-svg-block-l"/>
        {/* Spine — single C curve through */}
        <path d="M50,24 C 50,38 70,55 70,72 C 70,90 44,98 44,116" className="scoli-svg-spine-c"/>
        {/* Legs (subtle) */}
        <line x1="38" y1="118" x2="38" y2="152" className="scoli-svg-spine"/>
        <line x1="56" y1="118" x2="56" y2="152" className="scoli-svg-spine"/>
        {/* Block labels */}
        <text x="6" y="33" className="scoli-svg-label">1</text>
        <text x="86" y="68" className="scoli-svg-label" fill="var(--accent)">2</text>
        <text x="6" y="108" className="scoli-svg-label">3</text>
      </svg>
    );
  }

  /* SVG: 4C — four blocks (shoulders, thorax, lumbar, pelvis) with double curve */
  function Pattern4C() {
    return (
      <svg viewBox="0 0 100 160" preserveAspectRatio="xMidYMid meet">
        <line x1="50" y1="6" x2="50" y2="156" className="scoli-svg-axis"/>
        {/* Head */}
        <circle cx="52" cy="14" r="6" className="scoli-svg-block-l"/>
        {/* Block 1: shoulders */}
        <rect x="32" y="22" width="36" height="14" rx="2" className="scoli-svg-block-l"/>
        {/* Block 2: thorax — RIGHT */}
        <rect x="44" y="40" width="36" height="32" rx="2" className="scoli-svg-block-r"/>
        {/* Block 3: lumbar — LEFT */}
        <rect x="22" y="76" width="36" height="24" rx="2" className="scoli-svg-block-r"/>
        {/* Block 4: pelvis — RIGHT (counter-rotated against lumbar) */}
        <rect x="38" y="104" width="36" height="16" rx="2" className="scoli-svg-block-l"/>
        {/* Spine — S curve through */}
        <path d="M52,24 C 52,38 70,52 70,60 C 70,72 32,80 32,92 C 32,102 56,108 56,120" className="scoli-svg-spine-c"/>
        {/* Legs */}
        <line x1="44" y1="122" x2="44" y2="152" className="scoli-svg-spine"/>
        <line x1="62" y1="122" x2="62" y2="152" className="scoli-svg-spine"/>
        {/* Labels */}
        <text x="6" y="30" className="scoli-svg-label">1</text>
        <text x="86" y="56" className="scoli-svg-label" fill="var(--accent)">2</text>
        <text x="6" y="92" className="scoli-svg-label" fill="var(--accent)">3</text>
        <text x="86" y="116" className="scoli-svg-label">4</text>
      </svg>
    );
  }

  const PATTERN_FIGS = { "3c": Pattern3C, "4c": Pattern4C };

  function ScoliosisSection({ data }) {
    const lang = useLang();
    const concepts = (data && data.concepts) || [];
    const patterns = (data && data.patterns) || [];
    const phases = (data && data.phases) || [];
    return (
      <div className="scoli-wrap">
        <p className="scoli-lede">
          {lang === "th" ? (
            <>โปรแกรมดูแล <em>กระดูกสันหลังคด</em> — จริงๆ มันคือการที่กระดูกสันหลังเราบิดผิดรูปไปในหลายมิตินะ ทั้งเอียงด้านข้าง (Frontal), บิดหมุน (Transverse) และเสียโค้งธรรมชาติด้านข้าง (Sagittal) ผู้ป่วย <em>80–90%</em> ไม่ทราบสาเหตุ มักเกิดและลุกลามตอนวัยรุ่นที่กระดูกกำลังโต ครูพิลาทิสวินิจฉัยหรือเปลี่ยนโครงสร้างกระดูกไม่ได้นะ แต่เป้าหมายคือออกแบบการเคลื่อนไหวเพื่อช่วยจัดแนวกระดูกให้กลับมาตรงขึ้น ฝึกให้เรารู้ทันสรีระตัวเอง และปรับกล้ามเนื้อให้กลับมาสมดุลกันค่ะ</>
          ) : (
            <>Scoliosis is a <em>three-dimensional deformity</em> of the spine — lateral deviation (frontal), vertebral rotation (transverse), and a loss of the natural sagittal curves. <em>80–90%</em> of cases are idiopathic, typically appearing and progressing during adolescent growth. Pilates instructors cannot diagnose or change bony structure, but movement can be designed to restore vertical alignment, build awareness, and rebalance the muscles.</>
          )}
        </p>

        {/* Key concepts */}
        <div className="scoli-concepts">
          {concepts.map((c, i) => (
            <div key={i} className="scoli-concept">
              <div className="scoli-concept-label">{pick(c.label, lang)}</div>
              <div className="scoli-concept-name">{pick(c.name, lang)}</div>
              <div className="scoli-concept-text">{pick(c.text, lang)}</div>
            </div>
          ))}
        </div>

        {/* LS Patterns */}
        <div className="scoli-section-head">
          <span className="scoli-section-num">{lang === "th" ? "// การจำแนกแบบ Lehnert-Schroth" : "// Lehnert-Schroth classification"}</span>
          <span className="scoli-section-title">
            {lang === "th" ? <>รูปแบบ <em>3C · 4C</em></> : <>The <em>3C · 4C</em> patterns</>}
          </span>
          <p className="scoli-section-blurb">
            {lang === "th"
              ? "รูปแบบความคดของหลัง — มีทั้งแบบ 3 โค้ง และ 4 โค้ง ซึ่งเราต้องรู้รูปแบบก่อนถึงจะแก้ได้ตรงจุดนะ คลินิกส่วนใหญ่ใช้ระบบนี้วางแผนการแก้ — แบ่งร่างกายเป็นก้อนๆ ที่บิดสวนทางกัน เพื่อจัดท่าแก้แบบ Schroth ได้แม่นยำ"
              : "The framework most clinics use to plan corrective work — counter-rotating body blocks that map directly to Schroth-style derotation cues."}
          </p>
        </div>

        <div className="scoli-patterns">
          {patterns.map(p => {
            const Fig = PATTERN_FIGS[p.id];
            return (
              <div key={p.id} className="scoli-pattern">
                <div className="scoli-pattern-fig">{Fig ? <Fig /> : null}</div>
                <div>
                  <div className="scoli-pattern-name">{pick(p.name, lang)}</div>
                  <div className="scoli-pattern-tag">// {pick(p.tag, lang)}</div>
                  <p className="scoli-pattern-chars">{pick(p.chars, lang)}</p>
                  <ul className="scoli-pattern-details">
                    {pick(p.details, lang).map((d, i) => <li key={i}>{d}</li>)}
                  </ul>
                </div>
              </div>
            );
          })}
        </div>

        {/* 5-Phase protocol */}
        <div className="scoli-section-head">
          <span className="scoli-section-num">{lang === "th" ? "// โปรแกรมพิลาทิส" : "// pilates protocol"}</span>
          <span className="scoli-section-title">
            {lang === "th" ? <>5 ขั้นตอนกู้คืนหลัง <em>ตามแนว Schroth</em></> : <>Five phases · <em>Schroth-informed</em></>}
          </span>
          <p className="scoli-section-blurb">
            {lang === "th"
              ? "ลำดับการฝึกที่ออกแบบมาเพื่อคนหลังคดโดยเฉพาะนะ — เริ่มจากลดแรงกดทับ ฝึกหายใจเข้าฝั่งที่ปอดโดนเบียด เพิ่มความยืดหยุ่น แล้วค่อยปรับสมดุลกล้ามเนื้อกัน"
              : "A staged sequence built for scoliotic spines — decompress first, breathe into the concave lung, mobilize the curve, then rebalance the muscles asymmetrically."}
          </p>
        </div>

        <div className="scoli-protocol">
          {phases.map(ph => (
            <div key={ph.num} className="scoli-phase">
              <div className="scoli-phase-num">{ph.num}</div>
              <div className="scoli-phase-body">
                <div className="scoli-phase-title">{pick(ph.title, lang)}</div>
                <div className="scoli-phase-tag">// {pick(ph.tag, lang)}</div>
                <p className="scoli-phase-text">{pick(ph.text, lang)}</p>
              </div>
              <div className="scoli-phase-ex">
                <div className="scoli-phase-ex-label">{lang === "th" ? "// ท่าที่แนะนำ" : "// recommended exercises"}</div>
                <ul className="scoli-phase-ex-list">
                  {pick(ph.ex, lang).map((e, i) => {
                    // Entries can be plain strings or { text, exId } objects.
                    // When exId is set, clicking opens that exercise in the encyclopedia modal.
                    const isLink = e && typeof e === "object" && e.exId;
                    if (!isLink) {
                      return <li key={i}>{typeof e === "object" ? e.text : e}</li>;
                    }
                    const open = () => {
                      if (window.PilatesModal) {
                        window.PilatesModal.open("exercise", { id: e.exId, from: "scoliosis" });
                      }
                    };
                    return (
                      <li key={i}>
                        <button
                          type="button"
                          className="scoli-phase-ex-link"
                          onClick={open}
                          title={lang === "th" ? "เปิดการ์ดท่าฝึก" : "Open exercise card"}
                        >
                          <span>{e.text}</span>
                          <span className="scoli-phase-ex-arr">→</span>
                        </button>
                      </li>
                    );
                  })}
                </ul>
              </div>
            </div>
          ))}
        </div>

        <div className="scoli-disclaimer">
          <span className="scoli-disclaimer-mark">!</span>
          <span>
            {lang === "th"
              ? "ครูพิลาทิสไม่ใช่หมอวินิจฉัยนะ และเปลี่ยนโครงสร้างกระดูกหรือทดแทนการรักษาทางคลินิกไม่ได้ค่ะ โปรแกรมนี้เป็นแค่กรอบการเคลื่อนไหวที่ออกแบบมาทำงานร่วมกับแพทย์และนักกายภาพบำบัด"
              : "Pilates instructors are not diagnosticians; this work cannot change bony structure or replace clinical treatment. The protocol is a movement framework intended to complement medical care and physiotherapy."}
          </span>
        </div>
      </div>
    );
  }

  window.ScoliosisSection = ScoliosisSection;
})();
