// Trade.jsx — trade-account enquiry form.
//
// Different conversion path from /#quote — this is for interior
// designers, architects, builders, retailers and other specifiers
// who want trade pricing, account setup, or bulk-volume support.
//
// Same submit target as Quote (/api/contact) but with a "Trade
// enquiry" subject so the studio inbox can sort them.
//
// Layout mirrors the compact Quote form — fits on one screen.

const { useState } = React;

function Trade({ navigate }) {
  const [form, setForm] = useState({
    name: '',
    role: '',
    business: '',
    tradeType: '',
    email: '',
    phone: '',
    volume: '',
    website: '',
    notes: '',
  });
  const [submitting, setSubmitting] = useState(false);
  const [submitted, setSubmitted]   = useState(false);
  const [error, setError]           = useState(null);

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

  async function handleSubmit(e) {
    e.preventDefault();
    if (!form.name || !form.email || !form.business) {
      setError('Name, business and email are required.');
      return;
    }
    setSubmitting(true);
    setError(null);
    try {
      // Plain ASCII, same labelled-list style as Quote.jsx so the
      // studio reads both kinds of submission the same way. No
      // Unicode characters — keeps the email readable in every
      // client regardless of charset handling.
      const notesBlock = form.notes && form.notes.trim()
        ? form.notes.split('\n').map(l => '  ' + l).join('\n')
        : '  (no notes)';

      const lines = [
        'BUSINESS DETAILS',
        `  Business name:   ${form.business}`,
        `  Role:            ${form.role      || '(not specified)'}`,
        `  Trade type:      ${form.tradeType || '(not specified)'}`,
        `  Website:         ${form.website   || '(not provided)'}`,
        '',
        'EXPECTED VOLUME',
        `  Estimated annual purchase volume: ${form.volume || '(not specified)'}`,
        '',
        'NOTES FROM ENQUIRER',
        notesBlock,
      ].join('\n');

      // Subject — readable at a glance in the studio inbox.
      // Example: "Trade enquiry from Marble Studio Ltd (Interior Designer)"
      const typeBit = form.tradeType ? ` (${form.tradeType})` : '';
      const subject = `Trade enquiry from ${form.business}${typeBit}`;

      const r = await fetch('/api/contact', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          name:    form.name,
          email:   form.email,
          phone:   form.phone,
          subject,
          message: lines,
        }),
      });
      // /api/contact now exists server-side and returns proper status
      // codes (400 validation, 429 rate-limited, 500 server error).
      // Surface the error to the user instead of pretending success.
      if (!r.ok) {
        const data = await r.json().catch(() => ({}));
        throw new Error(data.error || `HTTP ${r.status}`);
      }
      setSubmitted(true);
    } catch (err) {
      setError(err.message || 'Something went wrong. Please email the studio instead.');
    } finally {
      setSubmitting(false);
    }
  }

  if (submitted) return (
    <div style={{
      paddingTop: 'var(--nav-h)', minHeight: '100vh',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      flexDirection: 'column', textAlign: 'center', padding: '40px',
      background: 'var(--cream)',
    }}>
      <div style={{
        width: '64px', height: '64px', borderRadius: '50%',
        background: 'var(--dark)',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        margin: '0 auto 32px',
      }}>
        <svg width="24" height="24" viewBox="0 0 24 24" fill="none">
          <polyline points="4,12 9,17 20,6" stroke="white" strokeWidth="1.5"/>
        </svg>
      </div>
      <p className="t-label" style={{ color: 'var(--terracotta)', marginBottom: '16px' }}>Trade enquiry received</p>
      <h1 style={{
        fontFamily: 'var(--serif)', fontSize: 'clamp(34px, 5vw, 60px)',
        fontWeight: 300, marginBottom: '20px',
      }}>
        We'll be in touch<br/><em>shortly</em>
      </h1>
      <p style={{
        fontFamily: 'var(--sans)', fontWeight: 300, fontSize: '15px',
        color: 'var(--dark-mid)', maxWidth: '480px', lineHeight: 1.7, marginBottom: '40px',
      }}>
        Thanks {form.name.split(' ')[0]}. The studio has your trade enquiry from <strong>{form.business}</strong> and we'll come back to <strong>{form.email}</strong> with trade pricing details and any next-step paperwork.
      </p>
      <button onClick={() => navigate('collections')} className="btn btn-dark" style={{ padding: '14px 32px' }}>
        Browse the catalogue →
      </button>
    </div>
  );

  return (
    <div style={{ paddingTop: 'var(--nav-h)', minHeight: '100vh', background: 'var(--cream)' }}>
      <div style={{
        maxWidth: '880px',
        margin: '0 auto',
        padding: 'clamp(20px, 2.4vw, 32px) clamp(20px, 4vw, 36px) clamp(20px, 2.4vw, 32px)',
      }}>
        {/* Compact header */}
        <div style={{ marginBottom: '18px' }}>
          <p className="t-label" style={{ color: 'var(--terracotta)', marginBottom: '6px' }}>Trade Enquiry</p>
          <h1 style={{
            fontFamily: 'var(--serif)', fontWeight: 300,
            fontSize: 'clamp(26px, 2.8vw, 36px)', lineHeight: 1.05,
          }}>
            Open a <em>trade account</em>
          </h1>
        </div>

        <form onSubmit={handleSubmit} className="trade-form">
          {/* Row 1 — Name · Role · Business */}
          <div className="trade-row trade-row-3">
            <Field label="Your name *" v={form.name}    onChange={set('name')}/>
            <Field label="Role"        v={form.role}    onChange={set('role')}    placeholder="e.g. Principal, Specifier"/>
            <Field label="Business *"  v={form.business} onChange={set('business')} placeholder="Studio / firm"/>
          </div>

          {/* Row 2 — Trade type · Email · Phone */}
          <div className="trade-row trade-row-3">
            <SelectField label="Trade type" v={form.tradeType} onChange={set('tradeType')}
              options={[
                '',
                'Interior Designer',
                'Architect',
                'Builder / Contractor',
                'Retailer',
                'Property Developer',
                'Specifier',
                'Other',
              ]}/>
            <Field label="Email *" v={form.email} onChange={set('email')} type="email"/>
            <Field label="Phone"   v={form.phone} onChange={set('phone')} type="tel"/>
          </div>

          {/* Row 3 — Volume · Website */}
          <div className="trade-row trade-row-2">
            <Field label="Estimated annual volume" v={form.volume}  onChange={set('volume')}  placeholder="e.g. 200 m² / year, or £25k"/>
            <Field label="Website / portfolio"     v={form.website} onChange={set('website')} placeholder="https://"/>
          </div>

          {/* Notes — full width */}
          <Field label="What you're looking for" v={form.notes} onChange={set('notes')}
            multiline rows={2}
            placeholder="Project types, preferred ranges, account terms, anything you'd like us to know"/>

          {/* Action */}
          <div className="trade-action">
            <button type="submit" className="btn btn-dark" disabled={submitting}
              style={{ padding: '12px 28px' }}>
              {submitting ? 'Sending…' : 'Open trade account  →'}
            </button>
            <p style={{ fontFamily: 'var(--sans)', fontSize: '11px', color: 'var(--dark-mid)', letterSpacing: '0.04em' }}>
              Trade enquiry · Confidential.
            </p>
          </div>

          {error && (
            <p style={{ fontFamily: 'var(--sans)', fontSize: '12px', color: 'var(--terracotta)', marginTop: '4px' }}>{error}</p>
          )}
        </form>

        <style>{`
          .trade-form { display: flex; flex-direction: column; gap: 14px; }
          .trade-row { display: grid; gap: 14px; }
          .trade-row-3 { grid-template-columns: 1fr 1fr 1fr; }
          .trade-row-2 { grid-template-columns: 1fr 1fr; }
          .trade-action {
            display: flex; align-items: center; gap: 18px;
            flex-wrap: wrap; padding-top: 4px;
          }
          @media (max-width: 720px) {
            .trade-row-3, .trade-row-2 { grid-template-columns: 1fr !important; }
          }
        `}</style>
      </div>
    </div>
  );
}

// ─── Field helpers — same visual style as Quote.jsx ────────────────
function Field({ label, v, onChange, type='text', placeholder, multiline, rows=2, inputMode }) {
  return (
    <label style={{ display: 'block' }}>
      <span style={{
        display: 'block', fontFamily: 'var(--sans)', fontSize: '10px',
        letterSpacing: '0.14em', textTransform: 'uppercase',
        color: 'var(--dark-mid)', marginBottom: '5px',
      }}>{label}</span>
      {multiline ? (
        <textarea value={v} onChange={onChange} rows={rows} placeholder={placeholder}
          style={{ ...fieldStyle, resize: 'vertical', minHeight: '54px' }}/>
      ) : (
        <input type={type} value={v} onChange={onChange} placeholder={placeholder} inputMode={inputMode}
          style={fieldStyle}/>
      )}
    </label>
  );
}
function SelectField({ label, v, onChange, options }) {
  return (
    <label style={{ display: 'block' }}>
      <span style={{
        display: 'block', fontFamily: 'var(--sans)', fontSize: '10px',
        letterSpacing: '0.14em', textTransform: 'uppercase',
        color: 'var(--dark-mid)', marginBottom: '5px',
      }}>{label}</span>
      <select value={v} onChange={onChange} style={fieldStyle}>
        {options.map(o => <option key={o} value={o}>{o || '— Select —'}</option>)}
      </select>
    </label>
  );
}
const fieldStyle = {
  width: '100%',
  background: 'white',
  border: '1px solid var(--cream-deep)',
  borderRadius: 0,
  padding: '9px 13px',
  fontFamily: 'var(--sans)', fontSize: '14px',
  color: 'var(--dark)',
  outline: 'none',
  transition: 'border-color 0.2s',
};

Object.assign(window, { Trade });
