// Contact / Questionnaire
function ContactPage({navigate}) {
  const [stage, setStage] = useState('mode'); // mode -> q1..q6 -> result
  const [mode, setMode] = useState(null); // 'readiness' | 'apply'
  const [answers, setAnswers] = useState({});
  const [submitting, setSubmitting] = useState(false);
  const [submitError, setSubmitError] = useState(null);
  const totalSteps = 7; // 6 q + result
  const stageIdx = stage === 'mode' ? 0 : stage === 'result' ? 7 : parseInt(stage.replace('q','')); 
  const progress = stage === 'mode' ? 0 : Math.min(100, (stageIdx / 6) * 100);

  const setA = (k, v, advance) => {
    setAnswers(a => ({...a, [k]: v}));
    if (advance) setTimeout(() => setStage(advance), 350);
  };

  // Score calc
  const computeScore = () => {
    let s = 0;
    const platforms = answers.q3 || [];
    if (platforms.includes('None')) s += 1;
    else if (platforms.length >= 3) s += 3;
    else s += 2;
    if (answers.q2 === '50+ brands' || answers.q2 === '16-50 brands') s += 3;
    else if (answers.q2 === '5-15 brands') s += 2;
    else s += 1;
    const ch = answers.q4 || '';
    if (ch.includes('flat') || ch.includes('ROI') || ch.includes('Stockouts')) s += 2;
    else if (ch.includes("don't know")) s += 1;
    else s += 1;
    if (answers.q5 === 'AED 200K – 500K/month' || answers.q5 === 'AED 500K+/month') s += 1;
    return Math.min(10, s);
  };

  // Disqualification
  const isDisqualified = answers.q1 === 'Other' && answers.q2 === '1-4 brands' && (answers.q3 || []).includes('None');

  return (
    <div data-screen-label="Contact">
      <section className="hero hero-half bg-navy" style={{position: 'relative', minHeight: '50vh'}}>
        <div className="hero-grid"></div>
        <div className="hero-glow hero-glow-1"></div>
        <div className="container hero-content">
          <FadeUp><span className="eyebrow">GET STARTED</span></FadeUp>
          <FadeUp delay={120}><h1 style={{fontSize: 'clamp(36px, 5vw, 60px)'}}>Find out where your brand stands on UAE q-commerce.</h1></FadeUp>
          <FadeUp delay={240}><p className="hero-sub">Take our 2-minute assessment — or apply to work with us directly.</p></FadeUp>
        </div>
      </section>

      <section className="section bg-white">
        <div className="container">
          {stage === 'mode' && (
            <FadeUp>
              <div className="quest-modes">
                <div className={`mode-card ${mode === 'readiness' ? 'selected' : ''}`} onClick={() => {setMode('readiness'); setTimeout(() => setStage('q1'), 250);}}>
                  <div className="mode-icon"><Icon.target /></div>
                  <h3>Get Your Q-Commerce Readiness Score</h3>
                  <p>Answer 5 questions. Get a personalized readiness score and recommendations.</p>
                </div>
                <div className={`mode-card ${mode === 'apply' ? 'selected' : ''}`} onClick={() => {setMode('apply'); setTimeout(() => setStage('q1'), 250);}}>
                  <div className="mode-icon"><Icon.briefcase /></div>
                  <h3>Apply to Work with Mantaga</h3>
                  <p>Tell us about your business. We review applications within 48 hours.</p>
                </div>
              </div>
            </FadeUp>
          )}

          {stage !== 'mode' && stage !== 'result' && (
            <>
              <div className="progress-bar">
                <div className="progress-fill" style={{width: `${progress}%`}}></div>
              </div>
              <div className="question-shell">
                <div className="q-back" onClick={() => {
                  if (stage === 'q1') setStage('mode');
                  else setStage('q' + (stageIdx - 1));
                }}>← Back</div>

                {stage === 'q1' && (
                  <FadeUp>
                    <h2>What best describes your company?</h2>
                    {[
                      ['FMCG Distributor', 'We hold distribution rights for multiple brands'],
                      ['Brand Owner', 'We own or manufacture our own products'],
                      ['Both', 'We distribute and have our own brands'],
                      ['Other', "We don't fit these categories"],
                    ].map(([k, sub]) => (
                      <button key={k} className={`opt-card ${answers.q1 === k ? 'selected' : ''}`} onClick={() => setA('q1', k, 'q2')}>
                        <span className="opt-check"></span>
                        <span><span className="opt-title">{k}</span><span className="opt-sub" style={{display: 'block'}}>{sub}</span></span>
                      </button>
                    ))}
                  </FadeUp>
                )}

                {stage === 'q2' && (
                  <FadeUp>
                    <h2>How many brands are in your portfolio?</h2>
                    {['1-4 brands', '5-15 brands', '16-50 brands', '50+ brands'].map(k => (
                      <button key={k} className={`opt-card ${answers.q2 === k ? 'selected' : ''}`} onClick={() => setA('q2', k, 'q3')}>
                        <span className="opt-check"></span>
                        <span className="opt-title">{k}</span>
                      </button>
                    ))}
                  </FadeUp>
                )}

                {stage === 'q3' && (
                  <FadeUp>
                    <h2>Which platforms are you currently selling on?</h2>
                    <p style={{color: 'var(--muted-text)', marginTop: -16, marginBottom: 24, fontSize: 14}}>Select all that apply.</p>
                    {['Talabat Mart', 'Noon / Noon Minutes', 'Amazon.ae', 'Careem Quik', 'None — we haven\'t started yet'].map(k => {
                      const sel = (answers.q3 || []).includes(k);
                      return (
                        <button key={k} className={`opt-card ${sel ? 'selected' : ''}`} onClick={() => {
                          const cur = answers.q3 || [];
                          let next;
                          if (k.startsWith('None')) next = sel ? [] : ['None'];
                          else next = sel ? cur.filter(x => x !== k) : [...cur.filter(x => !x.startsWith('None')), k];
                          setAnswers(a => ({...a, q3: next}));
                        }}>
                          <span className="opt-check"></span>
                          <span className="opt-title">{k}</span>
                        </button>
                      );
                    })}
                    <button className="btn btn-primary" style={{marginTop: 16}} onClick={() => setStage('q4')} disabled={!(answers.q3 || []).length}>Continue →</button>
                  </FadeUp>
                )}

                {stage === 'q4' && (
                  <FadeUp>
                    <h2>What's your biggest challenge right now?</h2>
                    {[
                      "We're not on q-commerce and don't know where to start",
                      "We're on platforms but sales are flat or declining",
                      "Stockouts and forecasting are a constant problem",
                      "We're spending on ads but can't measure ROI",
                      "Our brand principals want e-commerce data we don't have",
                      "We need a team to manage this — we don't have in-house capability",
                    ].map(k => (
                      <button key={k} className={`opt-card ${answers.q4 === k ? 'selected' : ''}`} onClick={() => setA('q4', k, 'q5')}>
                        <span className="opt-check"></span>
                        <span className="opt-title">{k}</span>
                      </button>
                    ))}
                  </FadeUp>
                )}

                {stage === 'q5' && (
                  <FadeUp>
                    <h2>What's your approximate monthly revenue on e-commerce platforms?</h2>
                    {['Not yet live', 'Under AED 50K/month', 'AED 50K – 200K/month', 'AED 200K – 500K/month', 'AED 500K+/month', 'Prefer not to say'].map(k => (
                      <button key={k} className={`opt-card ${answers.q5 === k ? 'selected' : ''}`} onClick={() => setA('q5', k, 'q6')}>
                        <span className="opt-check"></span>
                        <span className="opt-title">{k}</span>
                      </button>
                    ))}
                  </FadeUp>
                )}

                {stage === 'q6' && (
                  <FadeUp>
                    <h2>One last thing — your details.</h2>
                    <form onSubmit={async (e) => {
                      e.preventDefault();
                      if (submitting) return;
                      setSubmitting(true);
                      setSubmitError(null);
                      try {
                        const payload = {
                          access_key: 'ca7bac89-779b-4a04-ae6d-428a4a27840d',
                          subject: `New ${mode === 'readiness' ? 'Readiness Score' : 'Work Application'} from ${answers.name || 'website visitor'}`,
                          from_name: 'Mantaga Website',
                          replyto: answers.email || '',
                          name: answers.name || '',
                          email: answers.email || '',
                          company: answers.company || '',
                          role: answers.role || '',
                          mode: mode === 'readiness' ? 'Q-Commerce Readiness Score' : 'Apply to Work with Mantaga',
                          q1_company_type: answers.q1 || '',
                          q2_brand_count: answers.q2 || '',
                          q3_platforms: Array.isArray(answers.q3) ? answers.q3.join(', ') : (answers.q3 || ''),
                          q4_biggest_challenge: answers.q4 || '',
                          q5_monthly_revenue: answers.q5 || ''
                        };
                        const res = await fetch('https://api.web3forms.com/submit', {
                          method: 'POST',
                          headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' },
                          body: JSON.stringify(payload)
                        });
                        const data = await res.json();
                        if (!data.success) throw new Error(data.message || 'Submission failed');
                        setStage('result');
                      } catch (err) {
                        setSubmitError('Something went wrong sending your details. Please email sales@mantaga.com directly.');
                      } finally {
                        setSubmitting(false);
                      }
                    }}>
                      {[['name','Name'], ['company','Company name'], ['email','Email'], ['role','Role / Title']].map(([k, label]) => (
                        <div key={k} className="form-field">
                          <label>{label}</label>
                          <input required type={k === 'email' ? 'email' : 'text'} value={answers[k] || ''} onChange={e => setAnswers(a => ({...a, [k]: e.target.value}))}/>
                        </div>
                      ))}
                      {submitError && (
                        <div style={{marginTop: 12, padding: '10px 14px', background: 'rgba(232,96,76,0.08)', border: '1px solid rgba(232,96,76,0.3)', borderRadius: 8, color: 'var(--coral)', fontSize: 13}}>
                          {submitError}
                        </div>
                      )}
                      <button type="submit" disabled={submitting} className="btn btn-primary" style={{marginTop: 12, width: '100%', justifyContent: 'center', opacity: submitting ? 0.7 : 1, cursor: submitting ? 'wait' : 'pointer'}}>
                        {submitting ? 'Sending…' : (mode === 'readiness' ? 'Get My Results →' : 'Submit Application →')}
                      </button>
                    </form>
                  </FadeUp>
                )}
              </div>
            </>
          )}

          {stage === 'result' && (
            <FadeUp>
              <div style={{maxWidth: 720, margin: '0 auto'}}>
                {isDisqualified ? (
                  <div style={{textAlign: 'center'}}>
                    <span className="pill pill-coral" style={{marginBottom: 24}}>EARLY STAGE</span>
                    <h2 className="result-h2" style={{fontSize: 36, marginBottom: 16}}>We might not be the right fit — yet.</h2>
                    <p className="result-p" style={{fontSize: 17, color: 'var(--muted-text)', marginBottom: 32}}>Our full-service model works best for companies with 5+ brands or an existing e-commerce presence. But here's something that can help you get started:</p>
                    <a className="btn btn-primary" style={{marginRight: 12}}>Download the Q-Commerce Onboarding Checklist (free)</a>
                    <p style={{marginTop: 24, fontSize: 14, color: 'var(--muted-text)'}}>Think we got it wrong? Email <a href="mailto:sales@mantaga.com" style={{color: 'var(--coral)'}}>sales@mantaga.com</a> and tell us about your situation.</p>
                  </div>
                ) : mode === 'readiness' ? (
                  <ReadinessResult score={computeScore()} answers={answers} />
                ) : (
                  <div style={{textAlign: 'center'}}>
                    <div style={{
                      width: 80, height: 80, borderRadius: 40, background: 'var(--coral-soft)', 
                      display: 'flex', alignItems: 'center', justifyContent: 'center', margin: '0 auto 24px',
                    }}>
                      <svg width="36" height="36" viewBox="0 0 24 24" fill="none" stroke="var(--coral)" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><polyline points="20 6 9 17 4 12"/></svg>
                    </div>
                    <h2 className="result-h2" style={{fontSize: 36, marginBottom: 16}}>Application received.</h2>
                    <p className="result-p" style={{fontSize: 17, color: 'var(--muted-text)', marginBottom: 32}}>We review every application within 48 hours. If we're a good fit, we'll reach out to schedule a Q-Commerce Audit.</p>
                    <a href="#calendar" className="btn btn-primary">Want to skip the queue? Book a call directly →</a>
                  </div>
                )}
              </div>
            </FadeUp>
          )}
        </div>
      </section>

      {/* Calendar embed */}
      <section id="calendar" className="section bg-light">
        <div className="container">
          <div className="section-head" style={{textAlign: 'center', margin: '0 auto 48px'}}>
            <FadeUp><span className="eyebrow">DIRECT BOOKING</span></FadeUp>
            <FadeUp delay={100}><h2>Book a 30-minute Q-Commerce Audit</h2></FadeUp>
            <FadeUp delay={200}><p style={{color: 'var(--muted-text)', fontSize: 17}}>Free. No commitment. We'll review your brand's q-commerce opportunity and give you a clear action plan.</p></FadeUp>
          </div>
          <div style={{maxWidth: 720, margin: '0 auto'}}>
            <div className="cal-embed" style={{
              background: 'white', borderRadius: 20, padding: 48, border: '1px dashed var(--border)', textAlign: 'center',
              minHeight: 280, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
            }}>
              <div style={{fontFamily: 'var(--mono)', fontSize: 12, color: 'var(--muted-text)', textTransform: 'uppercase', letterSpacing: '0.1em', marginBottom: 12}}>[ Calendar embed ]</div>
              <div style={{fontSize: 16, color: 'var(--body-text)', marginBottom: 24}}>Cal.com / similar widget connected to <strong style={{color: 'var(--dark-text)'}}>sales@mantaga.com</strong></div>
              <div style={{display: 'grid', gridTemplateColumns: 'repeat(7, 1fr)', gap: 8, width: '100%', maxWidth: 420}}>
                {Array.from({length: 21}).map((_, i) => (
                  <div key={i} style={{
                    aspectRatio: 1, borderRadius: 8, 
                    background: i === 9 ? 'var(--coral)' : 'var(--light-gray)',
                    color: i === 9 ? 'white' : 'var(--dark-text)',
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                    fontSize: 12, fontWeight: 600,
                  }}>{i+1}</div>
                ))}
              </div>
            </div>
            <div style={{marginTop: 32, padding: 24, background: 'white', borderRadius: 12, border: '1px solid var(--border)'}}>
              <div style={{display: 'flex', alignItems: 'center', gap: 16}}>
                <div style={{width: 48, height: 48, borderRadius: 24, background: 'var(--navy)', display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'white', fontFamily: 'var(--display)', fontWeight: 700}}>AP</div>
                <div>
                  <div style={{fontWeight: 600, color: 'var(--dark-text)'}}>Anush Prabhu</div>
                  <div style={{fontSize: 13, color: 'var(--muted-text)'}}>Managing Director & Founder · <a href="mailto:sales@mantaga.com" style={{color: 'var(--coral)'}}>sales@mantaga.com</a></div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </section>
    </div>
  );
}

function ReadinessResult({score, answers}) {
  const [animScore, setAnimScore] = useState(0);
  useEffect(() => {
    const start = performance.now();
    const tick = (t) => {
      const p = Math.min(1, (t - start) / 1500);
      const ease = 1 - Math.pow(1 - p, 3);
      setAnimScore(score * ease);
      if (p < 1) requestAnimationFrame(tick);
    };
    requestAnimationFrame(tick);
  }, [score]);

  const C = 2 * Math.PI * 88;
  const offset = C - (animScore / 10) * C;
  const platforms = answers.q3 || [];
  const platformCount = platforms.filter(p => !p.startsWith('None')).length;

  const insights = [
    {
      label: 'Platform Coverage',
      text: platformCount === 0
        ? "You haven't started yet. The first 30 days of a launch are critical — get the right platforms first."
        : `You're on ${platformCount} of 4 major platforms. Expanding to the missing ones could increase your reach by ${Math.round((4-platformCount) * 18)}%.`,
    },
    {
      label: 'Portfolio Size',
      text: answers.q2 === '50+ brands' || answers.q2 === '16-50 brands'
        ? `With ${answers.q2}, you need systematic management — not ad-hoc listings.`
        : `${answers.q2 || 'Your portfolio'} fits well into our managed-operations model.`,
    },
    {
      label: 'Next Step',
      text: 'A 30-minute Q-Commerce Audit would give you a clear action plan tailored to your portfolio.',
    },
  ];

  return (
    <div style={{textAlign: 'center'}}>
      <div className="score-circle">
        <svg viewBox="0 0 200 200" style={{transform: 'rotate(-90deg)'}}>
          <circle cx="100" cy="100" r="88" fill="none" stroke="var(--border)" strokeWidth="8"/>
          <circle cx="100" cy="100" r="88" fill="none" stroke="var(--coral)" strokeWidth="8" strokeLinecap="round"
                  strokeDasharray={C} strokeDashoffset={offset} style={{transition: 'stroke-dashoffset 0.1s'}}/>
        </svg>
        <div style={{position: 'absolute', inset: 0, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center'}}>
          <div className="score-ring-text" style={{fontFamily: 'var(--display)', fontSize: 56, fontWeight: 800, color: 'var(--dark-text)', lineHeight: 1, letterSpacing: '-0.03em'}}>{animScore.toFixed(1)}</div>
          <div style={{fontFamily: 'var(--mono)', fontSize: 11, color: 'var(--muted-text)', textTransform: 'uppercase', letterSpacing: '0.1em', marginTop: 4}}>/ 10</div>
        </div>
      </div>
      <span className="pill pill-coral" style={{marginBottom: 16}}>YOUR READINESS SCORE</span>
      <h2 className="result-h2" style={{fontSize: 32, marginBottom: 16}}>{score >= 7 ? 'Ready to scale.' : score >= 4 ? 'Foundation in place.' : 'Early stage — but room to grow.'}</h2>
      <p style={{color: 'var(--muted-text)', fontSize: 17, marginBottom: 48, maxWidth: 540, margin: '0 auto 48px'}}>
        Based on your answers, here's what we'd recommend.
      </p>
      <div className="grid-3" style={{textAlign: 'left', marginBottom: 48}}>
        {insights.map((ins, i) => (
          <div key={i} className="card" style={{padding: 24}}>
            <div style={{fontFamily: 'var(--mono)', fontSize: 11, color: 'var(--coral)', textTransform: 'uppercase', letterSpacing: '0.1em', marginBottom: 12}}>{ins.label}</div>
            <p style={{fontSize: 14.5, color: 'var(--body-text)', lineHeight: 1.55}}>{ins.text}</p>
          </div>
        ))}
      </div>
      <a href="#calendar" className="btn btn-primary">Book Your Q-Commerce Audit →</a>
    </div>
  );
}

window.ContactPage = ContactPage;
