// Quote page — multi-field form with file upload and live WhatsApp deeplink preview
const { useState: useStateQ, useRef: useRefQ, useMemo: useMemoQ } = React;

function Quote() {
  const { go } = useRouter();
  const [form, setForm] = useStateQ({
    name: '',
    company: '',
    phone: '',
    email: '',
    service: 'Business Cards',
    quantity: '500',
    size: '90 × 55 mm',
    finish: 'Matt laminated',
    deadline: '',
    message: '',
  });
  const [files, setFiles] = useStateQ([]);
  const [drag, setDrag] = useStateQ(false);
  const [submitted, setSubmitted] = useStateQ(false);
  const fileInput = useRefQ(null);

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

  const addFiles = (newFiles) => {
    const arr = Array.from(newFiles).map(f => ({
      name: f.name, size: f.size, type: f.type
    }));
    setFiles(prev => [...prev, ...arr]);
  };

  const removeFile = (i) => setFiles(prev => prev.filter((_, idx) => idx !== i));

  const onDrop = (e) => {
    e.preventDefault();
    setDrag(false);
    if (e.dataTransfer.files) addFiles(e.dataTransfer.files);
  };

  const summary = useMemoQ(() => {
    const lines = [
      `Hi Arabian Prints, I'd like a quote.`,
      ``,
      `• Service: ${form.service}`,
      `• Quantity: ${form.quantity}`,
      `• Size: ${form.size}`,
      `• Finish: ${form.finish}`,
      form.deadline ? `• Deadline: ${form.deadline}` : null,
      form.name ? `• Name: ${form.name}` : null,
      form.company ? `• Company: ${form.company}` : null,
      files.length ? `• Artwork: ${files.length} file${files.length > 1 ? 's' : ''} attached` : null,
      form.message ? `\n${form.message}` : null,
    ].filter(Boolean);
    return lines.join('\n');
  }, [form, files]);

  const isValid = form.name.trim() && form.phone.trim() && form.service;

  if (submitted) {
    return (
      <main>
        <section className="page-head" style={{paddingBottom: 120}}>
          <div className="wrap">
            <div className="crumbs" style={{marginBottom: 18}}>
              <a href="#" onClick={(e) => { e.preventDefault(); go('home'); }}>Home</a>
              <span>/</span>
              <span style={{color:'var(--ink)'}}>Quote sent</span>
            </div>
            <h1>Quote sent.<br/><span style={{color:'var(--muted)'}}>We'll reply within the hour.</span></h1>
            <p className="lead" style={{maxWidth:'52ch', marginTop: 18}}>
              Thanks {form.name.split(' ')[0]}. Your brief for {form.quantity} × {form.service} is in our queue.
              We've also opened a WhatsApp draft so you can fast-track the conversation if you'd like.
            </p>
            <div style={{display:'flex', gap: 12, marginTop: 36, flexWrap:'wrap'}}>
              <a className="btn btn-wa btn-lg" href={waLink(summary)} target="_blank" rel="noopener">
                <WaIcon /> Open WhatsApp chat
              </a>
              <a className="btn btn-ghost btn-lg" href="#" onClick={(e) => { e.preventDefault(); setSubmitted(false); }}>Submit another quote</a>
              <a className="btn btn-ghost btn-lg" href="#" onClick={(e) => { e.preventDefault(); go('home'); }}>Back to home</a>
            </div>
            <div className="aside" style={{marginTop: 56, maxWidth: 560}}>
              <div className="eyebrow no-rule" style={{marginBottom: 12}}>Reference</div>
              <h3 style={{marginBottom: 16}}>Ticket #AP-{Math.floor(Math.random() * 90000 + 10000)}</h3>
              <div className="row"><div className="k">Service</div><div className="v">{form.service}</div></div>
              <div className="row"><div className="k">Quantity</div><div className="v">{form.quantity}</div></div>
              <div className="row"><div className="k">Deadline</div><div className="v">{form.deadline || '— flexible'}</div></div>
              <div className="row"><div className="k">Files</div><div className="v">{files.length} attached</div></div>
            </div>
          </div>
        </section>
      </main>
    );
  }

  return (
    <main>
      <section className="page-head">
        <div className="wrap">
          <div className="crumbs" style={{marginBottom: 18}}>
            <a href="#" onClick={(e) => { e.preventDefault(); go('home'); }}>Home</a>
            <span>/</span>
            <span style={{color:'var(--ink)'}}>Get a Quote</span>
          </div>
          <div className="page-head-row">
            <h1>Get a quote.<br/><span style={{color:'var(--muted)'}}>Reply within the hour.</span></h1>
            <p className="lead">Tell us the format, quantity and deadline — attach artwork if you have it. We'll come back with a fixed price, free design and a delivery slot.</p>
          </div>
        </div>
      </section>

      <section className="section">
        <div className="wrap">
          <div className="form-grid">
            <form onSubmit={(e) => { e.preventDefault(); if (isValid) setSubmitted(true); }}>
              <div className="eyebrow no-rule" style={{marginBottom: 24}}>Step 01 — About you</div>
              <div className="field-row">
                <div className="field">
                  <label>Your name <span className="req">*</span></label>
                  <input type="text" value={form.name} onChange={set('name')} placeholder="Full name" required />
                </div>
                <div className="field">
                  <label>Company / organisation</label>
                  <input type="text" value={form.company} onChange={set('company')} placeholder="Optional" />
                </div>
              </div>
              <div className="field-row">
                <div className="field">
                  <label>Phone / WhatsApp <span className="req">*</span></label>
                  <input type="tel" value={form.phone} onChange={set('phone')} placeholder="+971 …" required />
                </div>
                <div className="field">
                  <label>Email</label>
                  <input type="email" value={form.email} onChange={set('email')} placeholder="you@company.com" />
                </div>
              </div>

              <div className="eyebrow no-rule" style={{marginTop: 16, marginBottom: 24}}>Step 02 — The job</div>
              <div className="field-row">
                <div className="field">
                  <label>What are we printing? <span className="req">*</span></label>
                  <select value={form.service} onChange={set('service')}>
                    <option>Business Cards</option>
                    <option>Flyers &amp; Leaflets</option>
                    <option>Roll-up Banners</option>
                    <option>Signage &amp; Signboards</option>
                    <option>Exhibition Graphics</option>
                    <option>Vehicle Wraps</option>
                    <option>T-shirts &amp; Merch</option>
                    <option>Letterheads &amp; Stationery</option>
                    <option>Logo / Brand Design</option>
                    <option>Other (describe below)</option>
                  </select>
                </div>
                <div className="field">
                  <label>Quantity</label>
                  <input type="text" value={form.quantity} onChange={set('quantity')} placeholder="e.g. 500, 1000, 5000" />
                </div>
              </div>
              <div className="field-row">
                <div className="field">
                  <label>Size / format</label>
                  <input type="text" value={form.size} onChange={set('size')} placeholder="e.g. A5, 90×55mm, 6m × 3m" />
                </div>
                <div className="field">
                  <label>Finish</label>
                  <input type="text" value={form.finish} onChange={set('finish')} placeholder="e.g. matt lam, gold foil, spot UV" />
                </div>
              </div>
              <div className="field">
                <label>Deadline</label>
                <input type="text" value={form.deadline} onChange={set('deadline')} placeholder="e.g. Tomorrow 5pm, This Thursday" />
              </div>
              <div className="field">
                <label>Brief / message</label>
                <textarea rows="4" value={form.message} onChange={set('message')} placeholder="Anything we should know — references, colour brand guidelines, special finishes…" />
              </div>

              <div className="eyebrow no-rule" style={{marginTop: 16, marginBottom: 16}}>Step 03 — Artwork (optional)</div>
              <div
                className={"dropzone" + (drag ? ' drag' : '')}
                onClick={() => fileInput.current && fileInput.current.click()}
                onDragOver={(e) => { e.preventDefault(); setDrag(true); }}
                onDragLeave={() => setDrag(false)}
                onDrop={onDrop}
              >
                <UploadIcon />
                <div className="dropzone-h">Drop artwork here or click to browse</div>
                <div className="dropzone-sub">We'll review the file and confirm specs before printing.</div>
                <div className="dropzone-mono">PDF · AI · PSD · TIFF · JPG · PNG · up to 200 MB</div>
                <input ref={fileInput} type="file" multiple style={{display:'none'}} onChange={(e) => e.target.files && addFiles(e.target.files)} />
              </div>
              {files.length > 0 && (
                <div className="file-list">
                  {files.map((f, i) => (
                    <div className="file-row" key={i}>
                      <FileIcon />
                      <span className="name">{f.name}</span>
                      <span className="size">{formatSize(f.size)}</span>
                      <span className="x" onClick={() => removeFile(i)} aria-label="Remove file"><XIcon /></span>
                    </div>
                  ))}
                </div>
              )}

              <div style={{display:'flex', gap: 12, marginTop: 36, flexWrap:'wrap', alignItems:'center'}}>
                <button type="submit" className={"btn btn-primary btn-lg" + (isValid ? '' : '')} disabled={!isValid} style={{opacity: isValid ? 1 : 0.5}}>
                  Send brief <span className="btn-arrow">→</span>
                </button>
                <a className="btn btn-wa btn-lg" href={waLink(summary)} target="_blank" rel="noopener">
                  <WaIcon /> Send on WhatsApp
                </a>
                <span style={{fontSize: 12, color:'var(--muted)'}}>No advance payment. We'll never share your details.</span>
              </div>
            </form>

            <aside className="aside" style={{position:'sticky', top: 96}}>
              <div className="eyebrow no-rule" style={{marginBottom: 12}}>Preview · WhatsApp message</div>
              <h3>What we'll receive</h3>
              <div className="wa-preview">
                <div className="wa-bubble">{summary}</div>
                <div className="wa-time">just now · sending →</div>
              </div>
              <hr className="hr" style={{margin:'24px 0'}} />
              <div className="eyebrow no-rule" style={{marginBottom: 12}}>Direct line</div>
              <div className="row"><div className="k">Phone</div><div className="v"><a href={`tel:${PHONE_RAW}`}>{PHONE}</a></div></div>
              <div className="row"><div className="k">Email</div><div className="v"><a href={`mailto:${EMAIL}`}>{EMAIL}</a></div></div>
              <div className="row"><div className="k">Hours</div><div className="v">24/7 sales desk</div></div>
            </aside>
          </div>
        </div>
      </section>
    </main>
  );
}

Object.assign(window, { Quote });
