// Contact — inline form on warm paper (light) so it contrasts the dark Deployments above.

const WEB3FORMS_ENDPOINT = "https://api.web3forms.com/submit";

const fieldLabelStyle = (focused) => ({
  fontFamily: "var(--font-mono)",
  fontSize: 12,
  letterSpacing: "0.18em",
  fontWeight: 500,
  textTransform: "uppercase",
  color: focused ? "var(--site-accent, var(--flame))" : "var(--fg-2)",
  transition: "color var(--dur-fast) var(--ease-out)",
});

const fieldInputStyle = (focused, multiline) => ({
  fontFamily: "var(--font-sans)",
  fontSize: 17,
  color: "var(--fg-1)",
  background: "transparent",
  border: "none",
  borderBottom: `1px solid ${focused ? "var(--site-accent, var(--flame))" : "var(--border-2)"}`,
  padding: "12px 0",
  outline: "none",
  transition: "border-color var(--dur-fast) var(--ease-out)",
  resize: multiline ? "vertical" : "none",
  width: "100%",
  boxSizing: "border-box",
});

function ContactField({ label, placeholder, type = "text", value, onChange, multiline, required, name, autoComplete }) {
  const [focused, setFocused] = React.useState(false);
  const Tag = multiline ? "textarea" : "input";
  return (
    <label style={{ display: "flex", flexDirection: "column", gap: 10 }}>
      <span style={fieldLabelStyle(focused)}>{label}</span>
      <Tag
        type={type}
        name={name}
        value={value}
        onChange={(e) => onChange(e.target.value)}
        onFocus={() => setFocused(true)}
        onBlur={() => setFocused(false)}
        placeholder={placeholder}
        required={required}
        autoComplete={autoComplete}
        rows={multiline ? 4 : undefined}
        style={fieldInputStyle(focused, multiline)}
      />
    </label>
  );
}

function ContactSelectField({ label, value, onChange, options, required, name }) {
  const [focused, setFocused] = React.useState(false);
  return (
    <label style={{ display: "flex", flexDirection: "column", gap: 10 }}>
      <span style={fieldLabelStyle(focused)}>{label}</span>
      <select
        name={name}
        value={value}
        onChange={(e) => onChange(e.target.value)}
        onFocus={() => setFocused(true)}
        onBlur={() => setFocused(false)}
        required={required}
        style={{
          ...fieldInputStyle(focused, false),
          color: value ? "var(--fg-1)" : "var(--fg-3)",
          cursor: "pointer",
          appearance: "none",
          WebkitAppearance: "none",
          backgroundImage: `linear-gradient(45deg, transparent 50%, var(--fg-3) 50%), linear-gradient(135deg, var(--fg-3) 50%, transparent 50%)`,
          backgroundPosition: "calc(100% - 18px) calc(50% + 2px), calc(100% - 12px) calc(50% + 2px)",
          backgroundSize: "6px 6px, 6px 6px",
          backgroundRepeat: "no-repeat",
          paddingRight: 28,
        }}
      >
        <option value="" disabled>Select industry…</option>
        {options.map((opt) => (
          <option key={opt.value} value={opt.value}>{opt.label}</option>
        ))}
      </select>
    </label>
  );
}

function ContactDirectLink({ label, href, children }) {
  return (
    <DirectLink
      href={href}
      style={{
        display: "block",
        color: "var(--fg-1)",
        textDecoration: "none",
        borderRadius: 4,
        margin: "-4px -8px",
        padding: "4px 8px",
        transition: "color var(--dur-fast) var(--ease-out)",
      }}
      onMouseEnter={(e) => { e.currentTarget.style.color = "var(--site-accent, var(--flame))"; }}
      onMouseLeave={(e) => { e.currentTarget.style.color = "var(--fg-1)"; }}
    >
      <span style={{ color: "var(--fg-3)" }}>{label} </span>
      {children}
    </DirectLink>
  );
}

function getIndustryOptions() {
  const order = (typeof INDUSTRY_ORDER !== "undefined") ? INDUSTRY_ORDER : [];
  const industries = (typeof INDUSTRIES !== "undefined") ? INDUSTRIES : {};
  const options = order.map((slug) => ({
    value: slug,
    label: (industries[slug] && industries[slug].name) || slug,
  }));
  options.push({ value: "other", label: "Other" });
  return options;
}

function industryLabel(slug) {
  if (!slug) return "";
  if (slug === "other") return "Other";
  const industries = (typeof INDUSTRIES !== "undefined") ? INDUSTRIES : {};
  return (industries[slug] && industries[slug].name) || slug;
}

const EMPTY_FORM = { name: "", email: "", industry: "", company: "", brief: "" };

function Contact() {
  const industryOptions = React.useMemo(() => getIndustryOptions(), []);
  const [form, setForm] = React.useState(EMPTY_FORM);
  const [sent, setSent] = React.useState(false);
  const [submitting, setSubmitting] = React.useState(false);
  const [error, setError] = React.useState("");
  const set = (k) => (v) => setForm({ ...form, [k]: v });

  const handleSubmit = async (e) => {
    e.preventDefault();
    setError("");

    const accessKey = (window.__SITE_CONFIG && window.__SITE_CONFIG.web3formsAccessKey) || "";
    if (!accessKey) {
      setError("Form is not configured yet. Add your Web3Forms access key in site-config.js.");
      return;
    }

    setSubmitting(true);
    try {
      const response = await fetch(WEB3FORMS_ENDPOINT, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          Accept: "application/json",
        },
        body: JSON.stringify({
          access_key: accessKey,
          subject: `New brief — ${form.name.trim() || "promefy.com"}`,
          from_name: "Promefy Website",
          name: form.name.trim(),
          email: form.email.trim(),
          industry: industryLabel(form.industry),
          company: form.company.trim(),
          message: form.brief.trim(),
          botcheck: "",
        }),
      });
      const result = await response.json();

      if (response.ok && result.success) {
        setSent(true);
        return;
      }

      setError(result.message || "Could not send your brief. Try again or email sales@promefy.com.");
    } catch (err) {
      setError("Network error. Try again or email sales@promefy.com directly.");
    } finally {
      setSubmitting(false);
    }
  };

  const resetForm = () => {
    setSent(false);
    setError("");
    setForm(EMPTY_FORM);
  };

  return (
    <section id="contact" className="contact-section" style={{
      background: "var(--paper)",
      color: "var(--fg-1)",
      padding: "120px 0",
      position: "relative",
      overflow: "hidden",
    }}>
      <img src="assets/motif-wireframe-torus.svg" alt=""
        className="drift-y"
        style={{
          position: "absolute", right: "-160px", bottom: "-160px",
          width: 720, opacity: 0.22, pointerEvents: "none",
        }}/>

      <div className="container grid-2 contact-layout" style={{
        position: "relative",
        display: "grid",
        gridTemplateColumns: "minmax(0, 5fr) minmax(0, 7fr)",
        gap: 80, alignItems: "start",
      }}>
        <Reveal className="reveal-from-left col gap-6">
          <EyebrowLabel>// CONTACT · INTAKE_OPEN</EyebrowLabel>
          <h2 className="section-headline" style={{
            fontFamily: "var(--font-display)",
            fontSize: "clamp(40px, 5.5vw, 72px)",
            fontWeight: 500, letterSpacing: "-0.025em", lineHeight: 1.0,
            margin: 0, color: "var(--fg-1)", maxWidth: "12ch",
          }}>
            Tell us<AccentDot /> About the work.
          </h2>
          <p style={{
            fontFamily: "var(--font-sans)",
            fontSize: 16, lineHeight: 1.65,
            color: "var(--fg-2)", margin: 0, maxWidth: "42ch",
          }}>
            One short paragraph is enough. We reply within two business days with a 30-minute call slot.
          </p>

          <div style={{
            marginTop: 8,
            display: "flex", flexDirection: "column", gap: 14,
            padding: 24,
            border: "1px solid var(--border-1)",
            borderRadius: 8, background: "var(--bg-2)",
            fontFamily: "var(--font-mono)", fontSize: 14,
            color: "var(--fg-1)", lineHeight: 1.7,
          }}>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", fontSize: 12 }}>
              <span style={{ color: "var(--fg-2)", fontWeight: 500 }}>$ contact --direct</span>
              <span style={{ color: "var(--site-accent, var(--flame))", letterSpacing: "0.12em" }}>● MON–FRI</span>
            </div>
            <Hairline />
            <ContactDirectLink
              label="email"
              href="mailto:sales@promefy.com?subject=Inquiry%20from%20promefy.com"
            >
              sales@promefy.com
            </ContactDirectLink>
            <ContactDirectLink label="phone" href="tel:+601170068801">
              +60 11-7006 8801
            </ContactDirectLink>
          </div>
        </Reveal>

        <Reveal className="reveal-blur" delay={120}>
          {sent ? (
            <div className="col gap-4" style={{
              border: "1px solid var(--border-2)", borderRadius: 6, padding: 36,
              background: "var(--bg-1)",
            }}>
              <span style={{ fontFamily: "var(--font-mono)", fontSize: 11, letterSpacing: "0.18em", color: "var(--site-accent, var(--flame))" }}>● BRIEF RECEIVED</span>
              <h3 style={{ fontFamily: "var(--font-display)", fontSize: 32, fontWeight: 500, margin: 0, color: "var(--fg-1)" }}>
                Got it, {form.name || "friend"}.
              </h3>
              <p style={{ color: "var(--fg-2)", fontSize: 14, lineHeight: 1.6, margin: 0 }}>
                Your brief is queued. We'll write back to <span style={{ color: "var(--fg-1)" }}>{form.email || "your inbox"}</span> within two business days.
              </p>
              <div>
                <Button variant="secondary" onClick={resetForm}>Send another <ArrowGlyph /></Button>
              </div>
            </div>
          ) : (
            <form
              onSubmit={handleSubmit}
              style={{
                position: "relative",
                display: "grid",
                gridTemplateColumns: "1fr 1fr", gap: 32,
                padding: 32,
                border: "1px solid var(--fg-1)",
                borderRadius: 6, background: "var(--bg-1)",
                width: "100%",
                boxSizing: "border-box",
              }}
              className="grid-2 contact-form"
            >
              <input
                type="checkbox"
                name="botcheck"
                tabIndex={-1}
                autoComplete="off"
                aria-hidden="true"
                style={{ position: "absolute", opacity: 0, pointerEvents: "none", width: 0, height: 0 }}
              />

              <ContactField label="01 / NAME" name="name" placeholder="Maya Lin" value={form.name} onChange={set("name")} required autoComplete="name" />
              <ContactField label="02 / EMAIL" name="email" type="email" placeholder="maya@yourfirm.com" value={form.email} onChange={set("email")} required autoComplete="email" />
              <ContactSelectField
                label="03 / INDUSTRY"
                name="industry"
                value={form.industry}
                onChange={set("industry")}
                options={industryOptions}
                required
              />
              <ContactField
                label="04 / COMPANY"
                name="company"
                placeholder="Meridian Architecture"
                value={form.company}
                onChange={set("company")}
                required
                autoComplete="organization"
              />
              <div className="contact-form-full">
                <ContactField multiline name="message" label="05 / WHAT DO YOU NEED?" placeholder="We want a new website that doesn't look like 2008. Or: we have 12 years of permits as PDFs and want to search them…" value={form.brief} onChange={set("brief")} required />
              </div>
              {error && (
                <div className="contact-form-full" style={{ fontFamily: "var(--font-mono)", fontSize: 12, letterSpacing: "0.06em", color: "#B42318", lineHeight: 1.5 }}>
                  {error}
                </div>
              )}
              <div className="contact-form-full contact-form-footer" style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginTop: 12, flexWrap: "wrap", gap: 12 }}>
                <span style={{ fontFamily: "var(--font-mono)", fontSize: 12, letterSpacing: "0.16em", color: "var(--fg-3)", fontWeight: 500 }}>
                  5 FIELDS · ~ 60 SEC
                </span>
                <Button variant="flame" type="submit" disabled={submitting} style={submitting ? { opacity: 0.7, cursor: "wait" } : undefined}>
                  {submitting ? "Sending…" : <>Send brief <ArrowGlyph /></>}
                </Button>
              </div>
            </form>
          )}
        </Reveal>
      </div>
    </section>
  );
}

Object.assign(window, { Contact });
