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

/* ============================================================
   CONFIG — หน้าเว็บเรียก Vercel API เท่านั้น เพื่อไม่ให้ GAS URL/secret โผล่ใน client
   local preview จะใช้ข้อมูลตัวอย่าง ส่วนบน Vercel จะเรียก /api/orders
   ============================================================ */
const CONFIG = {
  API_URL: location.hostname === "127.0.0.1" || location.hostname === "localhost" ? "" : "/api/orders",
  SHOP_NAME: "Chachaa Store",
  SHOP_HANDLE: "minttt018",
};

/* ---- ข้อมูลตัวอย่าง (จะถูกแทนที่ด้วยข้อมูลจริงจาก /api/orders บน Vercel) ----
   หัวตารางในชีต: ชื่อ Account | ด้อมที่สั่ง | รายการที่สั่งซื้อ | รูปแบบการชำระ | ยอดที่เหลือ | สถานะของ */
const DEMO_ROWS = [
  { "ชื่อ Account":"@sherrybae25", "ด้อมที่สั่ง":"Genshin Durin Card", "รายการที่สั่งซื้อ":"กระเป๋า Durin", "รูปแบบการชำระ":"เต็มจำนวน", "ยอดที่เหลือ":"0", "สถานะของ":"กดจองแล้ว" },
  { "ชื่อ Account":"@uzxmx_2", "ด้อมที่สั่ง":"Genshin 04/2026", "รายการที่สั่งซื้อ":"Badge RF2 - Waze", "รูปแบบการชำระ":"เต็มจำนวน", "ยอดที่เหลือ":"0", "สถานะของ":"กำลังสั่งกลับ" },
  { "ชื่อ Account":"@F_HotaH", "ด้อมที่สั่ง":"Starrail 04/2026", "รายการที่สั่งซื้อ":"ชุด - Khashana", "รูปแบบการชำระ":"มัดจำ", "ยอดที่เหลือ":"0", "สถานะของ":"กดจองแล้ว" },
];

/* ---------- helpers ---------- */
const norm = (s) => String(s || "").trim().toLowerCase().replace(/^@/, "");

// แมปหัวตารางที่อาจเขียนต่างกันเล็กน้อย ให้กลายเป็น key ภายใน
function mapRow(r) {
  const get = (...keys) => {
    for (const k of keys) {
      const hit = Object.keys(r).find((x) => x.trim() === k);
      if (hit != null && r[hit] !== "") return r[hit];
    }
    return "";
  };
  return {
    account: String(get("ชื่อ Account", "Account", "account", "บัญชี")).trim().replace(/^@/, ""),
    dom: get("ด้อมที่สั่ง", "ด้อม", "Fandom"),
    items: get("รายการที่สั่งซื้อ", "รายการ", "Order"),
    pay: get("รูปแบบการชำระ", "การชำระ", "Payment"),
    balance: get("ยอดที่เหลือ", "ยอดคงเหลือ", "Balance"),
    status: get("สถานะของ", "สถานะของออเดอร์", "สถานะ", "Status"),
  };
}

// แปลงสถานะ -> ชนิด badge + ขั้นความคืบหน้า (1..5)
const STEPS = ["รอชำระ", "พรีออเดอร์", "ถึงไทย", "จัดส่ง", "สำเร็จ"];
function classify(statusRaw) {
  const s = String(statusRaw || "").toLowerCase();
  const has = (...w) => w.some((x) => s.includes(x));
  if (has("สำเร็จ", "เสร็จ", "ปิดออเดอร์", "ปิดออเดอ", "จบ", "รับของแล้ว")) return { type: "s-done", step: 5 };
  if (has("จัดส่ง", "ส่งแล้ว", "ems", "kerry", "flash", "ไปรษณีย์", "ส่งของ")) return { type: "s-ship", step: 4 };
  if (has("ถึงไทย", "ของถึง", "เข้าไทย", "ตรวจของ", "แพ็ค")) return { type: "s-arrive", step: 3 };
  if (has("กดจอง", "รอของ", "พรี", "เกาหลี", "กำลังสั่ง", "po", "preorder", "ระหว่างทาง")) return { type: "s-po", step: 2 };
  if (has("รอชำระ", "ค้างชำระ", "รอโอน", "ยังไม่ชำระ", "รอจ่าย")) return { type: "s-wait", step: 1 };
  return { type: "s-default", step: 2 };
}

const isPaid = (b) => {
  const t = String(b || "").trim().toLowerCase();
  return t === "" || t === "0" || t === "-" || t === "ชำระครบ" || t === "ครบ" || t === "0 บาท" || t === "0บาท";
};
const fmtBal = (b) => {
  const t = String(b || "").trim();
  if (/^\d+(\.\d+)?$/.test(t)) return Number(t).toLocaleString("th-TH") + " บาท";
  return t;
};

/* ---------- icons ---------- */
const CoralIcon = ({ s = 30, c = "#FF6F5E" }) => (
  <svg width={s} height={s} viewBox="0 0 32 32" fill="none">
    <path d="M16 29V16M16 16c0-3 2.4-4.2 2.4-7.2 0-1.8-1.4-3-1.4-3M16 16c0-2.6-2.6-3.6-2.6-6.4 0-1.4 1-2.6 1-2.6M16 20c-1.6-1.6-4-1.4-5.2-3.2-.8-1.2-.4-2.8-.4-2.8M16 21.5c1.7-1.5 4.2-1 5.6-2.8.9-1.2.6-3 .6-3"
      stroke={c} strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round" />
    <circle cx="16" cy="6" r="1.7" fill={c} />
    <circle cx="9.8" cy="13.4" r="1.5" fill={c} />
    <circle cx="22.4" cy="15" r="1.5" fill={c} />
  </svg>
);
const SearchIcon = () => (
  <svg width="22" height="22" viewBox="0 0 24 24" fill="none"><circle cx="11" cy="11" r="6.5" stroke="#fff" strokeWidth="2.4" /><path d="M16 16l4 4" stroke="#fff" strokeWidth="2.4" strokeLinecap="round" /></svg>
);
const XLogo = () => (
  <svg className="xi" viewBox="0 0 24 24" fill="currentColor"><path d="M18.244 2.25h3.308l-7.227 8.26 8.502 11.24h-6.66l-5.214-6.817L4.99 21.75H1.68l7.73-8.835L1.254 2.25H8.08l4.713 6.231 5.45-6.231zm-1.161 17.52h1.833L7.084 4.126H5.117l11.966 15.644z" /></svg>
);
const CheckIcon = () => (<svg width="14" height="14" viewBox="0 0 16 16" fill="none"><path d="M3 8.5l3.2 3.2L13 5" stroke="#1E8A5A" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round" /></svg>);

/* ---------- order card ---------- */
function OrderCard({ o, i }) {
  const { type } = classify(o.status);
  const paid = isPaid(o.balance);
  return (
    <div className="card" style={{ animationDelay: `${i * 0.07}s` }}>
      <div className="card-top">
        <div className="dom">
          <div className="meta">
            <div className="k">รายการที่สั่งซื้อ</div>
            <div className="v">{o.items || "—"}</div>
          </div>
        </div>
        <div className={`badge ${type}`}><span className="bd"></span>{o.status || "กำลังดำเนินการ"}</div>
      </div>

      <div className="subitem">
        <span className="subitem-label">ด้อมที่สั่ง</span>
        <span className="subitem-value">{o.dom || "—"}</span>
      </div>

      <div className="rows">
        <div className="row">
          <span className="rk">รูปแบบการชำระ</span>
          <span className="rv">{o.pay || "—"}</span>
        </div>
        <div className="row">
          <span className="rk">ยอดที่เหลือ</span>
          {paid
            ? <span className="rv paid"><CheckIcon />ชำระครบแล้ว</span>
            : <span className="rv bal">{fmtBal(o.balance)}</span>}
        </div>
      </div>

      <div className="acct">บัญชี <b>@{o.account}</b></div>
    </div>
  );
}

/* ---------- main app ---------- */
function App() {
  const [q, setQ] = useState("");
  const [view, setView] = useState("idle"); // idle | loading | results | notfound | error
  const [results, setResults] = useState([]);
  const [searched, setSearched] = useState("");
  const inputRef = useRef(null);

  const fetchRows = useCallback(async () => {
    if (!CONFIG.API_URL) {
      await new Promise((r) => setTimeout(r, 650)); // demo delay
      return DEMO_ROWS.map(mapRow);
    }
    const res = await fetch(CONFIG.API_URL);
    if (!res.ok) throw new Error("HTTP " + res.status);
    const json = await res.json();
    const arr = Array.isArray(json) ? json : (json.data || json.rows || []);
    return arr.map(mapRow);
  }, []);

  const doSearch = useCallback(async (raw) => {
    const term = norm(raw);
    if (!term) { inputRef.current && inputRef.current.focus(); return; }
    setView("loading");
    setSearched(raw.trim().replace(/^@/, ""));
    try {
      const rows = await fetchRows();
      const hits = rows.filter((r) => norm(r.account) === term);
      setResults(hits);
      setView(hits.length ? "results" : "notfound");
    } catch (e) {
      console.error(e);
      setView("error");
    }
  }, [fetchRows]);

  const reset = () => { setView("idle"); setResults([]); setQ(""); };

  const onKey = (e) => { if (e.key === "Enter") doSearch(q); };

  return (
    <div className="shell">
      <div className="brand">
        <div className="emblem"><CoralIcon s={34} /><span className="dot"></span></div>
        <div className="name">{CONFIG.SHOP_NAME}</div>
        <div className="tagline"><span className="tdot"></span>ติดตามสถานะออเดอร์ · @{CONFIG.SHOP_HANDLE}</div>
      </div>

      {view !== "results" && view !== "notfound" && (
        <div className="hero">
          <h1>เช็คสถานะออเดอร์ของคุณ</h1>
          <p>พิมพ์ชื่อบัญชี / ทวิตเตอร์ที่ใช้สั่งซื้อ<br />แล้วกดค้นหาสถานะออเดอร์ได้เลย</p>
        </div>
      )}

      {(view === "idle" || view === "loading") && (
        <div className="searchwrap">
          <div className="label"><CoralIcon s={15} c="#2F8B97" /> ค้นหาด้วย Account</div>
          <div className="field">
            <span className="at">@</span>
            <input
              ref={inputRef}
              value={q}
              onChange={(e) => setQ(e.target.value)}
              onKeyDown={onKey}
              placeholder="ชื่อบัญชี เช่น minttt018"
              autoComplete="off" autoCapitalize="off" spellCheck="false"
              disabled={view === "loading"}
            />
            <button className="gobtn" onClick={() => doSearch(q)} disabled={view === "loading"} aria-label="ค้นหา">
              <SearchIcon />
            </button>
          </div>

          {view === "loading"
            ? <div className="loader" style={{ marginTop: 16 }}>
                <div className="l-spin"></div>
                <div className="loadtxt">กำลังดำดิ่งค้นหา…</div>
              </div>
            : (
              <></>
            )}
        </div>
      )}

      {view === "results" && (
        <>
          <div className="results-head">
            <div className="count">พบ <b>{results.length}</b> ออเดอร์ของ @{searched}</div>
            <button className="backbtn" onClick={reset}>↩ ค้นใหม่</button>
          </div>
          <div className="cards">
            {results.map((o, i) => <OrderCard key={i} o={o} i={i} />)}
          </div>
        </>
      )}

      {view === "notfound" && (
        <div className="panel">
          <div className="icn"><CoralIcon s={40} c="#E0563F" /></div>
          <h3>ไม่พบออเดอร์</h3>
          <p>ไม่พบข้อมูลของ <b>@{searched}</b> ลองตรวจสอบการสะกดชื่อบัญชีอีกครั้ง หรือทักหาแอดมินได้เลยค่ะ</p>
          <button className="retry" onClick={reset}>ลองค้นหาใหม่</button>
        </div>
      )}

      {view === "error" && (
        <div className="panel">
          <div className="icn"><CoralIcon s={40} c="#E0563F" /></div>
          <h3>ดึงข้อมูลไม่สำเร็จ</h3>
          <p>เชื่อมต่อข้อมูลไม่ได้ชั่วคราว กรุณาลองใหม่อีกครั้ง หรือติดต่อแอดมิน</p>
          <button className="retry" onClick={() => doSearch(searched)}>ลองอีกครั้ง</button>
        </div>
      )}

      <div className="contact">
        <p className="note">หากข้อมูลผิดพลาดหรือมีข้อสงสัย<br />สามารถติดต่อแอดมินได้ที่</p>
        <a className="xbtn" href={`https://x.com/${CONFIG.SHOP_HANDLE}`} target="_blank" rel="noopener noreferrer">
          <XLogo /> Twitter (X) <span className="h">@{CONFIG.SHOP_HANDLE}</span>
        </a>
      </div>
    </div>
  );
}

/* ---------- subtle glass bubbles ---------- */
function spawnBubbles() {
  const ocean = document.querySelector(".ocean");
  if (!ocean) return;
  const N = 12;
  for (let i = 0; i < N; i++) {
    const b = document.createElement("span");
    const depth = Math.random();                 // 0 = far, 1 = near
    const tiny = depth < 0.48 || Math.random() < 0.38;
    const size = tiny
      ? 3 + Math.random() * 7
      : 10 + depth * depth * 26;
    const duration = 15 + (1 - depth) * 16 + Math.random() * 9;
    const drift = (Math.random() < 0.5 ? -1 : 1) * (8 + Math.random() * 26) * (0.45 + depth);
    const alpha = Math.min(0.48, 0.1 + depth * 0.34 + Math.random() * 0.08);
    const blur = depth < 0.42 ? 0.8 + (0.42 - depth) * 4.5 : Math.random() * 0.35;

    b.className = [
      "bubble",
      tiny ? "tiny" : "",
      depth < 0.38 ? "soft" : "",
      Math.random() < 0.1 && !tiny ? "cluster" : "",
    ].filter(Boolean).join(" ");
    b.style.setProperty("--size", size.toFixed(1) + "px");
    b.style.setProperty("--duration", duration.toFixed(1) + "s");
    b.style.setProperty("--delay", (-Math.random() * duration).toFixed(1) + "s");
    b.style.setProperty("--drift", drift.toFixed(1) + "px");
    b.style.setProperty("--alpha", alpha.toFixed(2));
    b.style.setProperty("--rim", (0.18 + depth * 0.38).toFixed(2));
    b.style.left = (Math.random() * 104 - 2).toFixed(2) + "vw";
    b.style.filter = "blur(" + blur.toFixed(2) + "px)";
    ocean.appendChild(b);
  }
}
spawnBubbles();

ReactDOM.createRoot(document.getElementById("root")).render(<App />);
