// About + Industries + RFQ pages

const AboutPage = ({ setPage, lang }) => {
  return (
    <>
      <section className="about-hero">
        <div className="container">
          <div className="crumb" style={{ marginBottom: 24 }}>{t('about.crumb', lang)}</div>
          <div className="about-hero-grid">
            <div>
              <div className="eyebrow" style={{ marginBottom: 12 }}>{t('about.eyebrow', lang)}</div>
              <h1 className="h-display" style={{ fontSize: 'clamp(36px, 4.4vw, 56px)' }}>
                {t('about.titleA', lang)}<span style={{ fontStyle: 'italic', fontWeight: 400, color: 'var(--accent)' }}>{t('about.titleAccent', lang)}</span>{t('about.titleB', lang)}
              </h1>
              <p className="lede" style={{ marginTop: 24 }}>{t('about.lede', lang)}</p>
            </div>
            <div style={{ aspectRatio: '4/3', background: 'var(--bg-sunken)', border: '1px solid var(--line)', borderRadius: 'var(--radius)', position: 'relative', overflow: 'hidden' }}>
              <FactoryPhoto which="entrance" />
              <div style={{ position: 'absolute', top: 16, left: 16, fontFamily: 'JetBrains Mono', fontSize: 10, color: '#fff', background: 'oklch(0 0 0 / 0.7)', padding: '4px 10px', borderRadius: 'var(--radius-sm)', letterSpacing: '0.08em' }}>{t('about.factory', lang)}</div>
            </div>
          </div>
        </div>
      </section>

      <section>
        <div className="container">
          <div className="section-head">
            <div className="l">
              <div className="eyebrow">{t('about.tl.eyebrow', lang)}</div>
              <h2 className="h-1">{t('about.tl.title', lang)}</h2>
            </div>
          </div>
          <div className="timeline">
            {[
              { year: '2010', i: 1 }, { year: '2015', i: 2 }, { year: '2020', i: 3 }, { year: '2024', i: 4 }, { year: '2026', i: 5 },
            ].map(x => (
              <div key={x.year} className="tl-item">
                <div className="year">{x.year}</div>
                <h4>{t(`about.tl.${x.i}.t`, lang)}</h4>
                <p>{t(`about.tl.${x.i}.d`, lang)}</p>
              </div>
            ))}
          </div>
        </div>
      </section>

      <section style={{ background: 'var(--bg-sunken)', borderTop: '1px solid var(--line)', borderBottom: '1px solid var(--line)' }}>
        <div className="container">
          <div className="section-head">
            <div className="l">
              <div className="eyebrow">{t('about.num.eyebrow', lang)}</div>
              <h2 className="h-1">{t('about.num.title', lang)}</h2>
            </div>
          </div>
          <div className="about-num-grid">
            {[
              { n: '12,000', u: 'm²', i: 1 },
              { n: '15', u: lang === 'zh' ? '年' : 'years', i: 2 },
              { n: '23', u: lang === 'zh' ? '国家' : 'countries', i: 3 },
              { n: '260', u: lang === 'zh' ? '团队' : 'team', i: 4 },
            ].map((s, i) => (
              <div key={i} className="about-num-cell">
                <div className="ix">{String(i + 1).padStart(2, '0')}</div>
                <div className="num-row">
                  <span className="num">{s.n}</span>
                  <span className="unit">{s.u}</span>
                </div>
                <div className="lbl">{t(`about.num.${s.i}.l`, lang)}</div>
              </div>
            ))}
          </div>
        </div>
      </section>

      <section>
        <div className="container" style={{ textAlign: 'center', maxWidth: 720 }}>
          <div className="eyebrow" style={{ marginBottom: 12 }}>{t('about.cta.eyebrow', lang)}</div>
          <h2 className="h-1" style={{ marginBottom: 16 }}>{t('about.cta.title', lang)}</h2>
          <p className="lede" style={{ margin: '0 auto 32px' }}>{t('about.cta.lede', lang)}</p>
          <div style={{ display: 'flex', gap: 12, justifyContent: 'center' }}>
            <button className="btn btn-accent btn-lg" onClick={() => setPage('rfq')}>{t('about.cta.1', lang)} <Arrow /></button>
            <button className="btn btn-ghost btn-lg" onClick={() => setPage('products')}>{t('about.cta.2', lang)}</button>
          </div>
        </div>
      </section>
    </>
  );
};

const IndustriesPage = ({ setPage, lang }) => {
  return (
    <>
      <section style={{ padding: '64px 0 32px', borderBottom: '1px solid var(--line)' }}>
        <div className="container">
          <div className="crumb" style={{ marginBottom: 16 }}>{lang === 'zh' ? '/ 首页 / 行业应用' : '/ HOME / INDUSTRIES'}</div>
          <div className="eyebrow" style={{ marginBottom: 12 }}>{t('ind.applications', lang)}</div>
          <h1 className="h-display" style={{ fontSize: 'clamp(36px, 4.4vw, 56px)' }}>{t('ind.pageTitle', lang)}</h1>
        </div>
      </section>
      <section>
        <div className="container">
          <div className="industries-page-grid">
            {INDUSTRIES.map((ind, i) => (
              <div key={ind.id} className="industries-page-cell">
                <div>
                  <div className="ix">{String(i + 1).padStart(2, '0')} / {String(INDUSTRIES.length).padStart(2, '0')}</div>
                  <h3 className="h-2" style={{ marginBottom: 12 }}>{t(`ind.${ind.id}.l`, lang)}</h3>
                  <p className="desc">{t(`ind.${ind.id}.d`, lang)}{t('ind.cellExtra', lang)}</p>
                  <button className="btn btn-ghost btn-sm" onClick={() => setPage('products')}>{t('ind.recommended', lang)} <Arrow size={12} /></button>
                </div>
                <div className="icon"><IndIcon name={ind.id} /></div>
              </div>
            ))}
          </div>
        </div>
      </section>
    </>
  );
};

const TURNSTILE_SITE_KEY = '0x4AAAAAADIMjmlPlJkWWBmt';

const RfqPage = ({ lang }) => {
  const [submitted, setSubmitted] = React.useState(false);
  const [submitting, setSubmitting] = React.useState(false);
  const [submitError, setSubmitError] = React.useState(null);
  const [refId, setRefId] = React.useState('');
  const [errors, setErrors] = React.useState({});
  const [form, setForm] = React.useState({ name: '', email: '', company: '', country: '', industry: '', message: '', website: '' });
  const [lines, setLines] = React.useState([{ sku: 'MG-100-SS', qty: 100 }]);
  const [turnstileToken, setTurnstileToken] = React.useState('');
  const turnstileRef = React.useRef(null);
  const turnstileWidgetId = React.useRef(null);

  React.useEffect(() => {
    let cancelled = false;
    const mount = () => {
      if (cancelled || !turnstileRef.current || !window.turnstile) return;
      // Already rendered? Skip
      if (turnstileWidgetId.current !== null) return;
      turnstileWidgetId.current = window.turnstile.render(turnstileRef.current, {
        sitekey: TURNSTILE_SITE_KEY,
        callback: (token) => setTurnstileToken(token),
        'error-callback': () => setTurnstileToken(''),
        'expired-callback': () => setTurnstileToken(''),
        'timeout-callback': () => setTurnstileToken(''),
        theme: 'light',
        appearance: 'always',
      });
    };
    if (window.turnstile) mount();
    else {
      // Script may load after this effect runs
      const interval = setInterval(() => { if (window.turnstile) { clearInterval(interval); mount(); } }, 200);
      return () => { cancelled = true; clearInterval(interval); };
    }
    return () => {
      cancelled = true;
      if (window.turnstile && turnstileWidgetId.current !== null) {
        try { window.turnstile.remove(turnstileWidgetId.current); } catch {}
        turnstileWidgetId.current = null;
      }
    };
  }, []);

  const onChange = (k) => (e) => setForm(f => ({ ...f, [k]: e.target.value }));

  const submit = async (e) => {
    e.preventDefault();
    const errs = {};
    if (!form.name.trim()) errs.name = t('rfq.f.err.required', lang);
    if (!/^\S+@\S+\.\S+$/.test(form.email)) errs.email = t('rfq.f.err.email', lang);
    if (!form.company.trim()) errs.company = t('rfq.f.err.required', lang);
    if (!turnstileToken) errs.turnstile = t('rfq.f.err.captcha', lang);
    setErrors(errs);
    if (Object.keys(errs).length > 0) return;

    setSubmitting(true);
    setSubmitError(null);
    const ref = `RFQ-${Date.now().toString().slice(-6)}`;
    try {
      const res = await fetch('/api/rfq', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ ...form, lines, lang, ref, 'cf-turnstile-response': turnstileToken }),
      });
      const data = await res.json().catch(() => ({}));
      if (!res.ok || !data.ok) {
        setSubmitError(data.error || `http_${res.status}`);
        setSubmitting(false);
        // Reset Turnstile on failure so user can retry
        if (window.turnstile && turnstileWidgetId.current !== null) {
          try { window.turnstile.reset(turnstileWidgetId.current); } catch {}
          setTurnstileToken('');
        }
        return;
      }
      setRefId(data.ref || ref);
      setSubmitted(true);
    } catch (err) {
      setSubmitError('network');
    } finally {
      setSubmitting(false);
    }
  };

  if (submitted) {
    return (
      <div className="container">
        <div className="rfq-layout">
          <div></div>
          <div className="rfq-success">
            <div className="check">✓</div>
            <h2 className="h-2" style={{ marginBottom: 8 }}>{t('rfq.s.title', lang)}</h2>
            <p style={{ color: 'var(--ink-2)', marginBottom: 24 }}>{t('rfq.s.ref', lang)} <span style={{ fontFamily: 'JetBrains Mono' }}>{refId}</span></p>
            <p style={{ color: 'var(--ink-2)', maxWidth: '40ch', margin: '0 auto', lineHeight: 1.6 }}>
              {t('rfq.s.body.a', lang)}<strong>{form.email}</strong>。
            </p>
            <button className="btn btn-ghost" style={{ marginTop: 32 }} onClick={() => { setSubmitted(false); setForm({ name: '', email: '', company: '', country: '', industry: '', message: '', website: '' }); }}>
              {t('rfq.s.again', lang)}
            </button>
          </div>
        </div>
      </div>
    );
  }

  return (
    <>
      <section style={{ padding: '48px 0 0' }}>
        <div className="container">
          <div className="crumb">{t('rfq.crumb', lang)}</div>
        </div>
      </section>
      <div className="container">
        <div className="rfq-layout">
          <div className="rfq-side">
            <div className="eyebrow" style={{ marginBottom: 12 }}>{t('rfq.eyebrow', lang)}</div>
            <h1 className="h-display" style={{ fontSize: 'clamp(32px, 3.6vw, 48px)' }}>{t('rfq.title', lang)}</h1>
            <p style={{ marginTop: 16 }}>{t('rfq.lede', lang)}</p>
            <div className="rfq-promise">
              {[1,2,3].map(i => (
                <div key={i} className="rfq-promise-item">
                  <div className="n">{String(i).padStart(2, '0')}</div>
                  <div className="t"><strong>{t(`rfq.p.${i}`, lang)}</strong>{t(`rfq.p.${i}d`, lang)}</div>
                </div>
              ))}
            </div>
            <ContactDetails lang={lang} />
          </div>
          <form className="form" onSubmit={submit}>
            {/* Spam honeypot — real users don't fill this; bots do */}
            <input
              type="text"
              name="website"
              tabIndex="-1"
              autoComplete="off"
              value={form.website}
              onChange={onChange('website')}
              style={{ position: 'absolute', left: '-10000px', width: 1, height: 1, opacity: 0 }}
              aria-hidden="true"
            />
            <div className="form-row">
              <div className="field">
                <label>{t('rfq.f.name', lang)}</label>
                <input value={form.name} onChange={onChange('name')} placeholder={t('rfq.f.name.ph', lang)} />
                {errors.name && <div className="field-error">{errors.name}</div>}
              </div>
              <div className="field">
                <label>{t('rfq.f.email', lang)}</label>
                <input type="email" value={form.email} onChange={onChange('email')} placeholder={t('rfq.f.email.ph', lang)} />
                {errors.email && <div className="field-error">{errors.email}</div>}
              </div>
            </div>
            <div className="form-row">
              <div className="field">
                <label>{t('rfq.f.company', lang)}</label>
                <input value={form.company} onChange={onChange('company')} placeholder={t('rfq.f.company.ph', lang)} />
                {errors.company && <div className="field-error">{errors.company}</div>}
              </div>
              <div className="field">
                <label>{t('rfq.f.country', lang)}</label>
                <input
                  list="rfq-countries"
                  value={form.country}
                  onChange={onChange('country')}
                  placeholder={lang === 'zh' ? '搜索或选择国家…' : 'Search or pick a country…'}
                  autoComplete="country-name"
                />
                <datalist id="rfq-countries">
                  {[...COUNTRIES].sort((a, b) => (lang === 'zh' ? a.zh.localeCompare(b.zh, 'zh') : a.en.localeCompare(b.en))).map(c => (
                    <option key={c.en} value={lang === 'zh' ? c.zh : c.en} />
                  ))}
                </datalist>
              </div>
            </div>
            <div className="form-row full">
              <div className="field">
                <label>{t('rfq.f.industry', lang)}</label>
                <select value={form.industry} onChange={onChange('industry')}>
                  <option value="">{t('rfq.f.industry.placeholder', lang)}</option>
                  {INDUSTRIES.map(i => <option key={i.id} value={i.id}>{t(`ind.${i.id}.l`, lang)}</option>)}
                  <option value="other">{t('rfq.f.industry.other', lang)}</option>
                </select>
              </div>
            </div>

            <div className="field" style={{ marginBottom: 16 }}>
              <label>{t('rfq.f.lines', lang)}</label>
              <div className="rfq-line-items">
                {lines.map((l, i) => (
                  <div key={i} className="rfq-line">
                    <input value={l.sku} onChange={e => setLines(ls => ls.map((x, j) => j === i ? { ...x, sku: e.target.value } : x))} placeholder={t('rfq.f.sku.ph', lang)} style={{ padding: '8px 10px', border: '1px solid var(--line)', borderRadius: 'var(--radius)', background: 'var(--bg)', fontSize: 13 }} />
                    <input type="number" value={l.qty} onChange={e => setLines(ls => ls.map((x, j) => j === i ? { ...x, qty: +e.target.value } : x))} placeholder={t('rfq.f.qty.ph', lang)} style={{ padding: '8px 10px', border: '1px solid var(--line)', borderRadius: 'var(--radius)', background: 'var(--bg)', fontSize: 13, fontFamily: 'JetBrains Mono' }} />
                    <button type="button" className="x" onClick={() => setLines(ls => ls.filter((_, j) => j !== i))}>✕</button>
                  </div>
                ))}
                <button type="button" className="btn btn-ghost btn-sm" onClick={() => setLines(ls => [...ls, { sku: '', qty: 1 }])} style={{ marginTop: 8 }}>{t('rfq.f.addLine', lang)}</button>
              </div>
            </div>

            <div className="form-row full">
              <div className="field">
                <label>{t('rfq.f.notes', lang)}</label>
                <textarea value={form.message} onChange={onChange('message')} placeholder={t('rfq.f.notes.ph', lang)} />
              </div>
            </div>

            <div style={{ marginTop: 16, display: 'flex', flexDirection: 'column', gap: 4 }}>
              <div ref={turnstileRef} />
              {errors.turnstile && <div className="field-error">{errors.turnstile}</div>}
            </div>
            {submitError && (
              <div style={{ marginTop: 16, padding: '12px 14px', border: '1px solid oklch(0.62 0.18 25 / 0.4)', background: 'oklch(0.62 0.18 25 / 0.08)', borderRadius: 'var(--radius)', fontSize: 13, color: 'oklch(0.45 0.18 25)' }}>
                {t('rfq.f.err.send', lang)}{submitError === 'network' ? '' : ` (${submitError})`}
              </div>
            )}
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginTop: 16 }}>
              <p style={{ fontSize: 12, color: 'var(--ink-3)', fontFamily: 'JetBrains Mono' }}>{t('rfq.f.required', lang)}</p>
              <button type="submit" className="btn btn-accent btn-lg" disabled={submitting} style={submitting ? { opacity: 0.6, cursor: 'wait' } : {}}>
                {submitting ? t('rfq.f.submitting', lang) : t('rfq.f.submit', lang)} <Arrow />
              </button>
            </div>
          </form>
        </div>
      </div>
      <BusinessHours lang={lang} />
      <FaqBlock lang={lang} />
    </>
  );
};

Object.assign(window, { AboutPage, IndustriesPage, RfqPage });
