/* Stream Translations — Contact form + Footer. Exports to window. */
const { useState: useStateC, useEffect: useEffectC } = React;

/* ===== Email delivery config (Web3Forms — no server, reliable CORS) =====
   Submissions POST to Web3Forms via AJAX and the success screen shows
   in place (no page reload). To change the access key or receiving
   address, update it in your Web3Forms account and replace accessKey. */
const FORM_CONFIG = {
  endpoint: "https://api.web3forms.com/submit",
  accessKey: "687a5997-86c3-4673-b400-132b2d6ec472",
  subject: "【お問い合わせ】Stream Translations サイトより",
  fromName: "Stream Translations サイト",
};

function Contact({ c, refEl }) {
  const f = c.contact.form;
  const [vals, setVals] = useStateC({ name: "", company: "", email: "", lang: "", message: "" });
  const [errs, setErrs] = useStateC({});
  const [sent, setSent] = useStateC(false);
  const [sending, setSending] = useStateC(false);
  const [sendErr, setSendErr] = useStateC("");

  const set = (k) => (e) => setVals((v) => ({ ...v, [k]: e.target.value }));

  const validate = () => {
    const e = {};
    if (!vals.name.trim()) e.name = f.errName;
    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(vals.email)) e.email = f.errEmail;
    if (!vals.message.trim()) e.message = f.errMessage;
    setErrs(e);
    return Object.keys(e).length === 0;
  };

  // Submit via AJAX to Web3Forms; show the success screen in place.
  const submit = async (ev) => {
    ev.preventDefault();
    setSendErr("");
    if (!validate()) return;
    setSending(true);
    const payload = {
      access_key: FORM_CONFIG.accessKey,
      subject: FORM_CONFIG.subject,
      from_name: FORM_CONFIG.fromName,
      name: vals.name,
      company: vals.company || "—",
      email: vals.email,
      replyto: vals.email,
      language: vals.lang || "—",
      message: vals.message,
      botcheck: false,
    };
    try {
      const res = await fetch(FORM_CONFIG.endpoint, {
        method: "POST",
        headers: { "Content-Type": "application/json", Accept: "application/json" },
        body: JSON.stringify(payload),
      });
      const data = await res.json().catch(() => ({}));
      if (data.success) { setSent(true); }
      else { setSendErr(f.errSend); }
    } catch (e) {
      setSendErr(f.errSend);
    } finally {
      setSending(false);
    }
  };

  const reset = () => {
    setVals({ name: "", company: "", email: "", lang: "", message: "" });
    setErrs({});
    setSent(false);
    setSending(false);
    setSendErr("");
  };

  return (
    <section className="lp-section lp-section--deep on-dark" id="contact" ref={refEl}>
      <div className="lp-wrap">
        <div className="lp-contact-grid">
          <Reveal className="lp-contact-intro">
            <p className="lp-eyebrow"><span className="bar" />{c.contact.eyebrow}</p>
            <h2 className="lp-h2">{c.contact.title}</h2>
            <p className="lp-lede">{c.contact.body}</p>
          </Reveal>

          <Reveal delay={1}>
            <div className="lp-contact-card">
              {sent ? (
                <div className="lp-thanks">
                  <div className="ic">
                    <svg width="30" height="30" viewBox="0 0 24 24" fill="none" stroke="#fff" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"><polyline points="20 6 9 17 4 12" /></svg>
                  </div>
                  <h3>{f.thanksTitle}</h3>
                  <p>{f.thanksBody}</p>
                  <button className="lp-btn lp-btn--primary" onClick={reset}>{f.again}</button>
                </div>
              ) : (
                <form className="lp-form" onSubmit={submit} noValidate>
                  <input type="checkbox" name="botcheck" style={{ display: "none" }} tabIndex="-1" autoComplete="off" />
                  <div className="lp-form-grid">
                    <div className="lp-field">
                      <label>{f.name}<span className="req">{f.required}</span></label>
                      <input className={"lp-input" + (errs.name ? " error" : "")} name="name" value={vals.name} onChange={set("name")} />
                      {errs.name && <span className="lp-err">{errs.name}</span>}
                    </div>
                    <div className="lp-field">
                      <label>{f.company}</label>
                      <input className="lp-input" name="company" value={vals.company} onChange={set("company")} />
                    </div>
                    <div className="lp-field">
                      <label>{f.email}<span className="req">{f.required}</span></label>
                      <input className={"lp-input" + (errs.email ? " error" : "")} name="email" type="email" value={vals.email} onChange={set("email")} />
                      {errs.email && <span className="lp-err">{errs.email}</span>}
                    </div>
                    <div className="lp-field">
                      <label>{f.lang}</label>
                      <select className="lp-select" name="language" value={vals.lang} onChange={set("lang")}>
                        <option value="">—</option>
                        {f.langOpts.map((o) => <option key={o} value={o}>{o}</option>)}
                      </select>
                    </div>
                    <div className="lp-field lp-field--full">
                      <label>{f.message}<span className="req">{f.required}</span></label>
                      <textarea className={"lp-textarea" + (errs.message ? " error" : "")} name="message" value={vals.message} onChange={set("message")} placeholder={f.messagePlaceholder} />
                      {errs.message && <span className="lp-err">{errs.message}</span>}
                    </div>
                  </div>
                  <div className="lp-form-foot">
                    <span className="hint">{f.hint}</span>
                    <button type="submit" className="lp-btn lp-btn--primary lp-btn--lg" disabled={sending}>
                      {sending ? f.sending : f.submit}{!sending && <Arrow />}
                    </button>
                  </div>
                  {sendErr && <p className="lp-send-err">{sendErr}</p>}
                </form>
              )}
            </div>
          </Reveal>
        </div>
      </div>
    </section>
  );
}

function Footer({ c, onNav, onContact }) {
  const ft = c.footer;
  return (
    <footer className="lp-footer">
      <div className="lp-wrap">
        <div className="lp-footer__top">
          <div className="lp-footer__brand">
            <div className="name"><span className="mark">S</span>{c.brand}</div>
            <p>{ft.tagline}</p>
          </div>
          <nav className="lp-footer__links">
            {ft.links.map((lnk) => (
              <a key={lnk.href} className="lp-footer__link" href={lnk.href} target="_blank" rel="noopener noreferrer">{lnk.label}</a>
            ))}
          </nav>
        </div>
        <div className="lp-footer__bottom">
          <span className="legal">{ft.legal}</span>
          <span className="note">{ft.note}</span>
        </div>
      </div>
    </footer>
  );
}

Object.assign(window, { Contact, Footer });
