// Quote.jsx — single-page "Request a Quote" form.
//
// Replaces the deleted SampleOrder 3-step sample flow. The brand has
// pivoted off the free-samples model; quoting is now the primary
// conversion path. Form posts to /api/contact (an existing endpoint
// in the venoraa-ceramics server.js that emails MAIL_TO via SMTP).
// On success the form swaps for a thank-you state.
//
// Pre-fill: when navigated from a tile detail page or cart, the
// caller can pass `prefill` data via App's pageData (e.g. tiles of
// interest, sqm). This component reads it from props.

const { useState } = React;

function Quote({ navigate, prefill }) {
  // Each tile line now carries up to three measurements:
  //   name  (chosen size)  —  N.NN m²  ·  N pcs
  // Any of the three trailing bits drops out cleanly if the
  // customer didn't fill it in, so we never email a line like
  // "HERMES CREAM () — 0 m² · 0 pcs" to the studio.
  const tilesPrefill = (prefill && Array.isArray(prefill.tiles))
    ? prefill.tiles.map(t => {
        const bits = [];
        if (t.sqm) bits.push(`${t.sqm} m²`);
        if (t.qty) bits.push(`${t.qty} pcs`);
        const sizeStr = t.size ? ' (' + t.size + ')' : '';
        const measStr = bits.length ? ' — ' + bits.join(' · ') : '';
        return `${t.name}${sizeStr}${measStr}`;
      }).join('\n')
    : '';

  const [form, setForm] = useState({
    name: '',
    email: '',
    phone: '',
    address: '',
    postcode: '',
    project: '',         // residential / commercial / trade
    sqm: prefill?.sqm || '',
    tiles: tilesPrefill,
    timeline: '',        // e.g. "Within 2 weeks"
    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) { setError('Name and email are required.'); return; }
    setSubmitting(true);
    setError(null);
    try {
      // ─── Compose the email body ──────────────────────────────
      // PLAIN ASCII ONLY. We deliberately avoid Unicode characters
      // (the middle dot, the multiplication sign, the superscript-2
      // for m²) because some email transports / clients strip the
      // UTF-8 charset declaration and render them as garbage "?"
      // boxes. ASCII renders correctly in every mail client on every
      // OS, no encoding negotiation needed.
      //
      // Layout style: each section is labelled, each field gets a
      // full sentence rather than a cryptic column. Easier to read
      // on a phone (where columns break) and easier for the studio
      // to forward / copy-paste fragments.

      // — Tiles block —
      // Per-tile list, one tile per "card" of 3 lines so the studio
      // can scan down the page rather than across columns.
      let tilesBlock = '  (none specified)';
      let tileCount  = 0;
      if (prefill && Array.isArray(prefill.tiles) && prefill.tiles.length) {
        tileCount = prefill.tiles.length;
        tilesBlock = prefill.tiles.map((t, i) => {
          const sizeLine = t.size ? `     Size:     ${t.size} cm` : '';
          const measBits = [];
          if (t.sqm) measBits.push(`${t.sqm} sqm`);
          if (t.qty) measBits.push(`${t.qty} pieces`);
          const measLine = measBits.length ? `     Quantity: ${measBits.join('  /  ')}` : '';
          return [`  ${i + 1}. ${t.name}`, sizeLine, measLine].filter(Boolean).join('\n');
        }).join('\n\n');
      } else if (form.tiles && form.tiles.trim()) {
        // Customer pasted/edited the tiles textarea by hand — keep
        // their formatting, just indent it under the heading.
        tilesBlock = form.tiles.split('\n').map(l => '  ' + l).join('\n');
        tileCount = form.tiles.split('\n').filter(Boolean).length;
      }

      // — Address block —
      const addrLines = [form.address, form.postcode].filter(Boolean);
      const addrBlock = addrLines.length
        ? addrLines.map(l => '  ' + l).join('\n')
        : '  (not provided)';

      // — Notes block —
      const notesBlock = form.notes && form.notes.trim()
        ? form.notes.split('\n').map(l => '  ' + l).join('\n')
        : '  (no notes)';

      // Assemble — clear labels, full words, no fancy glyphs.
      const lines = [
        'PROJECT DETAILS',
        `  Project type:      ${form.project  || '(not specified)'}`,
        `  Estimated area:    ${form.sqm ? form.sqm + ' sqm' : '(not specified)'}`,
        `  Timeline:          ${form.timeline || '(not specified)'}`,
        '',
        `TILES OF INTEREST${tileCount ? ` (${tileCount})` : ''}`,
        tilesBlock,
        '',
        'NOTES FROM CUSTOMER',
        notesBlock,
        '',
        'DELIVERY ADDRESS (optional)',
        addrBlock,
      ].join('\n');

      // Subject — keeps the most useful bits visible in the inbox
      // list. Plain ASCII, simple separators.
      // Example: "Quote from Jane Doe - 24 sqm, 2 tiles (Residential)"
      const subjBits = [];
      if (form.sqm)      subjBits.push(`${form.sqm} sqm`);
      if (tileCount)     subjBits.push(`${tileCount} ${tileCount === 1 ? 'tile' : 'tiles'}`);
      const tail = subjBits.length ? ` - ${subjBits.join(', ')}` : '';
      const project = form.project ? ` (${form.project})` : '';
      const subject = `Quote from ${form.name}${tail}${project}`;

      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 returns 4xx on validation failure or 429 if
      // the IP rate-limit kicked in. Surface the server's error
      // string so the user knows exactly what went wrong, rather
      // than silently swallowing it like the old dev fallback did.
      if (!r.ok) {
        const data = await r.json().catch(() => ({}));
        throw new Error(data.error || `HTTP ${r.status}`);
      }
      setSubmitted(true);
    } catch (e) {
      setError(e.message || 'Something went wrong. Please email us at 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' }}>Quote requested</p>
      <h1 style={{ fontFamily: 'var(--serif)', fontSize: 'clamp(36px, 5vw, 64px)', 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: '460px', lineHeight: 1.7, marginBottom: '40px' }}>
        Thanks {form.name.split(' ')[0]}. The studio has your request and we'll come back to you at <strong>{form.email}</strong> with pricing, lead times and any questions about your project.
      </p>
      <button onClick={() => navigate('collections')} className="btn btn-dark" style={{ padding: '14px 32px' }}>Continue browsing →</button>
    </div>
  );

  return (
    <div style={{ paddingTop: 'var(--nav-h)', minHeight: '100vh', background: 'var(--cream)' }}>
      <div style={{
        maxWidth: '880px',
        margin: '0 auto',
        // Tight vertical padding so the whole form lands in a typical
        // ~900 px viewport without scroll.
        padding: 'clamp(20px, 2.4vw, 32px) clamp(20px, 4vw, 36px) clamp(20px, 2.4vw, 32px)',
      }}>
        {/* Compact header — eyebrow + headline. */}
        <div style={{ marginBottom: '18px' }}>
          <p className="t-label" style={{ color: 'var(--terracotta)', marginBottom: '6px' }}>Request a Quote</p>
          <h1 style={{ fontFamily: 'var(--serif)', fontWeight: 300, fontSize: 'clamp(26px, 2.8vw, 36px)', lineHeight: 1.05 }}>
            Tell us about <em>your project</em>
          </h1>
        </div>

        <form onSubmit={handleSubmit} className="quote-form">
          {/* Row 1 — Name · Email · Phone */}
          <div className="quote-row quote-row-3">
            <Field label="Your name *" v={form.name}  onChange={set('name')}/>
            <Field label="Email *"     v={form.email} onChange={set('email')} type="email"/>
            <Field label="Phone"       v={form.phone} onChange={set('phone')} type="tel"/>
          </div>

          {/* Row 2 — Project · Coverage · Timeline */}
          <div className="quote-row quote-row-3">
            <Field label="Project type" v={form.project}  onChange={set('project')}  placeholder="Residential · Commercial · Trade"/>
            <Field label="Coverage (m²)" v={form.sqm}     onChange={set('sqm')}      placeholder="e.g. 24" inputMode="decimal"/>
            <Field label="Timeline"     v={form.timeline} onChange={set('timeline')} placeholder="e.g. Q3 install"/>
          </div>

          {/* Tiles — full width, prefilled when coming from the selection drawer */}
          <Field label="Tiles of interest" v={form.tiles} onChange={set('tiles')}
            multiline rows={2} placeholder="Paste tile names, or describe what you're after" full/>

          {/* Notes — full width, smaller */}
          <Field label="Anything else?" v={form.notes} onChange={set('notes')}
            multiline rows={2} placeholder="Room, palette, install date, anything you'd like us to know" full/>

          {/* Optional delivery line — inline, only takes 1 row, no longer two fields */}
          <Field label="Delivery address (optional)" v={form.address} onChange={set('address')}
            placeholder="Street, postcode — only if you'd like a sample dispatched" full/>

          {/* Action row */}
          <div className="quote-action">
            <button type="submit" className="btn btn-dark" disabled={submitting}
              style={{ padding: '12px 28px' }}>
              {submitting ? 'Sending…' : 'Send to studio  →'}
            </button>
            <p style={{ fontFamily: 'var(--sans)', fontSize: '11px', color: 'var(--dark-mid)', letterSpacing: '0.04em' }}>
              London trade &amp; specifier accounts welcome.
            </p>
          </div>

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

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

// Tiny field helper — keeps the form markup readable.
function Field({ label, v, onChange, type='text', placeholder, full, 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>
  );
}

const fieldStyle = {
  width: '100%',
  background: 'white',
  border: '1px solid var(--cream-deep)',
  borderRadius: 0,
  // Tighter vertical padding so each field is ~40 px instead of ~48 px —
  // multiplied across 7 fields that's ~60 px saved overall.
  padding: '9px 13px',
  fontFamily: 'var(--sans)', fontSize: '14px',
  color: 'var(--dark)',
  outline: 'none',
  transition: 'border-color 0.2s',
};

Object.assign(window, { Quote });
