// ============================================
// LOPOBYA — Welcome Discount Popup
// Muncul sekali per pengunjung (Meta ads landing).
// Kasih kode WELCOME20 → auto-apply di checkout.
// ============================================
const WelcomePopup = ({ lang = "id", setPage, config }) => {
  const SEEN_KEY  = "lopobya_welcome_seen";
  const VOUCH_KEY = "lopobya_pending_voucher";

  const t = (en, id) => (lang === "id" ? id : en);

  // Semua teks/gambar/diskon bisa diatur dari Admin → Dekorasi → Popup Diskon.
  // Kalau belum diatur, pakai default di bawah.
  const cfg      = config || {};
  const active   = cfg.active !== false;                 // default: tampil
  const PERCENT  = cfg.percent != null && cfg.percent !== "" ? cfg.percent : 20;
  const CODE     = String(cfg.code || "WELCOME20").toUpperCase();
  const HERO_IMG = cfg.image || "uploads/products/prod_09baa4116e8f4550e42049c8fe0d6517.jpg";
  const KICKER   = cfg.kicker || t("Welcome to LOPOBYA", "Selamat Datang di LOPOBYA");
  const TITLE    = cfg.title  || t("20% off your first order", "Diskon 20% pesanan pertamamu");
  const DESC     = cfg.desc   || t(
    "Be one of our first customers and enjoy 20% off your checkout. Use the code below — it's applied automatically.",
    "Jadi pelanggan pertama kami dan nikmati potongan 20% saat checkout. Pakai kode di bawah — otomatis terpasang di keranjang."
  );
  const BTN      = cfg.btnText || t("Shop Now", "Belanja Sekarang");

  const [show,    setShow]    = React.useState(false);
  const [mounted, setMounted] = React.useState(false);  // utk animasi masuk
  const [copied,  setCopied]  = React.useState(false);

  // Cek apakah sudah pernah lihat
  React.useEffect(() => {
    if (!active) return;   // dimatikan dari admin
    let seen = false;
    try { seen = localStorage.getItem(SEEN_KEY) === "1"; } catch {}
    if (seen) return;
    const tm = setTimeout(() => {
      setShow(true);
      requestAnimationFrame(() => setMounted(true));
      // Simpan kode supaya checkout auto-apply, walau popup ditutup
      try { localStorage.setItem(VOUCH_KEY, CODE); } catch {}
      if (typeof fbq === "function") fbq("trackCustom", "WelcomeOfferShown", { code: CODE, value: PERCENT });
    }, 900);
    return () => clearTimeout(tm);
  }, []);

  // Lock scroll body selama popup terbuka
  React.useEffect(() => {
    if (!show) return;
    const prev = document.body.style.overflow;
    document.body.style.overflow = "hidden";
    return () => { document.body.style.overflow = prev; };
  }, [show]);

  const markSeen = () => { try { localStorage.setItem(SEEN_KEY, "1"); } catch {} };

  const close = () => {
    markSeen();
    setMounted(false);
    setTimeout(() => setShow(false), 260);
  };

  const copyCode = () => {
    try {
      navigator.clipboard.writeText(CODE);
      setCopied(true);
      setTimeout(() => setCopied(false), 1800);
    } catch {}
  };

  const shopNow = () => {
    try { localStorage.setItem(VOUCH_KEY, CODE); } catch {}
    if (typeof fbq === "function") fbq("trackCustom", "WelcomeOfferClaimed", { code: CODE, value: PERCENT });
    markSeen();
    setMounted(false);
    setTimeout(() => { setShow(false); if (setPage) setPage("catalog"); }, 200);
  };

  if (!show) return null;

  return (
    <div
      onClick={close}
      style={{
        position: "fixed", inset: 0, zIndex: 10000,
        background: `rgba(17,17,17,${mounted ? 0.55 : 0})`,
        display: "flex", alignItems: "center", justifyContent: "center",
        padding: 20, transition: "background 0.3s ease",
      }}
    >
      <div
        onClick={(e) => e.stopPropagation()}
        style={{
          position: "relative", width: "100%", maxWidth: 420,
          background: "#f9f8f6", borderRadius: 4, overflow: "hidden",
          boxShadow: "0 24px 70px rgba(0,0,0,0.32)",
          textAlign: "center",
          opacity: mounted ? 1 : 0,
          transform: mounted ? "translateY(0) scale(1)" : "translateY(20px) scale(0.96)",
          transition: "opacity 0.3s ease, transform 0.35s cubic-bezier(.2,.7,.2,1)",
        }}
      >
        {/* Close button */}
        <button
          onClick={close} aria-label="Close"
          style={{
            position: "absolute", top: 12, right: 12, zIndex: 3,
            width: 30, height: 30, borderRadius: "50%",
            background: "rgba(0,0,0,0.45)", border: "none", fontSize: 20, lineHeight: 1,
            cursor: "pointer", color: "#fff", padding: 0,
            display: "flex", alignItems: "center", justifyContent: "center",
          }}
        >×</button>

        {/* Hero image + badge */}
        <div style={{ position: "relative", height: 210, overflow: "hidden", background: "#efece7" }}>
          <img
            src={HERO_IMG} alt="LOPOBYA"
            style={{ width: "100%", height: "100%", objectFit: "cover", objectPosition: "center", display: "block" }}
          />
          {/* Gradient bawah biar teks kebaca */}
          <div style={{
            position: "absolute", left: 0, right: 0, bottom: 0, height: "55%",
            background: "linear-gradient(to bottom, rgba(17,17,17,0) 0%, rgba(17,17,17,0.78) 100%)",
          }} />
          {/* Badge diskon */}
          <div style={{
            position: "absolute", top: 16, left: 16,
            background: "#111", color: "#fff", borderRadius: 999,
            padding: "9px 16px", display: "flex", alignItems: "baseline", gap: 4,
            boxShadow: "0 6px 18px rgba(0,0,0,0.25)",
          }}>
            <span style={{ fontFamily: "'Fraunces',serif", fontSize: 26, fontWeight: 600, lineHeight: 1 }}>
              {PERCENT}<span style={{ fontSize: 14 }}>%</span>
            </span>
            <span style={{
              fontFamily: "'DM Sans',sans-serif", fontSize: 10, fontWeight: 600,
              letterSpacing: "0.14em", textTransform: "uppercase", color: "#bda77e",
            }}>OFF</span>
          </div>
          {/* Headline di atas gradient */}
          <div style={{ position: "absolute", left: 22, right: 22, bottom: 16 }}>
            <p style={{
              fontFamily: "'DM Sans',sans-serif", fontSize: 9.5, letterSpacing: "0.22em",
              textTransform: "uppercase", color: "#dcd2c0", marginBottom: 5,
            }}>
              {KICKER}
            </p>
            <p style={{
              fontFamily: "'Fraunces',serif", fontSize: 25, fontWeight: 500,
              lineHeight: 1.15, color: "#fff", fontStyle: "italic",
            }}>
              {TITLE}
            </p>
          </div>
        </div>

        {/* Body */}
        <div style={{ padding: "22px 30px 28px" }}>
          <p style={{
            fontFamily: "'DM Sans',sans-serif", fontSize: 13.5, lineHeight: 1.6,
            color: "#555", marginBottom: 18,
          }}>
            {DESC}
          </p>

          {/* Code box */}
          <button
            onClick={copyCode}
            style={{
              width: "100%", border: "1.5px dashed #111", borderRadius: 3,
              background: "#fff", padding: "13px 16px", marginBottom: 16,
              cursor: "pointer", display: "flex", alignItems: "center", justifyContent: "center", gap: 10,
            }}
          >
            <span style={{
              fontFamily: "'DM Sans',sans-serif", fontSize: 19, fontWeight: 700,
              letterSpacing: "0.16em", color: "#111",
            }}>{CODE}</span>
            <span style={{
              fontFamily: "'DM Sans',sans-serif", fontSize: 10, letterSpacing: "0.1em",
              textTransform: "uppercase", color: copied ? "#1a8a4a" : "#999",
            }}>
              {copied ? t("Copied!", "Tersalin!") : t("Tap to copy", "Salin")}
            </span>
          </button>

          {/* CTA */}
          <button
            onClick={shopNow}
            style={{
              width: "100%", padding: "15px 24px", background: "#111", border: "none",
              cursor: "pointer", color: "#f9f8f6", borderRadius: 2,
              fontFamily: "'DM Sans',sans-serif", fontSize: 12, fontWeight: 600,
              letterSpacing: "0.16em", textTransform: "uppercase",
            }}
          >
            {BTN}
          </button>

          <button
            onClick={close}
            style={{
              marginTop: 12, background: "none", border: "none", cursor: "pointer",
              fontFamily: "'DM Sans',sans-serif", fontSize: 11.5, color: "#aaa",
              textDecoration: "underline", textUnderlineOffset: 3,
            }}
          >
            {t("No thanks", "Nanti saja")}
          </button>
        </div>
      </div>
    </div>
  );
};
