// หน้าเช็ก IMEI (ผ่าน sickw.com — proxy ที่เซิร์ฟเวอร์)
function ImeiPage({ user }) {
  const toast = useToast();
  const [imei, setImei] = React.useState("");
  const [service, setService] = React.useState("40");
  const [loading, setLoading] = React.useState(false);
  const [result, setResult] = React.useState(null);   // { ok, fields:[{k,v}], rawHtml, status, imei, service }
  const [history, setHistory] = React.useState(() => {
    try { return JSON.parse(localStorage.getItem("ss-imei-hist") || "[]"); } catch (e) { return []; }
  });

  // บริการยอดนิยมของ sickw — แก้เลข service ให้ตรงกับบัญชีได้
  const SERVICES = [
    { id: "40", label: "Apple MDM & iCloud & GSX Status" },
    { id: "3", label: "ข้อมูลพื้นฐาน (ยี่ห้อ/รุ่น/สี/ความจุ)" },
    { id: "30", label: "iPhone Carrier + SIM-Lock" },
    { id: "8", label: "Warranty / Activation (Apple)" },
    { id: "custom", label: "อื่นๆ (ระบุเลขเอง)" },
  ];
  const [customId, setCustomId] = React.useState("");

  // แปลงผลลัพธ์ (sickw คืน result เป็น HTML "Key: Value<br>") → คู่ key/value
  function parseResult(html) {
    if (typeof html !== "string") return { fields: [], rawHtml: "" };
    const clean = html.replace(/<br\s*\/?>/gi, "\n").replace(/<[^>]+>/g, "");
    const fields = [];
    clean.split("\n").forEach((line) => {
      const l = line.trim(); if (!l) return;
      const i = l.indexOf(":");
      if (i > 0 && i < 40) fields.push({ k: l.slice(0, i).trim(), v: l.slice(i + 1).trim() });
      else fields.push({ k: "", v: l });
    });
    return { fields, rawHtml: html };
  }

  function doCheck() {
    const id = (service === "custom" ? customId : service).trim();
    const code = imei.trim().replace(/\s+/g, "");
    if (!code) { toast("ใส่ IMEI หรือ Serial ก่อน", "danger"); return; }
    if (!id) { toast("เลือกบริการ / ใส่เลข service", "danger"); return; }
    if (!window.__ssImeiCheck) { toast("ระบบยังไม่พร้อม (ต้องออนไลน์กับเซิร์ฟเวอร์)", "danger"); return; }
    setLoading(true); setResult(null);
    window.__ssImeiCheck(code, id).then(({ httpOk, data }) => {
      setLoading(false);
      if (!data || !httpOk || data.ok === false) {
        const msg = (data && (data.error || data.result)) || "เช็กไม่สำเร็จ";
        setResult({ ok: false, status: "error", errMsg: String(msg), imei: code, service: id });
        toast(String(msg), "danger");
        return;
      }
      const parsed = parseResult(data.result);
      const rec = { ok: true, status: data.status, imei: code, service: id, fields: parsed.fields, rawHtml: parsed.rawHtml, at: Date.now() };
      setResult(rec);
      const h = [{ imei: code, service: id, at: rec.at, brief: (parsed.fields[0] && (parsed.fields[0].v || parsed.fields[0].k)) || "" }, ...history].slice(0, 20);
      setHistory(h);
      try { localStorage.setItem("ss-imei-hist", JSON.stringify(h)); } catch (e) {}
    }).catch((e) => { setLoading(false); toast("เชื่อมต่อไม่สำเร็จ", "danger"); });
  }

  function copyResult() {
    if (!result || !result.fields) return;
    const txt = result.fields.map((f) => (f.k ? f.k + ": " : "") + f.v).join("\n");
    if (navigator.clipboard) navigator.clipboard.writeText(txt).then(() => toast("คัดลอกผลแล้ว"));
  }

  return (
    <div>
      <SectionTitle>เช็ก IMEI / Serial</SectionTitle>
      <div style={{ display: "grid", gridTemplateColumns: "1.3fr 1fr", gap: 16, alignItems: "start" }}>
        {/* ซ้าย: ฟอร์มเช็ก */}
        <Card style={{ padding: 20 }}>
          <Field label="IMEI หรือ Serial Number">
            <TextInput value={imei} onChange={(e) => setImei(e.target.value)}
              onKeyDown={(e) => { if (e.key === "Enter") doCheck(); }}
              placeholder="เช่น 354442067957452 หรือ C39XXXXXXXXX" />
          </Field>
          <div style={{ height: 12 }} />
          <Field label="บริการ (service)">
            <select value={service} onChange={(e) => setService(e.target.value)} style={selStyle}>
              {SERVICES.map((s) => <option key={s.id} value={s.id}>{s.id === "custom" ? s.label : (s.id + " · " + s.label)}</option>)}
            </select>
          </Field>
          {service === "custom" && (
            <React.Fragment>
              <div style={{ height: 10 }} />
              <Field label="เลข service ID"><TextInput value={customId} onChange={(e) => setCustomId(e.target.value)} placeholder="เช่น 12" /></Field>
            </React.Fragment>
          )}
          <div style={{ marginTop: 18, display: "flex", gap: 10 }}>
            <Btn onClick={doCheck} disabled={loading}>{loading ? "กำลังเช็ก…" : "🔍 เช็กเลย"}</Btn>
            {imei && <Btn kind="ghost" onClick={() => { setImei(""); setResult(null); }}>ล้าง</Btn>}
          </div>
          <div style={{ marginTop: 14, padding: "10px 14px", background: T.chipBg, borderRadius: 10, fontSize: 11.5, color: T.sub, lineHeight: 1.7 }}>
            เชื่อมกับ sickw.com · แต่ละครั้งมีค่าใช้จ่ายตามบริการ · ผลลัพธ์ขึ้นกับเซิร์ฟเวอร์ Apple/ผู้ให้บริการ
          </div>
        </Card>

        {/* ขวา: ผลลัพธ์ */}
        <Card style={{ padding: 20, minHeight: 200 }}>
          <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 12 }}>
            <div style={{ fontWeight: 700, fontSize: 14 }}>ผลการเช็ก</div>
            {result && result.ok && <Btn sm kind="ghost" onClick={copyResult}>⧉ คัดลอก</Btn>}
          </div>
          {loading && <div style={{ color: T.sub, fontSize: 13, padding: "30px 0", textAlign: "center" }}>⏳ กำลังดึงข้อมูล…</div>}
          {!loading && !result && <div style={{ color: T.sub, fontSize: 13, padding: "30px 0", textAlign: "center" }}>ยังไม่มีผล — ใส่ IMEI แล้วกดเช็ก</div>}
          {!loading && result && !result.ok && (
            <div style={{ color: "#e74c3c", fontSize: 13, padding: "16px 0", whiteSpace: "pre-wrap" }}>✕ {result.errMsg}</div>
          )}
          {!loading && result && result.ok && (
            <div style={{ display: "grid", gap: 7 }}>
              {result.fields.map((f, i) => (
                <div key={i} style={{ display: "flex", gap: 10, fontSize: 13, borderBottom: "1px solid " + T.line, paddingBottom: 6 }}>
                  {f.k ? <span style={{ color: T.sub, minWidth: 130, flex: "0 0 130px" }}>{f.k}</span> : null}
                  <span style={{ fontWeight: f.k ? 600 : 400, wordBreak: "break-word" }}>{f.v}</span>
                </div>
              ))}
            </div>
          )}
        </Card>
      </div>

      {/* ประวัติเช็กล่าสุด */}
      {history.length > 0 && (
        <Card style={{ padding: 18, marginTop: 16 }}>
          <div style={{ fontWeight: 700, fontSize: 14, marginBottom: 10 }}>เช็กล่าสุด</div>
          <div style={{ display: "grid", gap: 6 }}>
            {history.map((h, i) => (
              <div key={i} onClick={() => { setImei(h.imei); setService(SERVICES.some((s) => s.id === h.service) ? h.service : "custom"); if (!SERVICES.some((s) => s.id === h.service)) setCustomId(h.service); }}
                style={{ display: "flex", gap: 12, fontSize: 12.5, color: T.sub, cursor: "pointer", padding: "5px 8px", borderRadius: 8 }}>
                <span style={{ fontWeight: 600, color: T.text }}>{h.imei}</span>
                <span>service {h.service}</span>
                {h.brief && <span style={{ marginLeft: "auto", opacity: .8 }}>{h.brief}</span>}
              </div>
            ))}
          </div>
        </Card>
      )}
    </div>
  );
}

const selStyle = {
  width: "100%", padding: "10px 12px", borderRadius: 10, border: "1px solid " + T.line,
  background: T.inputBg || "#fff", color: T.text, fontSize: 14, fontFamily: T.bodyFont,
};

window.ImeiPage = ImeiPage;
