/* Etsy order verification gate — shown before the editor when entering via an Etsy link.
   Demo logic: validates the order # format + a non-empty email, then "looks up" the order.
   In production this calls your backend / Etsy API. */
const { useState: useStateV, useEffect: useEffectV } = React;
const { PS_DATA: DV } = window;

/* demo "database" of paid Etsy orders keyed by reference */
const ETSY_DB = {
  "ETSY-4827-1193": { buyer: "Anna K.", email: "anna@example.com", productName: "Custom Family Poster", paid: 12, lockSize: "30x40", lockFrame: "oak", template: "name", purchased: "Digital file · 30 × 40 cm" },
  "ETSY-4820-7741": { buyer: "Mike R.", email: "mike@example.com", productName: "Custom Birth Poster", paid: 14, lockSize: "30x40", lockFrame: "oak", template: "birth", purchased: "Digital file · 30 × 40 cm" },
};

function normalizeRef(s) {
  let v = (s || "").toUpperCase().replace(/\s+/g, "");
  if (/^\d{4}-?\d{4}$/.test(v)) v = "ETSY-" + v.replace("-", "").replace(/(\d{4})(\d{4})/, "$1-$2");
  return v;
}
function validEmail(s) { return /^[^@\s]+@[^@\s]+\.[^@\s]+$/.test((s || "").trim()); }

function VerifyGate({ onVerified }) {
  const [ref, setRef] = useStateV("");
  const [email, setEmail] = useStateV("");
  const [err, setErr] = useStateV("");
  const [busy, setBusy] = useStateV(false);

  const submit = () => {
    setErr("");
    const r = normalizeRef(ref);
    if (!/^ETSY-\d{4}-\d{4}$/.test(r)) { setErr("That doesn't look like an Etsy order number (e.g. 4827-1193)."); return; }
    if (!validEmail(email)) { setErr("Enter the email you used on Etsy."); return; }
    setBusy(true);
    // simulate a lookup
    setTimeout(() => {
      const rec = ETSY_DB[r];
      if (!rec) { setBusy(false); setErr("We couldn't find that order. Check the number, or contact us."); return; }
      if (rec.email.toLowerCase() !== email.trim().toLowerCase()) { setBusy(false); setErr("That email doesn't match this order."); return; }
      const entry = { mode: "etsy", source: "etsy", orderRef: r, buyer: rec.buyer, productName: rec.productName,
        digital: true, paid: rec.paid, lockSize: rec.lockSize, lockFrame: rec.lockFrame, purchased: rec.purchased, template: rec.template };
      onVerified(entry);
    }, 650);
  };

  const field = (label, value, set, props) => (
    <label style={{ display: "block", marginBottom: 14 }}>
      <span style={{ fontSize: 12.5, fontWeight: 700, color: "var(--ink-2)", display: "block", marginBottom: 6 }}>{label}</span>
      <input value={value} onChange={e => { set(e.target.value); setErr(""); }} {...props}
        onKeyDown={e => { if (e.key === "Enter") submit(); }}
        style={{ width: "100%", padding: "13px 14px", border: "1.5px solid var(--line-2)", borderRadius: "var(--r-sm)", background: "var(--card)", color: "var(--ink)", fontSize: 15, outline: "none" }}
        onFocus={e => e.target.style.borderColor = "var(--clay)"} onBlur={e => e.target.style.borderColor = "var(--line-2)"} />
    </label>
  );

  return (
    <div className="grain" style={{ position: "relative", height: "100%", display: "flex", alignItems: "center", justifyContent: "center", padding: 20, background: "radial-gradient(120% 90% at 50% 0%, var(--paper-2), var(--paper))", overflow: "auto" }}>
      <div style={{ position: "relative", zIndex: 1, width: "min(420px, 100%)", background: "var(--card)", borderRadius: "var(--r-xl)", boxShadow: "var(--sh-lg)", border: "1px solid var(--line)", padding: "30px 28px 26px" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 11, marginBottom: 18 }}>
          <div style={{ width: 38, height: 38, borderRadius: 10, background: "var(--clay)", color: "#FFF7EF", display: "flex", alignItems: "center", justifyContent: "center", flex: "none" }}><Icon name="Frame" size={21} /></div>
          <div style={{ display: "flex", flexDirection: "column", lineHeight: 1.15 }}>
            <span style={{ fontFamily: "var(--serif)", fontSize: 19, fontWeight: 600 }}>Belle Maison</span>
            <span className="eyebrow" style={{ fontSize: 10 }}>Personalize your order</span>
          </div>
        </div>

        <h2 style={{ fontFamily: "var(--serif)", fontSize: 25, fontWeight: 600, margin: "0 0 6px", letterSpacing: "-.01em" }}>Let's find your order</h2>
        <p style={{ margin: "0 0 20px", color: "var(--ink-2)", fontSize: 14, lineHeight: 1.5 }}>Enter your Etsy order number and email so we can open the exact item you bought.</p>

        {field("Etsy order number", ref, setRef, { placeholder: "4827-1193", inputMode: "numeric", autoFocus: true })}
        {field("Email used on Etsy", email, setEmail, { placeholder: "you@email.com", type: "email" })}

        {err && (
          <div style={{ display: "flex", gap: 8, alignItems: "flex-start", padding: "10px 12px", background: "#F6E2D2", border: "1px solid #E7C2A6", borderRadius: "var(--r-sm)", color: "#8F4124", fontSize: 13, fontWeight: 600, marginBottom: 14, lineHeight: 1.4 }}>
            <Icon name="TriangleAlert" size={15} style={{ flex: "none", marginTop: 1 }} /> {err}
          </div>
        )}

        <button className="btn btn-primary" style={{ width: "100%" }} disabled={busy} onClick={submit}>
          {busy ? <><Icon name="LoaderCircle" size={18} className="spin" /> Finding your order…</> : <>Open my design <Icon name="ArrowRight" size={18} /></>}
        </button>

        <div style={{ display: "flex", alignItems: "center", gap: 8, marginTop: 18, padding: "11px 13px", background: "var(--paper-2)", borderRadius: "var(--r-sm)", color: "var(--ink-3)", fontSize: 12, lineHeight: 1.45 }}>
          <Icon name="ShieldCheck" size={15} style={{ flex: "none" }} />
          <span>Demo: try <b style={{ color: "var(--ink-2)" }}>4827-1193</b> with <b style={{ color: "var(--ink-2)" }}>anna@example.com</b>.</span>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { VerifyGate, ETSY_DB });
