/* ===================================================================
   GLOBALSTAFF — Request a Quote (construction inquiry)
   Route diagram → blueprint stone-elevation sketch. Bespoke quotes,
   so no auto price estimate.
   =================================================================== */

const SERVICE_TYPES = [
  "Natural Stone Installation",
  "Facade Cladding",
  "Decorative Stonework",
  "Landscape Stone Construction",
  "Other / not sure",
];
const SIZES = ["Under 50 m²", "50–150 m²", "150–500 m²", "500 m² and over"];
const TIMELINES = ["Within 1 month", "1–3 months", "3–6 months", "Flexible / planning"];

function QuoteBlueprint({ service, location }) {
  return (
    <svg className="quote-route-svg" viewBox="0 0 600 120" preserveAspectRatio="xMidYMid meet" aria-hidden="true">
      <defs>
        <pattern id="qbgrid" width="20" height="20" patternUnits="userSpaceOnUse">
          <path d="M20 0H0V20" fill="none" stroke="rgba(255,255,255,0.10)" strokeWidth="0.6" />
        </pattern>
      </defs>
      <rect width="600" height="120" fill="url(#qbgrid)" />

      {/* stone wall elevation sketch */}
      <g fill="none" stroke="rgba(247,245,241,0.45)" strokeWidth="1.4" strokeLinejoin="round">
        <rect x="60" y="30" width="480" height="60" />
        <path d="M60 50 h480 M60 70 h480" />
        <path d="M120 30 v20 M210 30 v20 M300 30 v20 M390 30 v20 M470 30 v20" />
        <path d="M90 50 v20 M170 50 v20 M250 50 v20 M340 50 v20 M430 50 v20 M510 50 v20" />
        <path d="M140 70 v20 M240 70 v20 M330 70 v20 M430 70 v20 M500 70 v20" />
      </g>

      {/* accent dimension line draws across */}
      <g stroke="#D99041" strokeWidth="1.4" fill="none">
        <path d="M60 102 h480" strokeDasharray="6 8" strokeLinecap="round" style={{ animation: "flow 12s linear infinite" }} />
        <path d="M60 97 v10 M540 97 v10" />
      </g>

      {/* labels */}
      <text x="60" y="22" className="quote-blueprint-label">{service ? service.toUpperCase() : "SERVICE"}</text>
      <text x="540" y="22" textAnchor="end" className="quote-blueprint-label accent">{location ? location.toUpperCase() : "PROJECT LOCATION"}</text>
    </svg>
  );
}

function Field({ label, name, value, onChange, error, type = "text", placeholder, options, half, textarea }) {
  return (
    <div className={"q-field" + (half ? " half" : "") + (error ? " err" : "")}>
      <label className="q-label caption mono" htmlFor={name}>{label}</label>
      {options ? (
        <select id={name} name={name} value={value} onChange={onChange} className="q-input">
          <option value="" disabled>Select…</option>
          {options.map((o) => <option key={o} value={o}>{o}</option>)}
        </select>
      ) : textarea ? (
        <textarea id={name} name={name} value={value} onChange={onChange} placeholder={placeholder} className="q-input q-textarea" />
      ) : (
        <input id={name} name={name} type={type} value={value} onChange={onChange} placeholder={placeholder} className="q-input" autoComplete="off" />
      )}
      {error && <span className="q-error caption">{error}</span>}
    </div>
  );
}

function Quote() {
  const [form, setForm] = useState({
    service: "", location: "", size: "", timeline: "", name: "", phone: "", email: "", message: "",
  });
  const [errors, setErrors] = useState({});
  const [sent, setSent] = useState(false);

  const onChange = (e) => {
    const { name, value } = e.target;
    setForm((f) => ({ ...f, [name]: value }));
    setErrors((er) => ({ ...er, [name]: undefined }));
  };

  const validate = () => {
    const e = {};
    if (!form.service) e.service = "Select a service";
    if (!form.location.trim()) e.location = "Required";
    if (!form.size) e.size = "Select a size";
    if (!form.timeline) e.timeline = "Select a timeline";
    if (!form.name.trim()) e.name = "Required";
    if (!/^[+0-9()\s-]{6,}$/.test(form.phone)) e.phone = "Enter a valid phone";
    if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(form.email)) e.email = "Enter a valid email";
    return e;
  };

  const submit = (e) => {
    e.preventDefault();
    const er = validate();
    setErrors(er);
    if (Object.keys(er).length === 0) setSent(true);
  };

  const progress = (() => {
    const fields = ["service", "location", "size", "timeline", "name", "phone", "email"];
    const filled = fields.filter((f) => String(form[f]).trim()).length;
    return Math.round((filled / fields.length) * 100);
  })();

  // preliminary cost estimate — indicative installed rate (€/m²) × area band
  const RATE = {
    "Natural Stone Installation": 220,
    "Facade Cladding": 320,
    "Decorative Stonework": 280,
    "Landscape Stone Construction": 180,
    "Other / not sure": 240,
  };
  const AREA = { "Under 50 m²": 35, "50–150 m²": 100, "150–500 m²": 325, "500 m² and over": 700 };
  const estimate = (() => {
    if (!form.service || !form.size) return null;
    const rate = RATE[form.service] || 240;
    const area = AREA[form.size] || 100;
    let mid = rate * area;
    if (form.timeline === "Within 1 month") mid *= 1.12; // expedited
    const round = (n) => Math.round(n / 500) * 500;
    const fmt = (n) => "€" + round(n).toLocaleString("en-US");
    return { low: fmt(mid * 0.82), high: fmt(mid * 1.2) };
  })();

  return (
    <section className="section quote-section" id="quote">
      <div className="container">
        <div className="section-head">
          <div>
            <span className="kicker reveal">Request a Quote</span>
            <h2 className="h2 reveal d1">Start your stone project</h2>
          </div>
          <p className="body section-head-sub reveal d2">
            Tell us about the work and where it is. A specialist reviews the details and returns a
            considered quote — bespoke to your stone and site.
          </p>
        </div>

        <div className="quote-card reveal d1">
          <div className="quote-diagram">
            <div className="quote-diagram-head">
              <span className="mono quote-diagram-title">Project sketch</span>
              <span className="mono quote-progress">{sent ? "SUBMITTED" : `${progress}% complete`}</span>
            </div>
            <QuoteBlueprint service={form.service} location={form.location} />
            <div className="quote-progress-bar">
              <span style={{ width: (sent ? 100 : progress) + "%" }} />
            </div>

            <div className="quote-est-strip" data-on={estimate ? "1" : "0"}>
              <div className="quote-est-strip-row">
                <span className="mono quote-est-strip-label">Preliminary estimate</span>
                <span className="quote-est-strip-val">{estimate ? `${estimate.low} – ${estimate.high}` : "—"}</span>
              </div>
              <span className="mono quote-est-strip-note">
                {estimate
                  ? "Indicative range · excl. VAT · confirmed after site survey"
                  : "Select service type & project size for an estimate"}
              </span>
            </div>
          </div>

          {sent ? (
            <div className="quote-success">
              <div className="quote-success-icon">
                <Icon name="check" size={56} stroke="#D99041" />
              </div>
              <h3 className="h3">Enquiry received</h3>
              <p className="body quote-success-text">
                Thank you, {form.name.split(" ")[0] || "there"}. Your enquiry for{" "}
                <strong>{form.service}</strong> at <strong>{form.location}</strong> is with our
                team. A specialist will reach out at <strong>{form.email}</strong> shortly.
              </p>
              <button className="btn btn-secondary" onClick={() => { setSent(false); setForm({ service:"",location:"",size:"",timeline:"",name:"",phone:"",email:"",message:"" }); }}>
                Submit another enquiry
              </button>
            </div>
          ) : (
            <form className="quote-form" onSubmit={submit} noValidate>
              <div className="q-group">
                <div className="q-group-label mono">Project</div>
                <div className="q-row">
                  <Field label="Service type" name="service" value={form.service} onChange={onChange} error={errors.service} options={SERVICE_TYPES} half />
                  <Field label="Project location" name="location" value={form.location} onChange={onChange} error={errors.location} placeholder="e.g. Tallinn, EE" half />
                </div>
                <div className="q-row">
                  <Field label="Project size" name="size" value={form.size} onChange={onChange} error={errors.size} options={SIZES} half />
                  <Field label="Timeline" name="timeline" value={form.timeline} onChange={onChange} error={errors.timeline} options={TIMELINES} half />
                </div>
              </div>

              <div className="q-group">
                <div className="q-group-label mono">Contact</div>
                <Field label="Full name" name="name" value={form.name} onChange={onChange} error={errors.name} placeholder="Your name" />
                <div className="q-row">
                  <Field label="Phone" name="phone" value={form.phone} onChange={onChange} error={errors.phone} placeholder="+372 …" half />
                  <Field label="Email" name="email" value={form.email} onChange={onChange} error={errors.email} placeholder="you@company.com" half />
                </div>
              </div>

              <div className="q-group">
                <div className="q-group-label mono">Details</div>
                <Field label="Message (optional)" name="message" value={form.message} onChange={onChange} placeholder="Stone preference, drawings, access, anything useful…" textarea />
              </div>

              <button type="submit" className="btn btn-accent btn-lg quote-submit">
                Send enquiry
                <svg className="arrow" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M5 12h14M13 6l6 6-6 6"/></svg>
              </button>
              <p className="caption quote-note">We reply within 1–2 business days. No obligation.</p>
            </form>
          )}
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { Quote });
