const { useState, useRef, useEffect } = React;

/* Icons — same hairline style as the rest of Herely */
const Arrow = () => (
  <svg className="arrow" viewBox="0 0 16 16" fill="none">
    <path d="M3 8h9M9 4l4 4-4 4" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round"/>
  </svg>
);
const ChevLeft = () => (
  <svg viewBox="0 0 14 14" width="13" height="13" fill="none">
    <path d="M9 3L5 7l4 4" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
  </svg>
);
const AlertGlyph = () => (
  <svg viewBox="0 0 14 14" width="12" height="12" fill="none">
    <circle cx="7" cy="7" r="6" stroke="currentColor" strokeWidth="1.2"/>
    <path d="M7 4v3.4M7 9.6v.01" stroke="currentColor" strokeWidth="1.3" strokeLinecap="round"/>
  </svg>
);
const Check = () => (
  <svg viewBox="0 0 22 22" width="24" height="24" fill="none">
    <path d="M5 11.5l4 4 8-9" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"/>
  </svg>
);
const Sun = () => (
  <svg viewBox="0 0 18 18" width="16" height="16" fill="none">
    <circle cx="9" cy="9" r="3.4" stroke="currentColor" strokeWidth="1.3"/>
    <path d="M9 1.4v2M9 14.6v2M1.4 9h2M14.6 9h2M3.6 3.6l1.4 1.4M13 13l1.4 1.4M3.6 14.4l1.4-1.4M13 5l1.4-1.4" stroke="currentColor" strokeWidth="1.3" strokeLinecap="round"/>
  </svg>
);
const Moon = () => (
  <svg viewBox="0 0 18 18" width="16" height="16" fill="none">
    <path d="M14.5 10.6A6 6 0 0 1 7.4 3.5a6 6 0 1 0 7.1 7.1Z" stroke="currentColor" strokeWidth="1.3" strokeLinejoin="round"/>
  </svg>
);

/* ── Validation ── */
const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/;
const PHONE_RE = /^[+]?[\d\s().-]{7,}$/;

const FIELDS = [
  { key:"name",  label:"Full name", type:"text",  autoComplete:"name",       placeholder:"Anya Sørensen",      inputMode:"text"  },
  { key:"email", label:"Email",     type:"email", autoComplete:"email",      placeholder:"anya@studio.co",     inputMode:"email" },
  { key:"phone", label:"Phone",     type:"tel",   autoComplete:"tel",        placeholder:"+49 30 1234 5678",   inputMode:"tel"   },
  { key:"city",  label:"City",      type:"text",  autoComplete:"address-level2", placeholder:"Berlin",         inputMode:"text"  },
];

function validateField(key, raw){
  const v = (raw || "").trim();
  switch(key){
    case "name":  return v.length < 2 ? "Please enter your full name." : "";
    case "email": return !v ? "Email is required." : !EMAIL_RE.test(v) ? "Enter a valid email address." : "";
    case "phone": return !v ? "Phone is required." : !PHONE_RE.test(v) ? "Enter a valid phone number." : "";
    case "city":  return v.length < 2 ? "Please tell us your city." : "";
    default: return "";
  }
}

function Field({ def, value, error, touched, onChange, onBlur }){
  const filled = (value || "").trim().length > 0;
  const showErr = !!error && touched;
  const msgId = `${def.key}-msg`;
  return (
    <div className={"field" + (showErr ? " err" : "") + (filled && !showErr ? " filled" : "")}>
      <div className="field-top">
        <label htmlFor={def.key}>{def.label}</label>
        <span className="req" aria-hidden="true">Required</span>
      </div>
      <input
        id={def.key}
        name={def.key}
        className="field-input"
        type={def.type}
        inputMode={def.inputMode}
        autoComplete={def.autoComplete}
        placeholder={def.placeholder}
        value={value}
        onChange={(e) => onChange(def.key, e.target.value)}
        onBlur={() => onBlur(def.key)}
        aria-invalid={showErr}
        aria-describedby={showErr ? msgId : undefined}
        aria-required="true"
      />
      <div className="field-msg" id={msgId} role={showErr ? "alert" : undefined}>
        {showErr && <><AlertGlyph/> {error}</>}
      </div>
    </div>
  );
}

function RequestAccess({ mode, onModeToggle, onNavigate }){
  const midnight = mode === "midnight";

  const [values, setValues] = useState({ name:"", email:"", phone:"", city:"" });
  const [errors, setErrors] = useState({});
  const [touched, setTouched] = useState({});
  const [status, setStatus] = useState("idle");   // idle · loading · success · error

  const onChange = (key, val) => {
    setValues(v => ({ ...v, [key]: val }));
    // live re-validate only once a field has been touched
    if (touched[key]) setErrors(e => ({ ...e, [key]: validateField(key, val) }));
    if (status === "error") setStatus("idle");
  };
  const onBlur = (key) => {
    setTouched(t => ({ ...t, [key]: true }));
    setErrors(e => ({ ...e, [key]: validateField(key, values[key]) }));
  };

  const validateAll = () => {
    const next = {};
    FIELDS.forEach(f => { next[f.key] = validateField(f.key, values[f.key]); });
    return next;
  };

  const onSubmit = async (e) => {
    e.preventDefault();
    const next = validateAll();
    setErrors(next);
    setTouched({ name:true, email:true, phone:true, city:true });
    const firstBad = FIELDS.find(f => next[f.key]);
    if (firstBad){
      const el = document.getElementById(firstBad.key);
      if (el) el.focus();
      return;
    }
    setStatus("loading");
    try {
      // Simulated submission. A real integration would POST here.
      await new Promise((res, rej) => setTimeout(() => {
        // Deterministic failure hook for testing the error state.
        if (values.email.trim().toLowerCase() === "fail@herely.co") rej(new Error("rejected"));
        else res();
      }, 1500));
      setStatus("success");
    } catch {
      setStatus("error");
    }
  };

  const reset = () => {
    setValues({ name:"", email:"", phone:"", city:"" });
    setErrors({}); setTouched({}); setStatus("idle");
  };

  const handleGoBack = (e) => {
    e.preventDefault();
    if (onNavigate) {
      onNavigate("/");
    }
  };

  return (
    <div className="page">
      <nav className="nav">
        <div className="wrap nav-inner">
          <BrandLogo href="/" onClick={handleGoBack} />
          <div className="nav-actions">
            <button type="button" className="mode-toggle" onClick={onModeToggle}
              aria-label={midnight ? "Switch to light mode" : "Switch to midnight mode"}
              title={midnight ? "Light mode" : "Midnight mode"}>
              {midnight ? <Sun/> : <Moon/>}
            </button>
          </div>
        </div>
      </nav>

      <main className="ra-main">
        <div className="ra-shell">
          <header className="ra-head">
            <div className="eyebrow">Founding rooms · 2026</div>
            <h1>Request <span className="ed">access.</span></h1>
            {status !== "success" && (
              <p className="lede">
                Herely opens to a small number of rooms at a time. Leave your details and
                we'll send one quiet reply when a place opens for you.
              </p>
            )}
          </header>

          <div className="ra-card">
            {status === "success" ? (
              <div className="ra-success" role="status" aria-live="polite">
                <div className="seal"><Check/></div>
                <div>
                  <h2>You're on the <span className="ed">list.</span></h2>
                  <p className="lede" style={{marginTop:12}}>
                    Thanks, {values.name.trim().split(" ")[0] || "there"}. We'll reach out at{" "}
                    <span style={{color:"var(--ink)"}}>{values.email.trim()}</span> the moment a founding
                    room opens near {values.city.trim()}.
                  </p>
                </div>
                <div className="echo">
                  <div className="echo-row"><span className="k">Email</span><span className="v">{values.email.trim()}</span></div>
                  <div className="echo-row"><span className="k">Phone</span><span className="v">{values.phone.trim()}</span></div>
                  <div className="echo-row"><span className="k">City</span><span className="v">{values.city.trim()}</span></div>
                </div>
                <button type="button" className="btn btn-ghost" onClick={reset}>Submit another</button>
              </div>
            ) : (
              <form className="ra-form" onSubmit={onSubmit} noValidate>
                {status === "error" && (
                  <div className="form-alert" role="alert">
                    <span className="dot"></span>
                    <div className="txt">
                      <b>We couldn't send that just now.</b> Something went wrong on our end —
                      please try again in a moment.
                    </div>
                  </div>
                )}
                {FIELDS.map(def => (
                  <Field
                    key={def.key}
                    def={def}
                    value={values[def.key]}
                    error={errors[def.key]}
                    touched={touched[def.key]}
                    onChange={onChange}
                    onBlur={onBlur}
                  />
                ))}
                <div className="ra-submit">
                  <button type="submit" className="btn btn-primary btn-full"
                    disabled={status === "loading"} aria-busy={status === "loading"}>
                    {status === "loading"
                      ? <><span className="spinner" aria-hidden="true"></span> Sending…</>
                      : <>Request Access <Arrow/></>}
                  </button>
                  <p className="ra-fineprint">
                    One short form, one quiet reply · No spam, ever
                  </p>
                </div>
              </form>
            )}
          </div>
        </div>
      </main>

      <footer className="ra-foot">
        <div className="ra-foot-inner">
          <BrandLogo style={{fontSize:15}} />
          <div className="mono">© 2026 Herely · Presence before profile.</div>
        </div>
      </footer>
    </div>
  );
}

Object.assign(window, { RequestAccess });
