// ContactForm — 参考画像ベースの問い合わせフォーム（B-Steepトーンに調整）
function ContactForm() {
  const [form, setForm] = React.useState({
    name: "", email: "", phone: "", company: "",
    message: "", source: "YouTube", agree: false,
  });
  const [submitted, setSubmitted] = React.useState(false);
  const [sending, setSending] = React.useState(false);
  const [sendError, setSendError] = React.useState("");
  const [errors, setErrors] = React.useState({});

  const GAS_URL = "https://script.google.com/a/macros/b-steep.com/s/AKfycbzn9Xwet24llq9CLQyBglRWrmDEOr1M-6m4y0pUfP6XmaqNKnlz4k0eD0ejVY2u27bA/exec";

  const update = (k) => (e) => {
    const v = e.target.type === "checkbox" ? e.target.checked : e.target.value;
    setForm((p) => ({ ...p, [k]: v }));
    if (errors[k]) setErrors((p) => { const n = { ...p }; delete n[k]; return n; });
  };

  const validate = () => {
    const e = {};
    if (!form.name.trim()) e.name = "お名前を入力してください";
    if (!form.email.trim()) e.email = "メールアドレスを入力してください";
    else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.email)) e.email = "正しい形式で入力してください";
    if (!form.phone.trim()) e.phone = "電話番号を入力してください";
    if (!form.company.trim()) e.company = "会社名を入力してください";
    if (!form.message.trim()) e.message = "お問い合わせ内容を入力してください";
    return e;
  };

  const onSubmit = async (e) => {
    e.preventDefault();
    const errs = validate();
    setErrors(errs);
    if (Object.keys(errs).length !== 0) return;

    setSending(true);
    setSendError("");
    try {
      // GASのdoPost(e)がe.postData.contentsから読むため、CORSを避けるtext/plainで送る
      await fetch(GAS_URL, {
        method: "POST",
        mode: "no-cors",
        headers: { "Content-Type": "text/plain;charset=utf-8" },
        body: JSON.stringify({
          name: form.name,
          email: form.email,
          phone: form.phone,
          company: form.company,
          message: form.message,
          source: form.source,
        }),
      });
      setSubmitted(true);
      window.scrollTo({ top: document.getElementById("contact-form").offsetTop - 80, behavior: "smooth" });
    } catch (err) {
      setSendError("送信中にエラーが発生しました。時間をおいて再度お試しください。");
    } finally {
      setSending(false);
    }
  };

  const labelStyle = { display: "block", fontSize: 13, fontWeight: 700, color: "var(--navy-900)", marginBottom: 8, letterSpacing: "0.04em" };
  const requiredStyle = { color: "#e11d48", marginLeft: 4, fontSize: 12 };
  const inputStyle = (hasError) => ({
    width: "100%",
    padding: "14px 16px",
    border: `1px solid ${hasError ? "#e11d48" : "var(--hair)"}`,
    borderRadius: 4,
    background: hasError ? "#fff5f6" : "var(--sky-50)",
    fontSize: 14,
    fontFamily: "var(--font-sans-body)",
    color: "var(--ink)",
    transition: "all 0.15s ease",
    outline: "none",
    letterSpacing: "0.04em",
  });
  const errStyle = { color: "#e11d48", fontSize: 12, marginTop: 6, fontWeight: 500 };

  return (
    <section id="contact-form" style={{ background: "#fff", padding: "96px 0 120px" }}>
      <div className="wrap" style={{ maxWidth: 820 }}>
        {/* Heading */}
        <div style={{ textAlign: "center", marginBottom: 48 }}>
          <div className="eyebrow" style={{ marginBottom: 14, justifyContent: "center" }}>
            <span className="dot" />CONTACT FORM
          </div>
          <h2 style={{
            margin: 0,
            fontSize: "clamp(26px, 3.4vw, 36px)",
            fontWeight: 700,
            color: "var(--navy-900)",
            letterSpacing: "0.04em",
          }}>
            お問い合わせフォーム
          </h2>
          <p style={{
            margin: "18px 0 0", fontSize: 14, color: "var(--ink-2)",
            lineHeight: 2, letterSpacing: "0.05em",
          }}>
            ご興味をお持ちいただきありがとうございます。<br />
            お問い合わせ内容をご記入ください。
          </p>
        </div>

        {submitted ? (
          /* Thank-you state */
          <div style={{
            background: "var(--sky-50)",
            border: "1px solid var(--sky-200)",
            borderRadius: 8,
            padding: "56px 32px",
            textAlign: "center",
          }}>
            <div style={{
              width: 56, height: 56, margin: "0 auto 22px",
              borderRadius: "50%", background: "var(--yellow)",
              display: "flex", alignItems: "center", justifyContent: "center",
            }}>
              <svg width="26" height="26" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" style={{ color: "var(--navy-900)" }}>
                <polyline points="20 6 9 17 4 12" />
              </svg>
            </div>
            <h3 style={{ margin: "0 0 12px", fontSize: 22, fontWeight: 700, color: "var(--navy-900)" }}>
              送信が完了しました
            </h3>
            <p style={{ margin: 0, fontSize: 14, color: "var(--ink-2)", lineHeight: 2 }}>
              お問い合わせありがとうございます。<br />
              担当者よりあらためてご連絡いたします。
            </p>
          </div>
        ) : (
          <form
            onSubmit={onSubmit}
            noValidate
            style={{
              background: "#fff",
              border: "1px solid var(--hair)",
              borderRadius: 8,
              padding: "44px 40px 40px",
              boxShadow: "0 2px 20px rgba(12, 37, 92, 0.04)",
            }}
          >
            <div style={{ display: "grid", gap: 24 }}>
              {/* 名前 */}
              <div>
                <label style={labelStyle} htmlFor="f-name">
                  お名前<span style={requiredStyle}>*</span>
                </label>
                <input
                  id="f-name" type="text" value={form.name} onChange={update("name")}
                  placeholder="山田 太郎" style={inputStyle(errors.name)}
                />
                {errors.name && <div style={errStyle}>{errors.name}</div>}
              </div>

              {/* メール */}
              <div>
                <label style={labelStyle} htmlFor="f-email">
                  メールアドレス<span style={requiredStyle}>*</span>
                </label>
                <input
                  id="f-email" type="email" value={form.email} onChange={update("email")}
                  placeholder="○○○@example.com" style={inputStyle(errors.email)}
                />
                {errors.email && <div style={errStyle}>{errors.email}</div>}
              </div>

              {/* 電話 */}
              <div>
                <label style={labelStyle} htmlFor="f-phone">
                  電話番号<span style={requiredStyle}>*</span>
                </label>
                <input
                  id="f-phone" type="tel" value={form.phone} onChange={update("phone")}
                  placeholder="08012345678" style={inputStyle(errors.phone)}
                />
                {errors.phone && <div style={errStyle}>{errors.phone}</div>}
              </div>

              {/* 会社名 */}
              <div>
                <label style={labelStyle} htmlFor="f-company">
                  会社名<span style={requiredStyle}>*</span>
                </label>
                <input
                  id="f-company" type="text" value={form.company} onChange={update("company")}
                  placeholder="株式会社B-Steep" style={inputStyle(errors.company)}
                />
                {errors.company && <div style={errStyle}>{errors.company}</div>}
              </div>

              {/* 内容 */}
              <div>
                <label style={labelStyle} htmlFor="f-message">
                  お問い合わせ内容<span style={requiredStyle}>*</span>
                </label>
                <textarea
                  id="f-message" rows={6} value={form.message} onChange={update("message")}
                  placeholder="お問い合わせ詳細を記載してください。"
                  style={{ ...inputStyle(errors.message), resize: "vertical", lineHeight: 1.8 }}
                />
                {errors.message && <div style={errStyle}>{errors.message}</div>}
              </div>

              {/* きっかけ */}
              <div>
                <label style={labelStyle} htmlFor="f-source">
                  弊社を知ったきっかけ<span style={requiredStyle}>*</span>
                </label>
                <div style={{ position: "relative" }}>
                  <select
                    id="f-source" value={form.source} onChange={update("source")}
                    style={{
                      ...inputStyle(false),
                      appearance: "none",
                      paddingRight: 44,
                      cursor: "pointer",
                      background: "var(--sky-50)",
                    }}
                  >
                    <option>YouTube</option>
                    <option>X (Twitter)</option>
                    <option>検索エンジン</option>
                    <option>知人・紹介</option>
                    <option>セミナー・イベント</option>
                    <option>その他</option>
                  </select>
                  <div style={{
                    position: "absolute", right: 16, top: "50%", transform: "translateY(-50%)",
                    pointerEvents: "none", color: "var(--ink-3)",
                  }}>
                    <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
                      <polyline points="6 9 12 15 18 9" />
                    </svg>
                  </div>
                </div>
              </div>

              {/* 送信 */}
              <div style={{ marginTop: 32, textAlign: "center" }}>
                {sendError && <div style={{ ...errStyle, textAlign: "center", marginBottom: 16 }}>{sendError}</div>}

                <div>
                  <button type="submit" disabled={sending} style={{
                    background: sending ? "var(--navy-500)" : "var(--navy-900)",
                    color: "#fff",
                    border: "none",
                    padding: "16px 52px",
                    borderRadius: 4,
                    fontSize: 14,
                    fontWeight: 700,
                    letterSpacing: "0.08em",
                    cursor: sending ? "not-allowed" : "pointer",
                    opacity: sending ? 0.7 : 1,
                    transition: "all 0.2s ease",
                    display: "inline-flex", alignItems: "center", gap: 12,
                  }}
                  onMouseOver={(e) => { if (!sending) { e.currentTarget.style.background = "var(--navy-700)"; e.currentTarget.style.transform = "translateY(-1px)"; } }}
                  onMouseOut={(e) => { if (!sending) { e.currentTarget.style.background = "var(--navy-900)"; e.currentTarget.style.transform = "translateY(0)"; } }}
                  >
                    {sending ? "送信中..." : "この内容で送信する"}
                    {!sending && (
                      <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
                        <line x1="5" y1="12" x2="19" y2="12" />
                        <polyline points="12 5 19 12 12 19" />
                      </svg>
                    )}
                  </button>
                </div>
              </div>
            </div>
          </form>
        )}
      </div>
    </section>
  );
}

window.ContactForm = ContactForm;
