// Lead intake form — Tier 1 (required) + Tier 2 (progressive disclosure)
const { useState: useFS, useRef: useFR } = React;
const CONFIG = window.CONFIG;

const US_STATES = [
  ["AL","Alabama"],["AK","Alaska"],["AZ","Arizona"],["AR","Arkansas"],["CA","California"],["CO","Colorado"],
  ["CT","Connecticut"],["DE","Delaware"],["FL","Florida"],["GA","Georgia"],["HI","Hawaii"],["ID","Idaho"],
  ["IL","Illinois"],["IN","Indiana"],["IA","Iowa"],["KS","Kansas"],["KY","Kentucky"],["LA","Louisiana"],
  ["ME","Maine"],["MD","Maryland"],["MA","Massachusetts"],["MI","Michigan"],["MN","Minnesota"],["MS","Mississippi"],
  ["MO","Missouri"],["MT","Montana"],["NE","Nebraska"],["NV","Nevada"],["NH","New Hampshire"],["NJ","New Jersey"],
  ["NM","New Mexico"],["NY","New York"],["NC","North Carolina"],["ND","North Dakota"],["OH","Ohio"],["OK","Oklahoma"],
  ["OR","Oregon"],["PA","Pennsylvania"],["RI","Rhode Island"],["SC","South Carolina"],["SD","South Dakota"],
  ["TN","Tennessee"],["TX","Texas"],["UT","Utah"],["VT","Vermont"],["VA","Virginia"],["WA","Washington"],
  ["WV","West Virginia"],["WI","Wisconsin"],["WY","Wyoming"],
].map(([short, name]) => ({ value: short, short, label: `${name} (${short})` }));

const BLANK = {
  firstName: "", lastName: "", phone: "", email: "", street: "", city: "", state: "", zip: "",
  types: [], preQual: "", timeline: "", bestTime: "", listingDate: "", cashOffer: false, notes: ""
};

// Fallback options when meta hasn't loaded yet
const DEFAULT_TYPES   = ["Buy", "Sell", "Lease"];
const DEFAULT_PQ      = ["Yes", "No", "Not sure"];
const DEFAULT_TL      = ["0-3mo", "3-6mo", "6-12mo", "12mo+"];

function LeadForm({ onSubmit, layout, meta }) {
  const [f, setF] = useFS({ ...BLANK });
  const [errors, setErrors] = useFS({});
  const [expanded, setExpanded] = useFS(false);
  const [submitting, setSubmitting] = useFS(false);
  const topRef = useFR(null);

  // Derive options from meta when available, falling back to defaults
  const typeApiToDisplay = { Buying: "Buy", Selling: "Sell", Leasing: "Lease" };
  const pqApiToDisplay   = { yes: "Yes", no: "No", not_sure: "Not sure" };
  const TYPE_OPTS = meta?.lead_type?.map((t) => typeApiToDisplay[t.id] || t.id) ?? DEFAULT_TYPES;
  const PQ_OPTS   = meta?.pre_qualified?.map((t) => pqApiToDisplay[(t.id || "").toLowerCase()] || t.identity) ?? DEFAULT_PQ;
  const TL_OPTS   = meta?.timeline?.map((t) => t.id) ?? DEFAULT_TL;

  const two = layout === "two";
  function set(k, v) { setF((p) => ({ ...p, [k]: v })); if (errors[k]) setErrors((e) => ({ ...e, [k]: null })); }
  function toggleType(t) {
    setF((p) => ({ ...p, types: p.types.includes(t) ? p.types.filter((x) => x !== t) : [...p.types, t] }));
    if (errors.types) setErrors((e) => ({ ...e, types: null }));
  }

  function validate() {
    const e = {};
    if (!f.firstName.trim()) e.firstName = "First name is required.";
    const phoneDigits = f.phone.replace(/\D/g, "");
    if (!f.phone.trim()) e.phone = "Phone is the primary way to reach the lead - required.";
    else if (phoneDigits.length < 10) e.phone = "Enter a valid 10-digit phone number.";
    if (f.email.trim() && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(f.email.trim())) e.email = "That email doesn't look right.";
    if (!f.city.trim()) e.city = "City is required.";
    if (!f.state) e.state = "State is required.";
    if (!f.types.length) e.types = "Pick at least one lead type.";
    if (!f.preQual) e.preQual = "Select a pre-qualification status.";
    return e;
  }

  async function submit(ev) {
    ev.preventDefault();
    const e = validate();
    setErrors(e);
    if (Object.keys(e).length) return;
    setSubmitting(true);
    try {
      const result = (await onSubmit({ ...f })) || {};
      if (result.errors && Object.keys(result.errors).length) {
        setErrors(result.errors);
      } else {
        setF({ ...BLANK });
        setExpanded(false);
        setErrors({});
      }
    } finally {
      setSubmitting(false);
    }
  }

  const isSell = f.types.includes("Sell");
  const filledTier2 = [f.timeline, f.bestTime, f.listingDate, f.notes].filter(Boolean).length + (f.cashOffer ? 1 : 0);

  return (
    <div style={{ maxWidth: 760, margin: "0 auto", padding: "32px 28px 80px" }} ref={topRef}>
      {/* heading */}
      <div className="fade-up" style={{ marginBottom: 22 }}>
        <div style={{ display: "flex", alignItems: "center", gap: 9, color: "var(--muted)", fontSize: 13, fontWeight: 600, marginBottom: 8 }}>
          <Icon name="filePlus" size={15} /> New lead
        </div>
        <h1 style={{ fontSize: 27, fontWeight: 800, margin: "0 0 6px", color: "var(--navy)", letterSpacing: "-.02em" }}>Log a new lead</h1>
        <p style={{ margin: 0, color: "var(--desc)", fontSize: 14.5 }}>
          Capture the essentials while the details are fresh. Six quick fields - the rest is optional.
        </p>
      </div>

      <form onSubmit={submit} className="fade-up" style={{ animationDelay: ".05s" }}>
        {/* TIER 1 card */}
        <div className="card" style={{ padding: 24, marginBottom: 16 }}>
          <SectionLabel n="1" title="The essentials" hint="Required" />
          <div style={{ display: "grid", gridTemplateColumns: two ? "1fr 1fr" : "1fr", gap: 18, marginTop: 18 }}>
            <Field label="First name" required error={errors.firstName}>
              <input className={"input" + (errors.firstName ? " err" : "")} value={f.firstName}
              onChange={(e) => set("firstName", e.target.value)} placeholder="e.g. Jordan" />
            </Field>
            <Field label="Last name" optional error={errors.lastName}>
              <input className={"input" + (errors.lastName ? " err" : "")} value={f.lastName}
              onChange={(e) => set("lastName", e.target.value)} placeholder="e.g. Avery" />
            </Field>
          </div>
          <div style={{ display: "grid", gridTemplateColumns: two ? "1fr 1fr" : "1fr", gap: 18, marginTop: 18 }}>
            <Field label="Phone" required error={errors.phone}>
              <input className={"input" + (errors.phone ? " err" : "")} value={f.phone} inputMode="tel"
              onChange={(e) => set("phone", formatPhone(e.target.value))} placeholder="(512) 555-0100" />
            </Field>
            <Field label="Email" optional error={errors.email} hint="Optional, lets the agent follow up by email">
              <input className={"input" + (errors.email ? " err" : "")} value={f.email} inputMode="email" type="email"
              onChange={(e) => set("email", e.target.value)} placeholder="name@email.com" />
            </Field>
          </div>

          {/* address */}
          <div style={{ marginTop: 18 }}>
            <label className="field-label">Property address <span className="opt">street &amp; ZIP optional</span></label>
            <div style={{ display: "grid", gap: 12 }}>
              <input className="input" value={f.street} onChange={(e) => set("street", e.target.value)} placeholder="Street address" />
              <div style={{ display: "grid", gridTemplateColumns: "minmax(0,1.3fr) 132px 96px", gap: 12 }}>
                <Field error={errors.city}>
                  <input className={"input" + (errors.city ? " err" : "")} value={f.city}
                  onChange={(e) => set("city", e.target.value)} placeholder="City *" />
                </Field>
                <Field error={errors.state ? " " : null}>
                  <div>
                    <CustomSelect value={f.state} onChange={(v) => set("state", v)} error={errors.state}
                      placeholder="State" searchable options={US_STATES} />
                  </div>
                </Field>
                <input className="input" value={f.zip} inputMode="numeric" maxLength={5}
                onChange={(e) => set("zip", e.target.value.replace(/\D/g, ""))} placeholder="ZIP" />
              </div>
            </div>
            {(errors.city || errors.state) && <div className="err-msg"><Icon name="alert" size={13} stroke={2.2} />City and state are required.</div>}
          </div>

          {/* lead type + prequal */}
          <div style={{ display: "grid", gridTemplateColumns: two ? "1fr 1fr" : "1fr", gap: 18, marginTop: 18 }}>
            <Field label="Lead type" required error={errors.types} hint="Select all that apply">
              <div style={{ display: "flex", gap: 9, flexWrap: "wrap" }}>
                {TYPE_OPTS.map((t) => {
                  const on = f.types.includes(t);
                  return (
                    <button key={t} type="button" onClick={() => toggleType(t)}
                    style={{ flex: two ? "1" : "0 0 auto", minWidth: 92, justifyContent: "center", display: "flex", alignItems: "center", gap: 7,
                      padding: "11px 18px", borderRadius: 11, cursor: "pointer", fontFamily: "inherit", fontWeight: 600, fontSize: 14,
                      border: "1.5px solid " + (on ? "var(--accent)" : "var(--field-border)"),
                      background: on ? "var(--accent-soft)" : "#fff", color: on ? "var(--accent)" : "var(--label-2)",
                      transition: "all .15s ease" }}>
                      {on && <Icon name="check" size={15} stroke={3} />}{t}
                    </button>
                  );
                })}
              </div>
            </Field>
            <Field label="Pre-qualified for a loan?" required error={errors.preQual}>
              <Segmented options={PQ_OPTS} value={f.preQual} onChange={(v) => set("preQual", v)} />
            </Field>
          </div>
        </div>

        {/* TIER 2 */}
        <div className="card" style={{ padding: 0, marginBottom: 20, overflow: "hidden" }}>
          <button type="button" onClick={() => setExpanded(!expanded)}
          style={{ width: "100%", display: "flex", alignItems: "center", gap: 12, border: "none", background: "transparent",
            cursor: "pointer", fontFamily: "inherit", padding: "18px 24px", textAlign: "left" }}>
            <span style={{ width: 32, height: 32, borderRadius: 9, background: "var(--st-high-bg)", color: "var(--emerald)",
              display: "grid", placeItems: "center", flexShrink: 0 }}>
              <Icon name={expanded ? "x" : "plus"} size={17} stroke={2.5} />
            </span>
            <div style={{ flex: 1 }}>
              <div style={{ fontWeight: 700, fontSize: 15, color: "var(--navy)" }}>Add more detail</div>
              <div style={{ fontSize: 13, color: "var(--muted)", marginTop: 1 }}>
                Optional high-value signal - timeline, best time to call, cash offer{filledTier2 > 0 && !expanded ? ` · ${filledTier2} added` : ""}
              </div>
            </div>
            <Icon name="chevDown" size={20} style={{ color: "var(--muted)", transform: expanded ? "rotate(180deg)" : "none", transition: "transform .2s ease" }} />
          </button>

          {expanded &&
          <div style={{ padding: "4px 24px 24px", animation: "fadeIn .25s ease both" }}>
            <div className="divider" style={{ marginBottom: 22 }}></div>
            <div style={{ display: "grid", gridTemplateColumns: two ? "1fr 1fr" : "1fr", gap: 20 }}>
              <Field label="Timeline" hint="How soon are they looking to act?">
                <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
                  {TL_OPTS.map((t) => {
                    const on = f.timeline === t;
                    return (
                      <button key={t} type="button" onClick={() => set("timeline", on ? "" : t)}
                      style={{ padding: "9px 15px", borderRadius: 99, cursor: "pointer", fontFamily: "inherit", fontWeight: 600, fontSize: 13.5,
                        border: "1.5px solid " + (on ? "var(--emerald)" : "var(--field-border)"),
                        background: on ? "var(--st-high-bg)" : "#fff", color: on ? "var(--emerald)" : "var(--label-2)", transition: "all .15s ease" }}>
                        {t}
                      </button>
                    );
                  })}
                </div>
              </Field>
              <Field label="Best time to call">
                <input className="input" type="datetime-local" value={f.bestTime} onChange={(e) => set("bestTime", e.target.value)} />
              </Field>
            </div>

            {isSell &&
            <div style={{ marginTop: 20, animation: "fadeUp .25s ease both" }}>
              <Field label="Desired listing date" hint="Shown because this is a Sell lead">
                <input className="input" type="date" value={f.listingDate} onChange={(e) => set("listingDate", e.target.value)} style={{ maxWidth: two ? "100%" : 260 }} />
              </Field>
            </div>
            }

            <div style={{ marginTop: 20, padding: "14px 16px", border: "1px solid var(--border)", borderRadius: 11, background: "#FBFCFD" }}>
              <Checkbox checked={f.cashOffer} onChange={(v) => set("cashOffer", v)} label="Interested in a cash offer" />
            </div>

            <div style={{ marginTop: 20 }}>
              <Field label="Additional information" hint="Anything the agent should know before reaching out">
                <textarea className="textarea" value={f.notes} onChange={(e) => set("notes", e.target.value)}
                placeholder="Context from the call - motivation, budget, preferences..." rows={3} />
              </Field>
            </div>
          </div>
          }
        </div>

        {/* footer actions */}
        <div style={{ display: "flex", alignItems: "center", gap: 14, justifyContent: "flex-end" }}>
          <div style={{ flex: 1, fontSize: 12.5, color: "var(--muted)", display: "flex", alignItems: "center", gap: 7, whiteSpace: "nowrap" }}>
            <Icon name="shield" size={14} style={{ color: "var(--emerald)" }} />
            Logged as <b style={{ color: "var(--label-2)", fontWeight: 600 }}>Mainstay</b> · routes to FUB automatically
          </div>
          <button type="button" className="btn btn-ghost" onClick={() => { setF({ ...BLANK }); setErrors({}); setExpanded(false); }}>Clear</button>
          <button type="submit" className="btn btn-emerald" disabled={submitting} style={{ minWidth: 150 }}>
            {submitting ? "Submitting..." : <>Submit lead <Icon name="arrowRight" size={17} stroke={2.4} /></>}
          </button>
        </div>
      </form>
    </div>
  );
}

function SectionLabel({ n, title, hint }) {
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 11 }}>
      <span style={{ width: 26, height: 26, borderRadius: 8, background: "var(--accent)", color: "#fff",
        display: "grid", placeItems: "center", fontWeight: 800, fontSize: 13, flexShrink: 0 }}>{n}</span>
      <div style={{ fontWeight: 700, fontSize: 16, color: "var(--navy)", whiteSpace: "nowrap" }}>{title}</div>
      {hint && <span style={{ marginLeft: "auto", fontSize: 12, fontWeight: 700, color: "var(--pink)",
        background: "var(--st-low-bg)", padding: "3px 10px", borderRadius: 99 }}>{hint}</span>}
    </div>
  );
}

window.LeadForm = LeadForm;
