// Waitlist page
const WaitlistPage = () => {
  const [form, setForm] = React.useState({
    name: "", email: "", role: "Traveler", referral: "",
  });
  const [sent, setSent] = React.useState(null);
  const [copied, setCopied] = React.useState(false);
  const [submitting, setSubmitting] = React.useState(false);
  const [error, setError] = React.useState("");
  const upd = (k) => (e) => setForm({...form, [k]: e.target.value});
  const submit = async (e) => {
    e.preventDefault();
    if (submitting) return;
    setSubmitting(true);
    setError("");
    try {
      const r = await fetch("/api/forms/waitlist", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          name: form.name,
          email: form.email,
          role: form.role,
          referral: form.referral || undefined,
        }),
      });
      const data = await r.json().catch(() => ({}));
      if (!r.ok || !data.ok) {
        setError("Something went wrong. Please try again.");
        setSubmitting(false);
        return;
      }
      const firstName = data.firstName || (form.name || "").trim().split(/\s+/)[0] || "Friend";
      window.__thanks = { kind: "waitlist", firstName, email: form.email, role: form.role, code: data.code };
      window.__setRoute && window.__setRoute("thanks");
    } catch (err) {
      setError("Network error. Please try again.");
      setSubmitting(false);
    }
  };
  const copy = () => {
    navigator.clipboard?.writeText(`trepic.co/waitlist?ref=${sent.code}`);
    setCopied(true);
    setTimeout(() => setCopied(false), 1800);
  };

  const benefits = [
    { t: "Priority access", d: "Be among the first invited to the beta, ahead of the public launch." },
    { t: "Founding Creator badge", d: "A permanent mark on your profile — earned only during this window." },
    { t: "Up to 20% commission rate", d: "The ceiling rate Trepic will ever offer creators — paid by the property, not by the traveler. Locked in for life." },
    { t: "Direct line to the founding team", d: "Monthly founder calls. Product input. A seat in the room." },
    { t: "Move up by referring friends", d: "Every friend who joins with your code moves you closer to day one." },
  ];

  return (
    <main>
      <section className="section" style={{paddingTop: "calc(var(--nav-h) + 80px)"}} data-screen-label="Waitlist">
        <div className="container">
          <div className="waitlist-grid">
            <div className="reveal">
              <div className="eyebrow" style={{marginBottom: 24}}>Join the Waitlist</div>
              <h1 className="display" style={{fontSize:"clamp(40px,5vw,64px)",marginBottom: 24}}>
                Be among the <em>first</em> to travel with Trepic.
              </h1>
              <p className="body-lg" style={{maxWidth: 480, marginBottom: 8}}>Founding members shape the platform and keep the highest commission rates we'll ever offer.</p>
              <ol className="benefit-list">
                {benefits.map((b,i) => (
                  <li key={b.t}>
                    <div className="bn">0{i+1}</div>
                    <div>
                      <div className="bt">{b.t}</div>
                      <div className="bd">{b.d}</div>
                    </div>
                  </li>
                ))}
              </ol>
            </div>

            <div className="reveal">
              {sent ? (
                <div className="success-block">
                  <div className="eyebrow on-dark" style={{color:"rgba(255,255,255,0.7)"}}>You're In</div>
                  <div style={{fontFamily:"var(--ff-display)",fontSize:"clamp(30px,3.4vw,48px)",lineHeight:1.15,margin:"24px 0 12px",fontStyle:"italic"}}>
                    Welcome, {sent.name || "traveler"}.
                  </div>
                  <p style={{color:"rgba(255,255,255,0.7)",margin:"0 auto 8px",maxWidth: 420}}>
                    We've saved your spot. Check {sent.email || "your inbox"} for confirmation.
                  </p>
                  <div style={{marginTop: 32, paddingTop: 32, borderTop: "1px solid rgba(255,255,255,0.15)"}}>
                    <div className="eyebrow on-dark" style={{color:"rgba(255,255,255,0.6)"}}>Your Referral Code</div>
                    <div className="code">{sent.code}</div>
                    <p style={{color:"rgba(255,255,255,0.7)",maxWidth:380,margin:"0 auto 20px",fontSize:14,lineHeight:1.55}}>
                      Share your code. Every friend who joins moves you up. Top referrers earn Founding Creator status.
                    </p>
                    <button type="button" onClick={copy} className="btn on-dark" style={{marginTop: 4}}>
                      {copied ? "Copied ✓" : "Copy Share Link"}
                    </button>
                  </div>
                  <p style={{color:"rgba(255,255,255,0.4)",fontSize:11,letterSpacing:"0.22em",textTransform:"uppercase",marginTop:32}}>
                    No spam. We only email when it's time.
                  </p>
                </div>
              ) : (
                <form onSubmit={submit} style={{border:"1px solid var(--c-line-strong)",padding:"40px 36px"}}>
                  <div className="field"><label>Name</label><input required value={form.name} onChange={upd("name")}/></div>
                  <div className="field"><label>Email</label><input required type="email" value={form.email} onChange={upd("email")}/></div>
                  <div className="field">
                    <label>I am a…</label>
                    <div className="toggle-row" style={{marginTop: 4}}>
                      {["Traveler","Creator","Hotel & Brand","Tourism Board"].map(r => (
                        <button type="button" key={r} className={"toggle-btn" + (form.role === r ? " on" : "")} onClick={()=>setForm({...form, role: r})}>{r}</button>
                      ))}
                    </div>
                  </div>
                  <div className="field">
                    <label>Referral Code <span className="opt">optional</span></label>
                    <input value={form.referral} onChange={upd("referral")} placeholder="e.g. LUNA-3142"/>
                  </div>
                  <button type="submit" disabled={submitting} className="btn lg" style={{marginTop: 16, width: "100%", opacity: submitting ? 0.6 : 1}}>
                    {submitting ? "Saving…" : <>Join the Waitlist <span className="arrow">→</span></>}
                  </button>
                  {error ? <p style={{color:"#b04040",fontSize:13,marginTop:12,textAlign:"center"}}>{error}</p> : null}
                  <p style={{fontSize:10,letterSpacing:"0.22em",textTransform:"uppercase",color:"var(--c-mute)",marginTop:24,textAlign:"center"}}>
                    No spam. We only email when it's time.
                  </p>
                </form>
              )}
            </div>
          </div>
        </div>
      </section>
    </main>
  );
};

Object.assign(window, { WaitlistPage });
