/* ============================================================
   NeuroRoute — Sales enquiry form (public).

   Opened by every "Contact ... Sales" CTA on the marketing site,
   on both the desktop page and the mobile edition. Replaces the
   old mailto: links, which lost the lead whenever the visitor had
   no desktop mail client configured.

   Flow: fill in -> verify the work email with a 4-digit code ->
   submit. The backend re-validates everything, burns the code on
   submit, and emails the lead to the sales team as HTML.

   Globals used: React, Icon, LeadFormState (below).
   Exposes: window.LeadForm, window.openLeadForm, window.useLeadForm
   ============================================================ */

const {useState: useStateLF, useEffect: useEffectLF} = React;

/* Kept in sync with leadSolutions in internal/gateway/lead_form.go — the server
   rejects anything not on its own list, so a value added here without adding it
   there is a 400 the visitor cannot get past. */
const LEAD_SOLUTIONS = [
  'AI cost optimization / routing',
  'Multi-provider gateway (one API)',
  'Spend controls & budgets',
  'Zero data retention / compliance',
  'Enterprise deployment / SSO',
  'Agent platform & MCP',
  'Something else',
];

/* Tiny external store so any CTA anywhere in either page tree can open the
   form without threading a callback through every component. */
var LEAD_OPEN = false;
var LEAD_SUBS = [];
function openLeadForm(){ LEAD_OPEN = true; LEAD_SUBS.forEach(function(f){ f(true); }); }
function closeLeadForm(){ LEAD_OPEN = false; LEAD_SUBS.forEach(function(f){ f(false); }); }
function useLeadForm(){
  var pair = useStateLF(LEAD_OPEN);
  useEffectLF(function(){
    LEAD_SUBS.push(pair[1]);
    return function(){ LEAD_SUBS = LEAD_SUBS.filter(function(f){ return f !== pair[1]; }); };
  }, []);
  return pair[0];
}

function LeadForm(){
  const open = useLeadForm();

  const [f, setF] = useStateLF({
    first_name:'', last_name:'', company:'', designation:'',
    email:'', mobile:'', otp:'', solution:'', message:'',
    consent:false, website:'',   // website = honeypot, must stay empty
  });
  const [sending, setSending]   = useStateLF(false);  // OTP request in flight
  const [sent, setSent]         = useStateLF(false);  // a code has been issued
  const [cooldown, setCooldown] = useStateLF(0);      // resend lockout, seconds
  const [busy, setBusy]         = useStateLF(false);  // submit in flight
  const [err, setErr]           = useStateLF('');
  const [done, setDone]         = useStateLF(false);

  const set = function(k){ return function(e){
    const v = e.target.type === 'checkbox' ? e.target.checked : e.target.value;
    setF(function(p){ var n = Object.assign({}, p); n[k] = v; return n; });
  }; };

  /* Resend cooldown. Purely a courtesy — the real cap is enforced server-side
     (3 codes per address per hour), which a page reload cannot bypass. */
  useEffectLF(function(){
    if(cooldown <= 0) return;
    const t = setTimeout(function(){ setCooldown(cooldown - 1); }, 1000);
    return function(){ clearTimeout(t); };
  }, [cooldown]);

  /* Reset to a clean form whenever it is reopened, so a previous submission's
     values (or error) never greet the next visitor. */
  useEffectLF(function(){
    if(!open) return;
    setErr(''); setDone(false); setBusy(false); setSending(false);
    setSent(false); setCooldown(0);
    setF({first_name:'',last_name:'',company:'',designation:'',email:'',
          mobile:'',otp:'',solution:'',message:'',consent:false,website:''});
  }, [open]);

  useEffectLF(function(){
    if(!open) return;
    const h = function(e){ if(e.key === 'Escape') closeLeadForm(); };
    window.addEventListener('keydown', h);
    document.body.style.overflow = 'hidden';   // stop the page scrolling behind
    return function(){
      window.removeEventListener('keydown', h);
      document.body.style.overflow = '';
    };
  }, [open]);

  if(!open) return null;

  const emailLooksValid = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(f.email.trim());

  const sendOtp = function(){
    if(!emailLooksValid){ setErr('Enter your work email first, then request a code.'); return; }
    setErr(''); setSending(true);
    fetch('/v1/public/lead/send-otp', {
      method:'POST', headers:{'Content-Type':'application/json'},
      body: JSON.stringify({email: f.email.trim()}),
    }).then(function(r){
      return r.json().catch(function(){ return {}; }).then(function(j){ return {ok:r.ok, j:j}; });
    }).then(function(res){
      setSending(false);
      if(!res.ok){ setErr(res.j.error || 'Could not send a code. Please try again.'); return; }
      setSent(true); setCooldown(45);
    }).catch(function(){
      setSending(false);
      setErr('Network error. Please check your connection and try again.');
    });
  };

  const submit = function(e){
    e.preventDefault();
    setErr('');
    if(!f.consent){ setErr('Please accept the privacy policy to continue.'); return; }
    if(!f.otp.trim()){ setErr('Enter the verification code we emailed you.'); return; }
    setBusy(true);
    fetch('/v1/public/lead/submit', {
      method:'POST', headers:{'Content-Type':'application/json'},
      body: JSON.stringify(f),
    }).then(function(r){
      return r.json().catch(function(){ return {}; }).then(function(j){ return {ok:r.ok, j:j}; });
    }).then(function(res){
      setBusy(false);
      if(!res.ok){ setErr(res.j.error || 'Something went wrong. Please try again.'); return; }
      setDone(true);
    }).catch(function(){
      setBusy(false);
      setErr('Network error. Please check your connection and try again.');
    });
  };

  return (
    <div className="lf-overlay" onClick={closeLeadForm}>
      <div className="lf" onClick={function(e){ e.stopPropagation(); }} role="dialog" aria-modal="true" aria-label="Contact NeuroRoute sales">
        <LeadFormStyles/>

        <div className="lf-hd">
          <div>
            <div className="lf-eyebrow">CONTACT SALES</div>
            <div className="lf-title">Talk to the NeuroRoute team</div>
          </div>
          <button className="lf-x" onClick={closeLeadForm} aria-label="Close"><Icon name="x" size={16}/></button>
        </div>

        {done ? (
          <div className="lf-done">
            <div className="lf-done-ic"><Icon name="checkcircle" size={30}/></div>
            <h3>Thank you — we have your enquiry.</h3>
            <p>Our sales team will be in touch at <b>{f.email}</b> shortly.</p>
            <button className="btn btn-grad lf-btn-xl" onClick={closeLeadForm}>Close</button>
          </div>
        ) : (
        <form className="lf-bd" onSubmit={submit}>
          <div className="lf-row">
            <label className="lf-f">
              <span>First Name <i>*</i></span>
              <input value={f.first_name} onChange={set('first_name')} placeholder="First Name" maxLength={120} required/>
            </label>
            <label className="lf-f">
              <span>Last Name <i>*</i></span>
              <input value={f.last_name} onChange={set('last_name')} placeholder="Last Name" maxLength={120} required/>
            </label>
          </div>

          <div className="lf-row">
            <label className="lf-f">
              <span>Company Name <i>*</i></span>
              <input value={f.company} onChange={set('company')} placeholder="Company Name" maxLength={120} required/>
            </label>
            <label className="lf-f">
              <span>Designation <i>*</i></span>
              <input value={f.designation} onChange={set('designation')} placeholder="Your Designation" maxLength={120} required/>
            </label>
          </div>

          <div className="lf-row">
            <label className="lf-f">
              <span>Email <i>*</i></span>
              <input type="email" value={f.email} onChange={set('email')} placeholder="Work Email" maxLength={254} required/>
            </label>
            <label className="lf-f">
              <span>Mobile Number <i>*</i></span>
              <input value={f.mobile} onChange={set('mobile')} placeholder="Work Mobile" maxLength={120} required/>
            </label>
          </div>

          <div className="lf-f">
            <span>Verify <i>*</i></span>
            <div className="lf-row lf-verify">
              <button type="button" className="btn btn-grad lf-otp-btn"
                onClick={sendOtp} disabled={sending || cooldown > 0}>
                {sending ? 'Sending…' : cooldown > 0 ? 'Resend in ' + cooldown + 's' : sent ? 'Resend OTP' : 'Send OTP'}
              </button>
              <input value={f.otp} onChange={set('otp')} placeholder="Enter OTP"
                inputMode="numeric" maxLength={4} autoComplete="one-time-code"/>
            </div>
            {sent && <div className="lf-hint">We emailed a 4-digit code to {f.email}. It expires in 5 minutes.</div>}
          </div>

          <label className="lf-f">
            <span>Solution Required <i>*</i></span>
            <select value={f.solution} onChange={set('solution')} required>
              <option value="">Select a solution</option>
              {LEAD_SOLUTIONS.map(function(s){ return <option key={s} value={s}>{s}</option>; })}
            </select>
          </label>

          <label className="lf-f">
            <textarea value={f.message} onChange={set('message')} rows={4} maxLength={4000}
              placeholder="Message — what are you trying to solve? Current monthly AI spend helps us help you."/>
          </label>

          {/* Honeypot: hidden from humans and from assistive tech; a bot that
              fills every input it finds gives itself away. */}
          <input className="lf-hp" type="text" name="website" tabIndex={-1} autoComplete="off"
            aria-hidden="true" value={f.website} onChange={set('website')}/>

          <label className="lf-consent">
            <input type="checkbox" checked={f.consent} onChange={set('consent')}/>
            <span>I agree with the site <a href="#/privacy" target="_blank" rel="noopener noreferrer">Privacy Policy</a> <i>*</i></span>
          </label>

          {err && <div className="lf-err"><Icon name="alert" size={14}/>{err}</div>}

          <button className="btn btn-grad lf-btn-xl" type="submit" disabled={busy}>
            {busy ? 'Sending…' : 'Submit enquiry'}
          </button>
          <div className="lf-foot">We reply from CloudSales@sislinfotech.com. No newsletter, no reselling your details.</div>
        </form>
        )}
      </div>
    </div>
  );
}

function LeadFormStyles(){
  return <style>{`
.lf-overlay{position:fixed;inset:0;z-index:2000;background:rgba(4,6,12,.78);backdrop-filter:blur(7px);
  display:flex;align-items:flex-start;justify-content:center;padding:28px 16px;overflow-y:auto;
  animation:lfFade .18s ease}
@keyframes lfFade{from{opacity:0}to{opacity:1}}
.lf{position:relative;width:100%;max-width:640px;background:var(--bg-1,#0f1117);border:1px solid var(--line-2,#242836);
  border-radius:18px;box-shadow:0 30px 90px rgba(0,0,0,.6);animation:lfUp .22s cubic-bezier(.2,.8,.3,1)}
@keyframes lfUp{from{opacity:0;transform:translateY(14px)}to{opacity:1;transform:none}}
.lf-hd{display:flex;align-items:flex-start;justify-content:space-between;gap:12px;
  padding:22px 24px 16px;border-bottom:1px solid var(--line,#1b1e29)}
.lf-eyebrow{font-size:10.5px;letter-spacing:.16em;font-weight:700;color:var(--blue,#5b8cff);margin-bottom:7px}
.lf-title{font-size:19px;font-weight:700;color:var(--tx-1,#f2f4f8);letter-spacing:-.01em}
.lf-x{background:transparent;border:1px solid var(--line-2,#242836);color:var(--tx-3,#8a90a2);
  width:32px;height:32px;border-radius:9px;cursor:pointer;display:grid;place-items:center;flex:none}
.lf-x:hover{color:var(--tx-1,#f2f4f8);border-color:var(--line-3,#333849)}
.lf-bd{padding:20px 24px 24px;display:flex;flex-direction:column;gap:14px}
.lf-row{display:grid;grid-template-columns:1fr 1fr;gap:14px}
.lf-f{display:flex;flex-direction:column;gap:7px;min-width:0}
.lf-f>span{font-size:12.5px;font-weight:600;color:var(--tx-2,#b6bccb)}
.lf-f>span>i{color:var(--magenta,#c05cff);font-style:normal}
.lf-f input,.lf-f select,.lf-f textarea{width:100%;background:var(--bg-0,#080910);color:var(--tx-1,#f2f4f8);
  border:1px solid var(--line-2,#242836);border-radius:10px;padding:11px 13px;font-size:14px;
  font-family:inherit;outline:none;transition:border-color .15s,box-shadow .15s}
.lf-f textarea{resize:vertical;min-height:96px;line-height:1.55}
.lf-f input::placeholder,.lf-f textarea::placeholder{color:var(--tx-4,#5c6273)}
.lf-f input:focus,.lf-f select:focus,.lf-f textarea:focus{border-color:var(--blue,#5b8cff);
  box-shadow:0 0 0 3px rgba(91,140,255,.16)}
.lf-verify{align-items:stretch}
.lf-otp-btn{width:100%;justify-content:center;padding:11px 14px;font-size:14px;border-radius:10px}
.lf-otp-btn:disabled{opacity:.6;cursor:not-allowed}
.lf-hint{font-size:12px;color:var(--tx-3,#8a90a2);margin-top:2px}
.lf-hp{position:absolute;left:-9999px;width:1px;height:1px;opacity:0;pointer-events:none}
.lf-consent{display:flex;align-items:flex-start;gap:10px;font-size:13px;color:var(--tx-2,#b6bccb);cursor:pointer}
.lf-consent input{width:16px;height:16px;flex:none;margin-top:1px;accent-color:var(--blue,#5b8cff);cursor:pointer}
.lf-consent i{color:var(--magenta,#c05cff);font-style:normal}
.lf-consent a{color:var(--blue,#5b8cff);text-decoration:none}
.lf-consent a:hover{text-decoration:underline}
.lf-err{display:flex;align-items:center;gap:8px;font-size:13px;color:#ff8b8b;
  background:rgba(255,90,90,.09);border:1px solid rgba(255,90,90,.25);border-radius:9px;padding:10px 12px}
.lf-btn-xl{width:100%;justify-content:center;padding:14px;font-size:15.5px;border-radius:12px;margin-top:2px}
.lf-btn-xl:disabled{opacity:.65;cursor:not-allowed}
.lf-foot{font-size:11.5px;color:var(--tx-4,#5c6273);text-align:center;line-height:1.5}
.lf-done{padding:38px 28px 34px;text-align:center;display:flex;flex-direction:column;align-items:center;gap:12px}
.lf-done-ic{color:var(--green,#3ddc97)}
.lf-done h3{margin:0;font-size:19px;color:var(--tx-1,#f2f4f8)}
.lf-done p{margin:0;font-size:14px;color:var(--tx-2,#b6bccb);line-height:1.6}
.lf-done .lf-btn-xl{max-width:220px;margin-top:10px}
@media (max-width:640px){
  .lf-overlay{padding:0}
  .lf{max-width:none;min-height:100%;border-radius:0;border:none}
  .lf-row{grid-template-columns:1fr}
  .lf-hd{position:sticky;top:0;background:var(--bg-1,#0f1117);z-index:2;border-radius:0}
  .lf-bd{padding:18px 18px 34px}
}
`}</style>;
}

window.LeadForm = LeadForm;
window.openLeadForm = openLeadForm;
window.useLeadForm = useLeadForm;
window.LEAD_SOLUTIONS = LEAD_SOLUTIONS;
