// Contact section

function Field({ label, name, type = "text", required, half, full, value, onChange, as = "input", options }) {
  return (
    <div style={{ gridColumn: full ? "1 / -1" : (half ? "span 1" : "1 / -1"), display: "flex", flexDirection: "column", gap: 8 }}>
      <label style={{
        fontFamily: "var(--mono)",
        fontSize: 10.5,
        letterSpacing: "0.16em",
        textTransform: "uppercase",
        color: "var(--muted)",
      }}>
        {label} {required && <span style={{ color: "var(--accent)" }}>*</span>}
      </label>
      {as === "textarea" ? (
        <textarea
          name={name}
          required={required}
          rows={4}
          value={value}
          onChange={onChange}
          style={{
            background: "transparent",
            border: "none",
            borderBottom: "1px solid var(--line-strong)",
            padding: "10px 0 14px",
            fontSize: 17,
            outline: "none",
            resize: "vertical",
            color: "var(--ink)",
            transition: "border-color 0.3s",
            fontFamily: "inherit",
          }}
          onFocus={(e) => e.currentTarget.style.borderColor = "var(--ink)"}
          onBlur={(e) => e.currentTarget.style.borderColor = "var(--line-strong)"}
        />
      ) : as === "select" ? (
        <select
          name={name}
          required={required}
          value={value}
          onChange={onChange}
          style={{
            background: "transparent",
            border: "none",
            borderBottom: "1px solid var(--line-strong)",
            padding: "10px 0 14px",
            fontSize: 17,
            outline: "none",
            color: value ? "var(--ink)" : "var(--muted-2)",
            appearance: "none",
            cursor: "pointer",
          }}
        >
          <option value="">Choose one…</option>
          {options.map((o) => (<option key={o} value={o}>{o}</option>))}
        </select>
      ) : (
        <input
          name={name}
          type={type}
          required={required}
          value={value}
          onChange={onChange}
          style={{
            background: "transparent",
            border: "none",
            borderBottom: "1px solid var(--line-strong)",
            padding: "10px 0 14px",
            fontSize: 17,
            outline: "none",
            color: "var(--ink)",
            transition: "border-color 0.3s",
          }}
          onFocus={(e) => e.currentTarget.style.borderColor = "var(--ink)"}
          onBlur={(e) => e.currentTarget.style.borderColor = "var(--line-strong)"}
        />
      )}
    </div>
  );
}

function SuccessCard({ onReset, name }) {
  return (
    <div style={{
      background: "var(--paper)",
      border: "1px solid var(--line)",
      borderRadius: 28,
      padding: "56px clamp(24px, 4vw, 48px)",
      position: "relative",
      overflow: "hidden",
      minHeight: 460,
      display: "flex",
      flexDirection: "column",
      justifyContent: "space-between",
    }}>
      {/* Soft accent glow */}
      <div aria-hidden style={{
        position: "absolute",
        top: "-40%",
        right: "-20%",
        width: "80%",
        height: "120%",
        background: "radial-gradient(closest-side, rgba(255,90,31,0.18), rgba(255,90,31,0) 70%)",
        filter: "blur(20px)",
        pointerEvents: "none",
      }}/>

      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", position: "relative", zIndex: 1 }}>
        <span className="tag">
          <span style={{ width: 6, height: 6, borderRadius: "50%", background: "var(--accent)" }}></span>
          Message received
        </span>
        <span className="idx">FORM 01 · SENT</span>
      </div>

      <div style={{ position: "relative", zIndex: 1 }}>
        {/* Check mark */}
        <div style={{
          width: 72, height: 72, borderRadius: "50%",
          background: "var(--ink)",
          display: "flex", alignItems: "center", justifyContent: "center",
          marginBottom: 28,
          animation: "popIn 0.6s cubic-bezier(0.2,0.8,0.2,1)",
        }}>
          <svg width="32" height="32" viewBox="0 0 32 32" fill="none">
            <path d="M8 16.5L13.5 22L24 11" stroke="var(--accent)" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" style={{
              strokeDasharray: 30,
              strokeDashoffset: 30,
              animation: "drawCheck 0.6s cubic-bezier(0.2,0.8,0.2,1) 0.3s forwards",
            }}/>
          </svg>
        </div>

        <h3 className="h-2" style={{ marginBottom: 16 }}>
          Thank you{name ? `, ${name.split(" ")[0]}` : ""}.<br/>
          <span style={{ color: "var(--muted-2)" }}>We'll be in touch shortly.</span>
        </h3>
        <p className="lede" style={{ maxWidth: "44ch", fontSize: 17 }}>
          Your message is in our inbox. Expect a reply from a real person within 24 hours — usually sooner. In the meantime, feel free to email us directly.
        </p>
      </div>

      <div style={{
        display: "flex",
        gap: 12,
        flexWrap: "wrap",
        position: "relative",
        zIndex: 1,
        paddingTop: 32,
        borderTop: "1px solid var(--line)",
        alignItems: "center",
        justifyContent: "space-between",
      }}>
        <a href="mailto:clients@youngdgroup.com" style={{
          fontFamily: "var(--mono)",
          fontSize: 12,
          letterSpacing: "0.14em",
          textTransform: "uppercase",
          color: "var(--ink)",
          borderBottom: "1px solid var(--line-strong)",
          paddingBottom: 2,
        }}>clients@youngdgroup.com</a>
        <button onClick={onReset} className="btn btn-secondary" type="button" style={{ height: 44, fontSize: 13.5 }}>
          Send another
          <span className="arrow"><ArrowR /></span>
        </button>
      </div>

      <style>{`
        @keyframes popIn {
          0% { transform: scale(0.4); opacity: 0; }
          100% { transform: scale(1); opacity: 1; }
        }
        @keyframes drawCheck {
          to { stroke-dashoffset: 0; }
        }
      `}</style>
    </div>
  );
}

function Contact() {
  const [form, setForm] = React.useState({
    name: "", business: "", email: "", phone: "", website: "", interest: "", goals: ""
  });
  const [status, setStatus] = React.useState("idle"); // idle | sending | sent | error
  const [errorMsg, setErrorMsg] = React.useState("");
  const update = (k) => (e) => setForm({ ...form, [k]: e.target.value });

  const submit = async (e) => {
    e.preventDefault();
    if (status === "sending") return;
    setStatus("sending");
    setErrorMsg("");

    // Compose the message field from interest + goals + website + business
    const messageParts = [];
    if (form.business) messageParts.push(`Business: ${form.business}`);
    if (form.website) messageParts.push(`Website: ${form.website}`);
    if (form.interest) messageParts.push(`Interested in: ${form.interest}`);
    if (form.goals) messageParts.push(`Goals: ${form.goals}`);
    const message = messageParts.join("\n\n");

    const payload = {
      name: form.name,
      email: form.email,
      phone: form.phone,
      message,
      // pass-through extras in case the webhook wants them
      business: form.business,
      website: form.website,
      interest: form.interest,
      goals: form.goals,
      source: "youngdgroup.com — strategy call form",
      submittedAt: new Date().toISOString(),
    };

    try {
      const res = await fetch(
        "https://services.leadconnectorhq.com/hooks/peIkQS6CRAnExZPhQj87/webhook-trigger/a52d2907-56ec-45d0-a2fe-54d208ca4dd2",
        {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify(payload),
        }
      );
      if (!res.ok) throw new Error(`Server responded ${res.status}`);
      setStatus("sent");
    } catch (err) {
      console.error("Form submit failed:", err);
      setErrorMsg("Something went wrong. Please email clients@youngdgroup.com directly.");
      setStatus("error");
    }
  };

  const resetForm = () => {
    setForm({ name: "", business: "", email: "", phone: "", website: "", interest: "", goals: "" });
    setStatus("idle");
    setErrorMsg("");
  };

  return (
    <section id="contact" style={{ padding: "140px 0 120px" }}>
      <div className="container">
        <div className="contact-grid" style={{
          display: "grid",
          gridTemplateColumns: "0.9fr 1.1fr",
          gap: 96,
          alignItems: "start",
        }}>
          {/* Left side */}
          <div>
            <Reveal><SectionLabel index="08" label="Contact" /></Reveal>
            <Reveal delay={120}>
              <h2 className="h-1" style={{ marginTop: 32 }}>
                Let's Build <br/>Something <span style={{ color: "var(--accent)" }}>Bigger.</span>
              </h2>
            </Reveal>
            <Reveal delay={200}>
              <p className="lede" style={{ marginTop: 28, maxWidth: "40ch" }}>
                Tell us where you are and where you want to go. We'll send back a candid plan, not a pitch deck.
              </p>
            </Reveal>

            <Reveal delay={280}>
              <div style={{
                marginTop: 56,
                padding: "28px 0",
                borderTop: "1px solid var(--line)",
                borderBottom: "1px solid var(--line)",
                display: "grid",
                gridTemplateColumns: "1fr 1fr",
                gap: 24,
              }}>
                <div>
                  <div className="idx" style={{ marginBottom: 8 }}>RESPONSE</div>
                  <div style={{ fontSize: 22, fontWeight: 500, letterSpacing: "-0.02em" }}>Within 24 hours</div>
                </div>
                <div>
                  <div className="idx" style={{ marginBottom: 8 }}>CALL DURATION</div>
                  <div style={{ fontSize: 22, fontWeight: 500, letterSpacing: "-0.02em" }}>30 minutes</div>
                </div>
                <div>
                  <div className="idx" style={{ marginBottom: 8 }}>WORKING HOURS</div>
                  <div style={{ fontSize: 16, fontWeight: 450 }}>Mon — Fri, 9—6 ET</div>
                </div>
                <div>
                  <div className="idx" style={{ marginBottom: 8 }}>EMAIL</div>
                  <a href="mailto:clients@youngdgroup.com" style={{ fontSize: 16, fontWeight: 450, borderBottom: "1px solid var(--line-strong)" }}>clients@youngdgroup.com</a>
                </div>
              </div>
            </Reveal>
          </div>

          {/* Form */}
          <Reveal delay={200}>
            {status === "sent" ? (
              <SuccessCard onReset={resetForm} name={form.name} />
            ) : (
            <form
              onSubmit={submit}
              style={{
                background: "var(--paper)",
                border: "1px solid var(--line)",
                borderRadius: 28,
                padding: "40px clamp(24px, 4vw, 48px) 36px",
                display: "grid",
                gridTemplateColumns: "1fr 1fr",
                gap: "28px 24px",
                position: "relative",
              }}
            >
              <div style={{ gridColumn: "1 / -1", display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 4 }}>
                <span className="tag"><span style={{ width: 6, height: 6, borderRadius: "50%", background: "var(--accent)" }}></span> Inquiry · Strategy Call</span>
                <span className="idx">FORM 01</span>
              </div>

              <Field label="Name" name="name" required half value={form.name} onChange={update("name")} />
              <Field label="Business Name" name="business" required half value={form.business} onChange={update("business")} />
              <Field label="Email" name="email" type="email" required half value={form.email} onChange={update("email")} />
              <Field label="Phone" name="phone" type="tel" half value={form.phone} onChange={update("phone")} />
              <Field label="Website" name="website" type="url" full value={form.website} onChange={update("website")} />
              <Field label="What are you interested in?" name="interest" as="select" full value={form.interest} onChange={update("interest")}
                options={[
                  "Full growth system",
                  "Website + SEO",
                  "Paid advertising",
                  "CRM + Sales systems",
                  "AI automation",
                  "Consulting / audit",
                  "Not sure yet",
                ]}
              />
              <Field label="Tell us about your business goals" name="goals" as="textarea" full value={form.goals} onChange={update("goals")} />

              <div style={{ gridColumn: "1 / -1", marginTop: 12, display: "flex", justifyContent: "space-between", alignItems: "center", flexWrap: "wrap", gap: 16 }}>
                <p style={{ margin: 0, fontSize: 12.5, color: status === "error" ? "var(--accent)" : "var(--muted)", maxWidth: "44ch" }}>
                  {status === "error"
                    ? errorMsg
                    : "By submitting, you'll get a reply from a person, not an autoresponder. We don't sell or share your info."}
                </p>
                <button type="submit" className="btn btn-primary" disabled={status === "sending"}>
                  {status === "sending" ? "Sending…" : "Schedule My Strategy Call"}
                  <span className="arrow"><ArrowUR /></span>
                </button>
              </div>
            </form>
            )}
          </Reveal>
        </div>
      </div>

      <style>{`
        @media (max-width: 980px) {
          .contact-grid { grid-template-columns: 1fr !important; gap: 56px !important; }
        }
      `}</style>
    </section>
  );
}

window.Contact = Contact;
