const QUOTE_STEPS = ["Photos & Scope", "Access", "Contact", "Review"];
const MAX_QUOTE_PHOTOS = 8;
const MAX_QUOTE_PHOTO_BYTES = 10 * 1024 * 1024;

function selectedQuoteWebhook() {
  const mode = QUOTE_WEBHOOK.mode === "test" ? "test" : QUOTE_WEBHOOK.mode === "production" ? "production" : "invalid";
  if (mode === "test") return { mode, url: QUOTE_WEBHOOK.testUrl };
  if (mode === "production") return { mode, url: QUOTE_WEBHOOK.url };
  return { mode, url: "" };
}

function QuoteRequestPage({ initial = {} }) {
  const [step, setStep] = useState(0);
  const [sent, setSent] = useState(false);
  const [ref, setRef] = useState("");
  const [photoFiles, setPhotoFiles] = useState([]);
  const [photoError, setPhotoError] = useState("");
  const [submitError, setSubmitError] = useState("");
  const [submitting, setSubmitting] = useState(false);
  const [form, setForm] = useState({
    name: "", email: "", phone: "", postal: "", area: "Hamilton",
    packageId: initial.package || "standard-reset",
    timeline: "Flexible", photos: "", access: "Driveway or garage door access",
    goal: "", keep: "", donate: "", recycle: "", dispose: "", concerns: "", attestation: false,
  });
  const pkg = packageById(form.packageId);
  const photoNames = photoFiles.map(f => f.name);
  const set = (k, v) => setForm(f => ({ ...f, [k]: v }));
  const canContinue = step === 0 ? form.packageId && form.goal && !photoError : step === 1 ? form.postal && form.access && form.attestation : step === 2 ? form.name && form.email && form.phone : true;

  function onPhotos(e) {
    const files = Array.from(e.target.files || []);
    const selected = files.slice(0, MAX_QUOTE_PHOTOS);
    const invalid = selected.find(file => !file.type.startsWith("image/"));
    const oversized = selected.find(file => file.size > MAX_QUOTE_PHOTO_BYTES);

    if (files.length > MAX_QUOTE_PHOTOS) {
      setPhotoError(`Please add up to ${MAX_QUOTE_PHOTOS} photos.`);
      setPhotoFiles([]);
      e.target.value = "";
      return;
    }
    if (invalid) {
      setPhotoError("Please upload image files only.");
      setPhotoFiles([]);
      e.target.value = "";
      return;
    }
    if (oversized) {
      setPhotoError("Each photo must be 10 MB or smaller.");
      setPhotoFiles([]);
      e.target.value = "";
      return;
    }

    setPhotoError("");
    setPhotoFiles(selected);
  }

  function buildQuotePayload(refCode) {
    const payload = new FormData();
    const fields = {
      reference: refCode,
      packageId: form.packageId,
      packageName: pkg.name,
      packageRange: pkg.range,
      name: form.name,
      email: form.email,
      phone: form.phone,
      postal: form.postal,
      area: form.area,
      timeline: form.timeline,
      goal: form.goal,
      access: form.access,
      keep: form.keep,
      donate: form.donate,
      recycle: form.recycle,
      dispose: form.dispose,
      concerns: form.concerns,
      photoLinksOrNotes: form.photos,
      photoCount: String(photoFiles.length),
      source: "garage-reset-hamilton-quote-form",
      submittedAt: new Date().toISOString(),
    };
    Object.entries(fields).forEach(([key, value]) => payload.append(key, value || ""));
    photoFiles.forEach(file => payload.append("photos", file, file.name));
    return payload;
  }

  async function submit() {
    if (submitting) return;
    setSubmitError("");
    const endpoint = selectedQuoteWebhook();
    if (!endpoint.url) {
      setSubmitError("The quote form is not connected yet. Please call or email us and mention your garage quote request.");
      return;
    }

    const refCode = genRef();
    setSubmitting(true);
    try {
      const response = await fetch(endpoint.url, {
        method: "POST",
        body: buildQuotePayload(refCode),
      });
      if (!response.ok) throw new Error(`Webhook returned ${response.status}`);
      setRef(refCode);
      setSent(true);
      window.scrollTo({ top: 0, behavior: "instant" });
    } catch (error) {
      console.error("Quote webhook submission failed", error);
      setSubmitError("We could not send the quote request right now. Your details are still here, so please try again or call/email us directly.");
    } finally {
      setSubmitting(false);
    }
  }

  if (sent) return <QuoteConfirmation refCode={ref} form={form} pkg={pkg} photoNames={photoNames} />;
  return <>
    <div className="page-header"><div className="container"><div className="breadcrumb"><a href="#/">Home</a> <span>/</span> <span>Quote Request</span></div><h1>Request a photo-based quote.</h1><p>No payment is collected here, and there is no obligation. We review your details and follow up with a quote range or questions.</p></div></div>
    <section className="section"><div className="container"><div className="quote-layout"><div className="quote-main"><div className="stepper">{QUOTE_STEPS.map((label,i)=><button key={label} className={'stepper-item '+(i===step?'current':i<step?'done':'')} disabled={i>step || submitting} onClick={()=>i<step&&setStep(i)}><span className="step-circle">{i<step?<Icon.Check/>:i+1}</span><span>{label}</span></button>)}</div>
      {step===0 && <div className="book-card"><h2>Add a few photos of your garage</h2><p className="muted">Photos help us give a realistic range and screen for items we cannot take. Phone photos are perfect.</p><div className="quote-photo-examples" aria-label="Example photos to include"><figure><img src="/public/images/quote-photo-example-wide.png" alt="Wide garage photo showing the full scope of the clean-out." loading="lazy" decoding="async" /><figcaption>Wide view</figcaption></figure><figure><img src="/public/images/quote-photo-example-wall.png" alt="Garage wall and shelving photo showing stored items and access." loading="lazy" decoding="async" /><figcaption>Walls and shelves</figcaption></figure><figure><img src="/public/images/quote-photo-example-items.png" alt="Close photo of grouped garage items for sorting and removal." loading="lazy" decoding="async" /><figcaption>Item close-ups</figcaption></figure></div><div className="photo-drop"><strong>Tap to add photos</strong><span className="small muted">JPG, PNG, or WebP · up to {MAX_QUOTE_PHOTOS} images · 10 MB each</span><input type="file" accept="image/*" multiple onChange={onPhotos}/>{photoError && <div className="form-error">{photoError}</div>}{photoNames.length > 0 && <div className="photo-list">{photoNames.map(name => <span className="photo-pill" key={name}>{name}</span>)}</div>}</div><SelectField label="Closest package" value={form.packageId} onChange={v=>set('packageId',v)} options={SERVICE_PACKAGES.map(p=>({value:p.id,label:`${p.name} — ${p.range}`}))}/><TextArea label="What do you want done? *" value={form.goal} onChange={v=>set('goal',v)} placeholder="Describe what should stay, go, be donated, recycled, or disposed."/><TextArea label="Photo links or extra notes" value={form.photos} onChange={v=>set('photos',v)} placeholder="Paste shared photo links if you prefer sending photos another way."/><div className="field-row"><Field label="Items to keep" value={form.keep} onChange={v=>set('keep',v)} placeholder="Tools, bikes, family items..."/><Field label="Donation candidates" value={form.donate} onChange={v=>set('donate',v)} placeholder="Shelving, furniture, usable goods..."/></div><div className="field-row"><Field label="Recycle candidates" value={form.recycle} onChange={v=>set('recycle',v)} placeholder="Metal, cardboard, electronics..."/><Field label="Dispose candidates" value={form.dispose} onChange={v=>set('dispose',v)} placeholder="Broken items, debris..."/></div></div>}
      {step===1 && <div className="book-card"><h2>Access and timing</h2><div className="field-row"><Field label="Postal code *" value={form.postal} onChange={v=>set('postal',v.toUpperCase())} placeholder="L8P 1A1"/><SelectField label="Service area" value={form.area} onChange={v=>set('area',v)} options={SERVICE_AREAS}/></div><SelectField label="Preferred timeline" value={form.timeline} onChange={v=>set('timeline',v)} options={["Flexible","Within 2 weeks","This week","Before listing or move date","Urgent"]}/><TextArea label="Access notes *" value={form.access} onChange={v=>set('access',v)} placeholder="Parking, stairs, tight driveway, locked gate, steep grade, or other constraints."/><TextArea label="Special concerns" value={form.concerns} onChange={v=>set('concerns',v)} placeholder="Heavy items, pests, mould, liquids, chemicals, or anything unusual."/><label className="check-row"><input type="checkbox" checked={form.attestation} onChange={e=>set('attestation',e.target.checked)}/><span>I understand hazardous chemicals, fuel/oil, unknown liquids, asbestos, sharps, biomedical or regulated waste, pressurized tanks, heavily contaminated materials, and infested materials cannot be collected.</span></label></div>}
      {step===2 && <div className="book-card"><h2>Your contact details</h2><p className="muted">We will reply with a quote range or any follow-up questions.</p><div className="field-row"><Field label="Name *" value={form.name} onChange={v=>set('name',v)} placeholder="Jane Smith"/><Field label="Phone *" value={form.phone} onChange={v=>set('phone',v)} placeholder="289-555-0198"/></div><Field label="Email *" type="email" value={form.email} onChange={v=>set('email',v)} placeholder="name@email.com"/></div>}
      {step===3 && <div className="book-card"><h2>Review request</h2><div className="summary-box"><h3>{pkg.name}</h3><p className="price">{pkg.range}</p><p>{pkg.summary}</p></div><ul className="summary-list"><li><strong>Customer:</strong> {form.name} · {form.phone}</li><li><strong>Area:</strong> {form.area} · {form.postal}</li><li><strong>Timeline:</strong> {form.timeline}</li><li><strong>Goal:</strong> {form.goal}</li><li><strong>Photos:</strong> {photoNames.length ? `${photoNames.length} selected locally` : (form.photos ? "Links or notes provided" : "No files selected yet")}</li></ul><p className="small muted">Submitting does not confirm a scheduled visit or final price. No payment is collected here. We will follow up to confirm we received everything needed.</p>{submitError && <div className="form-error submit-error">{submitError}</div>}</div>}
      <div className="book-nav"><button className="btn btn-ghost" disabled={step===0 || submitting} onClick={()=>setStep(s=>Math.max(0,s-1))}>Back</button>{step<3?<button className="btn btn-primary" disabled={!canContinue || submitting} onClick={()=>setStep(s=>s+1)}>Next <Icon.ArrowRight/></button>:<button className="btn btn-primary" disabled={submitting} onClick={submit}>{submitting ? "Submitting..." : "Submit request"} {!submitting && <Icon.ArrowRight/>}</button>}</div>
    </div><aside className="quote-side"><PackageCard pkg={pkg} compact/><div className="warn-box"><Icon.Warning/><p>Final quote depends on volume, weight, labour time, access, additional trips, and disposal requirements.</p></div><p className="small muted">No payment is collected here. No obligation to book.</p></aside></div></div></section>
  </>;
}

function Field({ label, value, onChange, placeholder, type="text" }) { return <div className="field-group"><label className="field-label">{label}</label><input className="field-input" type={type} value={value} onChange={e=>onChange(e.target.value)} placeholder={placeholder}/></div>; }
function TextArea({ label, value, onChange, placeholder }) { return <div className="field-row single"><div className="field-group"><label className="field-label">{label}</label><textarea className="field-textarea" value={value} onChange={e=>onChange(e.target.value)} placeholder={placeholder}/></div></div>; }
function SelectField({ label, value, onChange, options }) { return <div className="field-row single"><div className="field-group"><label className="field-label">{label}</label><select className="field-select" value={value} onChange={e=>onChange(e.target.value)}>{options.map(o => typeof o === 'string' ? <option key={o} value={o}>{o}</option> : <option key={o.value} value={o.value}>{o.label}</option>)}</select></div></div>; }
function QuoteConfirmation({ refCode, form, pkg, photoNames = [] }) { return <><div className="page-header"><div className="container"><h1>Quote request received.</h1><p>Reference <span className="mono">{refCode}</span>. We will review your details and follow up with questions or a quote range.</p></div></div><section className="section"><div className="container"><div className="success-box"><h2>Next step: review photos and scope.</h2><p>We will review your {pkg.name} request for {form.area}, check access and prohibited items, then follow up with a quote range or questions. No payment has been collected and no visit is confirmed yet.</p><p className="small muted">Photos noted: {photoNames.length ? photoNames.join(", ") : (form.photos || "none added yet")}</p></div><a className="btn btn-primary" href="#/">Back Home</a></div></section></>; }
Object.assign(window, { QuoteRequestPage, Field, TextArea, SelectField, QuoteConfirmation });
