// 2TTEST landing — section components
// Reads globals from components.jsx (Icon, fmtBaht, etc.)

const {
  Icon, fmtBaht, pct, CATS,
  BannerPlaceholder, Section, LoginModal,
} = window;

// ───────── Top Nav (sticky) ─────────
function TopNav({ user, onRequireAuth }) {
  const [scrolled, setScrolled] = useState(false);
  const [mobileOpen, setMobileOpen] = useState(false);
  const [menuOpen, setMenuOpen] = useState(false);

  const onLogout = () => {
    if (!window.confirm("ออกจากระบบ?")) return;
    try {
      localStorage.removeItem("ttest_auth_token");
      localStorage.removeItem("ttest_user_data");
      localStorage.removeItem("ttest_user_name");
    } catch {}
    window.location.reload();
  };

  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 8);
    onScroll();
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  const links = [
    { href: "#courses",  label: "คอร์ส" },
    { href: "#packages", label: "แพ็กเกจ" },
    { href: "#reviews",  label: "รีวิว" },
    { href: "#faq",      label: "FAQ" },
  ];

  return (
    <header className={`sticky top-0 z-40 bg-white/85 backdrop-blur ${scrolled ? "nav-shadow" : ""}`}>
      <div className="max-w-7xl mx-auto px-5 sm:px-8 h-16 flex items-center justify-between">
        <a href="#top" className="flex items-center gap-2.5 group">
          <Icon.Logo size={30}/>
          <span className="font-extrabold tracking-tight text-[18px]">2TTEST</span>
          <span className="hidden md:inline text-[12px] text-[var(--muted)] th ml-1">ฝึกข้อสอบออนไลน์</span>
        </a>

        <nav className="hidden md:flex items-center gap-1">
          {links.map(l => (
            <a key={l.href} href={l.href}
               className="th px-3 py-2 rounded-lg text-[14px] font-semibold text-[var(--ink-2)] hover:bg-[var(--panel)]">
              {l.label}
            </a>
          ))}
        </nav>

        <div className="hidden md:flex items-center gap-2">
          {user ? (
            <div className="relative">
              <button
                onClick={() => setMenuOpen(v => !v)}
                className="flex items-center gap-2 px-3 py-2 rounded-lg hover:bg-[var(--panel)] th text-[13px] font-semibold">
                <span className="w-8 h-8 rounded-full bg-[var(--brand-50)] text-[var(--brand-700)] flex items-center justify-center font-bold">
                  {(user.name || "?").charAt(0).toUpperCase()}
                </span>
                <span className="hidden lg:inline">สวัสดี, {user.name}</span>
                <Icon.ChevDown width="14" height="14" />
              </button>
              {menuOpen && (
                <>
                  <div className="fixed inset-0 z-30" onClick={() => setMenuOpen(false)}></div>
                  <div className="absolute right-0 top-12 w-52 z-40 bg-white rounded-xl border border-[var(--line)] py-2"
                       style={{ boxShadow: "0 16px 40px -12px rgba(11,18,32,0.18)" }}>
                    <div className="px-4 py-2 border-b border-[var(--line)]">
                      <div className="text-[13px] font-semibold truncate">{user.name}</div>
                    </div>
                    <a href="/student-dashboard/" className="px-4 py-2 text-[13px] hover:bg-[var(--panel)] flex items-center gap-2"><Icon.Stack width="14" height="14"/>My Courses</a>
                    <div className="border-t border-[var(--line)] my-1"></div>
                    <button onClick={onLogout} className="w-full text-left px-4 py-2 text-[13px] text-[#DC2626] hover:bg-[#FEE2E2] font-semibold flex items-center gap-2">
                      <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"/><polyline points="16 17 21 12 16 7"/><line x1="21" y1="12" x2="9" y2="12"/></svg>
                      ออกจากระบบ
                    </button>
                  </div>
                </>
              )}
            </div>
          ) : (
            <>
              <a href="/auth/login.html" className="btn-ghost px-4 py-2 text-[14px] th">เข้าสู่ระบบ</a>
              <a href="/auth/register.html" className="btn-primary px-4 py-2 text-[14px] th">สมัครฟรี</a>
            </>
          )}
        </div>

        <button onClick={() => setMobileOpen(v => !v)}
                className="md:hidden p-2 -mr-2 rounded-lg hover:bg-[var(--panel)]" aria-label="เมนู">
          {mobileOpen ? <Icon.X width="22" height="22" /> : <Icon.Menu width="22" height="22" />}
        </button>
      </div>

      {/* Mobile drawer */}
      {mobileOpen && (
        <div className="md:hidden border-t border-[var(--line)] bg-white">
          <div className="px-5 py-4 flex flex-col gap-1">
            {links.map(l => (
              <a key={l.href} href={l.href} onClick={() => setMobileOpen(false)}
                 className="th px-3 py-3 rounded-lg text-[15px] font-semibold hover:bg-[var(--panel)]">{l.label}</a>
            ))}
            <div className="hairline my-2"/>
            {user ? (
              <div className="grid gap-2">
                <a href="/student-dashboard/" className="btn-primary px-4 py-3 text-center th">My Courses</a>
                <button onClick={onLogout} className="btn-ghost px-4 py-3 text-center th text-[#DC2626] font-semibold">ออกจากระบบ</button>
              </div>
            ) : (
              <div className="grid grid-cols-2 gap-2">
                <a href="/auth/login.html" className="btn-ghost px-4 py-3 text-center th">เข้าสู่ระบบ</a>
                <a href="/auth/register.html" className="btn-primary px-4 py-3 text-center th">สมัครฟรี</a>
              </div>
            )}
          </div>
        </div>
      )}
    </header>
  );
}

// ───────── Hero ─────────
function Hero({ variant = "split", stats }) {
  const head = (
    <>
      <div className="kicker mb-4">2TTEST · Pre-Login</div>
      <h1 className="th text-4xl sm:text-5xl lg:text-6xl font-extrabold tracking-tight leading-[1.05] text-balance">
        ฝึกข้อสอบจริง<br/>
        <span style={{color:"var(--brand)"}}>เห็นพัฒนาการ</span> ทุกวัน
      </h1>
      <p className="th mt-5 text-[16px] sm:text-[18px] text-[var(--ink-2)] max-w-xl leading-relaxed">
        TOEIC · A-Level · ม.1 · ม.4 · กพ. ภาค ก. — ซื้อทีละชุด ใช้ภายในเวลาที่กำหนด
        ฝึกได้หลายรอบ มีสถิติคะแนน เปรียบเทียบกับเพื่อนในระบบ
      </p>
      <div className="mt-7 flex flex-wrap gap-3">
        <a href="#courses" className="btn-primary th px-5 py-3 text-[15px] inline-flex items-center gap-2">
          ดูคอร์สทั้งหมด <Icon.ArrowRight width="16" height="16"/>
        </a>
        <a href="#packages" className="btn-ghost th px-5 py-3 text-[15px]">ดูแพ็กเกจ</a>
      </div>
      <div className="mt-8 flex flex-wrap items-center gap-x-7 gap-y-3 text-[13px] text-[var(--muted)]">
        <span className="th inline-flex items-center gap-2"><Icon.Check width="16" height="16" style={{color:"var(--brand)"}}/>ข้อสอบจริง · เฉลยอย่างละเอียด</span>
        <span className="th inline-flex items-center gap-2"><Icon.Check width="16" height="16" style={{color:"var(--brand)"}}/>ใช้ได้ตามจำนวนวันที่กำหนด</span>
        <span className="th inline-flex items-center gap-2"><Icon.Check width="16" height="16" style={{color:"var(--brand)"}}/>ไม่ต้องสมัคร subscription</span>
      </div>
    </>
  );

  if (variant === "centered") {
    return (
      <section id="top" className="relative">
        <div className="absolute inset-0 hero-grid pointer-events-none"/>
        <div className="relative max-w-4xl mx-auto px-5 sm:px-8 pt-16 sm:pt-24 pb-12 text-center">
          <div className="kicker mb-4">2TTEST · Pre-Login</div>
          <h1 className="th text-5xl sm:text-6xl font-extrabold tracking-tight leading-[1.05] text-balance">
            ฝึกข้อสอบจริง <span style={{color:"var(--brand)"}}>เห็นพัฒนาการ</span> ทุกวัน
          </h1>
          <p className="th mt-5 text-[17px] text-[var(--ink-2)] max-w-2xl mx-auto leading-relaxed">
            ซื้อทีละชุด ใช้ตามเวลาที่กำหนด ฝึกได้หลายรอบ พร้อมสถิติพัฒนาการรายวัน
          </p>
          <div className="mt-7 flex flex-wrap gap-3 justify-center">
            <a href="#courses" className="btn-primary th px-5 py-3 text-[15px] inline-flex items-center gap-2">ดูคอร์สทั้งหมด <Icon.ArrowRight width="16" height="16"/></a>
            <a href="#packages" className="btn-ghost th px-5 py-3 text-[15px]">ดูแพ็กเกจ</a>
          </div>
          <StatRow stats={stats}/>
        </div>
      </section>
    );
  }

  // split
  return (
    <section id="top" className="relative">
      <div className="absolute inset-0 hero-grid pointer-events-none"/>
      <div className="relative max-w-7xl mx-auto px-5 sm:px-8 pt-12 sm:pt-20 pb-12 grid lg:grid-cols-12 gap-10 items-center">
        <div className="lg:col-span-7">{head}</div>

        {/* Right: composite "search-like" preview card — booking-engine flavor, original layout */}
        <div className="lg:col-span-5">
          <div className="card p-5 sm:p-6 shadow-[0_24px_48px_-24px_rgba(11,18,32,0.18)]">
            <div className="flex items-center justify-between mb-4">
              <div className="th text-[13px] font-semibold text-[var(--muted)]">เลือกคอร์สที่ใช่</div>
              <span className="chip"><Icon.Sparkle width="12" height="12"/> Live</span>
            </div>
            <div className="grid grid-cols-2 gap-2 mb-3">
              {Object.entries(CATS).slice(0, 4).map(([k, v]) => (
                <a key={k} href="#courses" className="th flex items-center gap-2 px-3 py-2.5 rounded-lg border border-[var(--line)] hover:border-[var(--brand)] hover:bg-[var(--brand-50)] transition text-[14px] font-semibold">
                  <span className={`w-7 h-7 rounded-md ${v.stripe} flex items-center justify-center font-extrabold text-[12px]`}>{v.glyph}</span>
                  {v.th}
                </a>
              ))}
            </div>
            <div className="flex items-center gap-2 px-3 py-2.5 rounded-lg border border-[var(--line)]">
              <Icon.Search width="16" height="16" style={{color:"var(--muted)"}}/>
              <input className="th flex-1 outline-none text-[14px] bg-transparent" placeholder="ค้นหา เช่น 'TOEIC Part 5'" />
              <span className="mono text-[11px] px-1.5 py-0.5 rounded bg-[var(--panel)] text-[var(--muted)]">↵</span>
            </div>
            <div className="hairline my-4"/>
            <StatRow stats={stats} compact/>
          </div>
        </div>
      </div>
    </section>
  );
}

function StatRow({ stats, compact }) {
  const items = stats || [
    { value: "10,000+", label: "นักเรียนใช้งาน" },
    { value: "95%",     label: "ผ่านเป้าหมาย" },
    { value: "4.8★",    label: "รีวิวเฉลี่ย" },
  ];
  return (
    <div className={`grid grid-cols-3 ${compact ? "gap-2" : "gap-4 mt-10 max-w-2xl mx-auto"}`}>
      {items.map((s, i) => (
        <div key={i} className={`${compact ? "" : "py-3"} text-center`}>
          <div className={`font-extrabold tracking-tight ${compact ? "text-xl" : "text-3xl"}`}>{s.value}</div>
          <div className="th text-[12px] text-[var(--muted)] mt-0.5">{s.label}</div>
        </div>
      ))}
    </div>
  );
}

// ───────── Active Season Banner ─────────
function SeasonBanner({ season }) {
  if (!season) return null;
  return (
    <div className="max-w-7xl mx-auto px-5 sm:px-8 -mt-2">
      <div className="rounded-xl border flex flex-col sm:flex-row sm:items-center gap-3 px-5 py-4"
           style={{ background: "var(--warm-bg)", borderColor: "var(--warm-line)", color: "var(--warm-fg)" }}>
        <div className="flex items-center gap-3 flex-1 min-w-0">
          <div className="w-9 h-9 rounded-full flex items-center justify-center"
               style={{ background: "rgba(146, 64, 14, 0.10)" }}>
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M12 2s4 4 4 8a4 4 0 0 1-8 0c0-1 .5-2 1-3 .5 1 1 1 1 1s-1-3 2-6Z"/><path d="M8 14a4 4 0 0 0 8 0"/></svg>
          </div>
          <div className="min-w-0">
            <div className="th font-bold text-[15px] truncate">{season.name} · ลด {season.discount_percent}% ทั้งระบบ</div>
            <div className="th text-[13px] opacity-80 truncate">
              {season.description || "ฉลองโปรโมชันพิเศษ ใช้ได้กับทุกชุดที่ร่วมรายการ"}
              {season.valid_until && <> · ถึง {season.valid_until}</>}
            </div>
          </div>
        </div>
        <a href="#courses" className="th inline-flex items-center gap-1.5 font-bold text-[14px] whitespace-nowrap">
          ดูชุดที่ร่วมรายการ <Icon.ChevRight width="14" height="14"/>
        </a>
      </div>
    </div>
  );
}

// ───────── Featured Packages ─────────
function PackageCard({ pkg, onBuy }) {
  const savings = (pkg.total_individual_price || 0) - (pkg.price || 0);
  // Bonus deck levels per package (hardcoded until Package model gains a column).
  // Maps any package whose name contains "ม.1" → free m1 vocab deck access.
  const bonusLevels = pkg.bonus_vocab_levels
    || (/ม\.?\s*1/.test(pkg.name || "") ? ["m1"] : []);
  const LEVEL_LABEL = { m1:"ม.1", m4:"ม.4", alevel:"A-Level", toeic:"TOEIC", gpax:"กพ.ภาค ก." };
  return (
    <div className="card p-6 flex flex-col h-full">
      <div className="flex items-start justify-between gap-3 mb-3">
        <div className="chip">แพ็กเกจ · {pkg.set_count} ชุด</div>
        {savings > 0 && (
          <div className="chip-warm chip">ประหยัด {fmtBaht(savings)}</div>
        )}
      </div>
      <h3 className="th text-xl font-extrabold tracking-tight">{pkg.name}</h3>
      <p className="th text-[14px] text-[var(--muted)] mt-1.5 leading-relaxed">{pkg.description}</p>

      <ul className="mt-4 space-y-2">
        {(pkg.sets || []).slice(0, 3).map(s => (
          <li key={s.id} className="th flex items-center gap-2 text-[13.5px]">
            <Icon.Check width="14" height="14" style={{color:"var(--brand)"}}/>
            <span className="truncate">{s.name}</span>
            <span className="ml-auto mono text-[12px] text-[var(--muted)]">{fmtBaht(s.price)}</span>
          </li>
        ))}
      </ul>

      {bonusLevels.length > 0 && (
        <div className="mt-4 rounded-xl border border-dashed p-3" style={{ borderColor:"var(--brand)", background:"var(--brand-50)" }}>
          <div className="flex items-center gap-2">
            <span className="th inline-flex items-center px-2 py-0.5 rounded-md text-[11px] font-bold" style={{ background:"var(--brand)", color:"#fff" }}>BONUS</span>
            <span className="th text-[13px] font-semibold" style={{ color:"var(--brand-700)" }}>
              Flashcard {bonusLevels.map(l => LEVEL_LABEL[l] || l).join(" + ")} ฟรี
            </span>
          </div>
          <div className="th text-[12px] text-[var(--muted)] mt-1.5">ฝึกคำศัพท์ภาษาอังกฤษพร้อมข้อสอบ — ปลดล็อกอัตโนมัติเมื่อซื้อ</div>
        </div>
      )}

      <div className="mt-5 hairline"/>
      <div className="mt-5 flex items-end justify-between gap-3">
        <div>
          <div className="flex items-baseline gap-2">
            <span className="text-2xl font-extrabold tracking-tight">{fmtBaht(pkg.price)}</span>
            {pkg.total_individual_price > pkg.price && (
              <span className="price-strike text-[13px]">{fmtBaht(pkg.total_individual_price)}</span>
            )}
          </div>
          <div className="th text-[12px] text-[var(--muted)] mt-1">ใช้ได้ {pkg.access_days} วัน · เริ่มนับเมื่อกดเริ่ม</div>
        </div>
        <button onClick={() => onBuy(pkg)} className="btn-primary th px-4 py-2.5 text-[14px] whitespace-nowrap">
          ดูรายละเอียด
        </button>
      </div>
    </div>
  );
}

function FeaturedPackages({ packages, onBuy }) {
  const list = (packages || []).slice(0, 3);
  if (!list.length) return null;
  return (
    <Section
      id="packages"
      kicker="Best value"
      title="แพ็กเกจประหยัด — ซื้อรวมคุ้มกว่า"
      subtitle="ผูกหลายชุดในแพ็กเกจเดียว ใช้งานต่อเนื่อง ประหยัดได้มากกว่าซื้อแยก"
      tone="panel"
    >
      <div className="grid md:grid-cols-2 lg:grid-cols-3 gap-5">
        {list.map(p => <PackageCard key={p.id} pkg={p} onBuy={onBuy}/>)}
      </div>
    </Section>
  );
}

// ───────── Course catalog ─────────
function CourseCard({ s, onBuy }) {
  const discount = pct(s.original_price, s.price) || s.season_discount_percent;
  return (
    <div data-set-id={s.id} className="card overflow-hidden flex flex-col">
      <BannerPlaceholder category={s.category} label={(CATS[s.category] || {}).th}/>
      <div className="p-5 flex flex-col flex-1">
        <div className="flex items-center gap-2 flex-wrap mb-2">
          {s.season_label && (
            <span className="chip chip-warm th inline-flex items-center gap-1.5">
              <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M12 2s4 4 4 8a4 4 0 0 1-8 0c0-1 .5-2 1-3 .5 1 1 1 1s-1-3 2-6Z"/></svg>
              {s.season_label}
            </span>
          )}
          {discount > 0 && <span className="chip" style={{background:'#FEE2E2', color:'#9F1239'}}>ลด {discount}%</span>}
        </div>
        <h3 className="th text-[16px] font-bold tracking-tight leading-snug">{s.name}</h3>
        <p className="th text-[13px] text-[var(--muted)] mt-1 line-clamp-2">{s.description}</p>

        <div className="th mt-3 flex items-center gap-3 text-[12.5px] text-[var(--ink-2)]">
          <span className="inline-flex items-center gap-1"><Icon.ListCheck width="14" height="14" style={{color:"var(--muted)"}}/>{s.question_count} ข้อ</span>
          <span className="inline-flex items-center gap-1"><Icon.Stack width="14" height="14" style={{color:"var(--muted)"}}/>{s.rounds_count} ชุด</span>
          <span className="inline-flex items-center gap-1"><Icon.Clock width="14" height="14" style={{color:"var(--muted)"}}/>{s.access_days} วัน</span>
        </div>

        <div className="mt-auto pt-4 flex items-end justify-between gap-3">
          <div>
            <div className="flex items-baseline gap-2">
              <span className="text-xl font-extrabold tracking-tight">{fmtBaht(s.price)}</span>
              {s.original_price && s.original_price > s.price && (
                <span className="price-strike text-[12.5px]">{fmtBaht(s.original_price)}</span>
              )}
            </div>
            {s.sales_count > 0 && (
              <div className="th text-[11.5px] text-[var(--muted)] mt-1">ขายแล้ว {s.sales_count.toLocaleString()} คน</div>
            )}
          </div>
          <button onClick={() => onBuy(s)} className="btn-primary th px-4 py-2 text-[14px]">ซื้อ</button>
        </div>
      </div>
    </div>
  );
}

function CourseCatalog({ sets, onBuy }) {
  const cats = ["all", ...Object.keys(CATS)];
  const [active, setActive] = useState("all");
  const [maxPrice, setMaxPrice] = useState(0); // 0 = no filter
  const [maxDays, setMaxDays] = useState(0);

  const filtered = useMemo(() => {
    return (sets || []).filter(s => {
      if (active !== "all" && s.category !== active) return false;
      if (maxPrice && s.price > maxPrice) return false;
      if (maxDays && s.access_days > maxDays) return false;
      return true;
    });
  }, [sets, active, maxPrice, maxDays]);

  return (
    <Section
      id="courses"
      kicker="Catalog"
      title="คอร์สและชุดข้อสอบทั้งหมด"
      subtitle="เลือกตามหมวดหมู่ ตัวกรองราคา หรือระยะเวลาใช้งาน"
    >
      {/* Tabs */}
      <div className="tabs-scroll -mx-5 sm:mx-0 px-5 sm:px-0 overflow-x-auto">
        <div className="inline-flex items-center gap-2 mb-5 p-1 rounded-xl bg-[var(--panel)] border border-[var(--line)]">
          {cats.map(k => {
            const isActive = active === k;
            const label = k === "all" ? "ทั้งหมด" : CATS[k]?.th;
            return (
              <button key={k} onClick={() => setActive(k)}
                className={`th px-3.5 py-2 rounded-lg text-[13.5px] font-semibold whitespace-nowrap transition
                  ${isActive ? "bg-white shadow-sm text-[var(--ink)] border border-[var(--line)]" : "text-[var(--muted)] hover:text-[var(--ink)]"}`}>
                {label}
              </button>
            );
          })}
        </div>
      </div>

      {/* Filters */}
      <div className="flex flex-wrap items-center gap-3 mb-7">
        <div className="th inline-flex items-center gap-2 text-[13px] text-[var(--muted)]">
          <Icon.Filter width="14" height="14"/> ตัวกรอง:
        </div>
        <FilterChip label="ราคา" value={maxPrice} options={[
          { v: 0, label: "ทั้งหมด" }, { v: 200, label: "≤ ฿200" },
          { v: 300, label: "≤ ฿300" }, { v: 500, label: "≤ ฿500" },
        ]} onChange={setMaxPrice}/>
        <FilterChip label="ระยะเวลา" value={maxDays} options={[
          { v: 0, label: "ทั้งหมด" }, { v: 14, label: "≤ 14 วัน" },
          { v: 30, label: "≤ 30 วัน" }, { v: 60, label: "≤ 60 วัน" },
        ]} onChange={setMaxDays}/>
        <div className="ml-auto th text-[13px] text-[var(--muted)]">{filtered.length} ชุด</div>
      </div>

      {/* Grid */}
      {filtered.length === 0 ? (
        <div className="card p-12 text-center">
          <div className="th text-[15px] font-semibold">ไม่มีชุดที่ตรงกับตัวกรอง</div>
          <div className="th text-[13px] text-[var(--muted)] mt-1">ลองปรับตัวกรองหรือเลือกหมวดอื่นดู</div>
        </div>
      ) : (
        <div className="grid sm:grid-cols-2 lg:grid-cols-3 gap-5">
          {filtered.map(s => <CourseCard key={s.id} s={s} onBuy={onBuy}/>)}
        </div>
      )}
    </Section>
  );
}

function FilterChip({ label, value, options, onChange }) {
  const [open, setOpen] = useState(false);
  const ref = useRef(null);
  useEffect(() => {
    const close = (e) => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    document.addEventListener("mousedown", close);
    return () => document.removeEventListener("mousedown", close);
  }, []);
  const cur = options.find(o => o.v === value) || options[0];
  return (
    <div ref={ref} className="relative">
      <button onClick={() => setOpen(v => !v)}
        className={`th inline-flex items-center gap-2 px-3 py-2 rounded-lg border text-[13px] font-semibold transition
          ${value ? "bg-[var(--brand-50)] border-[var(--brand)] text-[var(--brand-700)]" : "bg-white border-[var(--line)] hover:border-[#cfd6e3]"}`}>
        {label}: {cur.label} <Icon.ChevDown width="12" height="12"/>
      </button>
      {open && (
        <div className="absolute z-30 mt-1 left-0 w-44 rounded-lg border border-[var(--line)] bg-white shadow-lg p-1">
          {options.map(o => (
            <button key={o.v} onClick={() => { onChange(o.v); setOpen(false); }}
              className={`th block w-full text-left px-3 py-2 rounded-md text-[13.5px] hover:bg-[var(--panel)]
                ${o.v === value ? "font-bold text-[var(--brand-700)]" : ""}`}>
              {o.label}
            </button>
          ))}
        </div>
      )}
    </div>
  );
}

// ───────── How it works ─────────
function HowItWorks() {
  const steps = [
    { n: "01", th: "เลือกคอร์ส", desc: "เลือกหมวดหมู่และชุดข้อสอบที่ตรงกับเป้าหมาย ดูราคาและเวลาที่ใช้งานได้ก่อนซื้อ", icon: <Icon.Stack width="22" height="22"/> },
    { n: "02", th: "ฝึกข้อสอบ",  desc: "ทำข้อสอบเสมือนสนามจริง มี timer มีเฉลย ฝึกได้หลายรอบจนกว่าเวลาจะหมด", icon: <Icon.Bolt width="22" height="22"/> },
    { n: "03", th: "ติดตามผล",   desc: "ดูสถิติคะแนนรายรอบ เปรียบเทียบกับครั้งก่อน เห็นจุดที่ต้องพัฒนาแบบรายข้อ", icon: <Icon.TrendUp width="22" height="22"/> },
  ];
  return (
    <Section id="how" kicker="How it works" title="วิธีใช้งาน — 3 ขั้นตอน" subtitle="ออกแบบให้ใช้งานเหมือนสนามจริง พร้อมระบบติดตามพัฒนาการชัดเจน">
      <div className="grid md:grid-cols-3 gap-5">
        {steps.map((st, i) => (
          <div key={st.n} className="relative card p-7">
            <div className="mono text-[44px] font-extrabold leading-none text-[var(--brand-50)]">{st.n}</div>
            <div className="mt-2 -mt-8 relative z-10 w-12 h-12 rounded-xl flex items-center justify-center"
                 style={{background:"var(--brand)", color:"#fff"}}>
              {st.icon}
            </div>
            <h3 className="th text-[18px] font-bold tracking-tight mt-5">{st.th}</h3>
            <p className="th text-[14px] text-[var(--muted)] mt-2 leading-relaxed">{st.desc}</p>
          </div>
        ))}
      </div>
    </Section>
  );
}

// ───────── Social proof ─────────
function SocialProof() {
  // TODO real: hook to /public/stats once available
  const stats = [
    { value: "10,200+", label: "นักเรียนใช้งานจริง" },
    { value: "1.4M",    label: "ข้อสอบที่ฝึกสำเร็จ" },
    { value: "95%",     label: "ผ่านเป้าหมายส่วนตัว" },
    { value: "42",      label: "โรงเรียนพาร์ทเนอร์" },
  ];
  // TODO real: pull from review API
  const reviews = [
    { name: "ฟ้า", grade: "ม.6", text: "ฝึก A-Level คณิตทุกวันก่อนสอบจริง เห็นคะแนนค่อยๆ ขึ้นในระบบ มั่นใจขึ้นเยอะค่ะ", score: 5 },
    { name: "บีม", grade: "TOEIC", text: "ราคาคุ้ม ไม่ต้องสมัครรายเดือน ซื้อชุดเดียวฝึกได้หลายรอบ Part 5 พัฒนาขึ้นชัดเจน", score: 5 },
    { name: "พลอย", grade: "กพ. ภาค ก.", text: "ข้อสอบใกล้แนวจริงมาก เฉลยละเอียด ใช้เวลาอ่านสั้น แต่ผลออกดี", score: 5 },
  ];

  return (
    <section id="reviews" className="bg-[var(--ink)] text-white">
      <div className="max-w-7xl mx-auto px-5 sm:px-8 py-16 sm:py-24">
        <div className="kicker mb-3" style={{color:"#9DC2FF"}}>Trusted by</div>
        <h2 className="text-3xl sm:text-4xl font-extrabold tracking-tight max-w-3xl text-balance">
          นักเรียนกว่าหมื่นคน ฝึกกับ 2TTEST
        </h2>

        <div className="mt-10 grid grid-cols-2 md:grid-cols-4 gap-4">
          {stats.map(s => (
            <div key={s.label} className="rounded-2xl p-5 border border-white/10 bg-white/[0.04]">
              <div className="text-3xl sm:text-4xl font-extrabold tracking-tight">{s.value}</div>
              <div className="th mt-1 text-[13px] text-white/70">{s.label}</div>
            </div>
          ))}
        </div>

        <div className="mt-10 grid md:grid-cols-3 gap-5">
          {reviews.map((r, i) => (
            <div key={i} className="rounded-2xl p-6 bg-white/[0.05] border border-white/10">
              <div className="flex items-center gap-1 mb-3" style={{color:"#FBBF24"}}>
                {Array.from({length: r.score}).map((_, j) => <Icon.Star key={j} width="16" height="16"/>)}
              </div>
              <p className="th text-[14.5px] leading-relaxed text-white/90">"{r.text}"</p>
              <div className="mt-4 th text-[13px] text-white/60">— {r.name} · {r.grade}</div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

// ───────── FAQ ─────────
function FAQ({ settings }) {
  const refundDays = settings?.refund_window_days ?? 7;
  const payment = settings?.payment_text || "พร้อมเพย์ · บัตรเครดิต/เดบิต · TrueMoney";
  const items = [
    { q: "ใช้ได้กี่วันหลังซื้อ?", a: "แต่ละชุดจะระบุจำนวนวันใช้งานที่หน้า Catalog (เช่น 14/30/60 วัน) เริ่มนับตั้งแต่วันที่กดเริ่มฝึกครั้งแรก ไม่ใช่วันซื้อ" },
    { q: "ถ้าหมดอายุแล้วต้องซื้อใหม่ไหม?", a: "ใช่ — เมื่อครบกำหนด ระบบจะปิดการเข้าถึงชุดข้อสอบ คุณสามารถซื้อใหม่ได้ตลอด หรือเลือกแพ็กเกจที่มีระยะเวลาใช้งานนานขึ้น" },
    { q: "Refund ได้ไหม?", a: `ขอคืนเงินได้ภายใน ${refundDays} วันหลังซื้อ และต้องยังไม่กดเริ่มฝึก หากเริ่มฝึกแล้ว ถือว่าใช้งานบริการแล้ว` },
    { q: "มี Free trial ไหม?", a: "มีตัวอย่าง 5 ข้อต่อชุด ให้ทดลองดูแนวข้อสอบและเฉลยก่อนตัดสินใจซื้อ" },
    { q: "จ่ายเงินยังไง?", a: payment + " — ออกใบเสร็จอัตโนมัติทาง email ทันทีหลังชำระสำเร็จ" },
    { q: "มีกี่ข้อต่อชุด?", a: "ขึ้นกับชุด — ตั้งแต่ 30 ข้อ (ชุดเฉพาะวิชา) ไปจนถึง 240 ข้อ (ชุดสนามใหญ่) ดูได้ที่หน้า Catalog ทุกชุด" },
    { q: "ทำได้กี่ครั้ง?", a: "ภายในเวลาที่ใช้ได้ ทำซ้ำได้ไม่จำกัด ระบบเก็บสถิติทุกครั้งให้เห็นพัฒนาการชัดเจน" },
    { q: "ติดต่อยังไง?", a: `email: ${settings?.support_email || "support@2ttest.com"} · LINE: ${settings?.support_line || "@2ttest"}` },
  ];
  return (
    <Section id="faq" tone="panel" kicker="Questions" title="คำถามที่พบบ่อย" subtitle="ถ้าไม่เจอที่ต้องการ ติดต่อเราได้ทาง LINE หรือ email">
      <div className="grid md:grid-cols-2 gap-3">
        {items.map((it, i) => (
          <details key={i} className="faq card p-5">
            <summary className="flex items-start justify-between gap-3">
              <span className="th text-[15px] font-semibold tracking-tight pr-2">{it.q}</span>
              <Icon.ChevDown className="chev shrink-0 mt-1 transition-transform" width="18" height="18" style={{color:"var(--muted)"}}/>
            </summary>
            <p className="th text-[14px] text-[var(--ink-2)] mt-3 leading-relaxed">{it.a}</p>
          </details>
        ))}
      </div>
    </Section>
  );
}

// ───────── CTA + Footer ─────────
function CTASection() {
  return (
    <section className="relative overflow-hidden">
      <div className="max-w-7xl mx-auto px-5 sm:px-8 py-16 sm:py-24">
        <div className="rounded-3xl p-10 sm:p-16 text-center relative overflow-hidden"
             style={{background:"linear-gradient(135deg, var(--brand) 0%, #0857d6 100%)"}}>
          <div className="absolute inset-0 opacity-20"
               style={{backgroundImage:"radial-gradient(circle at 20% 20%, #fff 0, transparent 40%), radial-gradient(circle at 80% 80%, #FBBF24 0, transparent 40%)"}}/>
          <div className="relative">
            <div className="kicker text-white/80 mb-3">Get started</div>
            <h2 className="th text-white text-3xl sm:text-5xl font-extrabold tracking-tight text-balance">พร้อมเริ่มต้นแล้วหรือยัง?</h2>
            <p className="th text-white/90 mt-4 text-[16px] sm:text-[18px] max-w-xl mx-auto">
              สมัครฟรีใช้เวลาไม่ถึง 1 นาที — ทดลองตัวอย่างข้อสอบก่อนตัดสินใจซื้อได้ทุกชุด
            </p>
            <div className="mt-7 flex flex-wrap justify-center gap-3">
              <a href="/auth/register.html" className="th bg-white text-[var(--brand)] font-bold px-6 py-3.5 rounded-xl text-[15px] hover:bg-[var(--warm-bg)] transition">
                สมัครฟรี
              </a>
              <a href="#courses" className="th text-white border border-white/40 font-bold px-6 py-3.5 rounded-xl text-[15px] hover:bg-white/10 transition">
                ดูคอร์สก่อน
              </a>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

function Footer({ settings }) {
  return (
    <footer className="border-t border-[var(--line)] bg-white">
      <div className="max-w-7xl mx-auto px-5 sm:px-8 py-12 grid md:grid-cols-4 gap-8">
        <div className="md:col-span-2">
          <div className="flex items-center gap-2.5">
            <Icon.Logo size={28}/>
            <span className="font-extrabold tracking-tight text-[18px]">2TTEST</span>
          </div>
          <p className="th text-[13.5px] text-[var(--muted)] mt-3 max-w-sm leading-relaxed">
            {settings?.brand_tagline || "ระบบฝึกข้อสอบออนไลน์ — เห็นพัฒนาการจริง"}
          </p>
          <div className="mt-4 flex flex-col gap-2 text-[13.5px] text-[var(--ink-2)]">
            <a href={`mailto:${settings?.support_email || "support@2ttest.com"}`} className="th inline-flex items-center gap-2 hover:text-[var(--brand)]">
              <Icon.Mail width="16" height="16"/> {settings?.support_email || "support@2ttest.com"}
            </a>
            <a href={settings?.support_line_url || "#"} target="_blank" rel="noreferrer" className="th inline-flex items-center gap-2 hover:text-[var(--brand)]">
              <Icon.Line width="16" height="16"/> LINE: {settings?.support_line || "@2ttest"}
            </a>
          </div>
          {/* Social row — order by Thailand monthly active users (DataReportal):
              Facebook (≈50M) · TikTok (≈44M) · YouTube (≈44M) · Instagram (≈21M) */}
          <div className="mt-5">
            <div className="th text-[11.5px] uppercase tracking-wider font-bold text-[var(--muted)] mb-2">ติดตามเรา</div>
            <div className="flex items-center gap-2.5">
              {[
                { key: "facebook",  label: "Facebook",  Icon: Icon.Facebook,  href: settings?.social_facebook  || "https://www.facebook.com/profile.php?id=61589111372966" },
                { key: "tiktok",    label: "TikTok",    Icon: Icon.TikTok,    href: settings?.social_tiktok    || "https://www.tiktok.com/@2ttest" },
                { key: "youtube",   label: "YouTube",   Icon: Icon.YouTube,   href: settings?.social_youtube   || "#" },
                { key: "instagram", label: "Instagram", Icon: Icon.Instagram, href: settings?.social_instagram || "https://www.instagram.com/2ttest" },
              ].map(({ key, label, Icon: Ico, href }) => (
                <a key={key}
                   href={href}
                   target="_blank"
                   rel="noreferrer"
                   aria-label={label}
                   title={label}
                   className="th inline-flex items-center justify-center w-9 h-9 rounded-full border border-[var(--line)] text-[var(--ink-2)] hover:text-[var(--brand)] hover:border-[var(--brand)] transition-colors">
                  <Ico width="16" height="16"/>
                </a>
              ))}
            </div>
          </div>
        </div>

        <div>
          <div className="th text-[12px] uppercase tracking-wider font-bold text-[var(--muted)] mb-3">เมนู</div>
          <ul className="space-y-2 text-[14px]">
            <li><a className="th hover:text-[var(--brand)]" href="#courses">คอร์ส</a></li>
            <li><a className="th hover:text-[var(--brand)]" href="#packages">แพ็กเกจ</a></li>
            <li><a className="th hover:text-[var(--brand)]" href="#reviews">รีวิว</a></li>
            <li><a className="th hover:text-[var(--brand)]" href="#faq">FAQ</a></li>
          </ul>
        </div>

        <div>
          <div className="th text-[12px] uppercase tracking-wider font-bold text-[var(--muted)] mb-3">ข้อมูล</div>
          <ul className="space-y-2 text-[14px]">
            <li><a className="th hover:text-[var(--brand)]" href="/terms">เงื่อนไขการใช้งาน</a></li>
            <li><a className="th hover:text-[var(--brand)]" href="/privacy">นโยบายความเป็นส่วนตัว</a></li>
            <li><a className="th hover:text-[var(--brand)]" href="/refund">นโยบายคืนเงิน</a></li>
            <li><a className="th hover:text-[var(--brand)]" href="/contact">ติดต่อเรา</a></li>
          </ul>
        </div>
      </div>
      <div className="border-t border-[var(--line)]">
        <div className="max-w-7xl mx-auto px-5 sm:px-8 py-5 flex flex-col sm:flex-row items-center justify-between gap-2 text-[12.5px] text-[var(--muted)]">
          <div className="th flex items-center gap-3 flex-wrap">
            <span>© 2TTEST 2026 — All rights reserved</span>
            <span style={{ opacity:0.5 }}>·</span>
            <a href="/admin/" className="th text-[var(--muted)] hover:text-[var(--brand)] underline-offset-2 hover:underline">พนักงาน 2TTEST? เข้า admin →</a>
          </div>
          <div className="th">VAT {settings?.vat_percent ?? 7}% · {settings?.payment_text || "พร้อมเพย์ · บัตรเครดิต/เดบิต"}</div>
        </div>
      </div>
    </footer>
  );
}

Object.assign(window, {
  TopNav, Hero, SeasonBanner, FeaturedPackages, CourseCatalog,
  HowItWorks, SocialProof, FAQ, CTASection, Footer,
});
