const { useState } = React;

const LOGO = "https://newworld.co.za/cdn/shop/files/logo.png?v=1644768193";

function App() {
  const [done, setDone] = useState(false);
  const [submitting, setSubmitting] = useState(false);

  const [name, setName] = useState("");
  const [phoneIso, setPhoneIso] = useState("ZA");
  const [phone, setPhone] = useState("");

  const [optWa, setOptWa] = useState(false);

  const [errors, setErrors] = useState({});

  function dial(iso) {
    const c = window.COUNTRIES.find((x) => x.c === iso);
    return c ? c.d : "";
  }

  function validate() {
    const e = {};

    if (!name.trim()) e.name = "Please enter your full name.";
    else if (name.trim().length < 2) e.name = "That name looks a little short.";

    const digits = phone.replace(/\D/g, "");
    if (!digits) e.phone = "Please enter your mobile number.";
    else if (digits.length < 6) e.phone = "That number looks too short.";

    if (!optWa) e.channels = "Please consent to receive WhatsApp messages.";
    setErrors(e);
    return Object.keys(e).length === 0;
  }

  function onSubmit(ev) {
    ev.preventDefault();
    if (!validate()) {
      const first = document.querySelector(".has-error, .field-error");
      if (first) {
        const f = first.closest(".field") || first;
        window.scrollTo({ top: window.scrollY + f.getBoundingClientRect().top - 120, behavior: "smooth" });
      }
      return;
    }
    setSubmitting(true);
    const payload = {
      name: name.trim(),
      phone: "+" + dial(phoneIso) + " " + phone.trim(),
      countryCode: phoneIso,
      consent: { whatsapp_marketing: optWa },
      submittedAt: new Date().toISOString(),
    };
    fetch("/api/submit", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(payload),
    })
      .then((r) => {
        if (!r.ok) throw new Error("Bad response " + r.status);
        setSubmitting(false);
        setDone(true);
        window.scrollTo({ top: 0, behavior: "smooth" });
      })
      .catch((err) => {
        console.error("Submit failed →", err, payload);
        setSubmitting(false);
        setErrors({ submit: "Something went wrong saving your details. Please try again in a moment." });
      });
  }

  function reset() {
    setName(""); setPhone("");
    setPhoneIso("ZA");
    setOptWa(false);
    setErrors({});
    setDone(false);
  }

  return (
    <div className="page">
      <div className="card">
        {/* Brand panel */}
        <aside className="brand">
          <div className="brand-top">
            <img className="brand-logo" src={LOGO} alt="New World" />
          </div>
          <div className="brand-body">
            <h1 className="brand-headline">
              Signup for <br />the best deals.
            </h1>
            <p className="brand-sub">
              Join the New World list and get early access to launches, specials and in-store events.
            </p>
            <ul className="perks">
           
            </ul>
          </div>
          <div className="brand-foot">
            New World Menlyn &nbsp;·&nbsp; (012) 368 1104
          </div>
        </aside>

        {/* Form / success */}
        <main className="form-pane">
          {done ? (
            <Success name={name} onReset={reset} channels={{ whatsapp: optWa }} />
          ) : (
            <form className="form" onSubmit={onSubmit} noValidate autoComplete="off">
              <header className="form-head">
                <h2>Join the list</h2>
                <p>It takes less than a minute. We’ll only message you about things worth knowing.</p>
              </header>

              <TextField
                id="name" label="Full name" value={name}
                onChange={(v) => setName(v)} error={errors.name}
                placeholder="e.g. Thandi Mokoena" autoComplete="off"
              />

              <PhoneField
                id="phone" label="Mobile number"
                iso={phoneIso} number={phone}
                onIso={setPhoneIso} onNumber={setPhone}
                error={errors.phone}
              />

              <div className="consent">
                <Check id="optWa" checked={optWa} onChange={setOptWa} error={errors.channels}>
                  I consent to New World contacting me via WhatsApp to send me promotional offers, new product information, and competition updates. I have read the <a href="https://newworld.co.za/pages/whatsapp-marketing-privacy-policy" target="_blank" rel="noreferrer">WhatsApp Marketing Privacy Notice</a>.
                </Check>
                {errors.channels && <div className="field-error terms-error">{errors.channels}</div>}
              </div>

              <button type="submit" className={"submit" + (submitting ? " is-loading" : "")} disabled={submitting}>
                {submitting ? <span className="spinner" aria-hidden="true"></span> : null}
                <span>{submitting ? "Signing you up…" : "Sign me up"}</span>
              </button>
              {errors.submit && <div className="field-error" style={{ justifyContent: "center" }}>{errors.submit}</div>}

              
            </form>
          )}
        </main>
      </div>
    
    </div>
  );
}

function Success({ name, onReset, channels }) {
  const list = [
    channels.email && "email",
    channels.sms && "SMS",
    channels.whatsapp && "WhatsApp",
  ].filter(Boolean);
  const channelText =
    list.length === 0 ? "" :
    list.length === 1 ? list[0] :
    list.slice(0, -1).join(", ") + " & " + list[list.length - 1];
  const first = (name.trim().split(/\s+/)[0]) || "there";
  return (
    <div className="success">
      <div className="success-check">
        <svg viewBox="0 0 52 52" width="64" height="64" aria-hidden="true">
          <circle className="sc-ring" cx="26" cy="26" r="24" fill="none" stroke="currentColor" strokeWidth="3" />
          <path className="sc-tick" d="M15 27l8 8 15-16" fill="none" stroke="currentColor" strokeWidth="4" strokeLinecap="round" strokeLinejoin="round" />
        </svg>
      </div>
      <h2 className="success-title">You’re on the list, {first}! 🎉</h2>
      <p className="success-sub">
        Thanks for signing up. {channelText ? "We’ll reach out via " + channelText + " with deals worth your while." : "Your preferences are saved."}
        {" "}Keep an eye out — your first members-only offer is on the way.
      </p>
      <div className="success-actions">
        <a className="success-cta" href="https://newworld.co.za/collections/promotions" target="_blank" rel="noreferrer">
          Browse current deals
        </a>
        <button type="button" className="success-link" onClick={onReset}>
          Add another sign-up
        </button>
      </div>
    </div>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<App />);