/* contact.jsx — multi-step inquiry form with validation */
const { useState } = React;

const EVENT_TYPES = ["Wedding", "Private Event", "Corporate Event", "Floral Installation", "Custom Bouquet", "Other"];
const BUDGETS = ["Under $5,000", "$5,000 – $10,000", "$10,000 – $25,000", "$25,000 – $50,000", "$50,000+", "Unsure — would like guidance"];
const STEPS = [
  { id: "you", label: "About You" },
  { id: "event", label: "Your Event" },
  { id: "vision", label: "Your Vision" },
];

const validateStep = (step, data) => {
  const e = {};
  if (step === 0) {
    if (!data.name?.trim()) e.name = "Please share your name.";
    if (!data.email?.trim()) e.email = "Please share an email.";
    else if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(data.email)) e.email = "That email looks off.";
  }
  if (step === 1) {
    if (!data.eventDate) e.eventDate = "An approximate date helps.";
    if (!data.eventLocation?.trim()) e.eventLocation = "Where will it take place?";
    if (!data.eventType) e.eventType = "Please choose a type.";
  }
  if (step === 2) {
    if (!data.budget) e.budget = "An estimate helps us tailor the proposal.";
  }
  return e;
};

const ContactPage = ({ navigate }) => {
  const [step, setStep] = useState(0);
  const [data, setData] = useState({
    name: "", email: "", eventDate: "", eventLocation: "", eventType: "", budget: "", message: "",
  });
  const [errors, setErrors] = useState({});
  const [submitted, setSubmitted] = useState(false);

  const set = (k, v) => setData(d => ({ ...d, [k]: v }));

  const next = () => {
    const e = validateStep(step, data);
    setErrors(e);
    if (Object.keys(e).length === 0) {
      if (step < STEPS.length - 1) setStep(step + 1);
      else submit();
    }
  };
  const back = () => setStep(s => Math.max(0, s - 1));
  const submit = async () => {
    try {
      await fetch("https://zqvlxudryqajqrxmpgxg.supabase.co/rest/v1/inquiries", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          "apikey": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Inpxdmx4dWRyeXFhanFyeG1wZ3hnIiwicm9sZSI6ImFub24iLCJpYXQiOjE3Nzc4NjY5NjYsImV4cCI6MjA5MzQ0Mjk2Nn0.qf6kW9nz68DZjeHba6zzeCWyTCkAIqDSyBIbGBr6IFw",
          "Authorization": "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Inpxdmx4dWRyeXFhanFyeG1wZ3hnIiwicm9sZSI6ImFub24iLCJpYXQiOjE3Nzc4NjY5NjYsImV4cCI6MjA5MzQ0Mjk2Nn0.qf6kW9nz68DZjeHba6zzeCWyTCkAIqDSyBIbGBr6IFw",
          "Prefer": "return=minimal",
        },
        body: JSON.stringify({
          name: data.name,
          email: data.email,
          phone: data.phone || null,
          event_date: data.eventDate || null,
          event_location: data.eventLocation,
          event_type: data.eventType,
          budget: data.budget,
          message: data.message || null,
        }),
      });
    } catch (err) {
      console.error("Supabase submit error:", err);
    }
    setSubmitted(true);
    window.scrollTo({ top: 0, behavior: "smooth" });
  };

  return (
    <>
      <section style={{ background: "var(--ivory)", paddingTop: 200, paddingBottom: 80 }}>
        <div className="shell">
          <Reveal><span className="eyebrow rule-eyebrow">05 — Inquire</span></Reveal>
          <Reveal delay={1}>
            <h1 className="serif" style={{ marginTop: 28, maxWidth: "16ch", fontSize: "clamp(48px, 7vw, 108px)", fontWeight: 300, letterSpacing: "-0.01em" }}>
              Begin a <span style={{ fontStyle: "italic", color: "var(--accent-4)" }}>conversation</span>.
            </h1>
          </Reveal>
          <Reveal delay={2}>
            <p className="lede" style={{ marginTop: 36, maxWidth: 640 }}>
              We respond to every inquiry within three business days. The more you can share now,
              the more thoughtful our first proposal will be.
            </p>
          </Reveal>
        </div>
      </section>

      <section style={{ background: "var(--cream)", padding: "100px 0 160px" }}>
        <div className="shell" style={{ maxWidth: 1100, margin: "0 auto" }}>
          {submitted ? (
            <Reveal>
              <div style={{ background: "var(--ivory)", padding: "80px 60px", border: "1px solid var(--hairline-soft)", textAlign: "center", maxWidth: 720, margin: "0 auto" }}>
                <span className="serif" style={{ fontStyle: "italic", color: "var(--accent-4)", fontSize: 18 }}>Thank you, {data.name.split(" ")[0]}</span>
                <h2 className="serif" style={{ marginTop: 14, fontSize: 48 }}>Your inquiry is in.</h2>
                <p className="lede" style={{ marginTop: 24 }}>
                  We've received your details for {data.eventType.toLowerCase()} on {new Date(data.eventDate).toLocaleDateString("en-US", { month: "long", day: "numeric", year: "numeric" })} in {data.eventLocation}.
                </p>
                <p className="body-copy" style={{ marginTop: 18 }}>
                  Sophie or one of the studio designers will be in touch within three business days. In the meantime,
                  feel free to explore our portfolio.
                </p>
                <div style={{ display: "flex", gap: 14, justifyContent: "center", marginTop: 40 }}>
                  <button className="btn btn--ghost" onClick={() => navigate("portfolio")}>View Portfolio <Arrow /></button>
                  <button className="btn btn--primary" onClick={() => navigate("home")}>Back to Home</button>
                </div>
              </div>
            </Reveal>
          ) : (
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1.6fr", gap: 80, alignItems: "start" }} className="contact-grid">
              {/* Left rail — steps */}
              <div>
                <span className="eyebrow rule-eyebrow">Inquiry Form</span>
                <ol style={{ listStyle: "none", padding: 0, margin: "32px 0 0", display: "flex", flexDirection: "column", gap: 4 }}>
                  {STEPS.map((s, i) => (
                    <li key={s.id} style={{
                      display: "grid", gridTemplateColumns: "auto 1fr", gap: 18,
                      padding: "18px 0",
                      borderTop: "1px solid var(--hairline-soft)",
                      borderBottom: i === STEPS.length - 1 ? "1px solid var(--hairline-soft)" : "none",
                      cursor: i < step ? "pointer" : "default",
                      opacity: i === step ? 1 : 0.55,
                      transition: "opacity 240ms ease",
                    }} onClick={() => i < step && setStep(i)}>
                      <span className="serif" style={{ fontStyle: "italic", color: "var(--accent-4)", fontSize: 22 }}>0{i + 1}</span>
                      <div>
                        <div className="serif" style={{ fontSize: 22 }}>{s.label}</div>
                        <div style={{ fontSize: 11, letterSpacing: "0.18em", textTransform: "uppercase", color: "var(--plum-soft)", marginTop: 6 }}>
                          {i < step ? "Complete" : i === step ? "In Progress" : "Up Next"}
                        </div>
                      </div>
                    </li>
                  ))}
                </ol>
                <div style={{ marginTop: 40, paddingTop: 24, borderTop: "1px solid var(--hairline-soft)" }}>
                  <span className="eyebrow eyebrow--muted">Or write directly</span>
                  <p className="body-copy" style={{ marginTop: 10, fontSize: 14 }}>coastlineblooms@gmail.com</p>
                </div>
              </div>

              {/* Right — active step */}
              <div style={{ background: "var(--ivory)", padding: "56px 56px", border: "1px solid var(--hairline-soft)" }} className="contact-form">
                <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 36 }}>
                  <span className="eyebrow" style={{ color: "var(--accent-4)" }}>Step {step + 1} of {STEPS.length}</span>
                  <span style={{ fontSize: 11, letterSpacing: "0.2em", textTransform: "uppercase", color: "var(--plum-soft)" }}>{STEPS[step].label}</span>
                </div>
                {/* progress bar */}
                <div style={{ height: 1, background: "var(--hairline-soft)", marginBottom: 40, position: "relative" }}>
                  <div style={{
                    position: "absolute", left: 0, top: 0,
                    height: 1, width: `${((step + 1) / STEPS.length) * 100}%`,
                    background: "var(--accent-4)",
                    transition: "width 380ms cubic-bezier(.2,.7,.3,1)",
                  }} />
                </div>

                {step === 0 && (
                  <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 28 }}>
                    <Field label="Your Name" error={errors.name}>
                      <input type="text" value={data.name} onChange={e => set("name", e.target.value)} placeholder="Sienna Hale" />
                    </Field>
                    <Field label="Email" error={errors.email}>
                      <input type="email" value={data.email} onChange={e => set("email", e.target.value)} placeholder="sienna@example.com" />
                    </Field>
                    <Field label="Phone (optional)" full>
                      <input type="tel" value={data.phone || ""} onChange={e => set("phone", e.target.value)} placeholder="(310) 555-0119" />
                    </Field>
                  </div>
                )}

                {step === 1 && (
                  <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 28 }}>
                    <Field label="Event Date" error={errors.eventDate}>
                      <input type="date" value={data.eventDate} onChange={e => set("eventDate", e.target.value)} />
                    </Field>
                    <Field label="Event Location" error={errors.eventLocation}>
                      <input type="text" value={data.eventLocation} onChange={e => set("eventLocation", e.target.value)} placeholder="Malibu, CA" />
                    </Field>
                    <Field label="Event Type" error={errors.eventType} full>
                      <div style={{ display: "flex", flexWrap: "wrap", gap: 8, marginTop: 6 }}>
                        {EVENT_TYPES.map(t => (
                          <button key={t} type="button" onClick={() => set("eventType", t)}
                            style={{
                              padding: "10px 18px",
                              fontSize: 11, letterSpacing: "0.2em", textTransform: "uppercase", fontWeight: 500,
                              background: data.eventType === t ? "var(--plum)" : "transparent",
                              color: data.eventType === t ? "var(--ivory)" : "var(--plum)",
                              border: "1px solid " + (data.eventType === t ? "var(--plum)" : "var(--hairline)"),
                              cursor: "pointer",
                              transition: "all 200ms ease",
                            }}>{t}</button>
                        ))}
                      </div>
                    </Field>
                  </div>
                )}

                {step === 2 && (
                  <div style={{ display: "grid", gridTemplateColumns: "1fr", gap: 28 }}>
                    <Field label="Estimated Floral Budget" error={errors.budget}>
                      <div style={{ display: "flex", flexWrap: "wrap", gap: 8, marginTop: 6 }}>
                        {BUDGETS.map(b => (
                          <button key={b} type="button" onClick={() => set("budget", b)}
                            style={{
                              padding: "10px 18px",
                              fontSize: 11, letterSpacing: "0.2em", textTransform: "uppercase", fontWeight: 500,
                              background: data.budget === b ? "var(--plum)" : "transparent",
                              color: data.budget === b ? "var(--ivory)" : "var(--plum)",
                              border: "1px solid " + (data.budget === b ? "var(--plum)" : "var(--hairline)"),
                              cursor: "pointer",
                              transition: "all 200ms ease",
                            }}>{b}</button>
                        ))}
                      </div>
                    </Field>
                    <Field label="Tell Us About Your Vision">
                      <textarea rows={6} value={data.message} onChange={e => set("message", e.target.value)}
                        placeholder="Venue, palette, references, the feeling you want guests to remember…" />
                    </Field>
                  </div>
                )}

                <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginTop: 48, paddingTop: 28, borderTop: "1px solid var(--hairline-soft)" }}>
                  <button onClick={back} disabled={step === 0}
                    style={{
                      background: "transparent", border: 0, padding: "10px 0",
                      fontSize: 11, letterSpacing: "0.22em", textTransform: "uppercase", fontWeight: 500,
                      cursor: step === 0 ? "default" : "pointer",
                      opacity: step === 0 ? 0.3 : 1,
                      color: "var(--plum)",
                    }}>← Back</button>
                  <button className="btn btn--primary" onClick={next}>
                    {step === STEPS.length - 1 ? "Start Your Floral Proposal" : "Continue"} <Arrow />
                  </button>
                </div>
              </div>
            </div>
          )}
        </div>
        <style>{`
          @media (max-width: 860px) {
            .contact-grid { grid-template-columns: 1fr !important; gap: 40px !important; }
            .contact-form { padding: 32px !important; }
            .contact-form > div[style*="grid-template-columns: 1fr 1fr"] { grid-template-columns: 1fr !important; }
          }
        `}</style>
      </section>
    </>
  );
};

const Field = ({ label, children, error, full }) => (
  <div className={"field" + (error ? " field--error" : "")} style={{ gridColumn: full ? "1 / -1" : "auto" }}>
    <label>{label}</label>
    {children}
    {error && <span className="field-error">{error}</span>}
  </div>
);

Object.assign(window, { ContactPage });
