// Contact — inquiry form that POSTs to /api/contact (Cloudflare Pages Function)
function Contact({ lang }) {
  const t = (ja, en) => (lang === "ja" ? ja : en);
  const [form, setForm] = React.useState({
    company: "", name: "", email: "", product: "", market: "", message: "",
    website: "", // honeypot field — legitimate users leave this empty
  });
  const [errors, setErrors] = React.useState({});
  const [submitting, setSubmitting] = React.useState(false);
  const [submitted, setSubmitted] = React.useState(false);
  const [serverError, setServerError] = React.useState(null);

  const update = (k, v) => {
    setForm({ ...form, [k]: v });
    if (errors[k]) setErrors({ ...errors, [k]: null });
  };

  const validate = () => {
    const e = {};
    if (!form.company.trim()) e.company = t("必須項目です", "Required");
    if (!form.name.trim()) e.name = t("必須項目です", "Required");
    if (!form.email.trim()) e.email = t("必須項目です", "Required");
    else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.email)) e.email = t("有効なメールアドレスを入力してください", "Enter a valid email");
    if (!form.message.trim()) e.message = t("必須項目です", "Required");
    return e;
  };

  const mapServerErrors = (srv) => {
    if (!srv) return {};
    const out = {};
    for (const [k, code] of Object.entries(srv)) {
      if (code === "required") out[k] = t("必須項目です", "Required");
      else if (code === "invalid") out[k] = t("有効な形式で入力してください", "Invalid format");
      else if (code === "too_long") out[k] = t("文字数が長すぎます", "Too long");
      else out[k] = t("入力を確認してください", "Please check this field");
    }
    return out;
  };

  const submit = async (ev) => {
    ev.preventDefault();
    setServerError(null);
    const e = validate();
    if (Object.keys(e).length) { setErrors(e); return; }
    setSubmitting(true);

    try {
      const res = await fetch("/api/contact", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(form),
      });
      const data = await res.json().catch(() => ({}));

      if (res.ok && data.ok) {
        setSubmitted(true);
      } else if (data.errors) {
        setErrors(mapServerErrors(data.errors));
        setServerError(t("入力内容をご確認ください。", "Please review your inputs."));
      } else {
        setServerError(
          t(
            "送信に失敗しました。時間をおいて再度お試しください。",
            "Failed to send. Please try again later."
          )
        );
      }
    } catch (err) {
      setServerError(
        t(
          "ネットワークエラーが発生しました。通信状況をご確認ください。",
          "Network error. Please check your connection."
        )
      );
    } finally {
      setSubmitting(false);
    }
  };

  const markets = [
    "China", "United States", "Taiwan", "South Korea",
    "Singapore", "Thailand", "Vietnam", "Europe", "Other",
  ];

  if (submitted) {
    return (
      <section id="contact" style={{
        padding: "160px 32px",
        background: "linear-gradient(180deg, #EAF6FB 0%, #CDE8F3 100%)",
        minHeight: "60vh", display: "flex", alignItems: "center", justifyContent: "center",
      }}>
        <div style={{ textAlign: "center", maxWidth: 560 }}>
          <div style={{
            width: 72, height: 72, borderRadius: 999, margin: "0 auto 28px",
            background: "#fff", display: "flex", alignItems: "center", justifyContent: "center",
            boxShadow: "0 10px 40px rgba(45,109,148,0.16)",
          }}>
            <svg width="32" height="32" viewBox="0 0 32 32" fill="none">
              <path d="M7 16 L14 23 L25 10" stroke="#4AA8D0" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round" />
            </svg>
          </div>
          <h3 style={{
            fontFamily: "'Cormorant Garamond', 'Noto Serif JP', serif",
            fontSize: 44, fontWeight: 300, color: "#0f2238",
            margin: "0 0 16px", letterSpacing: "-0.01em",
          }}>
            {t("ありがとうございます", "Thank you")}
          </h3>
          <p style={{
            fontFamily: "'Noto Sans JP', 'Inter', sans-serif",
            fontSize: 15, lineHeight: 1.85, color: "#2a3a52", margin: 0,
          }}>
            {t(
              "お問い合わせを受け付けました。2営業日以内に担当者よりご返信いたします。",
              "We've received your inquiry. A team member will be in touch within two business days."
            )}
          </p>
          <button onClick={() => {
            setSubmitted(false);
            setForm({ company: "", name: "", email: "", product: "", market: "", message: "", website: "" });
          }}
            style={{
              marginTop: 36, padding: "12px 24px",
              background: "transparent", color: "#2d6d94",
              border: "1px solid #2d6d94", borderRadius: 999,
              fontFamily: "'Noto Sans JP', 'Inter', sans-serif",
              fontSize: 13, fontWeight: 500, letterSpacing: "0.08em",
              cursor: "pointer",
            }}>
            {t("別の問い合わせを送る", "Send another inquiry")}
          </button>
        </div>
      </section>
    );
  }

  return (
    <section id="contact" style={{
      padding: "140px 32px",
      background: "linear-gradient(180deg, #F0F8FC 0%, #EAF6FB 100%)",
      position: "relative", overflow: "hidden",
    }}>
      <div style={{ position: "absolute", inset: 0, opacity: 0.4 }}>
        <RiverBackground intensity={0.8} tone="light" />
      </div>

      <div style={{ position: "relative", zIndex: 2, maxWidth: 1320, margin: "0 auto" }}>
        <div style={{
          display: "grid", gridTemplateColumns: "1fr 1.3fr", gap: 96,
          alignItems: "start",
        }} className="contact-grid">
          <div style={{ position: "sticky", top: 120 }}>
            <SectionLabel num="06" label={t("お問い合わせ", "Contact")} />
            <h2 style={{
              fontFamily: "'Cormorant Garamond', 'Noto Serif JP', serif",
              fontSize: "clamp(36px, 4.4vw, 64px)",
              fontWeight: 300, lineHeight: 1.1, color: "#0f2238",
              margin: "40px 0 28px", letterSpacing: "-0.01em",
            }}>
              {t(<>まずはお気軽に、<br/>ご相談ください。</>, <>Let's start<br/>the conversation.</>)}
            </h2>
            <p style={{
              fontFamily: "'Noto Sans JP', 'Inter', sans-serif",
              fontSize: 15, lineHeight: 1.9, color: "#2a3a52",
              margin: "0 0 40px", maxWidth: 440,
            }}>
              {t(
                "越境ECのご相談、取扱ブランドのお問い合わせ、採用に関するご質問など、お気軽にご連絡ください。通常2営業日以内にご返信いたします。",
                "For cross-border EC consultations, partnership questions, or careers — reach out anytime. We respond within two business days."
              )}
            </p>

            <div style={{ borderTop: "1px solid rgba(45,109,148,0.2)", paddingTop: 28 }}>
              <div style={{ marginBottom: 16 }}>
                <div style={{
                  fontFamily: "'Inter', sans-serif",
                  fontSize: 10, letterSpacing: "0.22em", color: "#2d6d94",
                  textTransform: "uppercase", marginBottom: 6, fontWeight: 500,
                }}>Email</div>
                <div style={{ fontFamily: "'Inter', sans-serif", fontSize: 15, color: "#0f2238" }}>
                  info@riverence.co.jp
                </div>
              </div>
              <div style={{ marginBottom: 16 }}>
                <div style={{
                  fontFamily: "'Inter', sans-serif",
                  fontSize: 10, letterSpacing: "0.22em", color: "#2d6d94",
                  textTransform: "uppercase", marginBottom: 6, fontWeight: 500,
                }}>{t("営業時間", "Business hours")}</div>
                <div style={{ fontFamily: "'Noto Sans JP', sans-serif", fontSize: 15, color: "#0f2238" }}>
                  {t("平日 11:00 – 19:00 (JST)", "Mon–Fri 11:00 – 19:00 JST")}
                </div>
              </div>
            </div>
          </div>

          <form onSubmit={submit} noValidate style={{
            background: "#fff",
            padding: "48px 44px",
            border: "1px solid rgba(74,168,208,0.24)",
            boxShadow: "0 20px 60px rgba(15,34,56,0.06)",
          }}>
            {/* Honeypot — hidden from humans, filled only by bots */}
            <div aria-hidden="true" style={{
              position: "absolute", left: "-10000px", top: "auto",
              width: 1, height: 1, overflow: "hidden",
            }}>
              <label>
                Website (leave empty)
                <input type="text" tabIndex={-1} autoComplete="off"
                  value={form.website}
                  onChange={e => update("website", e.target.value)} />
              </label>
            </div>

            <FormRow>
              <Field label={t("会社名", "Company")} required error={errors.company}>
                <input value={form.company} onChange={e => update("company", e.target.value)}
                  maxLength={200} style={inputStyle} />
              </Field>
              <Field label={t("ご担当者名", "Your name")} required error={errors.name}>
                <input value={form.name} onChange={e => update("name", e.target.value)}
                  maxLength={200} style={inputStyle} />
              </Field>
            </FormRow>

            <FormRow>
              <Field label={t("メールアドレス", "Email")} required error={errors.email}>
                <input type="email" value={form.email} onChange={e => update("email", e.target.value)}
                  maxLength={320} style={inputStyle} />
              </Field>
              <Field label={t("展開希望市場", "Target market")}>
                <select value={form.market} onChange={e => update("market", e.target.value)} style={inputStyle}>
                  <option value="">{t("選択してください", "Select...")}</option>
                  {markets.map(m => <option key={m} value={m}>{m}</option>)}
                </select>
              </Field>
            </FormRow>

            <Field label={t("商品・ブランド概要", "Product / Brand")}>
              <input value={form.product} onChange={e => update("product", e.target.value)}
                maxLength={500}
                placeholder={t("例:コスメ、食品、アパレル…", "e.g. cosmetics, food, apparel...")}
                style={inputStyle} />
            </Field>

            <Field label={t("お問い合わせ内容", "Message")} required error={errors.message}>
              <textarea value={form.message} onChange={e => update("message", e.target.value)}
                rows={6} maxLength={8000}
                style={{ ...inputStyle, resize: "vertical", minHeight: 140, paddingTop: 14 }} />
            </Field>

            {serverError && (
              <div role="alert" style={{
                padding: "12px 16px",
                background: "rgba(217,67,74,0.08)",
                border: "1px solid rgba(217,67,74,0.3)",
                color: "#8e1e24",
                fontFamily: "'Noto Sans JP', 'Inter', sans-serif",
                fontSize: 13, lineHeight: 1.6,
                marginTop: 4, marginBottom: 16,
              }}>
                {serverError}
              </div>
            )}

            <button type="submit" disabled={submitting}
              style={{
                marginTop: 24, width: "100%",
                padding: "18px 32px",
                background: submitting ? "#9ab8c9" : "linear-gradient(135deg, #4AA8D0 0%, #2d6d94 100%)",
                color: "#fff", border: "none", borderRadius: 999,
                fontFamily: "'Noto Sans JP', 'Inter', sans-serif",
                fontSize: 14, fontWeight: 500, letterSpacing: "0.1em",
                cursor: submitting ? "wait" : "pointer",
                boxShadow: "0 10px 30px rgba(45,109,148,0.24)",
                transition: "all 240ms",
              }}>
              {submitting ? t("送信中…", "Sending...") : t("送信する →", "Send inquiry →")}
            </button>

            <p style={{
              marginTop: 20, fontSize: 11, color: "#6a7a92",
              fontFamily: "'Noto Sans JP', 'Inter', sans-serif",
              lineHeight: 1.7,
            }}>
              {t(
                "送信いただいた情報は、お問い合わせへの対応のみに使用します。",
                "Submitted information is used solely to respond to your inquiry."
              )}
            </p>
          </form>
        </div>
      </div>
    </section>
  );
}

function FormRow({ children }) {
  return (
    <div className="form-row" style={{
      display: "grid", gridTemplateColumns: "1fr 1fr", gap: 20,
    }}>
      {children}
    </div>
  );
}

function Field({ label, required, error, children }) {
  return (
    <div style={{ marginBottom: 22 }}>
      <label style={{
        display: "block",
        fontFamily: "'Noto Sans JP', 'Inter', sans-serif",
        fontSize: 11, letterSpacing: "0.16em",
        color: "#2d6d94", textTransform: "uppercase",
        marginBottom: 8, fontWeight: 500,
      }}>
        {label}{required && <span style={{ color: "#D9434A", marginLeft: 4 }}>*</span>}
      </label>
      {children}
      {error && (
        <div style={{
          marginTop: 6, fontSize: 12, color: "#D9434A",
          fontFamily: "'Noto Sans JP', 'Inter', sans-serif",
        }}>{error}</div>
      )}
    </div>
  );
}

const inputStyle = {
  width: "100%",
  padding: "12px 14px",
  border: "1px solid rgba(74,168,208,0.36)",
  borderRadius: 2,
  fontFamily: "'Noto Sans JP', 'Inter', sans-serif",
  fontSize: 14,
  color: "#0f2238",
  background: "#FAFAFA",
  outline: "none",
  transition: "all 200ms",
  boxSizing: "border-box",
};

Object.assign(window, { Contact });
