// backlot-form.jsx — the actual request form

// ── BACKEND ENDPOINT ────────────────────────────────────────────────────────
// Point this at your submit.php. Leave "" to run in demo mode (no real send).
//   • Same folder as the page:   "submit.php"
//   • Different host/subdomain:  "https://yourdomain.com/backlot/submit.php"
const SUBMIT_ENDPOINT = (typeof window !== "undefined" && window.BACKLOT_CFG && window.BACKLOT_CFG.endpoint) || "submit.php";
// ─────────────────────────────────────────────────────────────────────────────

const TOYOTA_MODELS = [
  "4Runner", "Avalon", "Camry", "Corolla", "Corolla Cross", "Crown", "GR86",
  "GR Corolla", "GR Supra", "Highlander", "Grand Highlander", "Land Cruiser",
  "Mirai", "Prius", "Prius Prime", "RAV4", "RAV4 Prime", "Sequoia",
  "Sienna", "Tacoma", "Tundra", "Venza", "bZ4X",
];

const URGENCY_OPTIONS = [
  { v: "rush", label: "Rush — needed in 48 hrs", note: "Air freight, premium" },
  { v: "standard", label: "Standard — needed this week", note: "Best availability" },
  { v: "scheduled", label: "Scheduled — within 2 weeks", note: "Lowest cost" },
];

function RequestForm({ onSubmit, accent = "#EB0A1E" }) {
  const [partInput, setPartInput] = React.useState("");
  const [parts, setParts] = React.useState([]); // start empty — a seeded demo part
                                                // was riding along on every real request
  const [year, setYear] = React.useState("");
  const [model, setModel] = React.useState("");
  const [trim, setTrim] = React.useState("");
  const [shop, setShop] = React.useState("");
  const [contact, setContact] = React.useState("");
  const [email, setEmail] = React.useState("");
  const [phone, setPhone] = React.useState("");
  const [urgency, setUrgency] = React.useState("standard");
  const [address, setAddress] = React.useState("");
  const [notes, setNotes] = React.useState("");
  const [submitting, setSubmitting] = React.useState(false);
  const [error, setError] = React.useState("");
  const [hp, setHp] = React.useState(""); // honeypot
  const partRef = React.useRef(null);

  function addPart(){
    const v = partInput.trim().toUpperCase();
    if(!v) return;
    if(parts.includes(v)) { setPartInput(""); return; }
    setParts(p => [...p, v]);
    setPartInput("");
  }
  function removePart(i){ setParts(p => p.filter((_, idx) => idx !== i)); }

  function handleKey(e){
    if(e.key === "Enter" || e.key === ",") { e.preventDefault(); addPart(); }
    if(e.key === "Backspace" && !partInput && parts.length) {
      setParts(p => p.slice(0, -1));
    }
  }

  async function submit(e){
    e.preventDefault();
    if(submitting) return;              // guard against a double submit
    setError("");

    // Fold in a part number that was typed but never committed with Enter or a
    // comma. Clicking Submit straight from the input used to silently drop it.
    const pending = partInput.trim().toUpperCase();
    const allParts = pending && !parts.includes(pending) ? [...parts, pending] : parts;
    if(!allParts.length){
      setError("Add at least one Toyota OEM part number.");
      return;
    }
    if(pending){ setParts(allParts); setPartInput(""); }

    setSubmitting(true);
    // Trim everything — a trailing space on the email made the server reject the
    // whole request with "A valid email is required."
    const payload = {
      parts: allParts,
      year, model, urgency,
      trim: trim.trim(),
      shop: shop.trim(),
      contact: contact.trim(),
      email: email.trim(),
      phone: phone.trim(),
      address: address.trim(),
      notes: notes.trim(),
      company_website: hp,
    };

    // Demo mode: no endpoint configured — just show the receipt.
    if(!SUBMIT_ENDPOINT){
      setTimeout(() => {
        setSubmitting(false);
        onSubmit && onSubmit(payload);
      }, 900);
      return;
    }

    try {
      const res = await fetch(SUBMIT_ENDPOINT, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(payload),
      });
      const json = await res.json().catch(() => ({}));
      if(!res.ok || !json.ok){
        throw new Error(json.error || ("Server returned " + res.status));
      }
      setSubmitting(false);
      onSubmit && onSubmit({ ...payload, ref: json.ref });
    } catch(err) {
      setSubmitting(false);
      // This is read by collision shops, not developers — never surface setup
      // instructions here, and always give them a way to reach a human.
      setError(
        /Failed to fetch|NetworkError|Load failed/i.test(err.message)
          ? "We couldn't reach our server, so this request was NOT submitted. Please call 210-870-1814 and we'll take it over the phone."
          : err.message + " — if this keeps happening, call 210-870-1814."
      );
    }
  }

  const valid = (parts.length > 0 || partInput.trim()) &&
                shop.trim() && contact.trim() && email.trim();
  const years = Array.from({length: 22}, (_, i) => 2026 - i);

  return (
    <form onSubmit={submit} style={{display:"flex", flexDirection:"column", gap:32}}>
      {/* Parts */}
      <div className="field">
        <label>① Parts — Toyota OEM part numbers</label>
        <div
          onClick={() => partRef.current && partRef.current.focus()}
          style={{
            background:"#0c0c0e", border:"1px solid var(--line-2)",
            padding:"10px 12px", display:"flex", flexWrap:"wrap", gap:8,
            minHeight:60, cursor:"text"
          }}
        >
          {parts.map((p, i) => (
            <span key={i} className="chip">
              {p}
              <span className="x" onClick={(e) => { e.stopPropagation(); removePart(i); }}>×</span>
            </span>
          ))}
          <input
            ref={partRef}
            value={partInput}
            onChange={e => setPartInput(e.target.value.toUpperCase())}
            onKeyDown={handleKey}
            onBlur={addPart}
            placeholder={parts.length ? "" : "e.g. 52119-06961"}
            className="mono"
            style={{
              flex:1, minWidth:160, background:"transparent", border:"none",
              outline:"none", color:"var(--ink)", padding:"4px 0", fontSize:14
            }}
          />
        </div>
        <div style={{fontSize:12, color:"var(--ink-3)", marginTop:-2}}>
          Press <span className="mono" style={{color:"var(--ink-2)"}}>Enter</span> or <span className="mono" style={{color:"var(--ink-2)"}}>,</span> to add multiple parts. Tap a chip's × to remove.
        </div>
      </div>

      {/* Vehicle */}
      <div className="field">
        <label>② Vehicle</label>
        <div className="v-grid">
          <select className="select" value={year} onChange={e => setYear(e.target.value)} required>
            <option value="">Year</option>
            {years.map(y => <option key={y} value={y}>{y}</option>)}
          </select>
          <select className="select" value={model} onChange={e => setModel(e.target.value)} required>
            <option value="">Model</option>
            {TOYOTA_MODELS.map(m => <option key={m} value={m}>{m}</option>)}
          </select>
          <input className="input" placeholder="Trim (opt.)" value={trim} onChange={e => setTrim(e.target.value)} style={{fontFamily:"Manrope, sans-serif"}}/>
        </div>
      </div>

      {/* Shop info */}
      <div className="field">
        <label>③ Collision center</label>
        <div className="duo-grid" style={{marginBottom:12}}>
          <input className="input" placeholder="Shop name" value={shop} onChange={e => setShop(e.target.value)} required style={{fontFamily:"Manrope, sans-serif"}}/>
          <input className="input" placeholder="Your name" value={contact} onChange={e => setContact(e.target.value)} required style={{fontFamily:"Manrope, sans-serif"}}/>
        </div>
        <div className="duo-grid">
          <input className="input" type="email" placeholder="Email" value={email} onChange={e => setEmail(e.target.value)} required style={{fontFamily:"Manrope, sans-serif"}}/>
          <input className="input" placeholder="Phone" value={phone} onChange={e => setPhone(e.target.value)} style={{fontFamily:"Manrope, sans-serif"}}/>
        </div>
      </div>

      {/* Urgency */}
      <div className="field">
        <label>④ When do you need it?</label>
        <div className="urgency-grid">
          {URGENCY_OPTIONS.map(o => {
            const sel = urgency === o.v;
            return (
              <button type="button" key={o.v} onClick={() => setUrgency(o.v)}
                style={{
                  background: sel ? "#150707" : "#0c0c0e",
                  border: `1px solid ${sel ? accent : "var(--line-2)"}`,
                  padding:"14px 12px", textAlign:"left", cursor:"pointer",
                  display:"flex", flexDirection:"column", gap:4,
                  position:"relative", transition:"all .15s",
                }}>
                {sel && <span style={{position:"absolute", top:10, right:10, width:8, height:8, borderRadius:"50%", background:accent}}/>}
                <span style={{fontFamily:"Antonio, sans-serif", fontSize:18, fontWeight:600, color:sel?"#fff":"var(--ink-2)"}}>{o.label.split(" — ")[0]}</span>
                <span style={{fontSize:11, color:"var(--ink-3)", letterSpacing:".06em", textTransform:"uppercase", fontFamily:"JetBrains Mono, monospace"}}>{o.label.split(" — ")[1]}</span>
                <span style={{fontSize:11, color:"var(--ink-4)", marginTop:4}}>{o.note}</span>
              </button>
            );
          })}
        </div>
      </div>

      {/* Ship address */}
      <div className="field">
        <label>⑤ Shipping address</label>
        <textarea className="textarea" rows="2" placeholder="Street, City, State, ZIP" value={address} onChange={e => setAddress(e.target.value)}/>
      </div>

      {/* Notes */}
      <div className="field">
        <label>⑥ Notes <span style={{color:"var(--ink-4)", textTransform:"none", letterSpacing:0}}>(optional)</span></label>
        <textarea className="textarea" placeholder="Fitment details, color codes, special instructions…" value={notes} onChange={e => setNotes(e.target.value)}/>
      </div>

      {/* Honeypot — hidden from humans, bots fill it and get silently dropped */}
      <input
        type="text" name="company_website" tabIndex="-1" autoComplete="off"
        value={hp} onChange={e => setHp(e.target.value)}
        aria-hidden="true"
        style={{position:"absolute", left:"-9999px", width:1, height:1, opacity:0}}
      />

      {error && (
        <div style={{
          background:"#1e0a0c", border:"1px solid var(--red)", color:"#FFB4BC",
          padding:"12px 14px", fontSize:13, display:"flex", gap:10, alignItems:"flex-start"
        }}>
          <span style={{color:"var(--red)", fontWeight:700}}>!</span>
          <span>{error}</span>
        </div>
      )}

      {/* Submit */}
      <div style={{display:"flex", alignItems:"center", justifyContent:"space-between", gap:24, paddingTop:8, borderTop:"1px solid var(--line)", flexWrap:"wrap"}}>
        <div style={{fontSize:12, color:"var(--ink-3)", maxWidth:380, lineHeight:1.5}}>
          Most requests get a sourcing confirmation in <span style={{color:"var(--ink)", fontWeight:600}}>under 30 minutes</span> during business hours. No payment due at submission.
        </div>
        <button type="submit" className="btn" disabled={!valid || submitting} style={{
          background: valid ? accent : "#2A1318",
          color: valid ? "#fff" : "var(--ink-4)",
          cursor: valid ? "pointer" : "not-allowed",
          padding:"18px 28px", fontSize:14
        }}>
          {submitting ? "Submitting…" : <>Submit request <span className="arr">→</span></>}
        </button>
      </div>
    </form>
  );
}

window.RequestForm = RequestForm;
