// LeadForm — copied verbatim from public/components/bottom.jsx with one fix:
// the upstream file has a JSX comment in an invalid position (between a ternary
// `:` and the JSX expression on line 309) which breaks Babel-standalone parsing.
// Per the build constraint we cannot modify files outside public/news/, so this
// is a local copy with that single line removed. All other behaviour, fields,
// hookId contract, POST payload shape, and Meta Pixel `Lead` firing are
// preserved verbatim from the upstream component.
//
// Source: /Users/aiops/gcd-landing/public/components/bottom.jsx (line 21–321)
// Removed: line 309 — `{/* Fix 5 — standardised CTA label across all surfaces */}`
// Kept: button label "Book my on-site consultation" (note: upstream uses this
//       label in the `:` branch; the `<form>`'s submit button shows the same
//       label, so the article-page form will read identically to the main LP).

function getFbclidNews() {
  try {
    return new URLSearchParams(window.location.search).get('fbclid') || '';
  } catch (e) {
    return '';
  }
}

const BUILD_TYPE_LABELS_NEWS = {
  "new-home": "New home",
  "renovation": "Large renovation",
  "kdr": "Knockdown-rebuild",
  "extension": "Extension",
  "other": "Not sure"
};

function LeadForm({ hookId }) {
  const [step, setStep] = useState(1);
  const [submitted, setSubmitted] = useState(false);
  const [fbclid] = useState(() => getFbclidNews());
  const [data, setData] = useState({
    buildType: "",
    scope: "",
    scopeNotes: "",
    homeSize: "",
    lotStatus: "",
    suburb: "",
    budget: "",
    timeline: "",
    name: "",
    mobile: "",
    email: "",
    notes: ""
  });
  const update = (k, v) => setData(d => ({ ...d, [k]: v }));

  const buildTypes = [
    { id: "new-home", label: "New home", sub: "Custom build from slab" },
    { id: "renovation", label: "Large renovation", sub: "Keep the shell, rebuild inside" },
    { id: "kdr", label: "Knockdown-rebuild", sub: "Demolish + rebuild on the same block" },
    { id: "extension", label: "Extension", sub: "Add onto an existing home" },
    { id: "other", label: "Not sure yet", sub: "We'll help you figure it out" },
  ];
  const homeSizes = ["2-3 bed", "4-5 bed", "6+ bed"];
  const lotStatuses = ["Own the lot", "Lot to purchase"];
  const renoScopes = ["Kitchen", "Bathroom", "Whole-home", "Multi-room"];
  const budgets = [
    "$200K - $300K",
    "$300K - $500K",
    "$500K - $1M",
    "$1M+",
    "Need help estimating"
  ];
  const timelines = [
    "Ready to start",
    "1 - 3 months",
    "3 - 6 months",
    "6 - 12 months",
    "Researching"
  ];

  const canNext = () => {
    if (step === 1) return !!data.buildType;
    if (step === 2) {
      if (!data.suburb) return false;
      if (data.buildType === "new-home") return !!data.homeSize && !!data.lotStatus;
      if (data.buildType === "renovation") return !!data.scope;
      return true;
    }
    if (step === 3) return !!data.budget && !!data.timeline;
    if (step === 4) return data.name && data.mobile && data.email;
    return false;
  };

  const submit = async (e) => {
    e && e.preventDefault();
    const payload = { hookId, ...data, fbclid, submittedAt: new Date().toISOString() };

    if (typeof fbq === 'function') {
      fbq('track', 'Lead', {
        content_name: 'GCD Renovation Consultation Enquiry',
        content_category: BUILD_TYPE_LABELS_NEWS[data.buildType] || data.buildType,
        value: 0,
        currency: 'AUD'
      });
    }

    try {
      const res = await fetch('https://gcd-landing-iota.vercel.app/api/lead', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload)
      });
      const json = await res.json().catch(() => ({}));
      console.log("[GCD lead_submitted]", { ok: res.ok, status: res.status, leadId: json.leadId, payload });
    } catch (err) {
      console.error("[GCD lead_submit_failed]", { error: String(err && err.message || err), payload });
    }

    setSubmitted(true);
  };

  if (submitted) {
    return (
      <div className="form__success">
        <div className="form__success-tick serif">✓</div>
        <h3 className="serif">Thanks, {data.name.split(' ')[0] || 'we got it'}.</h3>
        <p>
          Your enquiry is in. We'll be in touch within one business day to arrange a time to walk your block in <span className="mono">{data.suburb}</span>. If urgent, call us on <a href="tel:+61412950225" className="mono">0412 950 225</a>.
        </p>
        <p className="form__success-next mono">
          REF · {Date.now().toString(36).toUpperCase()}
        </p>
      </div>
    );
  }

  const stepTitles = {
    1: "What are you planning?",
    2: "Tell us about the project",
    3: "Budget and timeline",
    4: "Your details"
  };

  return (
    <form className="form" onSubmit={submit}>
      <div className="form__progress">
        <div className="form__progress-label mono">
          Step {step} of 4 · {stepTitles[step]}
        </div>
        <div className="form__progress-bar">
          <div className="form__progress-bar-fill" style={{ width: `${(step/4)*100}%` }}></div>
        </div>
        <div className="form__progress-dots">
          {[1,2,3,4].map(n => (
            <span key={n} className={`form__progress-dot ${n <= step ? 'is-done' : ''} ${n === step ? 'is-current' : ''}`}>
              <span className="mono">{n}</span>
            </span>
          ))}
        </div>
      </div>

      {step === 1 && (
        <div className="form__step">
          <h3 className="form__step-title">What are you planning?</h3>
          <div className="form__options form__options--grid">
            {buildTypes.map(b => (
              <button type="button" key={b.id}
                className={`form__option ${data.buildType === b.id ? 'is-selected' : ''}`}
                onClick={() => update('buildType', b.id)}>
                <span className="form__option-label">{b.label}</span>
                <span className="form__option-sub">{b.sub}</span>
              </button>
            ))}
          </div>
        </div>
      )}

      {step === 2 && (
        <div className="form__step">
          <h3 className="form__step-title">Tell us about the project</h3>

          {data.buildType === "new-home" && (
            <>
              <div className="form__group">
                <div className="form__group-label mono">Size</div>
                <div className="form__options form__options--chips">
                  {homeSizes.map(s => (
                    <button type="button" key={s}
                      className={`form__chip ${data.homeSize === s ? 'is-selected' : ''}`}
                      onClick={() => update('homeSize', s)}>{s}</button>
                  ))}
                </div>
              </div>
              <div className="form__group">
                <div className="form__group-label mono">Lot status</div>
                <div className="form__options form__options--chips">
                  {lotStatuses.map(s => (
                    <button type="button" key={s}
                      className={`form__chip ${data.lotStatus === s ? 'is-selected' : ''}`}
                      onClick={() => update('lotStatus', s)}>{s}</button>
                  ))}
                </div>
              </div>
            </>
          )}

          {data.buildType === "renovation" && (
            <>
              <div className="form__group">
                <div className="form__group-label mono">Scope</div>
                <div className="form__options form__options--chips">
                  {renoScopes.map(s => (
                    <button type="button" key={s}
                      className={`form__chip ${data.scope === s ? 'is-selected' : ''}`}
                      onClick={() => update('scope', s)}>{s}</button>
                  ))}
                </div>
              </div>
              <div className="form__group">
                <label className="form__field">
                  <span className="form__label mono">Or describe it in your own words (optional)</span>
                  <textarea value={data.scopeNotes} onChange={e => update('scopeNotes', e.target.value)} placeholder="What rooms? What's changing? Anything specific we should know?" rows="4" maxLength="600"></textarea>
                </label>
              </div>
            </>
          )}

          {(data.buildType === "kdr" || data.buildType === "extension" || data.buildType === "other") && (
            <div className="form__group">
              <label className="form__field">
                <span className="form__label mono">Tell us about the project (optional)</span>
                <textarea value={data.scopeNotes} onChange={e => update('scopeNotes', e.target.value)} placeholder="What's the scope? Lot size, design status, timing — whatever you can share." rows="4" maxLength="600"></textarea>
              </label>
            </div>
          )}

          <div className="form__group">
            <label className="form__field">
              <span className="form__label mono">Suburb or postcode</span>
              <input type="text" required value={data.suburb} onChange={e => update('suburb', e.target.value)} placeholder="Palm Beach, 4221, Bulimba..." list="gcd-suburbs" />
              <datalist id="gcd-suburbs">
                {["Palm Beach","Mermaid Beach","Burleigh Heads","Currumbin","Kirra","Kingscliff","Tweed Heads","Hope Island","Sanctuary Cove","Paradise Point","Bulimba","Paddington","New Farm","Ashgrove","Bardon","Hamilton","Teneriffe"].map(s => <option key={s} value={s} />)}
              </datalist>
            </label>
          </div>
        </div>
      )}

      {step === 3 && (
        <div className="form__step">
          <h3 className="form__step-title">Budget and timeline</h3>
          <div className="form__group">
            <div className="form__group-label mono">Budget bucket</div>
            <div className="form__options">
              {budgets.map(b => (
                <button type="button" key={b}
                  className={`form__option form__option--row ${data.budget === b ? 'is-selected' : ''}`}
                  onClick={() => update('budget', b)}>
                  <span className="form__option-label">{b}</span>
                  <span className="form__option-check serif">{data.budget === b ? '●' : '○'}</span>
                </button>
              ))}
            </div>
          </div>
          <div className="form__group">
            <div className="form__group-label mono">Timeline</div>
            <div className="form__options">
              {timelines.map(t => (
                <button type="button" key={t}
                  className={`form__option form__option--row ${data.timeline === t ? 'is-selected' : ''}`}
                  onClick={() => update('timeline', t)}>
                  <span className="form__option-label">{t}</span>
                  <span className="form__option-check serif">{data.timeline === t ? '●' : '○'}</span>
                </button>
              ))}
            </div>
          </div>
        </div>
      )}

      {step === 4 && (
        <div className="form__step">
          <h3 className="form__step-title">Your details</h3>
          <div className="form__fields">
            <label className="form__field">
              <span className="form__label mono">Full name</span>
              <input type="text" required value={data.name} onChange={e => update('name', e.target.value)} placeholder="Jane Citizen" />
            </label>
            <label className="form__field">
              <span className="form__label mono">Mobile · AU format</span>
              <input type="tel" required value={data.mobile} onChange={e => update('mobile', e.target.value)} placeholder="04xx xxx xxx" />
            </label>
            <label className="form__field form__field--full">
              <span className="form__label mono">Email</span>
              <input type="email" required value={data.email} onChange={e => update('email', e.target.value)} placeholder="you@example.com" />
            </label>
            <label className="form__field form__field--full">
              <span className="form__label mono">Anything else we should know? · optional</span>
              <textarea rows="3" value={data.notes} onChange={e => update('notes', e.target.value)} placeholder="Block address, existing plans, other builders quoted..."></textarea>
            </label>
          </div>
        </div>
      )}

      <div className="form__nav">
        {step > 1 && (
          <button type="button" className="btn btn--ghost btn--sm" onClick={() => setStep(s => s - 1)}>
            ← Back
          </button>
        )}
        <div style={{ flex: 1 }}></div>
        {step < 4 ? (
          <button type="button" className="btn" disabled={!canNext()}
            onClick={() => canNext() && setStep(s => s + 1)}>
            Next step
            <span className="btn__arrow">→</span>
          </button>
        ) : (
          <button type="submit" className="btn" disabled={!canNext()}>
            Book my site consultation
            <span className="btn__arrow">→</span>
          </button>
        )}
      </div>

      <p className="form__fineprint">
        Your information is used solely to arrange your consultation. We do not share it. We will reply within 1 business day. QBCC Licence <span className="mono">15253132</span> · NSW <span className="mono">389790C</span>. Master Builders Queensland member.
      </p>
    </form>
  );
}

window.LeadForm = LeadForm;
