// Page — Request Access
// Atelier-desk two-column layout: portrait plate left, application form right.
// Interactive fields, validation, chapter-style success overlay.

// ─── Shared form logic ──────────────────────────────────────────────
const LANGS = ["Français","English","Español","Deutsch","Italiano","العربية","Other"];
const COUNTRY_CODES = [
  {c:"+33",  f:"FR"},{c:"+44",  f:"UK"},{c:"+1",   f:"US"},
  {c:"+971", f:"AE"},{c:"+41",  f:"CH"},{c:"+377", f:"MC"},
  {c:"+39",  f:"IT"},{c:"+34",  f:"ES"},{c:"+49",  f:"DE"},
  {c:"+7",   f:"RU"},{c:"+852", f:"HK"},{c:"+65",  f:"SG"},
  {c:"+81",  f:"JP"}
];

const validate = (d) => {
  const err = {};
  if (!d.name || d.name.trim().length < 2) err.name = "Please share your full name";
  if (!d.email || !/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(d.email)) err.email = "A valid e-mail address, please";
  if (!d.phone || d.phone.replace(/\D/g,"").length < 6) err.phone = "A number we may reach you on";
  if (!d.city || d.city.trim().length < 2) err.city = "Your city of residence";
  return err;
};

// ─── Fine underline input (used by all 3 layouts) ────────────────────
const UnderlineField = ({label, name, value, onChange, error, placeholder, type="text", as="input", children, required=true}) => {
  const common = {
    name, value: value||"", onChange,
    placeholder,
    style:{
      width:"100%", background:"transparent",
      border:"none", outline:"none",
      borderBottom: error ? "1px solid #C4715A" : "1px solid rgba(170,135,87,.35)",
      padding:"12px 0 10px",
      font:"400 17px/1.4 var(--font-editorial)",
      color:"var(--epa-paper-ivory)",
      transition:"border-color .22s"
    },
    onFocus:e=>{if(!error) e.currentTarget.style.borderBottomColor="var(--epa-gold)"},
    onBlur:e=>{if(!error) e.currentTarget.style.borderBottomColor="rgba(170,135,87,.35)"}
  };
  return (
    <label style={{display:"block"}}>
      <div style={{font:"500 10px/1 var(--font-ui)", color:"var(--epa-gold)",
        letterSpacing:".28em", textTransform:"uppercase", marginBottom:12,
        display:"flex", justifyContent:"space-between", alignItems:"baseline"}}>
        <span>{label}{required && <span style={{color:"rgba(170,135,87,.5)"}}> ·</span>}</span>
        {error && <span style={{color:"#C4715A", fontSize:10, letterSpacing:".1em",
          fontStyle:"italic", textTransform:"none"}}>— {error}</span>}
      </div>
      {as==="textarea"
        ? <textarea rows={3} {...common} style={{...common.style, resize:"vertical", minHeight:64}}/>
        : as==="select"
          ? <select {...common}>{children}</select>
          : <input type={type} {...common}/>}
    </label>
  );
};

// ─── Phone with country select ──────────────────────────────────────
const PhoneField = ({dial, phone, onDial, onPhone, error}) => (
  <div>
    <div style={{font:"500 10px/1 var(--font-ui)", color:"var(--epa-gold)",
      letterSpacing:".28em", textTransform:"uppercase", marginBottom:12,
      display:"flex", justifyContent:"space-between", alignItems:"baseline"}}>
      <span>Telephone<span style={{color:"rgba(170,135,87,.5)"}}> ·</span></span>
      {error && <span style={{color:"#C4715A", fontSize:10, letterSpacing:".1em",
        fontStyle:"italic", textTransform:"none"}}>— {error}</span>}
    </div>
    <div style={{display:"grid", gridTemplateColumns:"120px 1fr", gap:18,
      borderBottom: error ? "1px solid #C4715A" : "1px solid rgba(170,135,87,.35)"}}>
      <select value={dial} onChange={onDial}
        style={{background:"transparent", border:"none", outline:"none",
          padding:"12px 0 10px", font:"400 17px/1.4 var(--font-editorial)",
          color:"var(--epa-champagne)"}}>
        {COUNTRY_CODES.map(c => <option key={c.c} value={c.c}>{c.c}  {c.f}</option>)}
      </select>
      <input value={phone} onChange={onPhone} placeholder="6 XX XX XX XX"
        style={{background:"transparent", border:"none", outline:"none",
          padding:"12px 0 10px", font:"400 17px/1.4 var(--font-editorial)",
          color:"var(--epa-paper-ivory)"}}/>
    </div>
  </div>
);

// ─── Success overlay — chapter-style ────────────────────────────────
const SuccessChapter = ({name, onClose}) => (
  <div style={{position:"fixed", inset:0, zIndex:100,
    background:"radial-gradient(ellipse at 50% 20%, #2A1C0E 0%, #0F0A06 55%, #050302 100%)",
    display:"flex", alignItems:"center", justifyContent:"center",
    animation:"fadeIn .8s ease-out"}}>
    <style>{`
      @keyframes fadeIn {from{opacity:0}to{opacity:1}}
      @keyframes rise {from{opacity:0; transform:translateY(18px)} to{opacity:1; transform:translateY(0)}}
    `}</style>
    <div style={{textAlign:"center", padding:"0 40px", maxWidth:760,
      animation:"rise 1s .2s both ease-out"}}>
      <div style={{font:"400 11px/1 var(--font-editorial)", color:"var(--epa-gold)",
        letterSpacing:".5em", textTransform:"uppercase", marginBottom:40}}>— Chapitre suivant · Reçu</div>

      {/* wax seal */}
      <div style={{
        width:110, height:110, margin:"0 auto 44px",
        borderRadius:"50%",
        background:"radial-gradient(circle at 35% 30%, #E8CFA0 0%, #C9A871 35%, #8B6530 75%, #4A3418 100%)",
        boxShadow:`
          0 1px 2px rgba(255,230,180,.4) inset,
          0 -6px 14px rgba(0,0,0,.55) inset,
          0 14px 34px -6px rgba(0,0,0,.75),
          0 4px 10px rgba(0,0,0,.5)
        `,
        display:"flex", alignItems:"center", justifyContent:"center", position:"relative"
      }}>
        <div style={{position:"absolute", inset:8, borderRadius:"50%",
          border:"1px solid rgba(60,38,15,.55)",
          boxShadow:"0 0 0 1px rgba(255,225,170,.22) inset"}}/>
        <div style={{font:"300 42px/1 var(--font-display)", color:"#3A2610",
          textShadow:"0 1px 0 rgba(255,230,180,.45), 0 -1px 1px rgba(0,0,0,.4)",
          letterSpacing:".04em"}}>EPA</div>
      </div>

      <h1 style={{font:"400 84px/1.02 var(--font-display)",
        letterSpacing:".02em", margin:"0 0 28px", color:"var(--epa-paper-ivory)"}}>
        {name ? `${name.split(" ")[0]},` : "Reçu —"}<br/>
        <em style={{color:"var(--epa-champagne)"}}>we will write to you.</em>
      </h1>

      <div style={{display:"flex", justifyContent:"center", margin:"0 0 36px"}}>
        <Arabesque w={120}/>
      </div>

      <p style={{font:"italic 300 19px/1.55 var(--font-editorial)",
        color:"var(--epa-text-secondary)", margin:"0 auto 20px", maxWidth:560}}>
        Your letter has arrived at the atelier.
        A founder will read it in the coming hours and reply within twenty-four.
      </p>
      <p style={{font:"italic 300 15px/1.55 var(--font-editorial)",
        color:"var(--epa-text-secondary)", margin:"0 auto 56px", maxWidth:460}}>
        All correspondence is held in confidence — within the atelier, and no further.
      </p>

      <button onClick={onClose} style={{
        background:"transparent", color:"var(--epa-champagne)",
        border:"1px solid var(--epa-gold-dark)",
        padding:"14px 26px", font:"500 12px/1 var(--font-ui)",
        letterSpacing:".24em", textTransform:"uppercase", cursor:"pointer"}}>
        Close this letter
      </button>
    </div>
  </div>
);

// ─── The page itself ───────────────────────────────────────────────
const RequestAccessPage = () => {
  React.useEffect(() => { if (window.lucide) lucide.createIcons(); });
  const [data, setData] = React.useState({name:"", email:"", dial:"+33", phone:"", city:"", lang:"Français", intro:"", message:""});
  const [errors, setErrors] = React.useState({});
  const [sent, setSent] = React.useState(false);
  const [sending, setSending] = React.useState(false);
  const [submitError, setSubmitError] = React.useState(null);

  const update = (k) => (e) => {
    const v = e.target.value;
    setData(d => ({...d, [k]:v}));
    if (errors[k]) setErrors(err => { const {[k]:_, ...rest} = err; return rest; });
  };

  // Netlify Forms: POST form-urlencoded to "/" with form-name=request-access.
  // A hidden detection form lives in request-access.html so Netlify registers
  // the form at deploy time. Locally (file:// or python server) the fetch
  // will fail gracefully — we still show the success overlay for the demo.
  const onSubmit = async (e) => {
    e.preventDefault();
    const err = validate(data);
    if (Object.keys(err).length) { setErrors(err); return; }

    setSending(true);
    setSubmitError(null);

    const body = new URLSearchParams({
      "form-name": "request-access",
      "bot-field": "",
      ...data
    }).toString();

    try {
      const res = await fetch("/", {
        method: "POST",
        headers: {"Content-Type": "application/x-www-form-urlencoded"},
        body
      });
      // On Netlify this returns 200. Locally it may 404 — still show success.
      if (!res.ok && window.location.hostname !== "localhost" && !window.location.hostname.includes("127.0.0.1")) {
        throw new Error("Submission failed (" + res.status + ")");
      }
      setSent(true);
    } catch (err) {
      console.warn("Form submission:", err);
      // In local dev, still show success so the UX can be previewed.
      if (window.location.protocol === "file:" || window.location.hostname === "localhost") {
        setSent(true);
      } else {
        setSubmitError("Something went wrong. Please try again, or write to concierge@eliteprivateagency.com.");
      }
    } finally {
      setSending(false);
    }
  };

  return (
    <div style={{background:"#0B0703", color:"var(--epa-paper-ivory)",
      width:"100%", minHeight:"100%", fontFamily:"var(--font-editorial)"}}>
      <SiteNav/>
      <AtelierLayout data={data} update={update} onSubmit={onSubmit} errors={errors} sending={sending} submitError={submitError}/>
      <SiteFooter/>
      {sent && <SuccessChapter name={data.name} onClose={() => setSent(false)}/>}
    </div>
  );
};
