// Contact page — form-first conversion-optimized
// v2: Form is the hero. Routing is inline. Progressive disclosure.

const ROUTES = [
  {slug:'sales',    label:'Sales',    name:'Book a demo',          sla:'Reply < 24h · 7 days',   email:'sales@quanttechnology.com',    color:'var(--accent)',         desc:'Evaluating QTG. Demo, scoping, pricing.',          msgPrompt:'Tell us what you\u2019re solving for. Existing stack, target launch date, anything we should know up-front.'},
  {slug:'partners', label:'Partners', name:'Partner integration',  sla:'Reply < 48h · weekdays', email:'partners@quanttechnology.com', color:'oklch(0.82 0.16 165)',  desc:'Platforms, PSPs, KYC, BI, data providers.',         msgPrompt:'Where would you plug in? Joint customers, existing integrations elsewhere, what you\u2019re proposing.'},
  {slug:'press',    label:'Press',    name:'Press & analyst',      sla:'Reply < 24h · weekdays', email:'press@quanttechnology.com',    color:'oklch(0.80 0.14 95)',   desc:'Briefings, on-record, brand assets.',               msgPrompt:'Story you\u2019re working on, named sources you need, fact-check items, deadline.'},
  {slug:'careers',  label:'Careers',  name:'Careers',              sla:'Reply < 72h · weekdays', email:'careers@quanttechnology.com',  color:'oklch(0.78 0.18 320)',  desc:'Engineering, design, risk, ops.',                   msgPrompt:'Role of interest, links to your work, what you\u2019re looking for next.'},
  {slug:'general',  label:'General',  name:'General enquiry',      sla:'Reply < 48h · weekdays', email:'hello@quanttechnology.com',    color:'oklch(0.78 0.16 220)',  desc:'Anything else - questions, feedback, general requests.', msgPrompt:'Tell us what you need. Whatever it is, we’ll point it to the right person.'},
];

const SCALES = ['Pre-launch','Launching · <1k accts','Scaling · 1k–10k','Established · 10k+','Enterprise'];
const PLATFORMS = ['YourPropFirm','Broker Infrastructure','QuantSentry','QuantCX','PropTradeGroup','TradoPay','All of the above'];

// Per-route qualification — drives the dynamic question set
const ROUTE_QUALIFY = {
  sales: [
    {key:'interest', label:"I'm evaluating",       kind:'chips',    options: PLATFORMS},
    {key:'scale',    label:'Scale',                kind:'chips',    options: SCALES},
    {key:'biz',      label:'Business type',        kind:'chips',    options:['Prop firm','Brokerage','White-label','Holdco / multi-brand','Greenfield']},
    {key:'stack',    label:'Current stack',        kind:'chips',    options:['cTrader','Match-Trader','DXtrade','TradeLocker','In-house','None yet']},
    {key:'timing',   label:'Target launch',        kind:'chips',    options:['<30 days','1–3 months','3–6 months','6–12 months','Exploring']},
    {key:'budget',   label:'Annual budget band',   kind:'chips',    options:['<€50k','€50–150k','€150–500k','€500k–1.5M','€1.5M+'], optional:true},
  ],
  partners: [
    {key:'interest', label:'Partnership type',     kind:'chips',    options:['Platform integration','PSP / Payments','KYC / Compliance','BI / Data','Marketing','Liquidity','Channel reseller','Other']},
    {key:'partnerCo',label:'Company type',         kind:'chips',    options:['Vendor / SaaS','LP / Liquidity','PSP','KYC provider','Reseller / SI','Media / Affiliate']},
    {key:'reach',    label:'Operator reach',       kind:'chips',    options:['<10 operators','10–50','50–200','200+','Direct enterprise only']},
    {key:'shape',    label:'Integration shape',    kind:'chips',    options:['REST API','Webhooks','SDK','OAuth / SSO','Data feed','Co-marketing only'], optional:true},
  ],
  press: [
    {key:'outlet',   label:'Outlet',               kind:'input',    placeholder:'FT, Bloomberg, Finance Magnates…'},
    {key:'angle',    label:'Angle',                kind:'chips',    options:['Company / strategy','Product / engineering','Risk / markets','Industry / commentary','Profile / interview']},
    {key:'deadline', label:'Deadline',             kind:'chips',    options:['Today','This week','Next 2 weeks','Long-form / no rush']},
    {key:'format',   label:'Format',               kind:'chips',    options:['Written quote','Recorded interview','Live / on-air','Background only'], optional:true},
  ],
  careers: [
    {key:'interest', label:'Department of interest',kind:'chips',   options:['Engineering','Design','Risk','Ops','Commercial','Compliance','Open application']},
    {key:'level',    label:'Seniority',            kind:'chips',    options:['Mid','Senior','Staff / Principal','Lead / Manager','Exec']},
    {key:'loc',      label:'Region',               kind:'chips',    options:['EU','MEA','APAC','Americas','Remote-only']},
    {key:'links',    label:'Portfolio / GitHub / LinkedIn', kind:'input', placeholder:'https://…', optional:true},
  ],
};

// --- The Form: lives inside the hero, single-column, progressive ---
const ContactFormCard = () => {
  const [route, setRoute] = React.useState('sales');
  const [name, setName] = React.useState('');
  const [email, setEmail] = React.useState('');
  const [company, setCompany] = React.useState('');
  const [role, setRole] = React.useState('');
  // message: per-route bag so switching tabs doesn't lose draft text
  const [messages, setMessages] = React.useState({});
  // answers: per-route bag, keyed by question key
  const [answers, setAnswers] = React.useState({});
  const [submitted, setSubmitted] = React.useState(false);
  const [submitting, setSubmitting] = React.useState(false);
  const [errorMsg, setErrorMsg] = React.useState('');
  // Honeypot — bots tend to fill every visible field. Hidden from real users
  // (CSS + aria), so any non-empty value flags a bot. The server silently
  // returns 200 in that case so bots can't probe the rejection signal.
  const [website, setWebsite] = React.useState('');

  const r = ROUTES.find(x => x.slug === route);
  const qs = ROUTE_QUALIFY[route] || [];
  const a = answers[route] || {};
  const setA = (k, v) => setAnswers(prev => ({...prev, [route]: {...(prev[route]||{}), [k]: v}}));
  const message = messages[route] || '';
  const setMessage = (v) => setMessages(prev => ({...prev, [route]: v}));

  // Progressive: only reveal qualifying questions once contact identity is plausible
  const ready = name.trim().length > 1 && /\S+@\S+\.\S+/.test(email);
  const showScope = ready;

  const composeMessage = () => {
    // Append the per-route qualifying answers under the user's message so the
    // Slack receiver gets full context without expanding the API contract.
    const filled = qs
      .map(q => ({label: q.label, val: (a[q.key] || '').toString().trim()}))
      .filter(x => x.val.length > 0);
    if (filled.length === 0) return message.trim();
    const ctx = filled.map(x => `• ${x.label}: ${x.val}`).join('\n');
    return `${message.trim()}\n\n— Context —\n${ctx}`;
  };

  const handleSubmit = async () => {
    if (!ready || submitting) return;
    setSubmitting(true);
    setErrorMsg('');
    try {
      const res = await fetch('/api/contact', {
        method: 'POST',
        headers: {'content-type': 'application/json'},
        body: JSON.stringify({
          route,
          name: name.trim(),
          email: email.trim(),
          company: company.trim(),
          role: role.trim(),
          message: composeMessage(),
          website, // honeypot — should be empty
        }),
      });
      if (res.ok) {
        setSubmitted(true);
        return;
      }
      let data = null;
      try { data = await res.json(); } catch (_) {}
      const msg = data && data.error && data.error.message
        ? data.error.message
        : 'Something went wrong. Please try again or email us directly.';
      setErrorMsg(msg);
    } catch (_) {
      setErrorMsg('Network error — please retry, or email us directly.');
    } finally {
      setSubmitting(false);
    }
  };

  if (submitted) {
    return (
      <div className="form-card form-card--done" style={{borderColor:r.color}}>
        <div className="kicker" style={{color:r.color}}>MESSAGE SENT</div>
        <h3 style={{marginTop:12, fontSize:28, letterSpacing:'-0.022em', lineHeight:1.15}}>
          Thanks &mdash; it&rsquo;s with our <span style={{color:r.color}}>{r.label.toLowerCase()}</span> team.
        </h3>
        <p style={{marginTop:14, fontSize:14, color:'var(--text-2)', lineHeight:1.6}}>
          A real person will read it and get back to you. No automated drip sequences, no bots.
        </p>
        <div style={{marginTop:22, display:'flex', gap:10, flexWrap:'wrap'}}>
          <a className="btn btn-ghost btn-sm" href="platforms">Browse Platforms</a>
          <a className="btn btn-ghost btn-sm" href="services">See Services</a>
          <button className="btn-link" style={{fontSize:13}} onClick={()=>{setSubmitted(false); setName(''); setEmail(''); setCompany(''); setRole(''); setAnswers({}); setMessages({}); setErrorMsg(''); setWebsite('');}}>Send Another</button>
        </div>
      </div>
    );
  }

  return (
    <div className="form-card">
      {/* Clean intro */}
      <div className="form-intro">
        <h3 className="form-title">How can we help?</h3>
        <p className="form-sub">Pick what fits, add a little context, and we&rsquo;ll get the right person back to you.</p>
      </div>

      {/* Route segmented control */}
      <div className="form-routes" role="tablist" aria-label="Reason for contact">
        {ROUTES.map(rt => (
          <button key={rt.slug}
            role="tab"
            aria-selected={route === rt.slug}
            onClick={() => setRoute(rt.slug)}
            className={`form-route ${route === rt.slug ? 'is-active' : ''}`}
            style={route === rt.slug ? {borderColor: rt.color, color: rt.color} : null}
          >
            {rt.label}
          </button>
        ))}
      </div>

      {/* Clean route context line */}
      <div className="form-route-ctx">
        <span className="form-route-dot" style={{background:r.color}}/>
        <span>{r.desc}</span>
      </div>

      {/* Always-visible: identity */}
      <div className="form-grid-2" style={{marginTop:18}}>
        <Field label="FULL NAME" placeholder="Maya Reinhart" value={name} onChange={setName} autoFocus/>
        <Field label="WORK EMAIL" placeholder="you@operator.io" type="email" value={email} onChange={setEmail}/>
        <Field label="COMPANY" placeholder="Operator Co." value={company} onChange={setCompany}/>
        <Field label="ROLE" placeholder="Head of Operations" value={role} onChange={setRole}/>
      </div>

      {/* MESSAGE — most important, always visible, route-aware */}
      <div className="form-message">
        <div className="form-message-head">
          <div className="kicker" style={{fontSize:10}}>YOUR MESSAGE</div>
        </div>
        <textarea
          className="form-message-area"
          placeholder={r.msgPrompt}
          value={message}
          onChange={e => setMessage(e.target.value)}
          rows={5}
          style={{borderColor: message.length > 0 ? r.color + '55' : null}}
        />
        <div className="form-message-foot mono">
          The more context you share, the faster we can help. Plain language is perfect.
        </div>
      </div>

      {/* Progressive: dynamic qualification questions per route */}
      <div className={`form-progress ${showScope ? 'is-open' : ''}`}>
        <div className="form-progress-inner">
          {qs.map((q, i) => {
            const val = a[q.key] || '';
            const optLabel = q.optional ? <span style={{color:'var(--text-4)', letterSpacing:0, textTransform:'none', fontWeight:400}}> · optional</span> : null;
            return (
              <div key={q.key} style={{marginTop: i===0 ? 18 : 14}}>
                <div className="kicker" style={{fontSize:10}}>{q.label.toUpperCase()}{optLabel}</div>
                {q.kind === 'chips' && (
                  <div className="chip-row">
                    {q.options.map(o => (
                      <button key={o} type="button" onClick={()=>setA(q.key, o)}
                        className={`chip ${val === o ? 'is-active' : ''}`}>
                        {o}
                      </button>
                    ))}
                  </div>
                )}
                {q.kind === 'input' && (
                  <input
                    value={val}
                    onChange={e => setA(q.key, e.target.value)}
                    placeholder={q.placeholder}
                    className="field-input"
                    style={{marginTop:6}}
                  />
                )}
                {q.kind === 'textarea' && (
                  <textarea
                    value={val}
                    onChange={e => setA(q.key, e.target.value)}
                    placeholder={q.placeholder}
                    className="form-textarea"
                  />
                )}
              </div>
            );
          })}
        </div>
      </div>

      {/* Honeypot — visually hidden, kept out of tab order, never autofilled */}
      <div aria-hidden="true" style={{position:'absolute', left:'-10000px', top:'auto', width:1, height:1, overflow:'hidden'}}>
        <label>
          Website (leave blank)
          <input
            type="text"
            tabIndex={-1}
            autoComplete="off"
            value={website}
            onChange={e => setWebsite(e.target.value)}
          />
        </label>
      </div>

      {/* Submit + trust */}
      <div className="form-submit">
        <button
          type="button"
          className="btn btn-primary"
          disabled={!ready || submitting}
          onClick={handleSubmit}
          style={{
            background: ready ? r.color : 'transparent',
            color: ready ? '#062019' : 'var(--text-4)',
            border: ready ? 'none' : '1px solid var(--line)',
            cursor: (ready && !submitting) ? 'pointer' : 'not-allowed',
            opacity: (ready && !submitting) ? 1 : 0.7
          }}
        >
          {submitting ? 'Sending…' : (ready ? `Send to ${r.label.toLowerCase()}` : 'Add your name + email')} <ArrowRight/>
        </button>
        <span className="mono form-or">OR</span>
        <a className="btn-link form-direct" href={`mailto:${r.email}`}>Email us directly <ArrowRight/></a>
      </div>

      {errorMsg ? (
        <div role="alert" className="mono" style={{marginTop:14, padding:'10px 12px', border:'1px solid oklch(0.65 0.2 25 / 0.5)', borderRadius:8, color:'oklch(0.85 0.16 25)', fontSize:12, letterSpacing:'0.04em', background:'oklch(0.65 0.2 25 / 0.08)'}}>
          {errorMsg}
        </div>
      ) : null}

    </div>
  );
};

const Dot = () => <span style={{width:4, height:4, borderRadius:'50%', background:'var(--accent)', display:'inline-block'}}/>;

const Field = ({label, placeholder, type='text', value, onChange, autoFocus}) => (
  <label className="field-label">
    <span className="kicker" style={{fontSize:10}}>{label}</span>
    <input
      type={type}
      placeholder={placeholder}
      value={value}
      onChange={e => onChange(e.target.value)}
      autoFocus={autoFocus}
      className="field-input"
    />
  </label>
);

// --- Hero with form on the right, message on the left ---
const ContactHero = () => (
  <section className="hero contact-hero">
    <div className="hero-grid-bg" />
    <div className="hero-glow" />
    <div className="container">
      <div className="contact-hero-grid">
        {/* Left: message */}
        <div className="contact-hero-msg">
          <div className="hero-pill">
            <span className="tag">CONTACT</span>
            <span>Real people. Fast answers.</span>
          </div>
          <h1 style={{maxWidth:'15ch', fontSize:'clamp(40px, 4.4vw, 64px)'}}>
            Talk to the people<br/>
            <i className="accent" style={{fontStyle:'normal'}}>who run it.</i>
          </h1>
          <p className="hero-sub" style={{maxWidth:'42ch'}}>
            Tell us what you're working on. A named QTG specialist replies directly — usually within the day. No bots, no marketing queue.
          </p>

          <div className="hero-meta kpi-strip" style={{marginTop:28}}>
            <div className="hero-meta-item"><span className="k">Sales</span><span className="v">&lt; 24h</span></div>
            <div className="hero-meta-item"><span className="k">Response</span><span className="v">&lt; 24h</span></div>
            <div className="hero-meta-item"><span className="k">Coverage</span><span className="v">24/7</span></div>
            <div className="hero-meta-item"><span className="k">Locations</span><span className="v">10</span></div>
          </div>
        </div>

        {/* Right: form (sticky on desktop) */}
        <div className="contact-hero-form">
          <ContactFormCard/>
        </div>
      </div>
    </div>
  </section>
);

// --- Below the fold: lighter route index, for users who want context ---
const RouteIndex = () => (
  <section id="routes" className="section-pad-sm" style={{borderTop:'1px solid var(--line)', borderBottom:'1px solid var(--line)'}}>
    <div className="container">
      <div style={{display:'flex', justifyContent:'space-between', alignItems:'baseline', marginBottom:24, flexWrap:'wrap', gap:12}}>
        <div>
          <div className="kicker">DIRECT ROUTES</div>
          <h2 style={{fontSize:'clamp(28px, 3.2vw, 40px)', fontWeight:450, letterSpacing:'-0.022em', marginTop:8}}>
            Prefer to skip the form? Write directly.
          </h2>
        </div>
      </div>
      <div style={{display:'grid', gridTemplateColumns:'repeat(3, 1fr)', gap:1, background:'var(--line)', border:'1px solid var(--line)', borderRadius:12, overflow:'hidden'}}>
        {ROUTES.map((p,i)=>(
          <a key={i} href={`mailto:${p.email}`} className="card route-card" style={{
            borderRadius:0, border:'none', background:'var(--surface)', padding:'22px 22px',
            display:'flex', flexDirection:'column', gap:10, minHeight:150
          }}>
            <div style={{display:'flex', justifyContent:'space-between', alignItems:'center'}}>
              <span className="mono" style={{fontSize:10.5, color:'var(--text-4)', letterSpacing:'0.12em'}}>{p.label.toUpperCase()}</span>
              <span style={{width:6, height:6, borderRadius:'50%', background:p.color}}/>
            </div>
            <div style={{fontFamily:'var(--font-sans)', fontSize:18, letterSpacing:'-0.018em', color:'var(--text)'}}>{p.name}</div>
            <div className="mono" style={{fontSize:11, color:p.color}}>{p.email}</div>
            <div style={{fontSize:12.5, color:'var(--text-2)', lineHeight:1.5}}>{p.desc}</div>
            <div style={{marginTop:'auto', paddingTop:6, fontSize:11.5, color:'var(--text-3)', display:'inline-flex', alignItems:'center', gap:6}}>
              {p.sla} <ArrowRight/>
            </div>
          </a>
        ))}
      </div>
    </div>
  </section>
);

// Locations — uses the dark GlobalMapPanel from the index page.
const ContactOffices = () => (
  <section id="offices" className="section-pad" style={{borderTop:'1px solid var(--line)'}}>
    <div className="container">
      <div className="section-head">
        <div>
          <div className="section-num">LOCATIONS</div>
          <h2 className="mt-4">Ten cities. Round-the-clock handoff.</h2>
        </div>
        <p className="lead">
          One company group, distributed across ten cities and three regions. Every contact route is staffed by humans
          working in overlapping shifts — not chased into one timezone.
        </p>
      </div>
      <div className="offices-grid" style={{display:'grid', gridTemplateColumns:'1fr', gap:24}}>
        <GlobalMapPanel />
      </div>
    </div>
  </section>
);

const ContactApp = () => (
  <>
    <Nav/>
    <ContactHero/>
    <RouteIndex/>
    <ContactOffices/>
    <Footer/>
    <QtgTweaks/>
  </>
);

ReactDOM.createRoot(document.getElementById('root')).render(<ContactApp/>);
