// fairfarms.com — trade enquiry form
const { Eyebrow, Button, Card, Input, Select, Textarea, Fieldset, Checkbox, Radio, Toast, ToastRegion, Icon, DataList } = window.FF;

const PRODUCTS = [
  'Black pepper, Kampot PGI',
  'Red pepper, Kampot PGI',
  'White pepper, Kampot PGI',
  'Long pepper',
  'Other spice or produce',
];

const COUNTRIES = ['France', 'Germany', 'Japan', 'Netherlands', 'United Kingdom', 'United States', 'Australia', 'Singapore', 'Other'];

const EMPTY = {
  company: '', country: '', name: '', email: '',
  products: [], volume: '', incoterm: 'FOB Sihanoukville',
  message: '', certificates: true,
};

const FIELD_LABEL = {
  company: 'Company', country: 'Country of import', name: 'Your name', email: 'Work email',
  products: 'What you need', volume: 'Indicative annual volume',
};

function validate(v) {
  const e = {};
  if (!v.company.trim()) e.company = 'Enter the company on the import licence.';
  if (!v.country) e.country = 'Select the country of import.';
  if (!v.name.trim()) e.name = 'Enter the name we should reply to.';
  if (!v.email.trim()) e.email = 'Enter a work email so we can send the quote.';
  else if (!/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(v.email.trim())) e.email = 'This address is incomplete — check the domain.';
  if (!v.products.length) e.products = 'Select at least one product.';
  if (!v.volume.trim()) e.volume = 'Enter an indicative volume, in kilograms.';
  else if (!/^\d[\d\s]*$/.test(v.volume.trim())) e.volume = 'Use whole kilograms, digits only.';
  else if (Number(v.volume.replace(/\s/g, '')) < 25) e.volume = 'Minimum order is 25 kg.';
  return e;
}

function Enquiry() {
  const [v, setV] = React.useState(EMPTY);
  const [errors, setErrors] = React.useState({});
  const [status, setStatus] = React.useState('idle'); // idle · submitting
  const [sent, setSent] = React.useState(null);
  const summaryRef = React.useRef(null);

  const set = (k) => (val) => {
    setV((s) => ({ ...s, [k]: val }));
    // Once a field has been called out, correct it as the user types — never re-validate
    // a field they have not reached yet.
    setErrors((s) => (s[k] ? { ...s, [k]: undefined } : s));
  };

  const toggleProduct = (p) => {
    setV((s) => ({ ...s, products: s.products.includes(p) ? s.products.filter((x) => x !== p) : [...s.products, p] }));
    setErrors((s) => (s.products ? { ...s, products: undefined } : s));
  };

  const onSubmit = (e) => {
    e.preventDefault();
    if (status === 'submitting') return;
    const found = validate(v);
    const keys = Object.keys(found);
    if (keys.length) {
      setErrors(found);
      window.requestAnimationFrame(() => {
        if (summaryRef.current) summaryRef.current.focus();
      });
      return;
    }
    setErrors({});
    setStatus('submitting');
    setTimeout(() => {
      setStatus('idle');
      setSent({ ref: 'FF-ENQ-2026-' + String(184 + Math.floor(Math.random() * 40)).padStart(4, '0'), company: v.company.trim() });
      setV(EMPTY);
    }, 1200);
  };

  const invalidKeys = Object.keys(errors).filter((k) => errors[k]);
  const submitting = status === 'submitting';

  return (
    <section id="enquiry" style={{ maxWidth: 'var(--container)', margin: '0 auto', padding: 'var(--space-12) var(--space-6)' }}>
      <Eyebrow>Trade enquiry</Eyebrow>
      <div style={{ display: 'grid', gridTemplateColumns: '1.5fr 1fr', gap: 'var(--space-10)', alignItems: 'end', margin: '16px 0 var(--space-9)' }}>
        <h2 style={{ margin: 0, font: 'var(--type-display-3)', color: 'var(--text-strong)', textWrap: 'pretty', maxWidth: '20ch' }}>
          Tell us what you need. We quote from the lot register.
        </h2>
        <p style={{ margin: 0, font: 'var(--type-body)', color: 'var(--text-muted)' }}>
          Every quote names the lots it comes from, with grade, moisture and the commune that
          grew it. One working day, from a person.
        </p>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1.5fr 1fr', gap: 'var(--space-10)', alignItems: 'start' }}>
        <form noValidate onSubmit={onSubmit} style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-6)' }}>
          {invalidKeys.length ? (
            <div
              ref={summaryRef}
              tabIndex={-1}
              role="alert"
              style={{
                display: 'flex', gap: 12, padding: 'var(--space-4) var(--space-5)',
                background: 'var(--status-danger-soft)', borderRadius: 'var(--radius-md)',
                borderLeft: '2px solid var(--ff-pepper)', outline: 'none',
              }}
            >
              <Icon name="alert-circle" size={18} style={{ color: 'var(--ff-pepper)', marginTop: 2, flex: '0 0 auto' }} />
              <div>
                <p style={{ margin: 0, font: 'var(--type-body-sm)', fontSize: 15, fontWeight: 600, color: 'var(--text-strong)' }}>
                  {invalidKeys.length === 1 ? 'One field needs attention' : invalidKeys.length + ' fields need attention'}
                </p>
                <ul style={{ margin: '6px 0 0', padding: 0, listStyle: 'none', display: 'flex', flexWrap: 'wrap', gap: '4px 16px' }}>
                  {invalidKeys.map((k) => (
                    <li key={k} style={{ font: 'var(--type-body-sm)', fontSize: 13, color: 'var(--text-muted)' }}>{FIELD_LABEL[k]}</li>
                  ))}
                </ul>
              </div>
            </div>
          ) : null}

          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 'var(--space-5)' }}>
            <Input
              id="enq-company" label="Company" required
              hint={errors.company ? undefined : 'As it appears on the import licence.'}
              error={errors.company} value={v.company} disabled={submitting}
              onChange={(e) => set('company')(e.target.value)}
            />
            <Select
              id="enq-country" label="Country of import" error={errors.country} value={v.country} disabled={submitting}
              onChange={(e) => set('country')(e.target.value)}
            >
              <option value="">Select a country</option>
              {COUNTRIES.map((c) => <option key={c} value={c}>{c}</option>)}
            </Select>
            <Input
              id="enq-name" label="Your name" required error={errors.name} value={v.name} disabled={submitting}
              onChange={(e) => set('name')(e.target.value)}
            />
            <Input
              id="enq-email" label="Work email" type="email" required error={errors.email} value={v.email} disabled={submitting}
              onChange={(e) => set('email')(e.target.value)}
            />
          </div>

          <Fieldset legend="What you need" required layout="grid" columns={2} error={errors.products}>
            {PRODUCTS.map((p) => (
              <Checkbox key={p} label={p} checked={v.products.includes(p)} disabled={submitting} onChange={() => toggleProduct(p)} />
            ))}
          </Fieldset>

          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1.4fr', gap: 'var(--space-5)', alignItems: 'start' }}>
            <Input
              id="enq-volume" label="Indicative annual volume" suffix="kg" inputMode="numeric" required
              hint={errors.volume ? undefined : 'Minimum order 25 kg.'}
              error={errors.volume} value={v.volume} disabled={submitting}
              onChange={(e) => set('volume')(e.target.value)}
            />
            <Fieldset legend="Incoterm" layout="row">
              {['FOB Sihanoukville', 'CIF, your port', 'EXW Phnom Penh'].map((t) => (
                <Radio key={t} name="enq-incoterm" label={t} value={t} checked={v.incoterm === t} disabled={submitting} onChange={() => set('incoterm')(t)} />
              ))}
            </Fieldset>
          </div>

          <Textarea
            id="enq-message" label="Anything else" rows={4} maxLength={600} value={v.message} disabled={submitting}
            hint="Formats, private label, delivery windows, questions about the audit."
            onChange={(e) => set('message')(e.target.value)}
          />

          <Checkbox
            label="Send the certificates with the quote"
            hint="Fair for Life, USDA NOP Organic, EU Organic and the Kampot Pepper PGI packager certificate."
            checked={v.certificates} disabled={submitting}
            onChange={(e) => set('certificates')(e.target.checked)}
          />

          <div style={{ display: 'flex', alignItems: 'center', gap: 'var(--space-4)', paddingTop: 'var(--space-2)', borderTop: '1px solid var(--border-hairline)' }}>
            <Button type="submit" size="lg" disabled={submitting} iconAfter={submitting ? undefined : 'chevron-right'}>
              {submitting ? 'Sending enquiry…' : 'Send enquiry'}
            </Button>
            <span aria-live="polite" style={{ font: 'var(--type-body-sm)', fontSize: 13, color: 'var(--text-meta)' }}>
              {submitting ? 'Sending to the trade desk in Phnom Penh…' : 'We reply within one working day, ICT.'}
            </span>
          </div>
        </form>

        <Card padding="lg" tone="sunken">
          <h3 style={{ margin: '0 0 var(--space-5)', font: 'var(--type-title-2)', color: 'var(--text-strong)' }}>What happens next</h3>
          <ol style={{ margin: 0, padding: 0, listStyle: 'none', display: 'flex', flexDirection: 'column' }}>
            {[
              'We check your volume against the open lots and reserve what fits.',
              'You get a quote naming each lot, its grade, moisture and commune.',
              'Samples ship free up to 200 g, on your courier account or ours.',
            ].map((t, i) => (
              <li key={t} style={{ display: 'flex', gap: 14, padding: '12px 0', borderBottom: i < 2 ? '1px solid var(--border-hairline)' : 'none' }}>
                <span style={{ font: 'var(--type-mono)', fontSize: 12, color: 'var(--ff-pepper)', paddingTop: 3 }}>{'0' + (i + 1)}</span>
                <span style={{ font: 'var(--type-body-sm)', color: 'var(--text-body)' }}>{t}</span>
              </li>
            ))}
          </ol>
          <div style={{ marginTop: 'var(--space-6)' }}>
            <DataList
              dense
              items={[
                { label: 'Reply time', value: '1 working day', mono: true },
                { label: 'Minimum order', value: '25 kg', mono: true },
                { label: 'Free sample', value: '200 g', mono: true },
                { label: 'Sailing', value: 'Every 2nd Friday' },
              ]}
            />
          </div>
          <p style={{ margin: 'var(--space-6) 0 0', font: 'var(--type-body-sm)', fontSize: 13, color: 'var(--text-muted)' }}>
            Prefer email? <a href="mailto:trade@fairfarms.com.kh">trade@fairfarms.com.kh</a><br />
            Sales office: Phnom Penh, 08:00–17:00 ICT.
          </p>
        </Card>
      </div>

      <ToastRegion>
        <Toast
          open={Boolean(sent)}
          message="Enquiry received"
          detail={sent ? sent.ref + ' · we reply to ' + sent.company + ' within one working day.' : undefined}
          onClose={() => setSent(null)}
        />
      </ToastRegion>
    </section>
  );
}
window.Enquiry = Enquiry;
