/* eslint-disable */
// Supabase 연결 정보 (anon key는 공개 키, 클라이언트에서 안전하게 사용 가능)
const SUPABASE_URL = "https://jyprynpvzwswtsiljzet.supabase.co";
const SUPABASE_ANON_KEY = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Imp5cHJ5bnB2endzd3RzaWxqemV0Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3Nzg0NDU3NTUsImV4cCI6MjA5NDAyMTc1NX0.ydv9rSLGK0I4ncskJBxv0dvfBTdo7nVIavlfXE1OCCk";

function InquiryForm({ t, p }) {
  const f = t.contact.form;
  const [state, setState] = React.useState({ name: "", email: "", company: "", subject: "", message: "" });
  const [sent, setSent] = React.useState(false);
  const [submitting, setSubmitting] = React.useState(false);
  const [error, setError] = React.useState("");

  const setField = (k) => (e) => setState(s => ({ ...s, [k]: e.target.value }));
  const valid = state.name.trim() && state.email.trim() && state.subject && state.message.trim();

  const submit = async (e) => {
    e.preventDefault();
    if (!valid || submitting) return;
    setSubmitting(true);
    setError("");
    try {
      const res = await fetch(`${SUPABASE_URL}/rest/v1/contact_submissions`, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          "apikey": SUPABASE_ANON_KEY,
          "Authorization": `Bearer ${SUPABASE_ANON_KEY}`,
          "Prefer": "return=minimal",
        },
        body: JSON.stringify({
          name: state.name.trim(),
          email: state.email.trim(),
          company: state.company.trim() || null,
          subject: state.subject,
          message: state.message.trim(),
        }),
      });
      if (!res.ok) {
        const text = await res.text().catch(() => "");
        throw new Error(text || `HTTP ${res.status}`);
      }
      setSent(true);
    } catch (err) {
      setError("전송에 실패했습니다. 잠시 후 다시 시도하거나 contact@forwardmax.kr 로 직접 메일 보내주세요.");
    } finally {
      setSubmitting(false);
    }
  };
  const reset = () => {
    setState({ name: "", email: "", company: "", subject: "", message: "" });
    setSent(false);
    setError("");
  };

  const labelStyle = {
    fontFamily: "var(--font-ui)", fontSize: 11, letterSpacing: "1.17px",
    textTransform: "uppercase", color: p.fgFaint,
    display: "flex", alignItems: "center", gap: 10,
  };
  const inputStyle = {
    appearance: "none", WebkitAppearance: "none", MozAppearance: "none",
    width: "100%", boxSizing: "border-box",
    background: "transparent", color: p.fg,
    border: "0", borderBottom: `1px solid ${p.hairline}`,
    padding: "14px 0 16px",
    fontFamily: "var(--font-display)", fontWeight: 500,
    fontSize: "clamp(20px, 2.2vw, 28px)", lineHeight: 1.2,
    letterSpacing: "0.2px",
    outline: "none",
    transition: "border-color 200ms ease",
  };
  const onFocus = (e) => { e.target.style.borderBottomColor = p.fg; };
  const onBlur  = (e) => { e.target.style.borderBottomColor = p.hairline; };

  return (
    <section data-screen-label="03 Form" style={{
      position: "relative", background: p.bg, color: p.fg,
      borderBottom: `1px solid ${p.hairline}`,
    }}>
      <div style={{ maxWidth: 1400, margin: "0 auto", padding: "140px 32px" }}>
        <div style={{ display: "grid", gridTemplateColumns: "minmax(0, 220px) 1fr", gap: 48, alignItems: "end", marginBottom: 72 }}>
          <div style={window.eyebrowStyle(p)}>— {f.eyebrow}</div>
          <div>
            <h2 style={{
              fontFamily: "var(--font-display)", fontWeight: 700,
              fontSize: "clamp(40px, 6vw, 92px)", lineHeight: 0.96,
              letterSpacing: "0.4px", textTransform: "uppercase",
              margin: "0 0 24px", textWrap: "balance",
            }}>{f.title}</h2>
            <p style={{
              fontFamily: "var(--font-ui)", fontSize: 18, lineHeight: 1.6,
              letterSpacing: "0.2px", color: p.fgMute, margin: 0,
              maxWidth: 640, textWrap: "pretty",
            }}>{f.body}</p>
          </div>
        </div>

        {sent ? (
          <div style={{
            display: "grid", gridTemplateColumns: "minmax(0, 220px) 1fr", gap: 48, alignItems: "start",
            padding: "72px 0",
            borderTop: `1px solid ${p.hairline}`, borderBottom: `1px solid ${p.hairline}`,
          }}>
            <div style={{
              fontFamily: "var(--font-ui)", fontSize: 11, letterSpacing: "1.17px",
              textTransform: "uppercase", color: p.fgFaint,
              display: "flex", alignItems: "center", gap: 10,
            }}>
              <span style={{ width: 6, height: 6, borderRadius: 999, background: p.fg, boxShadow: `0 0 0 4px ${p.hairlineSoft}` }} />
              Sent · {new Date().toLocaleDateString(undefined, { month: "short", day: "2-digit", year: "numeric" })}
            </div>
            <div>
              <div style={{ display: "flex", alignItems: "baseline", gap: 18, marginBottom: 28 }}>
                <svg width="32" height="20" viewBox="0 0 18 14" aria-hidden="true">
                  <path d="M0 1 L8 7 L0 13 Z M5 1 L13 7 L5 13 Z" fill="currentColor" />
                </svg>
                <span style={{
                  fontFamily: "var(--font-display)", fontWeight: 700,
                  fontSize: "clamp(28px, 4.6vw, 64px)", lineHeight: 1, letterSpacing: "0.2px",
                  textTransform: "uppercase",
                }}>Message received.</span>
              </div>
              <p style={{
                fontFamily: "var(--font-ui)", fontSize: 18, lineHeight: 1.6,
                letterSpacing: "0.2px", color: p.fgMute, margin: "0 0 32px",
                maxWidth: 640, textWrap: "pretty",
              }}>{f.success}</p>
              <button type="button" onClick={reset} style={{
                background: "transparent", border: `1px solid ${p.hairline}`, color: p.fg,
                padding: "12px 20px",
                fontFamily: "var(--font-ui)", fontSize: 11, letterSpacing: "1.17px",
                textTransform: "uppercase", cursor: "pointer",
                transition: "background 160ms ease, color 160ms ease",
              }}
              onMouseEnter={(ev) => { ev.currentTarget.style.background = p.fg; ev.currentTarget.style.color = p.bg; }}
              onMouseLeave={(ev) => { ev.currentTarget.style.background = "transparent"; ev.currentTarget.style.color = p.fg; }}>
                Send another
              </button>
            </div>
          </div>
        ) : (
          <form onSubmit={submit} style={{
            display: "grid",
            gridTemplateColumns: "repeat(2, minmax(0, 1fr))",
            gap: "36px 48px",
            paddingTop: 8,
          }}>
            <div style={{ gridColumn: "span 1" }}>
              <div style={labelStyle}>
                <span style={{ color: p.fgFaint }}>01 / Name</span>
                <span style={{ color: p.fg }}>·</span>
                <span>Required</span>
              </div>
              <input type="text" required value={state.name} onChange={setField("name")} onFocus={onFocus} onBlur={onBlur} placeholder="Lim Bonggi" style={inputStyle} />
            </div>
            <div style={{ gridColumn: "span 1" }}>
              <div style={labelStyle}>
                <span style={{ color: p.fgFaint }}>02 / Email</span>
                <span style={{ color: p.fg }}>·</span>
                <span>Required</span>
              </div>
              <input type="email" required value={state.email} onChange={setField("email")} onFocus={onFocus} onBlur={onBlur} placeholder="you@company.com" style={inputStyle} />
            </div>
            <div style={{ gridColumn: "span 1" }}>
              <div style={labelStyle}>
                <span style={{ color: p.fgFaint }}>03 / Company</span>
                <span style={{ color: p.fg }}>·</span>
                <span>Optional</span>
              </div>
              <input type="text" value={state.company} onChange={setField("company")} onFocus={onFocus} onBlur={onBlur} placeholder="—" style={inputStyle} />
            </div>
            <div style={{ gridColumn: "span 1" }}>
              <div style={labelStyle}>
                <span style={{ color: p.fgFaint }}>04 / Subject</span>
                <span style={{ color: p.fg }}>·</span>
                <span>Required</span>
              </div>
              <div style={{ position: "relative" }}>
                <select required value={state.subject} onChange={setField("subject")} onFocus={onFocus} onBlur={onBlur} style={{
                  ...inputStyle,
                  paddingRight: 36,
                  cursor: "pointer",
                  color: state.subject ? p.fg : p.fgFaint,
                }}>
                  <option value="" disabled style={{ color: "#000", background: "#fff" }}>Select one</option>
                  {f.subjects.map((s) => (
                    <option key={s} value={s} style={{ color: "#000", background: "#fff" }}>{s}</option>
                  ))}
                </select>
                <svg width="14" height="14" viewBox="0 0 14 14" aria-hidden="true" style={{
                  position: "absolute", right: 4, bottom: 22, pointerEvents: "none", color: p.fgMute,
                }}>
                  <path d="M2 5 L7 10 L12 5" stroke="currentColor" strokeWidth="1.4" fill="none" />
                </svg>
              </div>
            </div>
            <div style={{ gridColumn: "1 / -1" }}>
              <div style={labelStyle}>
                <span style={{ color: p.fgFaint }}>05 / Message</span>
                <span style={{ color: p.fg }}>·</span>
                <span>Required</span>
              </div>
              <textarea required value={state.message} onChange={setField("message")} onFocus={onFocus} onBlur={onBlur} rows={4} placeholder="Tell us about your operation, your sourcing project, or what you're trying to move." style={{
                ...inputStyle,
                fontSize: "clamp(18px, 1.6vw, 22px)",
                fontFamily: "var(--font-ui)", fontWeight: 400,
                resize: "vertical", minHeight: 120,
                paddingTop: 14,
              }} />
            </div>

            <div style={{ gridColumn: "1 / -1", display: "flex", flexWrap: "wrap", alignItems: "center", justifyContent: "space-between", gap: 16, marginTop: 16 }}>
              <div style={{
                fontFamily: "var(--font-ui)", fontSize: 11, letterSpacing: "1.17px",
                textTransform: "uppercase", color: error ? p.fg : p.fgFaint,
                maxWidth: 480,
              }}>{error || (valid ? "Ready to send" : "Fill required fields")}</div>
              <button type="submit" disabled={!valid || submitting} style={{
                display: "inline-flex", alignItems: "center", gap: 14,
                background: valid ? p.fg : "transparent",
                color: valid ? p.bg : p.fgFaint,
                border: `1px solid ${valid ? p.fg : p.hairline}`,
                padding: "18px 28px",
                fontFamily: "var(--font-ui)", fontSize: 13, letterSpacing: "1.4px",
                textTransform: "uppercase", fontWeight: 600,
                cursor: valid ? "pointer" : "not-allowed",
                transition: "transform 160ms ease, background 160ms ease, color 160ms ease",
              }}
              onMouseEnter={(ev) => { if (valid) ev.currentTarget.style.transform = "translateY(-1px)"; }}
              onMouseLeave={(ev) => { ev.currentTarget.style.transform = "translateY(0)"; }}>
                <svg width="18" height="12" viewBox="0 0 18 14" aria-hidden="true">
                  <path d="M0 1 L8 7 L0 13 Z M5 1 L13 7 L5 13 Z" fill="currentColor" />
                </svg>
                {submitting ? "Sending…" : f.submit}
              </button>
            </div>
          </form>
        )}
      </div>
    </section>
  );
}

window.InquiryForm = InquiryForm;
