/* global React */
const { useEffect: useEffectPP, useRef: useRefPP } = React;

// CRC-16/CCITT-FALSE (polynomial 0x1021, init 0xFFFF)
function _crc16(str) {
  let crc = 0xFFFF;
  for (let i = 0; i < str.length; i++) {
    crc ^= str.charCodeAt(i) << 8;
    for (let j = 0; j < 8; j++) {
      crc = (crc & 0x8000) ? ((crc << 1) ^ 0x1021) : (crc << 1);
    }
  }
  return (crc & 0xFFFF).toString(16).toUpperCase().padStart(4, "0");
}

function _tlv(tag, value) {
  return tag + String(value.length).padStart(2, "0") + value;
}

function _normalizeId(id) {
  const clean = id.replace(/[-\s]/g, "");
  if (/^0\d{9}$/.test(clean)) return "0066" + clean.slice(1);   // เบอร์โทร 10 หลัก
  if (/^\+66\d{9}$/.test(clean)) return "0066" + clean.slice(3); // +66
  return clean; // เลขบัตรประชาชน
}

function buildPromptPayPayload(promptPayId, amount) {
  const accountId = _normalizeId(promptPayId.trim());
  const merchantInfo = _tlv("00", "A000000677010111") + _tlv("01", accountId);
  let payload =
    _tlv("00", "01") +
    _tlv("01", amount > 0 ? "12" : "11") +
    _tlv("29", merchantInfo) +
    _tlv("52", "0000") +
    _tlv("53", "764") +
    (amount > 0 ? _tlv("54", amount.toFixed(2)) : "") +
    _tlv("58", "TH") +
    _tlv("59", "ParkingHome") +
    _tlv("60", "Bangkok") +
    "6304";
  return payload + _crc16(payload);
}

function PromptPayQR({ promptPayId, amount, size = 200 }) {
  const ref = useRefPP(null);

  useEffectPP(() => {
    if (!promptPayId || !ref.current) return;
    ref.current.innerHTML = "";
    const payload = buildPromptPayPayload(promptPayId, amount || 0);
    if (window.QRCode) {
      new window.QRCode(ref.current, {
        text: payload,
        width: size,
        height: size,
        colorDark: "#000000",
        colorLight: "#ffffff",
        correctLevel: window.QRCode.CorrectLevel.M,
      });
    }
  }, [promptPayId, amount, size]);

  if (!promptPayId) return (
    <div style={{ textAlign: "center", padding: 20, color: "var(--ink-3)", fontSize: "0.85rem" }}>
      กรุณาตั้งค่าเลขพร้อมเพย์ในหน้าตั้งค่าระบบ
    </div>
  );

  return (
    <div style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: 8 }}>
      <div ref={ref} style={{ lineHeight: 0, borderRadius: 8, overflow: "hidden" }}/>
      <div style={{ fontSize: "0.78rem", color: "var(--ink-3)" }}>สแกนชำระผ่าน PromptPay · {promptPayId}</div>
    </div>
  );
}

window.buildPromptPayPayload = buildPromptPayPayload;
window.PromptPayQR = PromptPayQR;
