// checkout.jsx — Buy button + modal with card form. Validates locally and
// transitions to a success state. No real payment is processed.

function luhnOk(num) {
  const s = String(num).replace(/\s+/g, "");
  if (!/^\d{12,19}$/.test(s)) return false;
  let sum = 0, alt = false;
  for (let i = s.length - 1; i >= 0; i--) {
    let n = +s[i];
    if (alt) { n *= 2; if (n > 9) n -= 9; }
    sum += n; alt = !alt;
  }
  return sum % 10 === 0;
}

function formatCardNumber(v) {
  return v.replace(/\D/g, "").slice(0, 19).replace(/(\d{4})(?=\d)/g, "$1 ");
}
function formatExp(v) {
  const d = v.replace(/\D/g, "").slice(0, 4);
  if (d.length <= 2) return d;
  return d.slice(0, 2) + "/" + d.slice(2);
}

function BuyButton({ label = "Buy ThumbForge", className = "btn primary xl" }) {
  const [open, setOpen] = React.useState(false);
  return (
    <>
      <button className={className} onClick={() => setOpen(true)}>
        <span>{label}</span>
        <span style={{opacity:0.7}}>→</span>
      </button>
      {open && <CheckoutModal onClose={() => setOpen(false)} />}
    </>
  );
}

function CheckoutModal({ onClose }) {
  const [email, setEmail] = React.useState("");
  const [name, setName] = React.useState("");
  const [card, setCard] = React.useState("");
  const [exp, setExp] = React.useState("");
  const [cvc, setCvc] = React.useState("");
  const [zip, setZip] = React.useState("");
  const [step, setStep] = React.useState("form"); // form | processing | done
  const [touched, setTouched] = React.useState({});

  // read price from data-price-num (synced w/ tweaks)
  const priceEl = typeof document !== "undefined" ? document.querySelector("[data-price-num]") : null;
  const price = priceEl ? +priceEl.textContent : 29;

  const errs = {
    email: !/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(email) ? "Enter a valid email." : "",
    name:  name.trim().length < 2 ? "Required." : "",
    card:  !luhnOk(card) ? "Card number doesn't look right." : "",
    exp:   !/^\d{2}\/\d{2}$/.test(exp) ? "MM/YY" : "",
    cvc:   !/^\d{3,4}$/.test(cvc) ? "3–4 digits" : "",
    zip:   zip.trim().length < 3 ? "Required." : "",
  };
  const valid = Object.values(errs).every(e => !e);

  function submit(e) {
    e.preventDefault();
    setTouched({email:1,name:1,card:1,exp:1,cvc:1,zip:1});
    if (!valid) return;
    setStep("processing");
    setTimeout(() => setStep("done"), 1400);
  }

  function onScrim(e) { if (e.target === e.currentTarget) onClose(); }

  React.useEffect(() => {
    const onKey = (e) => { if (e.key === "Escape") onClose(); };
    window.addEventListener("keydown", onKey);
    document.body.style.overflow = "hidden";
    return () => { window.removeEventListener("keydown", onKey); document.body.style.overflow = ""; };
  }, [onClose]);

  function F({k, label, children}) {
    const showErr = touched[k] && errs[k];
    return (
      <div className="field fill">
        <label>{label} {showErr && <span style={{color:"#c0392b", textTransform:"none", letterSpacing:0, fontFamily:"var(--ff-body)"}}>— {errs[k]}</span>}</label>
        {children}
      </div>
    );
  }

  return (
    <div className="modal-scrim" onClick={onScrim}>
      <div className="modal" role="dialog" aria-modal="true">
        {step === "form" && (
          <form onSubmit={submit} className="col gap-3">
            <div className="row between center">
              <span className="kicker">Order · one-time purchase</span>
              <button type="button" onClick={onClose} aria-label="Close"
                style={{background:"transparent", border:0, fontSize:22, color:"var(--ink-soft)", cursor:"default", lineHeight:1}}>×</button>
            </div>
            <h2 className="serif">ThumbForge<br/><em style={{color:"var(--accent-deep)"}}>for Windows</em></h2>
            <div className="summary">
              <div className="col gap-2">
                <span className="lab">Single-seat license · lifetime</span>
                <span className="muted" style={{fontSize:13}}>Includes one year of updates · email support</span>
              </div>
              <span className="serif" style={{fontSize:34}}>$<span data-price-num>{price}</span><span style={{fontSize:14, color:"var(--ink-mute)", fontFamily:"var(--ff-mono)"}}> USD</span></span>
            </div>

            <F k="email" label="Email (for the license key)">
              <input type="email" value={email} onChange={e=>setEmail(e.target.value)} onBlur={()=>setTouched(t=>({...t,email:1}))} placeholder="you@example.com" autoFocus />
            </F>
            <F k="name" label="Cardholder name">
              <input value={name} onChange={e=>setName(e.target.value)} onBlur={()=>setTouched(t=>({...t,name:1}))} placeholder="Jordan Maker" />
            </F>
            <F k="card" label="Card number">
              <input value={card} onChange={e=>setCard(formatCardNumber(e.target.value))} onBlur={()=>setTouched(t=>({...t,card:1}))} placeholder="4242 4242 4242 4242" inputMode="numeric" />
            </F>
            <div className="row">
              <F k="exp" label="Expiry">
                <input value={exp} onChange={e=>setExp(formatExp(e.target.value))} onBlur={()=>setTouched(t=>({...t,exp:1}))} placeholder="MM/YY" inputMode="numeric" />
              </F>
              <F k="cvc" label="CVC">
                <input value={cvc} onChange={e=>setCvc(e.target.value.replace(/\D/g,"").slice(0,4))} onBlur={()=>setTouched(t=>({...t,cvc:1}))} placeholder="123" inputMode="numeric" />
              </F>
              <F k="zip" label="ZIP / Postal">
                <input value={zip} onChange={e=>setZip(e.target.value.slice(0,10))} onBlur={()=>setTouched(t=>({...t,zip:1}))} placeholder="94110" />
              </F>
            </div>

            <button type="submit" className="btn primary lg" style={{marginTop:8}}>
              <span>Pay $<span data-price-num>{price}</span> and download</span>
            </button>
            <p className="mono muted" style={{fontSize:11, textAlign:"center", letterSpacing:".06em"}}>
              Payments are processed in test mode for this demo — no card is charged.
            </p>
          </form>
        )}

        {step === "processing" && (
          <div className="col gap-4 center-text" style={{padding:"40px 0"}}>
            <div className="mono" style={{fontSize:11, color:"var(--ink-mute)", letterSpacing:".14em"}}>PROCESSING PAYMENT</div>
            <div style={{height:4, width:240, margin:"0 auto", background:"var(--rule)", borderRadius:2, overflow:"hidden"}}>
              <div style={{height:"100%", width:"45%", background:"var(--accent)", animation:"tfBar 1.2s ease-in-out infinite"}}/>
            </div>
            <p className="muted" style={{fontSize:14}}>Authorizing card · generating license key…</p>
          </div>
        )}

        {step === "done" && (
          <div className="col gap-4 center-text" style={{padding:"24px 0 8px"}}>
            <div className="success">
              <div className="check">✓</div>
              <h2 className="serif" style={{marginTop:8}}>Thanks, you're set.</h2>
            </div>
            <p className="muted" style={{maxWidth:"40ch", margin:"0 auto"}}>
              We've sent a download link and your license key to <strong style={{color:"var(--ink)"}}>{email}</strong>. The installer is ~28 MB.
            </p>
            <div className="card" style={{textAlign:"left", maxWidth:380, margin:"8px auto 0"}}>
              <div className="mono" style={{fontSize:10.5, color:"var(--ink-mute)", letterSpacing:".14em", marginBottom:6}}>LICENSE KEY</div>
              <div className="mono" style={{fontSize:18, letterSpacing:".05em"}}>TF-{Math.random().toString(36).slice(2,6).toUpperCase()}-{Math.random().toString(36).slice(2,6).toUpperCase()}-{Math.random().toString(36).slice(2,6).toUpperCase()}</div>
            </div>
            <div className="row gap-3" style={{justifyContent:"center", marginTop:8}}>
              <button className="btn" onClick={onClose}>Download ThumbForge</button>
              <button className="btn ghost" onClick={onClose}>Close</button>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

window.BuyButton = BuyButton;
