// Contact page — interactive form + info
const { useState: useStateCt } = React;

function ContactPage({ onNav }) {
  const [form, setForm] = useStateCt({ name: "", company: "", email: "", budget: "", category: [], message: "" });
  const [step, setStep] = useStateCt(1);
  const [submitted, setSubmitted] = useStateCt(false);
  const [focused, setFocused] = useStateCt("");

  const totalSteps = 3;

  const toggleCat = (c) => {
    setForm((f) => ({ ...f, category: f.category.includes(c) ? f.category.filter((x) => x !== c) : [...f.category, c] }));
  };

  // 1. Formspreeへの非同期送信処理
  const handleSubmit = async () => {
    try {
      // いただいたFormspreeのエンドポイントを設定
      const response = await fetch("https://formspree.io/f/meoybqrp", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          "Accept": "application/json"
        },
        body: JSON.stringify({
          name: form.name,
          company: form.company,
          email: form.email,
          budget: form.budget,
          category: form.category.join(", "),
          message: form.message
        })
      });

      if (response.ok) {
        // 送信成功時にステートを更新（サンクス画面へ切り替え）
        setSubmitted(true);
      } else {
        alert("送信に失敗しました。入力内容をご確認の上、もう一度お試しください。");
      }
    } catch (error) {
      console.error("Formspree送信エラー:", error);
      alert("通信エラーが発生しました。インターネット接続を確認してください。");
    }
  };

  return (
    <div className="page-wrap">
      <section style={{ padding: "120px 0 60px", position: "relative", overflow: "hidden" }}>
        <div className="rail-right" />
        <div className="container">
          <span className="eyebrow">Contact</span>
          <h1 className="h-section" style={{ marginTop: 18, fontSize: "clamp(72px, 13vw, 240px)" }}>
            <Kinetic text="話を、" />
            <br />
            <span style={{ color: "var(--navy)" }}><Kinetic text="しませんか。" /></span>
          </h1>
          <p style={{ marginTop: 40, maxWidth: 640, fontSize: 17, lineHeight: 1.95, color: "var(--ink-2)" }}>
            戦略・実行・分析、その他ご相談なんでも。<br />
            3営業日以内に担当者よりご連絡いたします。
          </p>
        </div>
      </section>

      <section style={{ padding: "60px 0 120px" }}>
        <div className="container">
          <div style={{ display: "grid", gridTemplateColumns: "1.6fr 1fr", gap: 48, alignItems: "start" }}>
            
            {/* 左側: フォームエリア（白いカード部分） */}
            <div style={{ background: "var(--paper)", border: "1px solid var(--line)", borderRadius: 16, padding: 48 }}>
              
              {/* 2. 送信完了時は、このカードの中身だけをスムーズに切り替える（白画面化を防止） */}
              {submitted ? (
                <div style={{ textAlign: "center", padding: "40px 0", animation: "pageIn 0.6s var(--easing)" }}>
                  <div style={{ width: 100, height: 100, borderRadius: "50%", background: "var(--sky)", marginInline: "auto", display: "grid", placeItems: "center", fontSize: 50, marginBottom: 28, color: "var(--ink)" }}>✓</div>
                  <h2 style={{ fontFamily: "var(--f-display)", fontWeight: 900, fontSize: 36, letterSpacing: "-0.02em", marginBottom: 16 }}>
                    <Kinetic text="ありがとうございました。" />
                  </h2>
                  <p style={{ fontSize: 16, color: "var(--ink-2)", lineHeight: 1.85, marginBottom: 32 }}>
                    お問い合わせを受け付けました。<br />
                    3営業日以内に担当者よりご連絡いたします。
                  </p>
                  <a href="#top" className="btn btn--primary" data-cursor="hover" onClick={(e) => { e.preventDefault(); onNav("top"); }}>
                    トップへ戻る<span className="btn__arrow">→</span>
                  </a>
                </div>
              ) : (
                <>
                  {/* progress */}
                  <div style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 40 }}>
                    {[1, 2, 3].map((n) => (
                      <React.Fragment key={n}>
                        <div data-cursor="hover" onClick={() => setStep(n)} style={{
                          width: 40, height: 40, borderRadius: "50%",
                          background: step >= n ? "var(--navy)" : "var(--bg)",
                          color: step >= n ? "#fff" : "var(--ink-3)",
                          border: "1.5px solid " + (step >= n ? "var(--navy)" : "var(--line)"),
                          display: "grid", placeItems: "center",
                          fontFamily: "var(--f-en)", fontWeight: 700, fontSize: 14,
                          transition: "all 0.3s var(--easing)",
                          cursor: "none",
                        }}>{n}</div>
                        {n < 3 ? <div style={{ flex: 1, height: 2, background: step > n ? "var(--navy)" : "var(--line)", transition: "all 0.4s var(--easing)" }} /> : null}
                      </React.Fragment>
                    ))}
                    <span style={{ marginLeft: "auto", fontFamily: "var(--f-en)", fontSize: 12, fontWeight: 600, color: "var(--ink-3)", letterSpacing: "0.08em" }}>
                      Step {step} / {totalSteps}
                    </span>
                  </div>

                  {step === 1 && (
                    <div style={{ display: "flex", flexDirection: "column", gap: 32 }}>
                      <h2 style={{ fontFamily: "var(--f-display)", fontWeight: 900, fontSize: 36, letterSpacing: "-0.02em" }}>
                        まずは、お名前から。
                      </h2>
                      <Field label="お名前" value={form.name} onChange={(v) => setForm({ ...form, name: v })} placeholder="森田 伸之介" focused={focused === "name"} onFocus={() => setFocused("name")} onBlur={() => setFocused("")} />
                      <Field label="会社名" value={form.company} onChange={(v) => setForm({ ...form, company: v })} placeholder="株式会社frevia" focused={focused === "company"} onFocus={() => setFocused("company")} onBlur={() => setFocused("")} />
                      <Field label="メールアドレス" value={form.email} onChange={(v) => setForm({ ...form, email: v })} placeholder="media-frevia@frevia-web.com" focused={focused === "email"} onFocus={() => setFocused("email")} onBlur={() => setFocused("")} />
                    </div>
                  )}

                  {step === 2 && (
                    <div style={{ display: "flex", flexDirection: "column", gap: 28 }}>
                      <h2 style={{ fontFamily: "var(--f-display)", fontWeight: 900, fontSize: 36, letterSpacing: "-0.02em" }}>
                        どんなご相談？
                      </h2>
                      <div>
                        <div className="eyebrow" style={{ marginBottom: 16 }}>カテゴリ（複数選択可）</div>
                        <div style={{ display: "flex", flexWrap: "wrap", gap: 10 }}>
                          {["Web広告運用", "クリエイティブ制作", "LP制作・改善", "インハウス化支援", "戦略・データ分析", "その他"].map((c) => (
                            <button
                              key={c}
                              type="button"
                              data-cursor="hover"
                              onClick={() => toggleCat(c)}
                              style={{
                              padding: "14px 22px",
                              borderRadius: 999,
                              border: "1.5px solid " + (form.category.includes(c) ? "var(--navy)" : "var(--line)"),
                              background: form.category.includes(c) ? "var(--navy)" : "transparent",
                              color: form.category.includes(c) ? "#fff" : "var(--ink-2)",
                              fontSize: 14,
                              fontWeight: 500,
                                transition: "all 0.3s var(--easing)",
                              }}
                            >
                              {c}
                            </button>
                          ))}
                        </div>
                      </div>
                      <div>
                        <div className="eyebrow" style={{ marginBottom: 16 }}>月間広告予算（参考）</div>
                        <div style={{ display: "flex", flexWrap: "wrap", gap: 10 }}>
                          {["〜50万円", "50〜200万円", "200〜500万円", "500〜1000万円", "1000万円以上"].map((b) => (
                            <button
                              key={b}
                              type="button"
                              data-cursor="hover"
                              onClick={() => setForm({ ...form, budget: b })}
                              style={{
                              padding: "14px 22px",
                              borderRadius: 999,
                              border: "1.5px solid " + (form.budget === b ? "var(--terra)" : "var(--line)"),
                              background: form.budget === b ? "var(--terra)" : "transparent",
                              color: form.budget === b ? "#fff" : "var(--ink-2)",
                              fontSize: 14,
                              fontWeight: 500,
                                transition: "all 0.3s var(--easing)",
                              }}
                            >
                              {b}
                            </button>
                          ))}
                        </div>
                      </div>
                    </div>
                  )}

                  {step === 3 && (
                    <div style={{ display: "flex", flexDirection: "column", gap: 28 }}>
                      <h2 style={{ fontFamily: "var(--f-display)", fontWeight: 900, fontSize: 36, letterSpacing: "-0.02em" }}>
                        詳しく、教えてください。
                      </h2>
                      <Field
                        label="お問い合わせ内容"
                        value={form.message}
                        onChange={(v) => setForm({ ...form, message: v })}
                        placeholder="現在の課題、検討中の施策、ご質問など、自由にお書きください。"
                        textarea
                        focused={focused === "message"}
                        onFocus={() => setFocused("message")}
                        onBlur={() => setFocused("")}
                      />
                    </div>
                  )}

                  <div style={{ display: "flex", justifyContent: "space-between", marginTop: 48, alignItems: "center" }}>
                    {step > 1 ? (
                      <button data-cursor="hover" className="btn btn--ghost" onClick={() => setStep(step - 1)} style={{ padding: "14px 28px" }}>
                        ← 戻る
                      </button>
                    ) : null}
                    {step < 3 ? (
                      <Magnetic strength={0.25}>
                        <button data-cursor="hover" className="btn btn--primary" onClick={() => setStep(step + 1)}>
                          次へ<span className="btn__arrow">→</span>
                        </button>
                      </Magnetic>
                    ) : (
                      <Magnetic strength={0.25}>
                        {/* 3. onClick の処理先を handleSubmit に変更 */}
                        <button data-cursor="hover" className="btn btn--terra" onClick={handleSubmit}>
                          送信する<span className="btn__arrow">→</span>
                        </button>
                      </Magnetic>
                    )}
                  </div>
                </>
              )}
            </div>

            {/* 右側: 固定サイドバー情報エリア */}
            <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
              <div style={{ padding: 32, background: "var(--navy)", color: "#fff", borderRadius: 16 }}>
                <span className="eyebrow" style={{ color: "rgba(255,255,255,0.7)" }}>Office</span>
                <h3 style={{ fontFamily: "var(--f-display)", fontWeight: 900, fontSize: 26, marginTop: 18, letterSpacing: "-0.02em", color: "#fff" }}>
                  所在地
                </h3>
                <p style={{ marginTop: 16, fontSize: 14, lineHeight: 1.85, opacity: 0.92 }}>
                  〒104-0061<br />
                  東京都中央区銀座1-12-4<br />
                  N&amp;E BLD. 7階
                </p>
              </div>
              <div style={{ padding: 32, background: "var(--sky)", borderRadius: 16, color: "var(--ink)" }}>
                <span className="eyebrow">Email</span>
                <p style={{ marginTop: 18, fontFamily: "var(--f-en)", fontSize: 18, fontWeight: 600, letterSpacing: "-0.01em", color: "var(--ink)", wordBreak: "break-all" }}>media-frevia@frevia-web.com</p>
                <p style={{ marginTop: 8, fontSize: 13, color: "var(--ink-2)" }}>3営業日以内にご返信</p>
              </div>
              <div style={{ padding: 32, background: "var(--terra)", borderRadius: 16, color: "#fff", position: "relative", overflow: "hidden" }}>
                <span className="eyebrow" style={{ color: "rgba(255,255,255,0.85)" }}>Hours</span>
                <p style={{ marginTop: 18, fontSize: 22, fontFamily: "var(--f-display)", fontWeight: 900, color: "#fff" }}>平日 09:30 — 18:30</p>
                <p style={{ marginTop: 8, fontSize: 13, opacity: 0.9 }}>土日祝定休</p>
              </div>
            </div>
          </div>
        </div>
      </section>
    </div>
  );
}

function Field({ label, value, onChange, placeholder, textarea, focused, onFocus, onBlur }) {
  return (
    <label style={{ display: "block", position: "relative" }}>
      <div className="eyebrow" style={{ marginBottom: 12, color: focused ? "var(--navy)" : "var(--ink-3)", transition: "color 0.3s var(--easing)" }}>
        {label}
      </div>
      {textarea ? (
        <textarea
          data-cursor="text"
          data-cursor-label="TYPE"
          value={value}
          onChange={(e) => onChange(e.target.value)}
          onFocus={onFocus}
          onBlur={onBlur}
          placeholder={placeholder}
          rows={6}
          style={{
            width: "100%",
            padding: "20px 0",
            border: "none",
            borderBottom: "2px solid " + (focused ? "var(--navy)" : "var(--line)"),
            background: "transparent",
            fontFamily: "var(--f-body)",
            fontSize: 16,
            color: "var(--ink)",
            outline: "none",
            resize: "vertical",
            transition: "border-color 0.3s var(--easing)",
            cursor: "none",
          }}
        />
      ) : (
        <input
          data-cursor="text"
          data-cursor-label="TYPE"
          value={value}
          onChange={(e) => onChange(e.target.value)}
          onFocus={onFocus}
          onBlur={onBlur}
          placeholder={placeholder}
          style={{
            width: "100%",
            padding: "16px 0",
            border: "none",
            borderBottom: "2px solid " + (focused ? "var(--navy)" : "var(--line)"),
            background: "transparent",
            fontFamily: "var(--f-body)",
            fontSize: 20,
            color: "var(--ink)",
            outline: "none",
            transition: "border-color 0.3s var(--easing)",
            cursor: "none",
          }}
        />
      )}
    </label>
  );
}

window.ContactPage = ContactPage;