// Shared UI components + icons + helpers for 2TTEST landing
// Exposed to window so other Babel scripts can use them.

const { useState, useEffect, useRef, useMemo } = React;

// ───────── Icons (inline SVG, no external lib) ─────────
const Icon = {
  Logo: ({ size = 28, color = "var(--brand)" }) => (
    <svg width={size} height={size} viewBox="0 0 32 32" fill="none">
      <rect x="2" y="2" width="28" height="28" rx="8" fill={color}/>
      <path d="M9 11h14M16 11v12" stroke="#fff" strokeWidth="2.4" strokeLinecap="round"/>
      <circle cx="22.5" cy="20.5" r="3" fill="#FBBF24" stroke="#fff" strokeWidth="1.6"/>
    </svg>
  ),
  Search: (p) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" {...p}><circle cx="11" cy="11" r="7"/><path d="m20 20-3.5-3.5"/></svg>,
  Menu: (p) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" {...p}><path d="M4 7h16M4 12h16M4 17h16"/></svg>,
  X: (p) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" {...p}><path d="M6 6l12 12M18 6l-6 6-6 6"/></svg>,
  ChevDown: (p) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" {...p}><path d="m6 9 6 6 6-6"/></svg>,
  ChevRight: (p) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" {...p}><path d="m9 6 6 6-6 6"/></svg>,
  Sparkle: (p) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M12 3v4M12 17v4M3 12h4M17 12h4M5.6 5.6l2.8 2.8M15.6 15.6l2.8 2.8M5.6 18.4l2.8-2.8M15.6 8.4l2.8-2.8"/></svg>,
  Check: (p) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="m5 12 5 5L20 7"/></svg>,
  Clock: (p) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" {...p}><circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 2"/></svg>,
  Stack: (p) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="m3 7 9-4 9 4-9 4-9-4Z"/><path d="m3 12 9 4 9-4M3 17l9 4 9-4"/></svg>,
  ListCheck: (p) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M3 6h13M3 12h13M3 18h13"/><path d="m18 5 1.5 1.5L22 4M18 11l1.5 1.5L22 10M18 17l1.5 1.5L22 16"/></svg>,
  TrendUp: (p) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M3 17 9 11l4 4 8-8"/><path d="M14 4h7v7"/></svg>,
  Star: (p) => <svg viewBox="0 0 24 24" fill="currentColor" {...p}><path d="m12 2 3.1 6.5 7 .9-5.1 4.8 1.3 6.9L12 17.7 5.7 21l1.3-6.9L1.9 9.4l7-.9L12 2Z"/></svg>,
  Mail: (p) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" {...p}><rect x="3" y="5" width="18" height="14" rx="2"/><path d="m3 7 9 6 9-6"/></svg>,
  // LINE — match the official brand mark: rounded square chat bubble with
  // a downward tail at the bottom-left and the four wordmark letters
  // (L · I · N · E) drawn in line-style so it composes with the rest of
  // the minimal icon set.
  Line: (p) => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round" {...p}>
      {/* Speech-bubble body with bottom-left tail, classic LINE silhouette */}
      <path d="M21 11.2c0 4.6-4 8.3-9 8.3-.6 0-1.2-.1-1.8-.2L6 21l1.4-3.4C4.7 16 3 13.7 3 11.2 3 6.6 7 2.9 12 2.9s9 3.7 9 8.3z"/>
      {/* L */}
      <path d="M7.7 9.6v3.7h2"/>
      {/* I */}
      <path d="M11.3 9.6v3.7"/>
      {/* N */}
      <path d="M13.1 13.3V9.6l2.4 3.7V9.6"/>
      {/* E */}
      <path d="M19.2 9.6h-2v3.7h2M17.2 11.45h1.5"/>
    </svg>
  ),
  Shield: (p) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M12 3 4 6v6c0 5 3.5 8 8 9 4.5-1 8-4 8-9V6l-8-3Z"/><path d="m9 12 2 2 4-4"/></svg>,
  Bolt: (p) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M13 2 4 14h7l-1 8 9-12h-7l1-8Z"/></svg>,
  Filter: (p) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M3 5h18l-7 9v6l-4-2v-4L3 5Z"/></svg>,
  ArrowRight: (p) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M5 12h14M13 5l7 7-7 7"/></svg>,
  // Social — minimal line silhouettes that read as the brand at small sizes.
  // Facebook: lowercase "f" inside rounded square
  Facebook: (p) => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" {...p}>
      <rect x="3" y="3" width="18" height="18" rx="4"/>
      <path d="M14.5 8h-1.2c-.7 0-1.3.5-1.3 1.3V11h2.4l-.4 2.3h-2v6"/>
      <path d="M9.5 11h2.5"/>
    </svg>
  ),
  // TikTok: stylized music note (the official "d" silhouette)
  TikTok: (p) => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" {...p}>
      <path d="M14 4v10.5a3.5 3.5 0 1 1-3.5-3.5"/>
      <path d="M14 4c.4 2.5 2.2 4.4 4.7 4.7"/>
    </svg>
  ),
  // YouTube: rounded rectangle with play triangle
  YouTube: (p) => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" {...p}>
      <rect x="2.5" y="6" width="19" height="12" rx="3"/>
      <path d="m10.5 9.5 4.5 2.5-4.5 2.5z" fill="currentColor" stroke="none"/>
    </svg>
  ),
  // Instagram: rounded camera body with lens + indicator dot
  Instagram: (p) => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" {...p}>
      <rect x="3" y="3" width="18" height="18" rx="5"/>
      <circle cx="12" cy="12" r="4"/>
      <circle cx="17.3" cy="6.7" r=".7" fill="currentColor" stroke="none"/>
    </svg>
  ),
};

// ───────── Helpers ─────────
const fmtBaht = (n) => {
  if (n == null) return "";
  return "฿" + Math.round(n).toLocaleString("en-US");
};
const pct = (orig, price) => {
  if (!orig || !price || orig <= price) return null;
  return Math.round(((orig - price) / orig) * 100);
};

// Category palette + Thai labels
const CATS = {
  toeic:    { th: "TOEIC",      stripe: "stripe-placeholder", glyph: "T" },
  alevel:   { th: "A-Level",    stripe: "stripe-violet",      glyph: "A" },
  m1:       { th: "ม.1",        stripe: "stripe-emerald",     glyph: "1" },
  m4:       { th: "ม.4",        stripe: "stripe-rose",        glyph: "4" },
  gpax:     { th: "กพ. ภาค ก.", stripe: "stripe-yellow",      glyph: "ก" },
};

// Banner placeholder — no fake stock imagery
function BannerPlaceholder({ category, label, ratio = "16/10" }) {
  const cat = CATS[category] || CATS.toeic;
  return (
    <div
      className={`relative overflow-hidden rounded-t-[14px] ${cat.stripe}`}
      style={{ aspectRatio: ratio }}
    >
      <div className="absolute inset-0 flex items-center justify-center">
        <div className="text-[64px] font-extrabold opacity-60 leading-none select-none">{cat.glyph}</div>
      </div>
      <div className="absolute left-3 top-3">
        <span className="chip chip-neutral mono" style={{background:'rgba(255,255,255,0.85)'}}>{label || cat.th}</span>
      </div>
    </div>
  );
}

// Section wrapper with consistent rhythm
function Section({ id, kicker, title, subtitle, children, tone = "white", className = "" }) {
  const bg = tone === "panel" ? "bg-[var(--panel)]" : tone === "ink" ? "bg-[var(--ink)] text-white" : "bg-white";
  return (
    <section id={id} className={`${bg} ${className}`}>
      <div className="max-w-7xl mx-auto px-5 sm:px-8 py-16 sm:py-24">
        {(kicker || title) && (
          <div className="mb-10 sm:mb-14">
            {kicker && <div className="kicker mb-3">{kicker}</div>}
            {title && <h2 className="text-3xl sm:text-4xl font-extrabold tracking-tight max-w-3xl text-balance">{title}</h2>}
            {subtitle && <p className="mt-3 text-[15px] text-[var(--muted)] max-w-2xl">{subtitle}</p>}
          </div>
        )}
        {children}
      </div>
    </section>
  );
}

// Login-required modal
function LoginModal({ open, onClose }) {
  useEffect(() => {
    if (!open) return;
    const onKey = (e) => e.key === "Escape" && onClose();
    document.addEventListener("keydown", onKey);
    return () => document.removeEventListener("keydown", onKey);
  }, [open, onClose]);

  if (!open) return null;
  return (
    <div className="modal-backdrop" onClick={onClose}>
      <div className="modal animate-fadeup" onClick={(e) => e.stopPropagation()}>
        <div className="flex items-start justify-between mb-3">
          <div className="w-10 h-10 rounded-full flex items-center justify-center" style={{background:'var(--brand-50)', color:'var(--brand)'}}>
            <Icon.Shield width="20" height="20" />
          </div>
          <button onClick={onClose} className="p-2 -m-2 rounded-lg hover:bg-[var(--panel)]" aria-label="ปิด">
            <Icon.X width="18" height="18" />
          </button>
        </div>
        <h3 className="text-xl font-bold tracking-tight">กรุณาเข้าสู่ระบบเพื่อซื้อ</h3>
        <p className="text-[14px] text-[var(--muted)] mt-1.5">
          คุณต้องมีบัญชี 2TTEST เพื่อสั่งซื้อชุดข้อสอบและเข้าฝึกได้
        </p>
        <div className="mt-6 grid grid-cols-2 gap-3">
          <a href="/auth/login.html" className="btn-ghost text-center py-2.5">เข้าสู่ระบบ</a>
          <a href="/auth/register.html" className="btn-primary text-center py-2.5">สมัครฟรี</a>
        </div>
        <div className="mt-4 text-[12px] text-[var(--muted)] text-center">
          การสมัครใช้เวลา &lt; 1 นาที · ไม่มีค่าใช้จ่ายในการสมัคร
        </div>
      </div>
    </div>
  );
}

// API helper
const API_BASE = (() => {
  if (typeof localStorage !== "undefined") {
    const o = localStorage.getItem("ttest_api_url");
    if (o) return o;
  }
  const h = (typeof window !== "undefined" && window.location && window.location.hostname) || "";
  if (h === "localhost" || h === "127.0.0.1" || h === "0.0.0.0") return "http://localhost:8000";
  return "https://2ttest.up.railway.app";
})();

async function safeFetch(path) {
  try {
    const r = await fetch(API_BASE + path, { headers: { "accept": "application/json" } });
    if (!r.ok) throw new Error("HTTP " + r.status);
    return await r.json();
  } catch (e) {
    console.warn("[2TTEST] fetch failed:", path, e.message);
    return null;
  }
}

// ───────── Real-data only — show empty state if API doesn't return ─────────
// (Demo seed previously here was 9 fake ExamSets + 3 fake Packages + Songkran sale.
//  Removed to avoid misleading visitors into thinking those products exist.)
const MOCK_SETS     = [];
const MOCK_PACKAGES = [];
const MOCK_SEASON   = null;
const MOCK_SETTINGS = {
  brand_name: "2TTEST",
  brand_tagline: "ระบบฝึกข้อสอบออนไลน์ — เห็นพัฒนาการจริง",
  brand_logo_url: null,
  brand_primary_color: "#0A6CFF",
  support_email: "support@2ttest.com",
  support_line: "@2ttest",
  payment_text: "พร้อมเพย์ · บัตรเครดิต/เดบิต · TrueMoney",
  vat_percent: 7,
  refund_window_days: 7,
};

// Expose to other Babel scripts
Object.assign(window, {
  Icon, fmtBaht, pct, CATS,
  BannerPlaceholder, Section, LoginModal,
  API_BASE, safeFetch,
  MOCK_SETS, MOCK_PACKAGES, MOCK_SEASON, MOCK_SETTINGS,
});
