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

function TerminalPOSDemo({ brandName = "Green Grocer", currency = "USD", style = "retail", accent = "#009859" }) {
  const [stage, setStage] = useState("entry");
  const [amount, setAmount] = useState("0");
  const [progress, setProgress] = useState(0);
  const [pressedKey, setPressedKey] = useState(null);
  const qrRef = useRef(null);

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

  const formatted = () => {
    const n = parseInt(amount || "0", 10);
    return `${Math.floor(n / 100).toLocaleString()}.${String(n % 100).padStart(2, "0")}`;
  };

  const press = (k) => {
    setPressedKey(k);
    setTimeout(() => setPressedKey(null), 120);
    if (k === "⌫") return setAmount(amount.length <= 1 ? "0" : amount.slice(0, -1));
    if (k === "C") return setAmount("0");
    if (amount.length >= 9) return;
    setAmount(amount === "0" ? k : amount + k);
  };

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

  useEffect(() => {
    if (stage !== "qr") return;
    const t = setInterval(() => setProgress((p) => {
      if (p >= 100) { clearInterval(t); setStage("paid"); return 100; }
      return p + 2.5;
    }), 100);
    return () => clearInterval(t);
  }, [stage]);

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

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

  const Screen = () => (
    <div style={termStyles.screenGlass}>
      <div style={termStyles.glare} />
      <div style={termStyles.screen}>
        <div style={termStyles.screenTop}>
          <span style={{ fontSize: 10, color: "#83968F", letterSpacing: "0.1em" }}>{brandName.toUpperCase()} · POS #04</span>
          <span style={termStyles.live}><span style={termStyles.liveDot} />LIVE</span>
        </div>

        {stage === "entry" && (
          <div style={termStyles.screenBody}>
            <div style={{ fontSize: 9, color: "#83968F", letterSpacing: "0.14em" }}>AMOUNT DUE</div>
            <div style={termStyles.bigAmt}>
              <span style={{ fontSize: 22, color: "#7a9185", fontWeight: 500 }}>{sym}</span>
              {formatted()}
            </div>
            <div style={{ fontSize: 9, color: "#83968F", letterSpacing: "0.08em" }}>{currency} · PRESS CHARGE</div>
          </div>
        )}

        {stage === "qr" && (
          <div style={termStyles.screenBodyQr}>
            <div style={{ textAlign: "center", fontSize: 10, color: "#83968F", letterSpacing: "0.08em" }}>
              TOTAL {sym}{formatted()} {currency}
            </div>
            <div ref={qrRef} style={{ padding: 7, background: "#fff", borderRadius: 8 }} />
            <div style={termStyles.progWrap}>
              <div style={{ ...termStyles.progBar, width: `${progress}%` }} />
            </div>
            <div style={{ fontSize: 9, color: "#83968F", letterSpacing: "0.08em" }}>
              {progress < 40 ? "WAITING FOR SCAN…" : progress < 85 ? "PAYMENT DETECTED…" : "CONFIRMING…"}
            </div>
          </div>
        )}

        {stage === "paid" && (
          <div style={termStyles.screenBody}>
            <div style={termStyles.approved}>✓ APPROVED</div>
            <div style={termStyles.bigAmt}>
              <span style={{ fontSize: 22, color: "#7a9185", fontWeight: 500 }}>{sym}</span>
              {formatted()}
            </div>
            <div style={{ fontSize: 9, color: "#83968F", fontFamily: "monospace" }}>{txHash}</div>
          </div>
        )}
      </div>
    </div>
  );

  const keys = ["1","2","3","4","5","6","7","8","9","C","0","⌫"];

  // RETAIL: 3D Verifone/Ingenico-style vertical terminal
  if (style === "retail") {
    return (
      <div data-r="terminal-root" style={termStyles.scene}>
        <div style={termStyles.floorShadow} />
        <div style={termStyles.retailWrap}>
          {/* Back panel shadow depth */}
          <div style={termStyles.retailShell}>
            {/* Top bezel / brand plate */}
            <div style={termStyles.retailTopBezel}>
              <div style={termStyles.brandPlate}>
                <div style={termStyles.ledDot} />
                <span style={{ fontSize: 9, color: "#a0a0a0", letterSpacing: "0.16em", fontWeight: 500 }}>ALLSCALE PAY</span>
              </div>
            </div>

            <div style={termStyles.retailBody}>
              {/* Screen with bezel + glass */}
              <div style={termStyles.retailBezel}>
                <Screen />
              </div>

              {/* Physical keypad grid */}
              <div style={termStyles.keypadSurround}>
                <div style={termStyles.keypadGrid}>
                  {keys.map((k) => (
                    <PhysicalKey key={k} label={k} pressed={pressedKey === k} onClick={() => press(k)} />
                  ))}
                </div>

                {/* Action strip */}
                <div style={termStyles.actionStrip}>
                  <PhysicalActionKey label="CANCEL" tone="red" onClick={reset} small />
                  <PhysicalActionKey
                    label={stage === "entry" ? "CHARGE" : stage === "qr" ? "CANCEL" : "NEW SALE"}
                    tone="green"
                    onClick={stage === "paid" ? reset : stage === "qr" ? reset : charge}
                    accent={accent}
                  />
                </div>
              </div>

              {/* Card reader slot + contactless zone */}
              <div style={termStyles.readerZone}>
                <div style={termStyles.contactlessRing}>
                  <div style={termStyles.contactlessIcon}>
                    <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="#4a4a4a" strokeWidth="1.8" strokeLinecap="round">
                      <path d="M8 5c2 2 3 4 3 7s-1 5-3 7"/>
                      <path d="M12 3c3 3 4 5 4 9s-1 6-4 9"/>
                      <path d="M16 1c4 4 5 6 5 11s-1 7-5 11"/>
                    </svg>
                  </div>
                </div>
                <div style={termStyles.cardSlot}>
                  <div style={termStyles.slotInner} />
                  <span style={{ fontSize: 8, color: "#707070", letterSpacing: "0.14em", marginTop: 4 }}>INSERT CARD</span>
                </div>
              </div>
            </div>
          </div>

          {/* Stand base / foot */}
          <div style={termStyles.retailBaseRing}>
            <div style={termStyles.retailBase} />
          </div>
        </div>
      </div>
    );
  }

  // MODERN TABLET — Square-style 3D countertop register
  return (
    <div data-r="terminal-root" style={termStyles.scene}>
      <div style={termStyles.floorShadow} />
      <div style={termStyles.tabletWrap}>
        {/* Tablet hovering on metal stand */}
        <div style={termStyles.tabletBody}>
          {/* Bezel */}
          <div style={termStyles.tabletBezel}>
            {/* Inner screen with two zones */}
            <div style={termStyles.tabletScreen}>
              <div style={termStyles.tabletSide1}>
                <Screen />
              </div>
              <div style={termStyles.tabletSide2}>
                <div style={termStyles.tabletKeypadGrid}>
                  {keys.map((k) => (
                    <SoftKey key={k} label={k} pressed={pressedKey === k} onClick={() => press(k)} />
                  ))}
                </div>
                <button
                  onClick={stage === "paid" ? reset : stage === "qr" ? reset : charge}
                  style={{ ...termStyles.tabletCharge, background: stage === "entry" ? accent : "#1a2d25" }}>
                  {stage === "entry" ? `CHARGE ${sym}${formatted()}` : stage === "qr" ? "CANCEL" : "NEW SALE"}
                </button>
              </div>
            </div>
            {/* Front-facing camera dot */}
            <div style={termStyles.frontCam} />
            {/* Brand mark */}
            <div style={termStyles.tabletBrand}>allscale</div>
          </div>
        </div>

        {/* Metal stand neck */}
        <div style={termStyles.tabletNeck} />
        {/* Stand puck base */}
        <div style={termStyles.tabletPuck}>
          <div style={termStyles.tabletPuckTop} />
        </div>
      </div>
    </div>
  );
}

/* ── Physical button components ── */
function PhysicalKey({ label, pressed, onClick }) {
  return (
    <button
      onMouseDown={onClick}
      style={{
        ...termStyles.physKey,
        transform: pressed ? "translateY(2px)" : "translateY(0)",
        boxShadow: pressed
          ? "inset 0 2px 4px rgba(0,0,0,0.35), 0 0 0 1px #0a0a0a"
          : "0 2px 0 #0a0a0a, 0 3px 4px rgba(0,0,0,0.4), inset 0 1px 0 rgba(255,255,255,0.1)",
      }}>
      <span style={termStyles.physKeyLabel}>{label}</span>
    </button>
  );
}

function PhysicalActionKey({ label, tone, onClick, small, accent }) {
  const palettes = {
    red: {
      bg: "linear-gradient(180deg, #9a2b2b 0%, #6a1818 100%)",
      lip: "#3a0a0a",
      text: "#ffd8d6",
    },
    green: {
      bg: `linear-gradient(180deg, ${accent || "#12D16B"} 0%, #047a3f 100%)`,
      lip: "#023820",
      text: "#ffffff",
    },
  };
  const p = palettes[tone];
  return (
    <button
      onMouseDown={onClick}
      style={{
        ...termStyles.actionKey,
        flex: small ? "0 0 80px" : 1,
        background: p.bg,
        color: p.text,
        boxShadow: `0 3px 0 ${p.lip}, 0 5px 8px rgba(0,0,0,0.35), inset 0 1px 0 rgba(255,255,255,0.25)`,
      }}
      onMouseUpCapture={(e) => { e.currentTarget.style.transform = "translateY(0)"; }}
      onPointerDownCapture={(e) => { e.currentTarget.style.transform = "translateY(2px)"; e.currentTarget.style.boxShadow = `0 1px 0 ${p.lip}, inset 0 2px 4px rgba(0,0,0,0.25)`; }}
      onPointerUpCapture={(e) => { e.currentTarget.style.transform = "translateY(0)"; e.currentTarget.style.boxShadow = `0 3px 0 ${p.lip}, 0 5px 8px rgba(0,0,0,0.35), inset 0 1px 0 rgba(255,255,255,0.25)`; }}
      onPointerLeave={(e) => { e.currentTarget.style.transform = "translateY(0)"; e.currentTarget.style.boxShadow = `0 3px 0 ${p.lip}, 0 5px 8px rgba(0,0,0,0.35), inset 0 1px 0 rgba(255,255,255,0.25)`; }}
    >
      {label}
    </button>
  );
}

function SoftKey({ label, pressed, onClick }) {
  return (
    <button onMouseDown={onClick}
      style={{
        ...termStyles.softKey,
        background: pressed ? "#e5eeea" : "#fff",
        transform: pressed ? "scale(0.97)" : "scale(1)",
      }}>
      {label}
    </button>
  );
}

const termStyles = {
  scene: {
    position: "relative", display: "flex", flexDirection: "column",
    alignItems: "center", padding: "20px 10px 40px",
    perspective: 1400,
  },
  floorShadow: {
    position: "absolute", bottom: 16, width: 320, height: 28,
    background: "radial-gradient(ellipse at center, rgba(0,0,0,0.25) 0%, transparent 70%)",
    filter: "blur(4px)", pointerEvents: "none",
  },

  // Screen (shared) — with glass glare + subtle curvature
  screenGlass: {
    position: "relative", background: "#000", borderRadius: 10,
    padding: 1, boxShadow: "inset 0 0 0 1px rgba(255,255,255,0.04)",
    overflow: "hidden",
  },
  glare: {
    position: "absolute", top: 0, left: 0, right: 0, height: "55%",
    background: "linear-gradient(180deg, rgba(255,255,255,0.08) 0%, transparent 100%)",
    pointerEvents: "none", zIndex: 2,
  },
  screen: {
    position: "relative", zIndex: 1,
    background: "linear-gradient(180deg, #0d3527 0%, #0a2b1f 100%)",
    borderRadius: 9, padding: "14px 16px",
    color: "#fff", fontFamily: "Archivo, sans-serif",
    minHeight: 200, display: "flex", flexDirection: "column", gap: 8,
  },
  screenTop: { display: "flex", justifyContent: "space-between", alignItems: "center" },
  live: { display: "inline-flex", alignItems: "center", gap: 5, color: "#12D16B", fontSize: 9, fontWeight: 500, letterSpacing: "0.08em" },
  liveDot: { width: 6, height: 6, borderRadius: "50%", background: "#12D16B", boxShadow: "0 0 6px #12D16B", animation: "pulse 1.4s infinite" },
  screenBody: { flex: 1, display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", gap: 6, textAlign: "center" },
  screenBodyQr: { flex: 1, display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", gap: 8 },
  bigAmt: {
    fontSize: 40, fontWeight: 700, letterSpacing: "-0.04em", fontVariantNumeric: "tabular-nums",
    color: "#fff", display: "flex", alignItems: "baseline", gap: 4,
    textShadow: "0 0 20px rgba(18,209,107,0.12)",
  },
  approved: { fontSize: 11, color: "#12D16B", letterSpacing: "0.12em", fontWeight: 500, textShadow: "0 0 8px rgba(18,209,107,0.4)" },
  progWrap: { width: 150, height: 3, background: "rgba(255,255,255,0.1)", borderRadius: 999, overflow: "hidden" },
  progBar: { height: "100%", background: "#12D16B", transition: "width .15s linear", boxShadow: "0 0 6px #12D16B" },

  /* RETAIL — 3D Ingenico/Verifone style */
  retailWrap: {
    position: "relative",
    transform: "rotateX(4deg)",
    transformStyle: "preserve-3d",
  },
  retailShell: {
    width: 300,
    background: "linear-gradient(180deg, #2a2a2d 0%, #18181a 50%, #0f0f10 100%)",
    borderRadius: "28px 28px 22px 22px",
    padding: "16px 14px 20px",
    boxShadow: `
      0 1px 0 rgba(255,255,255,0.08) inset,
      0 -2px 0 rgba(0,0,0,0.5) inset,
      -2px 0 0 rgba(0,0,0,0.3) inset,
      2px 0 0 rgba(0,0,0,0.3) inset,
      0 30px 50px rgba(0,0,0,0.35),
      0 12px 20px rgba(0,0,0,0.25)
    `,
    border: "1px solid #1e1e20",
    position: "relative",
  },
  retailTopBezel: {
    display: "flex", justifyContent: "center", marginBottom: 12,
    padding: "6px 0",
  },
  brandPlate: {
    display: "inline-flex", alignItems: "center", gap: 8,
    padding: "4px 10px", background: "rgba(0,0,0,0.4)",
    borderRadius: 999, border: "1px solid rgba(255,255,255,0.04)",
    boxShadow: "inset 0 1px 2px rgba(0,0,0,0.4)",
  },
  ledDot: {
    width: 5, height: 5, borderRadius: "50%",
    background: "#12D16B", boxShadow: "0 0 6px #12D16B, 0 0 2px #fff",
  },
  retailBody: {
    background: "linear-gradient(180deg, #1a1a1c 0%, #0d0d0f 100%)",
    borderRadius: "20px 20px 16px 16px",
    padding: "14px 12px 14px",
    boxShadow: "inset 0 2px 6px rgba(0,0,0,0.6), inset 0 -1px 0 rgba(255,255,255,0.02)",
  },
  retailBezel: {
    background: "#000", padding: 4, borderRadius: 12, marginBottom: 14,
    boxShadow: "inset 0 0 0 2px #0a0a0a, 0 2px 4px rgba(0,0,0,0.4)",
  },
  keypadSurround: {
    background: "linear-gradient(180deg, #0a0a0c 0%, #151517 100%)",
    padding: 10, borderRadius: 12,
    boxShadow: "inset 0 2px 4px rgba(0,0,0,0.5)",
  },
  keypadGrid: { display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 7 },
  physKey: {
    height: 44, borderRadius: 8, border: 0,
    background: "linear-gradient(180deg, #3a3a3d 0%, #222224 48%, #1a1a1c 100%)",
    color: "#fff", fontFamily: "inherit", cursor: "pointer",
    display: "flex", alignItems: "center", justifyContent: "center",
    transition: "transform 0.08s, box-shadow 0.08s",
    position: "relative",
  },
  physKeyLabel: {
    fontSize: 17, fontWeight: 500, color: "#e8e8e8",
    textShadow: "0 1px 0 rgba(0,0,0,0.5)",
  },
  actionStrip: {
    display: "flex", gap: 8, marginTop: 8,
  },
  actionKey: {
    height: 42, borderRadius: 8, border: 0,
    fontFamily: "inherit", fontSize: 13, fontWeight: 700,
    letterSpacing: "0.1em", cursor: "pointer",
    transition: "all 0.08s",
    textShadow: "0 1px 1px rgba(0,0,0,0.3)",
  },
  readerZone: {
    marginTop: 12, display: "flex", alignItems: "center", justifyContent: "space-between",
    padding: "10px 8px 4px",
  },
  contactlessRing: {
    width: 42, height: 42, borderRadius: "50%",
    background: "linear-gradient(180deg, #1a1a1c, #0a0a0c)",
    display: "flex", alignItems: "center", justifyContent: "center",
    boxShadow: "inset 0 1px 2px rgba(255,255,255,0.04), inset 0 -1px 2px rgba(0,0,0,0.5)",
    border: "1px solid #0a0a0a",
  },
  contactlessIcon: { opacity: 0.7 },
  cardSlot: { display: "flex", flexDirection: "column", alignItems: "center" },
  slotInner: {
    width: 120, height: 5, background: "#000", borderRadius: 2,
    boxShadow: "inset 0 2px 3px rgba(0,0,0,0.9)",
  },
  retailBaseRing: {
    width: 240, height: 14, background: "linear-gradient(180deg, #1a1a1c, #050505)",
    borderRadius: "0 0 8px 8px", marginTop: -2,
    boxShadow: "0 8px 12px rgba(0,0,0,0.3)",
  },
  retailBase: {
    width: 180, height: 8, margin: "6px auto 0",
    background: "#0a0a0c", borderRadius: "0 0 6px 6px",
    opacity: 0.6,
  },

  /* MODERN TABLET — Square-style 3D countertop */
  tabletWrap: {
    position: "relative",
    display: "flex", flexDirection: "column", alignItems: "center",
    transform: "rotateX(6deg)",
    transformStyle: "preserve-3d",
  },
  tabletBody: {
    position: "relative",
    transformStyle: "preserve-3d",
  },
  tabletBezel: {
    width: 560, padding: 14,
    background: "linear-gradient(180deg, #fafaf8 0%, #ebebe8 100%)",
    borderRadius: 24,
    boxShadow: `
      inset 0 1px 0 rgba(255,255,255,0.9),
      inset 0 -2px 0 rgba(0,0,0,0.06),
      0 2px 0 #c8c8c5,
      0 6px 0 #b0b0ad,
      0 18px 32px rgba(0,0,0,0.18),
      0 4px 12px rgba(0,0,0,0.08)
    `,
    position: "relative",
    border: "1px solid #d8d8d5",
  },
  tabletScreen: {
    background: "#FDFFFE", borderRadius: 14, padding: 16,
    display: "grid", gridTemplateColumns: "1.1fr 1fr", gap: 14,
    border: "1px solid #E5EEEA",
    boxShadow: "inset 0 0 0 1px rgba(255,255,255,0.9), 0 1px 2px rgba(0,0,0,0.04)",
    position: "relative", overflow: "hidden",
  },
  tabletSide1: { display: "flex", flexDirection: "column" },
  tabletSide2: { display: "flex", flexDirection: "column", gap: 10 },
  tabletKeypadGrid: { display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 8, flex: 1 },
  softKey: {
    height: 52, borderRadius: 12, border: "1px solid #E5EEEA",
    fontSize: 20, fontWeight: 500, fontFamily: "inherit",
    color: "#0C3124", cursor: "pointer",
    boxShadow: "0 1px 2px rgba(0,0,0,0.03), inset 0 -2px 0 #ECF1EE",
    transition: "all 0.08s",
  },
  tabletCharge: {
    width: "100%", padding: "16px 12px", borderRadius: 14, border: 0,
    color: "#fff", fontFamily: "inherit", fontSize: 14, fontWeight: 700,
    letterSpacing: "0.08em", cursor: "pointer",
    boxShadow: "0 4px 12px rgba(0,152,89,0.25), inset 0 1px 0 rgba(255,255,255,0.18)",
  },
  frontCam: {
    position: "absolute", top: 7, left: "50%", transform: "translateX(-50%)",
    width: 6, height: 6, borderRadius: "50%", background: "#222",
    boxShadow: "inset 0 0 0 1px rgba(255,255,255,0.1)",
  },
  tabletBrand: {
    position: "absolute", bottom: 4, left: "50%", transform: "translateX(-50%)",
    fontSize: 9, color: "#b8b8b5", letterSpacing: "0.14em",
    fontFamily: "Archivo, sans-serif", fontWeight: 500,
  },
  tabletNeck: {
    width: 36, height: 38,
    background: "linear-gradient(180deg, #b8b8b5 0%, #8c8c89 50%, #6e6e6b 100%)",
    marginTop: -2,
    borderRadius: "0 0 4px 4px",
    boxShadow: "inset 2px 0 3px rgba(255,255,255,0.25), inset -2px 0 3px rgba(0,0,0,0.2)",
  },
  tabletPuck: {
    width: 190, height: 22,
    background: "linear-gradient(180deg, #9a9a97 0%, #6a6a67 60%, #4a4a47 100%)",
    borderRadius: "50%",
    boxShadow: "0 12px 20px rgba(0,0,0,0.25), inset 0 2px 2px rgba(255,255,255,0.2), inset 0 -2px 3px rgba(0,0,0,0.3)",
    position: "relative",
    marginTop: -2,
  },
  tabletPuckTop: {
    position: "absolute", top: 2, left: "10%", right: "10%",
    height: 6, borderRadius: "50%",
    background: "linear-gradient(180deg, rgba(255,255,255,0.3), transparent)",
  },
};

// Inject keyframes once
if (typeof document !== "undefined" && !document.getElementById("term-kf")) {
  const s = document.createElement("style");
  s.id = "term-kf";
  s.textContent = `@keyframes pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.35; } }`;
  document.head.appendChild(s);
}

window.TerminalPOSDemo = TerminalPOSDemo;
