// ── About + Contact pages ────────────────────────────────────────────

function About({ goTo }) {
  useFadeUp();
  return (
    <div data-screen-label="about">
      <section className="container" style={{ paddingTop: 80, paddingBottom: 80 }}>
        <div className="eyebrow" style={{ marginBottom: 14 }}>◇ &nbsp; The atelier</div>
        <div>
          <h1 className="display" style={{
            fontSize: 'clamp(80px, 12vw, 200px)', margin: 0, lineHeight: .9,
          }}>JT</h1>
          <div style={{
            fontFamily: 'var(--font-display)',
            fontSize: 'clamp(14px, 2.8vw, 44px)',
            letterSpacing: '.32em',
            textTransform: 'uppercase',
            color: 'var(--crimson)',
            fontWeight: 400,
            marginTop: '0.18em',
          }}>ATELIER</div>
        </div>
      </section>

      <section className="container fade-up" style={{ paddingTop: 60, paddingBottom: 120 }}>
        <div className="about-story-grid" style={{
          display: 'grid', gridTemplateColumns: '1fr 1.6fr', gap: 80,
          alignItems: 'flex-start',
        }}>
          <div className="fade-up about-story-sticky" style={{ position: 'sticky', top: 100 }}>
            {/* Storefront photo */}
            <div style={{
              marginBottom: 36,
              overflow: 'hidden',
              borderRadius: 2,
              boxShadow: '0 12px 48px rgba(0,0,0,.38)',
            }}>
              <img
                src="assets/storefront.jpg"
                alt="JT Atelier storefront"
                className="parallax-img"
                onError={e => { e.currentTarget.parentElement.style.display = 'none'; }}
                style={{
                  width: '100%',
                  display: 'block',
                  objectFit: 'cover',
                  aspectRatio: '4/3',
                }}
              />
            </div>

            <div className="eyebrow" style={{ marginBottom: 18 }}>◇ &nbsp; Founded May 2026</div>
            <div className="display" style={{ fontSize: 46, lineHeight: 1.05 }}>
              <em>A moment<br/>of discovery.</em>
            </div>
            <div style={{
              marginTop: 32, paddingTop: 28,
              borderTop: '.5px solid var(--line)',
            }}>
              <div style={{ fontSize: 12, lineHeight: 1.7, color: 'var(--fg-3)' }}>
                American design.<br/>
                Pakistani craftsmanship.<br/>
                Made to order, for you.
              </div>
            </div>
          </div>

          <div className="fade-up" style={{
            fontSize: 16, lineHeight: 1.85, color: 'var(--fg-2)',
            display: 'flex', flexDirection: 'column', gap: 28,
          }}>
            <p style={{ margin: 0, fontSize: 20, lineHeight: 1.65, color: 'var(--fg)' }}>
              At JT Atelier, every piece begins with a moment of discovery.
            </p>

            <p style={{ margin: 0 }}>
              What started as a personal search for exceptional leather led to something
              far greater. After exploring and purchasing jackets from around the world,
              I found myself continually drawn to the craftsmanship coming out of
              Pakistan — pieces that felt more intentional, more refined, and more honest
              than anything I had experienced before. The quality, the detail, and the
              value spoke for themselves. It wasn't just outerwear; it was artistry.
            </p>

            <p style={{ margin: 0 }}>
              In May of 2026, that realization became something tangible. JT Atelier was
              founded with a simple but meaningful purpose: to share that level of
              craftsmanship with others who value quality, authenticity, and timeless design.
            </p>

            <p style={{ margin: 0 }}>
              This brand is the result of a collaboration between cultures — an American
              eye for design and a Pakistani tradition of master leather craftsmanship.
              Together, we've created something that honors both perspectives: timeless,
              made-to-order leather outerwear that reflects precision, individuality, and
              care in every stitch.
            </p>

            <div style={{
              borderLeft: '2px solid var(--crimson)',
              paddingLeft: 24, margin: '8px 0',
            }}>
              <p style={{ margin: 0, fontStyle: 'italic', color: 'var(--fg)', fontSize: 17, lineHeight: 1.75 }}>
                Because each piece is crafted specifically for you, our process takes time.
                Orders are made to order and typically arrive within two to four weeks.
                We believe this time is not a delay, but a commitment — to quality, to
                detail, and to creating something truly personal.
              </p>
            </div>

            <p style={{ margin: 0 }}>
              Our relationship with our customers matters just as much as the garments
              we create. We take pride in being responsive, attentive, and dedicated to
              making sure every experience with JT Atelier feels as exceptional as the
              product itself. From your first question to the moment your jacket arrives,
              we are here to ensure you feel confident, valued, and taken care of.
            </p>

            <p style={{ margin: 0, color: 'var(--fg)', fontWeight: 500 }}>
              JT Atelier isn't just about leather jackets. It's about honoring
              craftsmanship, bridging worlds, and delivering something worth waiting for.
            </p>
          </div>
        </div>
      </section>

      <section className="container fade-up" style={{ paddingTop: 80, paddingBottom: 120, textAlign: 'center' }}>
        <div className="display" style={{ fontSize: 'clamp(40px, 6vw, 80px)', lineHeight: 1 }}>
          <em className="gradient-text">Go bespoke.</em>
        </div>
        <div style={{ display: 'flex', gap: 14, justifyContent: 'center', marginTop: 36, flexWrap: 'wrap' }}>
          <button className="btn" onClick={() => window.openBespoke && window.openBespoke()}>
            Start here <span className="arrow">→</span>
          </button>
          <button className="btn ghost" onClick={() => goTo('contact')}>
            Get in touch
          </button>
        </div>
      </section>

      <SiteReviews />
    </div>
  );
}

const SOCIAL = [];

function Contact({ goTo }) {
  useFadeUp();
  return (
    <div data-screen-label="contact">
      <section className="container" style={{ paddingTop: 80, paddingBottom: 60 }}>
        <div className="eyebrow" style={{ marginBottom: 14 }}>◇ &nbsp; Get in touch</div>
        <h1 className="display" style={{
          fontSize: 'clamp(56px, 9vw, 160px)', margin: 0, lineHeight: 1,
        }}>
          <em>Talk</em> <span className="gradient-text" style={{ fontStyle: 'italic' }}>to us.</span>
        </h1>
        <p style={{
          fontSize: 16, lineHeight: 1.7, color: 'var(--fg-2)',
          maxWidth: 520, marginTop: 32,
        }}>
          Questions about sizing, custom commissions, or care —
          we reply within 24 hours, every day of the week.
        </p>
      </section>

      <section className="container fade-up" style={{ paddingTop: 80, paddingBottom: 60 }}>
        <div className="contact-form-grid" style={{
          display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 80, alignItems: 'flex-start',
        }}>
          <div>
            <div className="eyebrow" style={{ marginBottom: 14 }}>◇ &nbsp; Send a note</div>
            <h2 className="display" style={{ fontSize: 'clamp(40px, 5vw, 72px)', margin: 0, lineHeight: 1 }}>
              Drop us a line.
            </h2>
            <p style={{
              fontSize: 14, lineHeight: 1.7, color: 'var(--fg-2)',
              marginTop: 18, maxWidth: 380,
            }}>
              For a custom commission, use the <button
                onClick={() => window.openBespoke && window.openBespoke()}
                style={{ color: 'var(--fg)', textDecoration: 'underline', textUnderlineOffset: 4 }}>
                Bespoke programme
              </button> instead — it'll capture what we need much faster.
            </p>
          </div>
          <ContactForm />
        </div>
      </section>
    </div>
  );
}

function ContactBlock({ eyebrow, title, body, top, border }) {
  return (
    <div style={{
      padding: '48px 40px',
      borderTop: top ? '.5px solid var(--line)' : 'none',
      borderLeft: border ? '.5px solid var(--line)' : 'none',
    }}>
      <div className="eyebrow" style={{ marginBottom: 18 }}>{eyebrow}</div>
      <div className="display" style={{
        fontSize: 36, lineHeight: 1.05, marginBottom: 18,
      }}>
        <em>{title}</em>
      </div>
      <div style={{ fontSize: 14, lineHeight: 1.7, color: 'var(--fg-2)' }}>
        {body}
      </div>
    </div>
  );
}

function ContactForm() {
  const [form, setForm] = React.useState({ name: '', email: '', subject: 'General', message: '' });
  const [sent, setSent] = React.useState(false);
  const [sending, setSending] = React.useState(false);
  const [err, setErr] = React.useState('');
  const set = (k, v) => setForm((f) => ({ ...f, [k]: v }));

  const submit = async (e) => {
    e.preventDefault();
    if (!form.email) return;
    if (form.subject !== 'Affiliate Program' && !form.message) return;
    setSending(true);
    setErr('');
    try {
      const res = await fetch('/api/contact', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(form),
      });
      const data = await res.json().catch(() => ({}));
      if (!res.ok) throw new Error(data.error || 'Something went wrong.');
      setSent(true);
    } catch (e) {
      setErr(e.message || 'Could not send your message. Please try again.');
    } finally {
      setSending(false);
    }
  };

  if (sent) {
    const wasAffiliate = form.subject === 'Affiliate Program';
    return (
      <div style={{
        border: '.5px solid var(--line-2)',
        padding: 32,
        textAlign: 'center',
      }}>
        <div className="display" style={{ fontSize: 36, marginBottom: 12 }}>
          <em className="gradient-text">{wasAffiliate ? 'Check your inbox.' : 'Sent.'}</em>
        </div>
        <p style={{ color: 'var(--fg-2)', fontSize: 14, lineHeight: 1.6 }}>
          {wasAffiliate
            ? 'Your affiliate application form is on its way. Fill it out and reply — we review applications within 3–5 business days.'
            : "We'll reply within 24 hours."
          }
        </p>
      </div>
    );
  }

  const isAffiliate = form.subject === 'Affiliate Program';

  return (
    <form onSubmit={submit} style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
        <input className="commission-input" type="text" placeholder="Your name"
          value={form.name} onChange={(e) => set('name', e.target.value)} />
        <input className="commission-input" type="email" placeholder="Email *" required
          value={form.email} onChange={(e) => set('email', e.target.value)} />
      </div>
      <select className="commission-input" value={form.subject} onChange={(e) => set('subject', e.target.value)}
        style={{ appearance: 'none' }}>
        <option>General inquiry</option>
        <option>Bespoke commission</option>
        <option>Order status &amp; tracking</option>
        <option>Returns &amp; exchanges</option>
        <option>Sizing &amp; fit</option>
        <option>Payment &amp; billing</option>
        <option>Product care</option>
        <option>Press &amp; media</option>
        <option>Affiliate Program</option>
      </select>
      {isAffiliate ? (
        <div style={{
          border: '.5px solid var(--line-2)',
          padding: '18px 20px',
          display: 'flex', gap: 14, alignItems: 'flex-start',
        }}>
          <div style={{ fontSize: 20, lineHeight: 1, flexShrink: 0, marginTop: 2 }}>✦</div>
          <div>
            <div style={{ fontSize: 13, color: 'var(--fg)', fontWeight: 600, marginBottom: 6 }}>
              We'll send the application to your email instantly.
            </div>
            <div style={{ fontSize: 12, color: 'var(--fg-2)', lineHeight: 1.6 }}>
              Enter your name and email above, then click Send. You'll receive a full affiliate application form — fill it out and reply directly. No PayPal account is required to apply.
            </div>
          </div>
        </div>
      ) : (
        <textarea className="commission-textarea" rows={5} required placeholder="Your message *"
          value={form.message} onChange={(e) => set('message', e.target.value)}
          style={{ marginTop: 0 }} />
      )}
      <button type="submit" className="btn" style={{ marginTop: 4 }} disabled={sending}>
        {sending ? 'Sending…' : isAffiliate
          ? <> Request application <span className="arrow">→</span></>
          : <> Send message <span className="arrow">→</span></>
        }
      </button>
      {err && (
        <div className="mono" style={{ color: '#e57373', fontSize: 10, marginTop: 8 }}>
          {err}
        </div>
      )}
    </form>
  );
}

function SiteReviews() {
  const [reviews, setReviews] = React.useState(null);
  const [showForm, setShowForm] = React.useState(false);
  const [form, setForm] = React.useState({ name: '', rating: 5, comment: '' });
  const [images, setImages] = React.useState([]);
  const [submitted, setSubmitted] = React.useState(false);
  const [submitting, setSubmitting] = React.useState(false);

  React.useEffect(() => {
    fetch('/api/admin?a=review_list')
      .then(r => r.json())
      .then(d => setReviews(d.reviews || []))
      .catch(() => setReviews([]));
  }, []);

  const handleImages = async (e) => {
    const files = [...e.target.files].slice(0, 3 - images.length);
    if (!files.length) return;
    const compressed = await Promise.all(files.map(compressReviewImage));
    setImages(prev => [...prev, ...compressed].slice(0, 3));
    e.target.value = '';
  };

  const submit = async () => {
    if (!form.name.trim() || !form.rating) return;
    setSubmitting(true);
    try {
      const r = await fetch('/api/admin?a=review_submit', {
        method: 'POST', headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ product_id: 'general', reviewer_name: form.name, rating: form.rating, comment: form.comment, images }),
      });
      if (r.ok) { setSubmitted(true); setShowForm(false); }
    } catch {}
    setSubmitting(false);
  };

  const avg = reviews && reviews.length ? reviews.reduce((s, r) => s + (r.rating || 0), 0) / reviews.length : null;
  const fieldStyle = { width: '100%', border: '.5px solid var(--line-2)', borderRadius: 3, padding: '10px 14px', fontSize: 13, background: 'transparent', color: 'var(--fg)', outline: 'none', boxSizing: 'border-box', fontFamily: 'inherit' };
  const fieldLabel = (t) => (
    <div className="mono" style={{ fontSize: 9, letterSpacing: '.14em', textTransform: 'uppercase', color: 'var(--fg-3)', marginBottom: 7 }}>{t}</div>
  );

  return (
    <section className="container fade-up" style={{ paddingTop: 80, paddingBottom: 100, borderTop: '.5px solid var(--line)' }}>
      <div className="eyebrow" style={{ marginBottom: 14 }}>◇ &nbsp; Client voices</div>
      <div style={{ display: 'flex', alignItems: 'baseline', gap: 20, marginBottom: 48, flexWrap: 'wrap' }}>
        <h2 className="display" style={{ fontSize: 'clamp(36px, 5vw, 64px)', margin: 0, lineHeight: 1 }}>
          <em>What they say.</em>
        </h2>
        {avg && (
          <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
            <ReviewStars n={Math.round(avg)} size={18} />
            <span style={{ color: 'var(--fg-2)', fontSize: 14 }}>
              {avg.toFixed(1)} · {reviews.length} review{reviews.length !== 1 ? 's' : ''}
            </span>
          </div>
        )}
      </div>

      {/* Reviews grid */}
      {reviews && reviews.length > 0 && (
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(280px, 1fr))', gap: 24, marginBottom: 64 }}>
          {reviews.map(rv => <ReviewCard key={rv.id} rv={rv} />)}
        </div>
      )}

      {/* Empty state */}
      {reviews && reviews.length === 0 && !showForm && (
        <p style={{ fontSize: 14, color: 'var(--fg-3)', marginBottom: 36 }}>No reviews yet — be the first to share your experience.</p>
      )}

      {/* Write a review */}
      <div style={{ borderTop: reviews && reviews.length > 0 ? '.5px solid var(--line-2)' : 'none', paddingTop: reviews && reviews.length > 0 ? 48 : 0, maxWidth: 560 }}>
        <div className="mono" style={{ fontSize: 9, letterSpacing: '.22em', textTransform: 'uppercase', color: 'var(--fg-3)', marginBottom: 20 }}>
          Share your experience
        </div>

        {submitted ? (
          <p className="mono" style={{ fontSize: 12, color: 'var(--fg-3)', letterSpacing: '.04em' }}>
            Thank you — your review is pending approval and will appear here shortly.
          </p>
        ) : showForm ? (
          <div>
            <div style={{ marginBottom: 16 }}>
              {fieldLabel('Your name')}
              <input value={form.name} onChange={e => setForm(f => ({ ...f, name: e.target.value }))} style={fieldStyle} placeholder="Full name" />
            </div>

            <div style={{ marginBottom: 16 }}>
              {fieldLabel('Rating')}
              <div style={{ display: 'flex', gap: 2 }}>
                {[1,2,3,4,5].map(n => (
                  <button key={n} onClick={() => setForm(f => ({ ...f, rating: n }))}
                    style={{ background: 'none', border: 'none', cursor: 'pointer', fontSize: 32, color: n <= form.rating ? '#c9a233' : 'var(--line-2)', padding: '0 3px', lineHeight: 1, transition: 'color .1s' }}>★</button>
                ))}
              </div>
            </div>

            <div style={{ marginBottom: 16 }}>
              {fieldLabel('Your review')}
              <textarea value={form.comment} onChange={e => setForm(f => ({ ...f, comment: e.target.value }))}
                rows={5} style={{ ...fieldStyle, resize: 'vertical' }} placeholder="Share your experience with JT Atelier — the quality, fit, and craft…" />
            </div>

            <div style={{ marginBottom: 28 }}>
              {fieldLabel('Photos — optional, up to 3')}
              {images.length > 0 && (
                <div style={{ display: 'flex', gap: 8, marginBottom: 10, flexWrap: 'wrap' }}>
                  {images.map((src, i) => (
                    <div key={i} style={{ position: 'relative' }}>
                      <img src={src} style={{ width: 80, height: 80, objectFit: 'cover', borderRadius: 3, border: '.5px solid var(--line-2)' }} alt="review" />
                      <button onClick={() => setImages(imgs => imgs.filter((_, j) => j !== i))}
                        style={{ position: 'absolute', top: -5, right: -5, background: '#c0392b', color: '#fff', border: 'none', borderRadius: '50%', width: 18, height: 18, cursor: 'pointer', fontSize: 12, lineHeight: '18px', padding: 0, textAlign: 'center' }}>×</button>
                    </div>
                  ))}
                </div>
              )}
              {images.length < 3 && (
                <label style={{ display: 'inline-flex', alignItems: 'center', gap: 8, cursor: 'pointer', border: '.5px solid var(--line-2)', borderRadius: 3, padding: '8px 14px', fontSize: 12, fontFamily: 'var(--font-mono)', color: 'var(--fg-3)', letterSpacing: '.05em' }}>
                  <span>+ Add photo{images.length > 0 ? ' (' + images.length + '/3)' : 's'}</span>
                  <input type="file" accept="image/*" multiple style={{ display: 'none' }} onChange={handleImages} />
                </label>
              )}
            </div>

            <div style={{ display: 'flex', gap: 12 }}>
              <button className="btn" onClick={submit} disabled={submitting || !form.name.trim()} style={{ padding: '12px 24px', opacity: (submitting || !form.name.trim()) ? .5 : 1 }}>
                {submitting ? 'Sending…' : 'Submit review →'}
              </button>
              <button className="btn ghost" onClick={() => { setShowForm(false); setImages([]); setForm({ name: '', rating: 5, comment: '' }); }} style={{ padding: '12px 24px' }}>
                Cancel
              </button>
            </div>
          </div>
        ) : (
          <button className="btn ghost" onClick={() => setShowForm(true)} style={{ padding: '12px 28px' }}>
            Write a review
          </button>
        )}
      </div>
    </section>
  );
}

Object.assign(window, { About, Contact, SOCIAL });
