/* global React, QRCode */
const { useState, useEffect, useRef } = React;

function MobilePOSDemo({ brandName = "Green Grocer", currency = "USD", accent = "#009859" }) {
  const [stage, setStage] = useState("entry"); // entry, qr, paid
  const [amount, setAmount] = useState("0");
  const [progress, setProgress] = useState(0);
  const qrRef = useRef(null);

  const symbols = { USD: "$", CAD: "CA$", SGD: "S$", HKD: "HK$" };
  const sym = symbols[currency] || "$";

  // Format amount like a cash-register: right-to-left cents
  const formatted = () => {
    const n = parseInt(amount || "0", 10);
    const dollars = Math.floor(n / 100);
    const cents = String(n % 100).padStart(2, "0");
    return `${dollars.toLocaleString()}.${cents}`;
  };

  const press = (k) => {
    if (amount.length >= 9) return;
    if (amount === "0") setAmount(k);
    else setAmount(amount + k);
  };
  const back = () => setAmount(amount.length <= 1 ? "0" : amount.slice(0, -1));
  const clear = () => { setAmount("0"); };

  const charge = () => {
    if (amount === "0") return;
    setStage("qr");
    setProgress(0);
  };

  // Auto-advance: customer "scans" and pays
  useEffect(() => {
    if (stage !== "qr") return;
    const t = setInterval(() => {
      setProgress((p) => {
        if (p >= 100) { clearInterval(t); setStage("paid"); return 100; }
        return p + 2;
      });
    }, 90);
    return () => clearInterval(t);
  }, [stage]);

  // Draw QR when entering qr stage
  useEffect(() => {
    if (stage !== "qr" || !qrRef.current || !window.QRCode) return;
    const checkoutId = "chk_" + Math.random().toString(36).slice(2, 10);
    const url = `https://pay.allscale.io/c/${checkoutId}?amount=${formatted()}&ccy=${currency}&m=${encodeURIComponent(brandName)}`;
    qrRef.current.innerHTML = "";
    new QRCode(qrRef.current, {
      text: url, width: 220, height: 220,
      colorDark: "#0C3124", colorLight: "#FFFFFF", correctLevel: QRCode.CorrectLevel.H,
    });
  }, [stage, amount, currency, brandName]);

  const reset = () => { setStage("entry"); setAmount("0"); setProgress(0); };

  const txHash = "0x" + Math.random().toString(16).slice(2, 10) + "…" + Math.random().toString(16).slice(2, 6);

  return (
    <div style={mobStyles.app}>
      {/* App header */}
      <div style={mobStyles.header}>
        <div style={mobStyles.merchantRow}>
          <div style={mobStyles.merchantDot}>{brandName.slice(0, 1)}</div>
          <div>
            <div style={{ fontSize: 14, fontWeight: 500 }}>{brandName}</div>
            <div style={{ fontSize: 11, color: "#83968F" }}>Tap to charge</div>
          </div>
        </div>
        <div style={mobStyles.currencyPill}>{currency}</div>
      </div>

      {stage === "entry" && (
        <>
          <div style={mobStyles.amountBlock}>
            <div style={mobStyles.amountLabel}>Amount</div>
            <div style={mobStyles.amountRow}>
              <span style={mobStyles.sym}>{sym}</span>
              <span style={mobStyles.amount}>{formatted()}</span>
            </div>
            <div style={mobStyles.subtle}>Customer pays with any stablecoin wallet</div>
          </div>

          <div style={mobStyles.keypad}>
            {["1","2","3","4","5","6","7","8","9",".","0","⌫"].map((k, i) => {
              const isBack = k === "⌫";
              const isDot = k === ".";
              return (
                <button key={i} style={mobStyles.key}
                  onClick={() => isBack ? back() : (isDot ? null : press(k))}>
                  {k}
                </button>
              );
            })}
          </div>

          <button style={{ ...mobStyles.charge, background: accent, opacity: amount === "0" ? 0.4 : 1 }}
            onClick={charge} disabled={amount === "0"}>
            Charge {sym}{formatted()}
          </button>
        </>
      )}

      {stage === "qr" && (
        <div style={mobStyles.qrStage}>
          <div style={mobStyles.qrTotal}>
            <div style={{ fontSize: 12, color: "#83968F", letterSpacing: 0 }}>Total due</div>
            <div style={mobStyles.qrAmount}>{sym}{formatted()} <span style={mobStyles.ccy}>{currency}</span></div>
          </div>
          <div style={mobStyles.qrFrame}>
            <div ref={qrRef} style={{ display: "flex", justifyContent: "center" }} />
            <div style={mobStyles.qrCorner} />
            <div style={{ ...mobStyles.qrCorner, right: 0, left: "auto" }} />
            <div style={{ ...mobStyles.qrCorner, bottom: 0, top: "auto" }} />
            <div style={{ ...mobStyles.qrCorner, right: 0, bottom: 0, top: "auto", left: "auto" }} />
          </div>
          <div style={mobStyles.qrHelp}>Scan with any wallet · USDT · USDC</div>
          <div style={mobStyles.progWrap}>
            <div style={{ ...mobStyles.progBar, width: `${progress}%` }} />
          </div>
          <div style={{ ...mobStyles.subtle, textAlign: "center", marginTop: 10 }}>
            {progress < 40 ? "Waiting for scan…" : progress < 85 ? "Payment detected…" : "Confirming on-chain…"}
          </div>
          <button style={mobStyles.cancel} onClick={reset}>Cancel</button>
        </div>
      )}

      {stage === "paid" && (
        <div style={mobStyles.paidStage}>
          <div style={mobStyles.checkCircle}>
            <svg width="44" height="44" viewBox="0 0 24 24" fill="none" stroke="#fff" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><path d="m5 12 4 4 10-10" /></svg>
          </div>
          <div style={mobStyles.paidAmt}>{sym}{formatted()}</div>
          <div style={mobStyles.paidLbl}>Paid · {currency}</div>
          <div style={mobStyles.receipt}>
            <div style={mobStyles.rRow}><span>Method</span><span>USDT · Polygon</span></div>
            <div style={mobStyles.rRow}><span>Fee</span><span>0.5%</span></div>
            <div style={mobStyles.rRow}><span>Settled</span><span>Instant</span></div>
            <div style={mobStyles.rRow}><span>Tx</span><span style={{ fontFamily: "monospace" }}>{txHash}</span></div>
          </div>
          <div style={mobStyles.paidActions}>
            <button style={mobStyles.secondaryBtn}>Send receipt</button>
            <button style={{ ...mobStyles.charge, background: accent, marginTop: 0 }} onClick={reset}>New charge</button>
          </div>
        </div>
      )}
    </div>
  );
}

const mobStyles = {
  app: {
    position: "absolute", inset: 0, background: "#FDFFFE",
    display: "flex", flexDirection: "column", padding: "52px 20px 24px",
    fontFamily: "Archivo, sans-serif", color: "#0C3124",
  },
  header: {
    display: "flex", justifyContent: "space-between", alignItems: "center",
    paddingBottom: 14,
  },
  merchantRow: { display: "flex", gap: 10, alignItems: "center" },
  merchantDot: {
    width: 36, height: 36, borderRadius: 12, background: "#F2F8F5",
    color: "#009859", fontWeight: 700, display: "flex", alignItems: "center", justifyContent: "center",
  },
  currencyPill: {
    fontSize: 12, padding: "6px 10px", borderRadius: 999, background: "#F2F8F5",
    color: "#0C3124", fontWeight: 500,
  },
  amountBlock: { padding: "30px 6px 16px", textAlign: "center" },
  amountLabel: { fontSize: 12, color: "#83968F", marginBottom: 10 },
  amountRow: { display: "flex", alignItems: "baseline", justifyContent: "center", gap: 4 },
  sym: { fontSize: 28, fontWeight: 500, color: "#83968F" },
  amount: { fontSize: 52, fontWeight: 700, letterSpacing: "-0.04em", fontVariantNumeric: "tabular-nums" },
  subtle: { fontSize: 12, color: "#83968F", marginTop: 6 },
  keypad: {
    display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 8,
    margin: "4px 0 14px",
  },
  key: {
    height: 54, borderRadius: 16, border: 0, background: "#F2F8F5", color: "#0C3124",
    fontSize: 22, fontWeight: 500, fontFamily: "inherit", cursor: "pointer",
  },
  charge: {
    width: "100%", padding: 16, borderRadius: 999, border: 0, color: "#fff",
    fontSize: 17, fontWeight: 500, fontFamily: "inherit", cursor: "pointer",
    letterSpacing: "-0.02em",
  },
  qrStage: { flex: 1, display: "flex", flexDirection: "column", alignItems: "center", paddingTop: 10 },
  qrTotal: { textAlign: "center", marginBottom: 14 },
  qrAmount: { fontSize: 34, fontWeight: 700, letterSpacing: "-0.03em", fontVariantNumeric: "tabular-nums" },
  ccy: { fontSize: 14, color: "#83968F", fontWeight: 500, marginLeft: 4 },
  qrFrame: {
    position: "relative", padding: 14, background: "#fff",
    border: "1px solid #E5EEEA", borderRadius: 22,
  },
  qrCorner: {
    position: "absolute", top: 0, left: 0, width: 18, height: 18,
    borderTop: "2.5px solid #009859", borderLeft: "2.5px solid #009859",
    borderRadius: "6px 0 0 0",
  },
  qrHelp: { fontSize: 12, color: "#83968F", marginTop: 14 },
  progWrap: {
    width: "80%", height: 6, background: "#E5EEEA", borderRadius: 999, marginTop: 18, overflow: "hidden",
  },
  progBar: { height: "100%", background: "#009859", transition: "width .15s linear" },
  cancel: {
    marginTop: "auto", padding: "12px 18px", borderRadius: 999, border: "1px solid #E4E6E5",
    background: "transparent", fontFamily: "inherit", fontSize: 14, fontWeight: 500, cursor: "pointer",
  },
  paidStage: { flex: 1, display: "flex", flexDirection: "column", alignItems: "center", paddingTop: 16 },
  checkCircle: {
    width: 72, height: 72, borderRadius: "50%", background: "#009859",
    display: "flex", alignItems: "center", justifyContent: "center", marginBottom: 12,
  },
  paidAmt: { fontSize: 36, fontWeight: 700, letterSpacing: "-0.03em", fontVariantNumeric: "tabular-nums" },
  paidLbl: { fontSize: 13, color: "#83968F", marginTop: 4 },
  receipt: {
    width: "100%", marginTop: 24, padding: "14px 16px", background: "#FAFBFA",
    border: "1px solid #E5EEEA", borderRadius: 16, fontSize: 13,
  },
  rRow: { display: "flex", justifyContent: "space-between", padding: "6px 0", color: "#0C3124" },
  paidActions: { marginTop: "auto", width: "100%", display: "flex", flexDirection: "column", gap: 10 },
  secondaryBtn: {
    width: "100%", padding: 14, borderRadius: 999, border: "1px solid #E4E6E5",
    background: "#fff", color: "#0C3124", fontFamily: "inherit", fontSize: 15, fontWeight: 500, cursor: "pointer",
  },
};

window.MobilePOSDemo = MobilePOSDemo;
