// ─────────────────────────────────────────────────────────
//  Lead Form — 3-step conversational wizard
// ─────────────────────────────────────────────────────────

const { useState: useStateF } = React;

const SEGMENTS = [
  { id:'realestate', l:'Real Estate / Realty', s:'Luxury developers, brokerages' },
  { id:'fashion',    l:'Fashion / Couture',    s:'D2C, atelier, lifestyle' },
  { id:'saas',       l:'SaaS / B2B',           s:'Seed → Series B' },
  { id:'hospitality',l:'Hospitality / F&B',    s:'Hotels, restaurants, retreats' },
  { id:'enterprise', l:'Enterprise / Other',   s:'Tell us in the next step' },
];

const BUDGETS = [
  { id:'a', l:'Under $25K',     s:'Single landing or audit' },
  { id:'b', l:'$1K – $75K',     s:'Marketing site + automation' },
  { id:'c', l:'$75K – $250K',   s:'Full platform build' },
  { id:'d', l:'$250K +',        s:'Multi-quarter retainer' },
];

// Strip control chars and suspicious sequences
function safe(s) {
  return s
    .replace(/[<>]/g, '')
    .replace(/javascript:/gi, '')
    .replace(/on\w+=/gi, '')
    .replace(/\s+/g, ' ')
    .trim()
    .slice(0, 200);
}
function safeEmail(s) {
  return s.replace(/[<>"'`]/g, '').replace(/\s+/g, '').slice(0, 120);
}
function safePhone(s) {
  return s.replace(/[^\d+\-\s()]/g, '').slice(0, 22);
}

function LeadForm() {
  const [step, setStep] = useStateF(0);
  const [data, setData] = useStateF({
    segment:'', budget:'',
    name:'', email:'', phone:'',
  });
  const [sent, setSent] = useStateF(false);

  const stepValid = [
    () => !!data.segment,
    () => !!data.budget,
    () => data.name.length > 1 && /@/.test(data.email) && data.phone.length > 5,
  ];

  const submit = () => {
    if (!stepValid[2]()) return;
    setSent(true);
  };

  const id = 'WB-' + Math.floor(Math.random() * 9000 + 1000) + '-' +
             new Date().toISOString().slice(2,10).replace(/-/g,'');

  return (
    <section className="section shell" data-screen-label="Engage">
      <div>
        <div className="kicker">§04 · Lead Ingestion · By appointment</div>
        <h2 style={{
          fontFamily:'var(--serif)', fontWeight:400,
          fontSize:'clamp(40px, 5vw, 76px)', lineHeight:1.0,
          letterSpacing:'-0.02em', margin:'18px 0 0', maxWidth:'18ch',
          textWrap:'balance',
        }}>
          Three questions.<br/>
          <span style={{fontStyle:'italic', color:'var(--accent)'}}>Then we talk.</span>
        </h2>
      </div>

      <div className="form-wrap">
        <div className="form-meta">
          <p style={{
            fontSize:17, lineHeight:1.55, color:'var(--muted)', maxWidth:'42ch', margin:0,
          }}>
            We take two new engagements per quarter. The form below screens for fit —
            answers go directly to the principal, never a sales floor.
          </p>

          <div className="progress">
            {['Segment', 'Budget', 'Contact'].map((label, i) => (
              <div key={label}
                className={`step-row ${i === step ? 'active' : ''} ${i < step ? 'done' : ''}`}>
                <span className="n">{i < step ? '✓' : i + 1}</span>
                <span>Step {String(i + 1).padStart(2,'0')} · {label}</span>
              </div>
            ))}
          </div>
        </div>

        <div className="form-stage">
          {sent ? (
            <div className="success">
              <div className="success-check">✓</div>
              <span className="kicker">§Sent · routed to principal</span>
              <h3>You&rsquo;re in the queue.</h3>
              <p style={{color:'var(--muted)', margin:0, maxWidth:'46ch', lineHeight:1.55}}>
                We&rsquo;ll reply within 48 hours with either a calendar link or a referral if
                we&rsquo;re a wrong fit. Either way — straight answer.
              </p>

              <div className="receipt">
                <div className="row"><span className="l">Reference</span><span className="v">{id}</span></div>
                <div className="row"><span className="l">Segment</span><span className="v">{SEGMENTS.find(s=>s.id===data.segment)?.l}</span></div>
                <div className="row"><span className="l">Budget</span><span className="v">{BUDGETS.find(b=>b.id===data.budget)?.l}</span></div>
                <div className="row"><span className="l">Routed</span><span className="v" style={{color:'var(--accent)'}}>rohit@webbrandify.com</span></div>
                <div className="row"><span className="l">SLA</span><span className="v">48h response</span></div>
              </div>
            </div>
          ) : (
            <>
              <span className="step-num">Step {String(step + 1).padStart(2,'0')} of 03</span>

              {step === 0 && (
                <>
                  <h3>Which segment best describes you?</h3>
                  <div className="opt-grid">
                    {SEGMENTS.map(s => (
                      <button
                        key={s.id}
                        className={`opt-btn magnetic-trigger ${data.segment===s.id?'active':''}`}
                        onClick={() => setData({...data, segment:s.id})}
                      >
                        <span className="opt-l">{s.l}</span>
                        <span className="opt-s">{s.s}</span>
                      </button>
                    ))}
                  </div>
                </>
              )}

              {step === 1 && (
                <>
                  <h3>What&rsquo;s the rough engagement budget?</h3>
                  <div className="opt-grid">
                    {BUDGETS.map(b => (
                      <button
                        key={b.id}
                        className={`opt-btn magnetic-trigger ${data.budget===b.id?'active':''}`}
                        onClick={() => setData({...data, budget:b.id})}
                      >
                        <span className="opt-l">{b.l}</span>
                        <span className="opt-s">{b.s}</span>
                      </button>
                    ))}
                  </div>
                </>
              )}

              {step === 2 && (
                <>
                  <h3>Where should we route the reply?</h3>
                  <div className="field-row">
                    <label>Full name</label>
                    <input
                      value={data.name}
                      placeholder="First Last"
                      onChange={e => setData({...data, name: safe(e.target.value)})}
                    />
                  </div>
                  <div className="field-row">
                    <label>Work email</label>
                    <input
                      value={data.email}
                      placeholder="you@company.com"
                      onChange={e => setData({...data, email: safeEmail(e.target.value)})}
                    />
                  </div>
                  <div className="field-row">
                    <label>Verified phone · with country code</label>
                    <input
                      value={data.phone}
                      placeholder="+91 98765 43210"
                      onChange={e => setData({...data, phone: safePhone(e.target.value)})}
                    />
                  </div>
                  <div style={{
                    fontFamily:'var(--mono)', fontSize:10.5, letterSpacing:'0.16em',
                    textTransform:'uppercase', color:'var(--muted)', marginTop:8,
                  }}>
                    🔒 Input sanitized · TLS · principal-only routing
                  </div>
                </>
              )}

              <div className="form-foot">
                <button
                  className="f-back magnetic-trigger"
                  onClick={() => step > 0 && setStep(step - 1)}
                  disabled={step === 0}
                  style={{visibility: step === 0 ? 'hidden' : 'visible'}}
                >← Back</button>
                {step < 2 ? (
                  <button
                    className="f-next magnetic-trigger"
                    disabled={!stepValid[step]()}
                    onClick={() => setStep(step + 1)}
                  >
                    <span>Continue</span>
                    <span className="a">→</span>
                  </button>
                ) : (
                  <button
                    className="f-next magnetic-trigger"
                    disabled={!stepValid[2]()}
                    onClick={submit}
                  >
                    <span>Send to principal</span>
                    <span className="a">→</span>
                  </button>
                )}
              </div>
            </>
          )}
        </div>
      </div>
    </section>
  );
}

window.LeadForm = LeadForm;
