// Contact — Start a project. Sector-qualified enquiry with file-upload affordance.

function Contact({ navigate, prefilledProject }) {
  const data = window.DS_DATA;
  const [enquiryType, setEnquiryType] = useState("new-project");
  const [sector, setSector] = useState(prefilledProject ? data.projects.find((p) => p.id === prefilledProject)?.sector || "" : "");
  const [budget, setBudget] = useState("");
  const [files, setFiles] = useState([]);
  const [submitted, setSubmitted] = useState(false);
  const [form, setForm] = useState({
    name: "", email: "", phone: "", company: "",
    location: "", timeline: "", message: "",
  });
  const [errors, setErrors] = useState({});

  const enquiryTypes = [
    { id: "new-project", label: "New project" },
    { id: "vendor", label: "Vendor" },
    { id: "careers", label: "Careers" },
    { id: "media", label: "Press / media" },
    { id: "general", label: "General" },
  ];

  const budgets = [
    "Under $250k",
    "$250k — $1M",
    "$1M — $5M",
    "$5M — $20M",
    "$20M+",
    "Prefer not to say",
  ];

  const projectTypes = {
    hospitality: ["Restaurant", "Café", "Hotel public realm", "Bar / lounge"],
    commercial: ["Office HQ", "Retail / showroom", "Co-working"],
    residential: ["Villa (ground-up)", "Villa (fit-out)", "Penthouse", "Apartment"],
    healthcare: ["Clinic", "Specialist medical"],
    wellness: ["Spa", "Wellness centre"],
    tower: ["Mixed-use", "Residential tower", "Commercial tower"],
  };

  const onFileDrop = (e) => {
    e.preventDefault();
    const list = Array.from(e.dataTransfer.files);
    setFiles((f) => [...f, ...list]);
  };
  const onFileChange = (e) => {
    const list = Array.from(e.target.files);
    setFiles((f) => [...f, ...list]);
  };

  const submit = (e) => {
    e.preventDefault();
    const errs = {};
    if (!form.name) errs.name = "required";
    if (!form.email) errs.email = "required";
    if (!/.+@.+\..+/.test(form.email) && form.email) errs.email = "format";
    if (enquiryType === "new-project" && !sector) errs.sector = "required";
    if (enquiryType === "new-project" && !form.message) errs.message = "required";
    setErrors(errs);
    if (Object.keys(errs).length === 0) setSubmitted(true);
  };

  if (submitted) {
    return (
      <div className="page-enter" data-screen-label="08 Contact / Submitted">
        <section className="container section">
          <Eyebrow>Submitted</Eyebrow>
          <h1 className="h-1" style={{ maxWidth: "16ch", marginTop: 12 }}>
            Thanks, {form.name.split(" ")[0] || "there"}.
          </h1>
          <p className="lede muted" style={{ maxWidth: "52ch", marginTop: 18 }}>
            A sector lead will be in touch within two working days. If your brief is urgent, call us on <a href={`tel:${data.brand.phone.replace(/\s/g, "")}`} style={{ color: "var(--accent)", borderBottom: "1px solid currentColor" }}>{data.brand.phone}</a>.
          </p>
          <div style={{ marginTop: 36, display: "flex", gap: 12 }}>
            <Button onClick={() => navigate({ name: "projects" })}>See the work</Button>
            <Button variant="ghost" onClick={() => { setSubmitted(false); setForm({ name: "", email: "", phone: "", company: "", location: "", timeline: "", message: "" }); }}>Submit another</Button>
          </div>
          <hr className="hairline" style={{ marginTop: 64 }} />
          <div style={{ marginTop: 36, display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 24 }} className="conf-grid">
            <ConfirmCell label="Enquiry" value={enquiryTypes.find((t) => t.id === enquiryType)?.label || ""} />
            <ConfirmCell label="Sector" value={data.sectors.find((s) => s.id === sector)?.label || "—"} />
            <ConfirmCell label="Files attached" value={String(files.length || 0)} />
          </div>
          <style>{`@media (max-width: 720px) { .conf-grid { grid-template-columns: 1fr !important; } }`}</style>
        </section>
      </div>
    );
  }

  return (
    <div className="page-enter" data-screen-label="08 Contact">
      <section className="container" style={{ paddingTop: "clamp(56px, 6vw, 96px)", paddingBottom: "clamp(28px, 3vw, 48px)" }}>
        <Eyebrow>Start a project</Eyebrow>
        <h1 className="h-1" style={{ maxWidth: "16ch", marginTop: 12 }}>
          Send us a brief.
        </h1>
        <p className="lede muted" style={{ maxWidth: "52ch", marginTop: 18 }}>
          The more detail you share — scope, programme, drawings — the faster a sector lead can come back with a real build approach. We reply within two working days.
        </p>
      </section>

      <section className="container" style={{ paddingBottom: "clamp(72px, 8vw, 120px)" }}>
        <div style={{ display: "grid", gridTemplateColumns: "1.6fr 1fr", gap: "clamp(40px, 5vw, 80px)" }} className="contact-grid">
          {/* Form */}
          <form onSubmit={submit} noValidate>
            <fieldset style={{ border: "none", padding: 0, margin: 0 }}>
              <legend className="label" style={{ marginBottom: 10 }}>01 / Enquiry type</legend>
              <div className="radio-row" role="radiogroup" aria-label="Enquiry type">
                {enquiryTypes.map((t) => (
                  <button
                    type="button"
                    key={t.id}
                    onClick={() => setEnquiryType(t.id)}
                    className={"radio-pill" + (enquiryType === t.id ? " is-active" : "")}
                    role="radio"
                    aria-checked={enquiryType === t.id}
                  >{t.label}</button>
                ))}
              </div>
            </fieldset>

            {enquiryType === "new-project" ? (
              <>
                <fieldset style={{ border: "none", padding: 0, margin: "40px 0 0" }}>
                  <legend className="label" style={{ marginBottom: 10 }}>02 / Sector{errors.sector ? <span className="field-error" style={{ marginLeft: 8 }}>required</span> : null}</legend>
                  <div className="radio-row" role="radiogroup" aria-label="Sector">
                    {data.sectors.map((s) => (
                      <button
                        type="button"
                        key={s.id}
                        onClick={() => setSector(s.id)}
                        className={"radio-pill" + (sector === s.id ? " is-active" : "")}
                        role="radio"
                        aria-checked={sector === s.id}
                      >{s.short}</button>
                    ))}
                  </div>
                </fieldset>

                {sector ? (
                  <fieldset style={{ border: "none", padding: 0, margin: "32px 0 0" }}>
                    <legend className="label" style={{ marginBottom: 10 }}>Project type</legend>
                    <div className="radio-row">
                      {(projectTypes[sector] || []).map((t) => (
                        <span key={t} className="chip" style={{ pointerEvents: "none", fontSize: 12 }}>{t}</span>
                      ))}
                    </div>
                  </fieldset>
                ) : null}

                <fieldset style={{ border: "none", padding: 0, margin: "40px 0 0" }}>
                  <legend className="label" style={{ marginBottom: 10 }}>03 / Indicative budget</legend>
                  <div className="radio-row" role="radiogroup">
                    {budgets.map((b) => (
                      <button
                        type="button"
                        key={b}
                        onClick={() => setBudget(b)}
                        className={"radio-pill" + (budget === b ? " is-active" : "")}
                      >{b}</button>
                    ))}
                  </div>
                </fieldset>
              </>
            ) : null}

            <fieldset style={{ border: "none", padding: 0, margin: "40px 0 0" }}>
              <legend className="label" style={{ marginBottom: 18 }}>{enquiryType === "new-project" ? "04 / " : "02 / "}Your details</legend>
              <div className="form-grid">
                <Field label="Name" value={form.name} onChange={(v) => setForm({ ...form, name: v })} error={errors.name} />
                <Field label="Email" type="email" value={form.email} onChange={(v) => setForm({ ...form, email: v })} error={errors.email} />
                <Field label="Phone" value={form.phone} onChange={(v) => setForm({ ...form, phone: v })} placeholder="+971" />
                <Field label="Company / project owner" value={form.company} onChange={(v) => setForm({ ...form, company: v })} />
                {enquiryType === "new-project" ? (
                  <>
                    <Field label="Project location" value={form.location} onChange={(v) => setForm({ ...form, location: v })} placeholder="Dubai, UAE" />
                    <Field label="Programme / timeline" value={form.timeline} onChange={(v) => setForm({ ...form, timeline: v })} placeholder="e.g. Mob July, handover Dec" />
                  </>
                ) : null}
                <div className="field full">
                  <label>Tell us about the brief {errors.message ? <span className="field-error" style={{ marginLeft: 8 }}>required</span> : null}</label>
                  <textarea
                    value={form.message}
                    onChange={(e) => setForm({ ...form, message: e.target.value })}
                    placeholder={enquiryType === "new-project" ? "Site, scope, programme, anything we should know early." : "How can we help?"}
                  ></textarea>
                </div>
              </div>
            </fieldset>

            {enquiryType === "new-project" ? (
              <fieldset style={{ border: "none", padding: 0, margin: "32px 0 0" }}>
                <legend className="label" style={{ marginBottom: 12 }}>05 / Drawings & supporting files (optional)</legend>
                <label
                  className="file-drop"
                  onDragOver={(e) => e.preventDefault()}
                  onDrop={onFileDrop}
                  style={{ display: "block" }}
                >
                  <div>Drop drawings, PDFs or images here — or <span style={{ textDecoration: "underline" }}>browse</span></div>
                  <div className="small muted" style={{ marginTop: 6 }}>PDF, JPG, PNG, DWG · up to 50MB total</div>
                  <input type="file" multiple onChange={onFileChange} style={{ display: "none" }} />
                </label>
                {files.length > 0 ? (
                  <ul style={{ listStyle: "none", padding: 0, margin: "14px 0 0" }}>
                    {files.map((f, i) => (
                      <li key={i} style={{ fontFamily: "var(--font-mono)", fontSize: 12, padding: "8px 0", borderBottom: "1px solid var(--border)", display: "flex", justifyContent: "space-between" }}>
                        <span>{f.name}</span>
                        <button type="button" onClick={() => setFiles(files.filter((_, j) => j !== i))} style={{ color: "var(--muted)" }}>Remove</button>
                      </li>
                    ))}
                  </ul>
                ) : null}
              </fieldset>
            ) : null}

            <div style={{ marginTop: 48, display: "flex", gap: 12, alignItems: "center", flexWrap: "wrap" }}>
              <Button onClick={submit}>Submit brief</Button>
              <span className="small muted">We respond within two working days · Mon–Fri 08:30–18:00 GST</span>
            </div>
          </form>

          {/* Aside */}
          <aside style={{ position: "sticky", top: 100, alignSelf: "start" }}>
            <div style={{ border: "1px solid var(--border)", padding: 28 }}>
              <Eyebrow>Direct</Eyebrow>
              <h3 className="h-3" style={{ marginTop: 12 }}>Or talk to us directly.</h3>
              <div style={{ marginTop: 24, display: "flex", flexDirection: "column", gap: 10 }}>
                <a href={`tel:${data.brand.phone.replace(/\s/g, "")}`} className="paragraph" style={{ borderBottom: "1px solid var(--border)", paddingBottom: 10 }}>
                  <span className="label" style={{ display: "block", marginBottom: 4 }}>Phone</span>
                  {data.brand.phone}
                </a>
                <a href={`mailto:${data.brand.email}`} className="paragraph" style={{ borderBottom: "1px solid var(--border)", paddingBottom: 10 }}>
                  <span className="label" style={{ display: "block", marginBottom: 4 }}>Email</span>
                  {data.brand.email}
                </a>
                <div className="paragraph" style={{ paddingBottom: 10 }}>
                  <span className="label" style={{ display: "block", marginBottom: 4 }}>Address</span>
                  {data.brand.address.line1}<br />
                  {data.brand.address.area}<br />
                  {data.brand.address.city}, {data.brand.address.country}
                </div>
                <div className="paragraph">
                  <span className="label" style={{ display: "block", marginBottom: 4 }}>Hours</span>
                  Mon – Fri · 08:30 – 18:00 GST
                </div>
              </div>
              <hr className="hairline" style={{ margin: "28px 0" }} />
              <Eyebrow>Routing</Eyebrow>
              <ul style={{ margin: "12px 0 0", padding: 0, listStyle: "none", fontSize: 13, color: "var(--muted)" }}>
                <li style={{ padding: "8px 0", borderBottom: "1px solid var(--border)", display: "flex", justifyContent: "space-between" }}><span>New project</span><span>Build / Elevaré</span></li>
                <li style={{ padding: "8px 0", borderBottom: "1px solid var(--border)", display: "flex", justifyContent: "space-between" }}><span>Vendor</span><span>Procurement</span></li>
                <li style={{ padding: "8px 0", borderBottom: "1px solid var(--border)", display: "flex", justifyContent: "space-between" }}><span>Careers</span><span>People & Culture</span></li>
                <li style={{ padding: "8px 0", display: "flex", justifyContent: "space-between" }}><span>Press</span><span>Comms</span></li>
              </ul>
            </div>
          </aside>
        </div>
        <style>{`@media (max-width: 880px) { .contact-grid { grid-template-columns: 1fr !important; } }`}</style>
      </section>
    </div>
  );
}

function Field({ label, value, onChange, type = "text", placeholder = "", error }) {
  return (
    <div className="field">
      <label>{label}{error ? <span className="field-error" style={{ marginLeft: 8 }}>{error === "format" ? "invalid" : "required"}</span> : null}</label>
      <input
        type={type}
        value={value}
        placeholder={placeholder}
        onChange={(e) => onChange(e.target.value)}
      />
    </div>
  );
}

function ConfirmCell({ label, value }) {
  return (
    <div style={{ borderTop: "1px solid var(--border)", paddingTop: 14 }}>
      <div className="label">{label}</div>
      <div className="h-4" style={{ marginTop: 4 }}>{value}</div>
    </div>
  );
}

Object.assign(window, { Contact });
