// Upload & Order — file-first flow
const { useState: useStateU, useRef: useRefU } = React;

const UP_PRODUCTS = ['Business Cards', 'Flyers & Leaflets', 'Roll-up Banner', 'Signage', 'Exhibition Graphics', 'Vehicle Wraps', 'T-shirts', 'Letterhead', 'Other'];
const UP_DEADLINES = ['24-hour express', '2 working days', 'This week', 'Flexible'];

function Upload() {
  const { go } = useRouter();
  const [files, setFiles] = useStateU([]);
  const [drag, setDrag] = useStateU(false);
  const [product, setProduct] = useStateU('Business Cards');
  const [qty, setQty] = useStateU('500');
  const [deadline, setDeadline] = useStateU('24-hour express');
  const [notes, setNotes] = useStateU('');
  const [name, setName] = useStateU('');
  const [phone, setPhone] = useStateU('');
  const [step, setStep] = useStateU(1);   // 1=files+spec, 2=contact, 3=confirm
  const [submitted, setSubmitted] = useStateU(false);
  const fileInput = useRefU(null);

  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 = `Hi Arabian Prints, I've uploaded artwork for an order.\n\n• Product: ${product}\n• Quantity: ${qty}\n• Deadline: ${deadline}\n• Files: ${files.length}\n${notes ? '\n' + notes : ''}`;

  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)'}}>Order placed</span>
            </div>
            <h1>Order received.<br/><span style={{color:'var(--muted)'}}>We're on it.</span></h1>
            <p className="lead" style={{maxWidth:'52ch', marginTop: 18}}>
              Thanks {name.split(' ')[0] || 'there'}. We've got {files.length} file{files.length === 1 ? '' : 's'} and your spec. A studio operator will preflight your artwork and call you on {phone || PHONE} within the hour.
            </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
              </a>
              <a className="btn btn-ghost btn-lg" href="#" onClick={(e) => { e.preventDefault(); setSubmitted(false); setStep(1); setFiles([]); setName(''); setPhone(''); setNotes(''); }}>Place another order</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}}>Order reference</div>
              <h3 style={{marginBottom: 16}}>#AP-{Math.floor(Math.random() * 90000 + 10000)}</h3>
              <div className="row"><div className="k">Product</div><div className="v">{product}</div></div>
              <div className="row"><div className="k">Quantity</div><div className="v">{qty}</div></div>
              <div className="row"><div className="k">Deadline</div><div className="v">{deadline}</div></div>
              <div className="row"><div className="k">Files</div><div className="v">{files.length} preflighting</div></div>
              <div className="row"><div className="k">Status</div><div className="v" style={{color:'var(--cta)'}}>● Awaiting preflight</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)'}}>Upload &amp; Order</span>
          </div>
          <div className="page-head-row">
            <h1>Upload &amp; order.<br/><span style={{color:'var(--muted)'}}>Skip the back-and-forth.</span></h1>
            <p className="lead">Already have your artwork ready? Drop the file, pick the format, tell us when you need it. We'll preflight your PDF and call you to confirm — usually within the hour.</p>
          </div>
        </div>
      </section>

      <section className="section">
        <div className="wrap">
          <div className="form-grid">
            <div>
              {/* Step progress */}
              <div style={{display:'flex', gap: 0, marginBottom: 40, borderBottom:'1px solid var(--line)', paddingBottom: 16}}>
                {[
                  { n: 1, label: 'Upload + spec' },
                  { n: 2, label: 'Your details' },
                  { n: 3, label: 'Confirm' },
                ].map(s => (
                  <div key={s.n} style={{flex: 1, opacity: step === s.n ? 1 : 0.45, transition:'opacity 0.2s'}}>
                    <div style={{fontFamily:'var(--font-mono)', fontSize: 11, color: step === s.n ? 'var(--cta)' : 'var(--muted)', letterSpacing:'0.08em'}}>Step 0{s.n}</div>
                    <div style={{fontFamily:'var(--font-display)', fontSize: 18, fontWeight: 600, marginTop: 4, letterSpacing:'-0.015em'}}>{s.label}</div>
                  </div>
                ))}
              </div>

              {step === 1 && (
                <>
                  <div
                    className={"upload-bigdrop" + (drag ? ' drag' : '')}
                    onClick={() => fileInput.current && fileInput.current.click()}
                    onDragOver={(e) => { e.preventDefault(); setDrag(true); }}
                    onDragLeave={() => setDrag(false)}
                    onDrop={onDrop}
                  >
                    <div className="upload-icon">↑</div>
                    <div className="upload-h">Drop your artwork here</div>
                    <div className="upload-sub">or click to browse files</div>
                    <div className="upload-formats">PDF · AI · PSD · TIFF · JPG · PNG · ZIP · max 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" style={{marginTop: 18}}>
                      {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)}><XIcon /></span>
                        </div>
                      ))}
                    </div>
                  )}

                  <div style={{marginTop: 40}}>
                    <div className="eyebrow no-rule" style={{marginBottom: 16}}>What are we printing?</div>
                    <div className="pill-row" style={{marginBottom: 24}}>
                      {UP_PRODUCTS.map(p => (
                        <button key={p} className={"pill" + (product === p ? ' active' : '')} onClick={() => setProduct(p)}>{p}</button>
                      ))}
                    </div>

                    <div className="field-row">
                      <div className="field">
                        <label>Quantity</label>
                        <input type="text" value={qty} onChange={(e) => setQty(e.target.value)} placeholder="e.g. 500, 1000" />
                      </div>
                      <div className="field">
                        <label>When do you need it?</label>
                        <select value={deadline} onChange={(e) => setDeadline(e.target.value)}>
                          {UP_DEADLINES.map(d => <option key={d}>{d}</option>)}
                        </select>
                      </div>
                    </div>
                    <div className="field">
                      <label>Notes (optional)</label>
                      <textarea rows="3" value={notes} onChange={(e) => setNotes(e.target.value)} placeholder="Bleed sizes, colour notes, special finishes…" />
                    </div>
                  </div>

                  <div style={{display:'flex', gap: 12, marginTop: 24, flexWrap:'wrap'}}>
                    <button className="btn btn-primary btn-lg" onClick={() => setStep(2)} disabled={files.length === 0} style={{opacity: files.length === 0 ? 0.5 : 1}}>
                      Continue <span className="btn-arrow">→</span>
                    </button>
                    {files.length === 0 && <span style={{fontSize: 12, color:'var(--muted)', alignSelf:'center'}}>Drop a file to continue.</span>}
                  </div>
                </>
              )}

              {step === 2 && (
                <>
                  <div className="field">
                    <label>Your name <span className="req">*</span></label>
                    <input type="text" value={name} onChange={(e) => setName(e.target.value)} placeholder="Full name" />
                  </div>
                  <div className="field">
                    <label>Phone / WhatsApp <span className="req">*</span></label>
                    <input type="tel" value={phone} onChange={(e) => setPhone(e.target.value)} placeholder="+971 …" />
                  </div>
                  <p style={{fontSize: 13, color:'var(--muted)', marginTop: 16, marginBottom: 24}}>
                    We'll call to confirm artwork details and arrange delivery. No advance payment — pay only when you're happy with the proof.
                  </p>
                  <div style={{display:'flex', gap: 12, flexWrap:'wrap'}}>
                    <button className="btn btn-ghost btn-lg" onClick={() => setStep(1)}>← Back</button>
                    <button className="btn btn-primary btn-lg" onClick={() => setStep(3)} disabled={!name.trim() || !phone.trim()} style={{opacity: (name.trim() && phone.trim()) ? 1 : 0.5}}>
                      Review &amp; place order <span className="btn-arrow">→</span>
                    </button>
                  </div>
                </>
              )}

              {step === 3 && (
                <>
                  <h2 className="h-card" style={{fontSize: 28, marginBottom: 28}}>Ready to send?</h2>
                  <div className="aside" style={{marginBottom: 28}}>
                    <div className="eyebrow no-rule" style={{marginBottom: 12}}>Your order</div>
                    <div className="row"><div className="k">Product</div><div className="v">{product}</div></div>
                    <div className="row"><div className="k">Quantity</div><div className="v">{qty}</div></div>
                    <div className="row"><div className="k">Deadline</div><div className="v">{deadline}</div></div>
                    <div className="row"><div className="k">Files</div><div className="v">{files.length}</div></div>
                    <div className="row"><div className="k">Contact</div><div className="v">{name}<br/><span style={{fontWeight:400, color:'var(--muted)', fontSize: 13}}>{phone}</span></div></div>
                  </div>
                  <div style={{display:'flex', gap: 12, flexWrap:'wrap'}}>
                    <button className="btn btn-ghost btn-lg" onClick={() => setStep(2)}>← Edit</button>
                    <button className="btn btn-primary btn-lg" onClick={() => setSubmitted(true)}>
                      Place order <span className="btn-arrow">→</span>
                    </button>
                  </div>
                </>
              )}
            </div>

            <aside className="aside" style={{position:'sticky', top: 96}}>
              <div className="eyebrow no-rule" style={{marginBottom: 12}}>Why upload here?</div>
              <h3>Skip the back-and-forth.</h3>
              <p style={{fontSize: 14, color:'var(--ink-2)', marginTop: 12}}>
                We preflight your file before we quote — checking bleed, CMYK conversion, font outlines and DPI. You get a proof back the same day, every time.
              </p>
              <hr className="hr" style={{margin:'24px 0'}} />
              <div className="eyebrow no-rule" style={{marginBottom: 16}}>What we accept</div>
              <div className="row"><div className="k">Preferred</div><div className="v">PDF / X-1a, CMYK, 3mm bleed</div></div>
              <div className="row"><div className="k">Native</div><div className="v">AI, INDD, PSD (with fonts)</div></div>
              <div className="row"><div className="k">Raster</div><div className="v">TIFF, JPG @ 300dpi+</div></div>
              <div className="row"><div className="k">Web</div><div className="v">PNG (large format only)</div></div>
              <div className="row"><div className="k">Max size</div><div className="v">200 MB / file</div></div>
            </aside>
          </div>
        </div>
      </section>

      <section className="section" style={{background:'var(--paper-2)', borderTop:'1px solid var(--line)'}}>
        <div className="wrap">
          <SectionHead eyebrow="How it works" title="From upload to delivery in four steps." />
          <div className="steps">
            <div className="step">
              <div className="step-n">01 — Upload</div>
              <div className="step-h">Drop your file</div>
              <div className="step-p">Upload artwork and tell us the format, quantity and deadline.</div>
            </div>
            <div className="step">
              <div className="step-n">02 — Preflight</div>
              <div className="step-h">We check it for press</div>
              <div className="step-p">Our studio reviews bleeds, fonts and colour profile within an hour.</div>
            </div>
            <div className="step">
              <div className="step-n">03 — Confirm</div>
              <div className="step-h">Proof + fixed quote</div>
              <div className="step-p">A WhatsApp proof and a fixed price for your sign-off. No advance payment.</div>
            </div>
            <div className="step">
              <div className="step-n">04 — Print + ship</div>
              <div className="step-h">Free UAE delivery</div>
              <div className="step-p">We print, package and ship. 24h express on most stationery products.</div>
            </div>
          </div>
        </div>
      </section>
    </main>
  );
}

Object.assign(window, { Upload });
