/* app.jsx — Chowdaheadz Custom Shop, main assembly + get-pricing flow. */

function ShopHeader() {
  return (
    <header style={{ position: 'sticky', top: 0, zIndex: 40 }}>
      <div className="ch-promo-bar" style={{ background: 'var(--chowdahead-red)', color: '#fff', textAlign: 'center', padding: '9px 16px', fontFamily: 'Oswald, sans-serif', fontWeight: 600, fontSize: 12, letterSpacing: '.12em', textTransform: 'uppercase' }}>
        Designed, Printed &amp; Shipped from Just Outside Boston &middot; Fast Turnaround &middot; 100% Satisfaction
      </div>
      <div style={{ background: 'rgba(247,244,236,.86)', backdropFilter: 'blur(8px)', borderBottom: '1px solid var(--line)' }}>
        <div className="ch-header-inner" style={{ maxWidth: 1240, margin: '0 auto', padding: '0 24px', height: 66, display: 'flex', alignItems: 'center', gap: 20 }}>
          <a href="index.html" aria-label="Chowdaheadz home"><img className="ch-header-logo" src="assets/logo-chowdaheadz.png" alt="Chowdaheadz" style={{ height: 34, width: 'auto', display: 'block' }} /></a>
        </div>
      </div>
    </header>
  );
}

function Reassurance() {
  const items = [
    { icon: 'truck', t: 'Fast turnaround', s: 'Ships in 5–7 business days' },
    { icon: 'check', t: 'Free setup', s: 'No screen or art fees, ever' },
    { icon: 'mapPin', t: 'Made local', s: 'Printed in Woburn, MA' },
    { icon: 'star', t: '100% guaranteed', s: 'Love it or we reprint it' },
  ];
  return (
    <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(200px, 1fr))', gap: 1, background: 'var(--line)', border: '1px solid var(--line)', borderRadius: 8, overflow: 'hidden' }}>
      {items.map(it => (
        <div key={it.t} style={{ background: '#fff', padding: '16px 18px', display: 'flex', alignItems: 'center', gap: 12 }}>
          <div style={{ width: 38, height: 38, borderRadius: 999, background: 'var(--paper-2)', display: 'flex', alignItems: 'center', justifyContent: 'center', flex: 'none', color: 'var(--dark-royal)' }}><Icon name={it.icon} size={20} color={it.icon === 'star' ? 'var(--grizzly-gold)' : 'var(--dark-royal)'} /></div>
          <div>
            <div style={{ fontFamily: 'Oswald, sans-serif', fontWeight: 700, fontSize: 14, textTransform: 'uppercase', color: 'var(--ink)' }}>{it.t}</div>
            <div style={{ fontFamily: 'Montserrat, sans-serif', fontSize: 12.5, color: 'var(--ink-3)' }}>{it.s}</div>
          </div>
        </div>
      ))}
    </div>
  );
}


const CH_APPAREL_SIZES = ['XS', 'S', 'M', 'L', 'XL', '2XL', '3XL', '4XL'];
const CH_HAT_SIZES = ['One Size'];

function sizeListForGarment(garmentId) {
  return garmentId === 'hat' ? CH_HAT_SIZES : CH_APPAREL_SIZES;
}

function SizeInquiryModal({ open, customer, summary, sizeSummary, onClose, onSent }) {
  const [status, setStatus] = React.useState('form');
  const [error, setError] = React.useState('');

  React.useEffect(() => {
    if (open) {
      setStatus('form');
      setError('');
    }
  }, [open]);

  if (!open) return null;

  const submit = async (e) => {
    e.preventDefault();
    if (status === 'sending') return;
    setStatus('sending');
    setError('');
    try {
      const f = e.target.elements;
      await submitQuote({
        name: (f.inquiry_name && f.inquiry_name.value) || '',
        email: (f.inquiry_email && f.inquiry_email.value) || '',
        phone: (f.inquiry_phone && f.inquiry_phone.value) || '',
        company: (customer && customer.company) || '',
        town: (customer && customer.town) || '',
        notes: (f.inquiry_notes && f.inquiry_notes.value) || '',
        summary,
        sizeSummary,
      });
      setStatus('sent');
      if (onSent) onSent('Inquiry sent — thank you!');
    } catch (err) {
      setError((err && err.message) || 'Something went wrong sending your inquiry.');
      setStatus('error');
    }
  };

  const fieldStyle = { display: 'block', width: '100%', marginTop: 6, padding: '11px 13px', borderRadius: 6, border: '1px solid var(--line-strong)', fontFamily: 'Montserrat, sans-serif', fontSize: 14, color: 'var(--ink)', boxSizing: 'border-box', background: '#fff' };
  const labelTxt = { fontFamily: 'Oswald, sans-serif', fontWeight: 600, fontSize: 12.5, textTransform: 'uppercase', letterSpacing: '.04em', color: 'var(--ink)' };

  return (
    <div
      className="ch-quote-modal-backdrop"
      style={{
        position: 'fixed',
        inset: 0,
        zIndex: 100,
        background: 'rgba(12,18,48,.55)',
        display: 'flex',
        alignItems: 'flex-start',
        justifyContent: 'center',
        padding: 'max(20px, 4vh) 20px 20px',
        overflowY: 'auto',
      }}>
      <div
        className="ch-quote-modal"
        onClick={e => e.stopPropagation()}
        style={{
          background: 'var(--paper)',
          borderRadius: 10,
          width: 'min(520px, 100%)',
          maxHeight: 'calc(100vh - max(40px, 8vh))',
          overflow: 'auto',
          boxShadow: 'var(--shadow-lg)',
          border: '2px solid var(--vintage-navy)',
        }}>
        <div style={{ background: 'var(--vintage-navy)', padding: '18px 24px', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <span style={{ fontFamily: 'Anton, sans-serif', fontSize: 24, color: '#fff', textTransform: 'uppercase', letterSpacing: '.01em' }}>Send Us An Inquiry</span>
          <button onClick={onClose} disabled={status === 'sending'} style={{ background: 'none', border: 'none', cursor: status === 'sending' ? 'not-allowed' : 'pointer', color: '#fff', padding: 4 }}><Icon name="x" size={22} color="#fff" /></button>
        </div>

        {status === 'sent' ? (
          <div style={{ padding: '40px 28px', textAlign: 'center' }}>
            <div style={{ width: 58, height: 58, borderRadius: 999, background: 'var(--kelly-green)', margin: '0 auto 16px', display: 'flex', alignItems: 'center', justifyContent: 'center' }}><Icon name="check" size={30} color="#fff" /></div>
            <h3 style={{ margin: '0 0 8px', fontFamily: 'Oswald, sans-serif', fontWeight: 700, fontSize: 22, textTransform: 'uppercase', color: 'var(--ink)' }}>Inquiry sent!</h3>
            <p style={{ margin: 0, fontFamily: 'Montserrat, sans-serif', fontSize: 14.5, color: 'var(--ink-2)', lineHeight: 1.6 }}>Thanks — our team will review your message and get back to you shortly.</p>
            <div style={{ marginTop: 22 }}><Button variant="dark" onClick={onClose}>Close</Button></div>
          </div>
        ) : (
          <form onSubmit={submit} style={{ padding: 24, position: 'relative' }}>
            <p style={{ margin: '0 0 18px', fontFamily: 'Montserrat, sans-serif', fontSize: 14, color: 'var(--ink-2)', lineHeight: 1.6 }}>Have a question or extra detail for the Chowdaheadz team? Send it here and we will email you back.</p>
            <div style={{ background: '#fff', border: '1px solid var(--line)', borderRadius: 8, padding: '12px 14px', marginBottom: 18, fontFamily: 'Montserrat, sans-serif', fontSize: 13, color: 'var(--ink-2)' }}>
              <div><strong style={{ color: 'var(--ink)' }}>Your design:</strong> {summary}</div>
              {sizeSummary && <div style={{ marginTop: 6 }}><strong style={{ color: 'var(--ink)' }}>Sizes:</strong> {sizeSummary}</div>}
            </div>
            <label style={{ display: 'block', marginBottom: 14 }}>
              <span style={labelTxt}>Name</span>
              <input name="inquiry_name" type="text" required defaultValue={(customer && customer.name) || ''} placeholder="Tom from Southie" style={fieldStyle} />
            </label>
            <label style={{ display: 'block', marginBottom: 14 }}>
              <span style={labelTxt}>Email</span>
              <input name="inquiry_email" type="email" required defaultValue={(customer && customer.email) || ''} placeholder="you@email.com" style={fieldStyle} />
            </label>
            <label style={{ display: 'block', marginBottom: 14 }}>
              <span style={labelTxt}>Phone (optional)</span>
              <input name="inquiry_phone" type="tel" defaultValue={(customer && customer.phone) || ''} placeholder="(617) 555-0142" style={fieldStyle} />
            </label>
            <label style={{ display: 'block', marginBottom: 20 }}>
              <span style={labelTxt}>Message</span>
              <textarea name="inquiry_notes" rows={4} required placeholder="Tell us what you need help with." style={{ ...fieldStyle, resize: 'vertical' }} />
            </label>
            {status === 'error' && <p style={{ margin: '0 0 14px', fontFamily: 'Montserrat, sans-serif', fontSize: 13, lineHeight: 1.5, color: 'var(--chowdahead-red)' }}>{error}</p>}
            <Button variant="primary" size="lg" full disabled={status === 'sending'}>{status === 'sending' ? 'Sending…' : 'Send Inquiry'}</Button>
          </form>
        )}
      </div>
    </div>
  );
}

function SizePricingPage({ initialRows, customer, quoteSummary, onBack, onSent }) {
  const seededRows = React.useMemo(() => initialRows && initialRows.length ? initialRows : [CH_GARMENT_OPTS[0]], [initialRows]);
  const [sizeQty, setSizeQty] = React.useState({});
  const [colorChoice, setColorChoice] = React.useState(() => Object.fromEntries(seededRows.map(row => [row.id, row.selectedColorIdx || 0])));
  const [status, setStatus] = React.useState('form');
  const [error, setError] = React.useState('');
  const [inquiryOpen, setInquiryOpen] = React.useState(false);

  const rows = seededRows.map(opt => {
    const sizes = sizeListForGarment(opt.id);
    const breakdown = sizes.reduce((acc, size) => {
      const value = (sizeQty[opt.id] && sizeQty[opt.id][size]) || 0;
      if (value > 0) acc[size] = value;
      return acc;
    }, {});
    const total = Object.values(breakdown).reduce((sum, value) => sum + value, 0);
    const tierIdx = tierIndexFor(total || 1);
    const unitPrice = opt.prices[tierIdx] || 0;
    const colorIdx = Math.min(colorChoice[opt.id] || 0, Math.max((opt.colors || []).length - 1, 0));
    const selectedColor = opt.colors && opt.colors.length ? opt.colors[colorIdx] : null;
    return { ...opt, sizes, breakdown, total, tier: CH_TIERS[tierIdx], unitPrice, lineTotal: total * unitPrice, colorIdx, selectedColor };
  });
  const grandTotal = rows.reduce((sum, row) => sum + row.lineTotal, 0);
  const totalPieces = rows.reduce((sum, row) => sum + row.total, 0);
  const sizeSummary = rows.filter(row => row.total > 0).map(row => {
    const sizes = Object.entries(row.breakdown).map(([size, qty]) => `${size}: ${qty}`).join(', ');
    const color = row.selectedColor ? ` — ${row.selectedColor.name}` : '';
    return `${row.name}${color} (${row.total}): ${sizes}`;
  }).join(' | ');
  const sizeBreakdown = rows.reduce((acc, row) => {
    if (row.total > 0) acc[row.name] = { color: row.selectedColor && row.selectedColor.name, sizes: row.breakdown };
    return acc;
  }, {});
  const livePricing = rows.filter(row => row.total > 0).map(row => ({
    garment: row.name,
    color: row.selectedColor && row.selectedColor.name,
    quantity: row.total,
    tier: row.tier && row.tier.label,
    unitPrice: row.unitPrice,
    subtotal: row.lineTotal,
  }));

  const updateSize = (garmentId, size, raw) => {
    const nextQty = Math.max(0, Math.min(9999, parseInt(raw, 10) || 0));
    setSizeQty(current => ({
      ...current,
      [garmentId]: { ...(current[garmentId] || {}), [size]: nextQty },
    }));
  };

  const sendSizes = async () => {
    if (!totalPieces || status === 'sending') return;
    setStatus('sending');
    setError('');
    try {
      await submitSizeSelection({
        name: customer.name,
        email: customer.email,
        phone: customer.phone,
        company: customer.company,
        town: customer.town,
        summary: quoteSummary,
        sizeSummary,
        sizeBreakdown,
        livePricing,
      });
      setStatus('sent');
      if (onSent) onSent('Sizes sent — thank you!');
    } catch (err) {
      setError((err && err.message) || 'Something went wrong sending your sizes.');
      setStatus('error');
    }
  };

  return (
    <div style={{ minHeight: '100vh', background: 'var(--paper)' }}>
      <div style={{ background: 'var(--vintage-navy)', color: '#fff' }}>
        <div className="ch-hero-inner" style={{ maxWidth: 1240, margin: '0 auto', padding: '26px 24px 24px' }}>
          <div style={{ fontFamily: 'Oswald, sans-serif', fontWeight: 600, fontSize: 13, letterSpacing: '.16em', textTransform: 'uppercase', color: 'var(--grizzly-gold)' }}>Step 2</div>
          <h1 className="ch-hero-title" style={{ margin: '4px 0 0', fontFamily: 'Anton, sans-serif', fontSize: 'clamp(30px, 4.4vw, 56px)', lineHeight: 1, textTransform: 'uppercase', letterSpacing: '.01em' }}>Select Sizes &amp; See Live Pricing</h1>
        </div>
      </div>

      <div className="ch-page-shell" style={{ maxWidth: 1240, margin: '0 auto', padding: '28px 24px 64px' }}>
        <p className="ch-size-instructions" style={{ margin: '0 0 18px', padding: '14px 16px', background: 'var(--paper-2)', border: '1px solid var(--line)', borderRadius: 8, fontFamily: 'Montserrat, sans-serif', fontWeight: 700, fontSize: 15, lineHeight: 1.55, color: 'var(--chowdahead-red)' }}>Your inquiry was sent. Add the size breakdown below to see your estimated total, then send sizes to the Chowdaheadz team. Once we receive your sizes we will respond quickly with a formal quote that you can fill out to complete your order. You will review your art, placement and pricing before the job is approved!</p>
        <div className="ch-size-page-grid" style={{ display: 'grid', gridTemplateColumns: 'minmax(0, 1fr) 340px', gap: 28, alignItems: 'start' }}>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
            {rows.map(row => (
              <section key={row.id} className="ch-info-card" style={{ background: '#fff', border: '1px solid var(--line)', borderRadius: 10, padding: '22px 24px' }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', gap: 16, alignItems: 'baseline', marginBottom: 16 }}>
                  <div>
                    <h2 style={{ margin: 0, fontFamily: 'Oswald, sans-serif', fontWeight: 700, fontSize: 20, textTransform: 'uppercase', color: 'var(--ink)' }}>{row.name}</h2>
                    <div style={{ marginTop: 3, fontFamily: 'Montserrat, sans-serif', fontSize: 12.5, color: 'var(--ink-3)' }}>{row.sub}</div>
                  </div>
                  <div style={{ textAlign: 'right', fontFamily: 'Montserrat, sans-serif', fontSize: 13, color: 'var(--ink-2)' }}>
                    <strong style={{ display: 'block', fontFamily: 'Oswald, sans-serif', fontSize: 18, color: 'var(--chowdahead-red)' }}>{row.total ? chFmtShort(row.unitPrice) : '—'} each</strong>
                    {row.total ? `${row.tier.label} tier` : 'Enter sizes'}
                  </div>
                </div>
                {row.colors && row.colors.length ? (
                  <div style={{ marginBottom: 16 }}>
                    <div style={{ marginBottom: 9, fontFamily: 'Oswald, sans-serif', fontWeight: 700, fontSize: 13, textTransform: 'uppercase', letterSpacing: '.04em', color: 'var(--ink)' }}>Color: {row.selectedColor && row.selectedColor.name}</div>
                    <div className="ch-color-swatches" style={{ display: 'flex', flexWrap: 'wrap', gap: 10 }}>
                      {row.colors.map((c, i) => (
                        <ColorSwatch key={c.name} c={c} active={i === row.colorIdx} onClick={() => setColorChoice(current => ({ ...current, [row.id]: i }))} />
                      ))}
                    </div>
                  </div>
                ) : null}
                <div className="ch-size-grid" style={{ display: 'grid', gridTemplateColumns: row.sizes.length > 1 ? `repeat(${row.sizes.length}, minmax(0, 1fr))` : 'repeat(auto-fit, minmax(120px, 1fr))', gap: 10 }}>
                  {row.sizes.map(size => (
                    <label key={size} style={{ display: 'block', padding: '10px 12px', background: 'var(--paper-2)', border: '1px solid var(--line)', borderRadius: 8 }}>
                      <span style={{ display: 'block', marginBottom: 7, fontFamily: 'Oswald, sans-serif', fontWeight: 700, fontSize: 13, textTransform: 'uppercase', color: 'var(--ink)' }}>{size}</span>
                      <input type="number" inputMode="numeric" min="0" max="9999" step="1" value={(sizeQty[row.id] && sizeQty[row.id][size]) || ''} placeholder="0" onChange={e => updateSize(row.id, size, e.target.value)} aria-label={`${row.name} ${size} quantity`} style={{ display: 'block', width: '100%', boxSizing: 'border-box', padding: '10px 9px', border: '1px solid var(--line-strong)', borderRadius: 6, background: '#fff', fontFamily: 'Oswald, sans-serif', fontWeight: 700, fontSize: 20, color: 'var(--ink)', fontVariantNumeric: 'tabular-nums' }} />
                    </label>
                  ))}
                </div>
              </section>
            ))}
          </div>

          <aside className="ch-info-card" style={{ position: 'sticky', top: 20, background: '#fff', border: '1px solid var(--line)', borderRadius: 10, padding: '22px 24px', boxShadow: 'var(--shadow-sm)' }}>
            <div style={{ fontFamily: 'Oswald, sans-serif', fontWeight: 700, fontSize: 18, textTransform: 'uppercase', color: 'var(--ink)' }}>Live Pricing</div>
            <div style={{ marginTop: 12, display: 'flex', flexDirection: 'column', gap: 10 }}>
              {rows.filter(row => row.total > 0).length ? rows.filter(row => row.total > 0).map(row => (
                <div key={row.id} style={{ borderBottom: '1px solid var(--line)', paddingBottom: 10, fontFamily: 'Montserrat, sans-serif', fontSize: 13, color: 'var(--ink-2)' }}>
                  <strong style={{ display: 'block', color: 'var(--ink)' }}>{row.name}</strong>
                  {row.selectedColor && <span style={{ display: 'block', marginBottom: 2 }}>Color: {row.selectedColor.name}</span>}
                  {row.total} × {chFmtShort(row.unitPrice)} = <strong>{chFmt(row.lineTotal)}</strong>
                </div>
              )) : <p style={{ margin: 0, fontFamily: 'Montserrat, sans-serif', fontSize: 13, lineHeight: 1.55, color: 'var(--ink-3)' }}>Enter sizes to calculate your estimated total.</p>}
            </div>
            <div style={{ marginTop: 16, paddingTop: 16, borderTop: '2px solid var(--vintage-navy)', display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
              <span style={{ fontFamily: 'Oswald, sans-serif', fontWeight: 700, fontSize: 15, textTransform: 'uppercase', color: 'var(--ink)' }}>{totalPieces} pieces</span>
              <span style={{ fontFamily: 'Anton, sans-serif', fontSize: 34, color: 'var(--chowdahead-red)' }}>{chFmt(grandTotal)}</span>
            </div>
            {status === 'sent' ? (
              <div style={{ marginTop: 14, display: 'flex', flexDirection: 'column', gap: 10 }}>
                <div style={{ padding: '12px 14px', borderRadius: 8, background: 'rgba(0,144,72,.1)', color: 'var(--kelly-green)', fontFamily: 'Oswald, sans-serif', fontWeight: 700, textTransform: 'uppercase' }}>Sizes sent!</div>
                <Button variant="outline" full onClick={onBack}>Back To Design</Button>
                <Button variant="dark" full onClick={() => setInquiryOpen(true)}>Send us an inquiry</Button>
              </div>
            ) : (
              <div style={{ marginTop: 18, display: 'flex', flexDirection: 'column', gap: 10 }}>
                <Button variant="primary" size="lg" full disabled={!totalPieces || status === 'sending'} onClick={sendSizes}>{status === 'sending' ? 'Sending…' : 'Send Sizes'}</Button>
              </div>
            )}
            {status === 'error' && <p style={{ margin: '12px 0 0', fontFamily: 'Montserrat, sans-serif', fontSize: 13, lineHeight: 1.5, color: 'var(--chowdahead-red)' }}>{error}</p>}
            <p style={{ margin: '14px 0 0', fontFamily: 'Montserrat, sans-serif', fontSize: 12, lineHeight: 1.5, color: 'var(--ink-3)' }}>Pricing is an instant estimate based on selected quantities. Our team will confirm final details before production and send you an invoice for payment. Shipping charges may also apply. Need help now? Email custom@chowdaheadz.com. We will email you very shortly to finalize your order!</p>
          </aside>
        </div>
      </div>
      <SizeInquiryModal
        open={inquiryOpen}
        customer={customer}
        summary={quoteSummary}
        sizeSummary={sizeSummary}
        onClose={() => setInquiryOpen(false)}
        onSent={message => { if (onSent) onSent(message); }}
      />
    </div>
  );
}

function CustomShop() {
  const [garmentId, setGarmentId] = React.useState('tee');
  const [colorIdx, setColorIdx] = React.useState(0);
  const [artwork, setArtwork] = React.useState(null);
  const [fileName, setFileName] = React.useState('');
  const [quantities, setQuantities] = React.useState(Object.fromEntries(CH_GARMENT_OPTS.map(opt => [opt.id, 0])));
  const [cartCount, setCartCount] = React.useState(0);
  const [quoteOpen, setQuoteOpen] = React.useState(false);
  const [toast, setToast] = React.useState('');
  const [page, setPage] = React.useState('design');
  const [customerInfo, setCustomerInfo] = React.useState(null);
  const [studioOpen, setStudioOpen] = React.useState(false);
  const [studioTab, setStudioTab] = React.useState('add');
  const [studioDoc, setStudioDoc] = React.useState(null);
  // print placement: 1 = artwork fits the standard print zone; offset is a
  // fraction of the zone height (negative = up)
  const [artScale, setArtScale] = React.useState(1);
  const [artOffsetY, setArtOffsetY] = React.useState(0);
  const resetPlacement = () => { setArtScale(1); setArtOffsetY(0); };

  const garment = CH_GARMENT_OPTS.find(g => g.id === garmentId);
  const colors = garment.colors;
  const color = colors[Math.min(colorIdx, colors.length - 1)];
  const totalQty = CH_GARMENT_OPTS.reduce((sum, opt) => sum + (quantities[opt.id] || 0), 0);
  const quantityRows = CH_GARMENT_OPTS.map(opt => ({ ...opt, qty: quantities[opt.id] || 0 }));
  const quantitySummary = totalQty > 0
    ? quantityRows.filter(opt => opt.qty > 0).map(opt => `${opt.name}: ${opt.qty}`).join(', ')
    : 'No quantity entered';
  const quantityBreakdown = quantityRows.reduce((acc, opt) => {
    if (opt.qty > 0) acc[opt.name] = opt.qty;
    return acc;
  }, {});
  const summary = `${totalQty || 0} total pieces · ${garment.name} preview · ${color.name}`;

  React.useEffect(() => { if (toast) { const t = setTimeout(() => setToast(''), 2600); return () => clearTimeout(t); } }, [toast]);

  const selectGarment = (opt) => {
    setGarmentId(opt.id);
    setColorIdx(0);
  };

  const labelStyle = { fontFamily: 'Oswald, sans-serif', fontWeight: 600, fontSize: 13, textTransform: 'uppercase', letterSpacing: '.03em', color: 'var(--ink)' };
  const selectedGarmentsForSizing = quantityRows
    .filter(opt => opt.qty > 0)
    .map(opt => ({ ...opt, selectedColorIdx: opt.id === garmentId ? colorIdx : 0 }));

  if (page === 'sizes' && customerInfo) {
    return (
      <SizePricingPage
        initialRows={selectedGarmentsForSizing.length ? selectedGarmentsForSizing : [{ ...garment, selectedColorIdx: colorIdx }]}
        customer={customerInfo}
        quoteSummary={summary}
        onBack={() => setPage('design')}
        onSent={message => setToast(message)}
      />
    );
  }

  return (
    <div style={{ minHeight: '100vh', background: 'var(--paper)' }}>
      <ShopHeader />
      {/* hero band */}
      <div style={{ background: 'var(--vintage-navy)', backgroundImage: 'repeating-linear-gradient(135deg, rgba(255,255,255,.025) 0 2px, transparent 2px 22px)', color: '#fff' }}>
        <div className="ch-hero-inner" style={{ maxWidth: 1240, margin: '0 auto', padding: '26px 24px 24px' }}>
          <div style={{ fontFamily: 'Oswald, sans-serif', fontWeight: 600, fontSize: 13, letterSpacing: '.16em', textTransform: 'uppercase', color: 'var(--grizzly-gold)' }}>The Custom Shop</div>
          <h1 className="ch-hero-title" style={{ margin: '4px 0 0', fontFamily: 'Anton, sans-serif', fontSize: 'clamp(26px, 3.6vw, 46px)', lineHeight: 1, textTransform: 'uppercase', letterSpacing: '.01em', whiteSpace: 'nowrap' }}>Print Your Own Wicked Good Gear</h1>
          <p className="ch-hero-copy" style={{ margin: '14px 0 0', maxWidth: '76rem', whiteSpace: 'normal', fontFamily: 'Montserrat, sans-serif', fontSize: 16, lineHeight: 1.6, color: 'rgba(247,244,236,.82)' }}>Design your shirt right here — add text in print-ready fonts, upload your art, or describe your idea and let AI design it for you. Pick your garment, enter your quantity, get custom pricing. Designed by you, printed by us, just outside Boston. We keep our color options limited and instead keep the garments always in stock for fast turnaround. We also use high quality blanks so you get a great finished product at a lower cost than anywhere else!</p>
        </div>
      </div>

      <div className="ch-page-shell" style={{ maxWidth: 1240, margin: '0 auto', padding: '28px 24px 64px' }}>
        <div className="ch-shop-grid" style={{ display: 'grid', gridTemplateColumns: 'minmax(0, 1fr) minmax(0, 1.05fr)', gap: 36, alignItems: 'start' }}>

          {/* ---------- LEFT: preview ---------- */}
          <div className="ch-preview-col" style={{ position: 'sticky', top: 20 }}>
            <div className="ch-preview-card" style={{ background: '#fff', border: '1px solid var(--line)', borderRadius: 10, overflow: 'hidden', boxShadow: 'var(--shadow-sm)' }}>
              <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '12px 18px', borderBottom: '1px solid var(--line)' }}>
                <span style={labelStyle}>Live Preview</span>
                <span style={{ fontFamily: 'Oswald, sans-serif', fontWeight: 600, fontSize: 11.5, textTransform: 'uppercase', letterSpacing: '.05em', color: 'var(--ink-3)', border: '1px solid var(--line-strong)', borderRadius: 999, padding: '3px 10px' }}>Front</span>
              </div>
              <div className="ch-preview-stage" style={{ background: color.img ? '#fff' : 'linear-gradient(180deg, var(--paper-2), var(--paper))', padding: '10px 20px 0', height: 480, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                {color.img
                  ? <PhotoTee src={color.img} artwork={artwork} light={chLuminance(color.hex) > 0.5} printZone={garment.printZone} strings={color.strings} artScale={artScale} artOffsetY={artOffsetY} />
                  : <Garment type={garmentId} color={color.hex} artwork={artwork} scale={artScale} offsetY={artOffsetY * (CH_GARMENTS[garmentId] || CH_GARMENTS.tee).print.h} />}
              </div>
              <div className="ch-preview-meta" style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '14px 18px', borderTop: '1px solid var(--line)' }}>
                <div>
                  <div style={{ fontFamily: 'Oswald, sans-serif', fontWeight: 700, fontSize: 17, textTransform: 'uppercase', color: 'var(--ink)' }}>{garment.name}</div>
                  <div style={{ fontFamily: 'Montserrat, sans-serif', fontSize: 12.5, color: 'var(--ink-3)' }}>{garment.sub}</div>
                </div>
                <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                  <span style={{ width: 18, height: 18, borderRadius: 999, background: color.hex, border: '1px solid rgba(0,0,0,.12)', display: 'inline-block' }} />
                  <span style={{ fontFamily: 'Montserrat, sans-serif', fontSize: 13, fontWeight: 600, color: 'var(--ink-2)' }}>{color.name}</span>
                </div>
              </div>
            </div>
            <p style={{ margin: '12px 4px 0', fontFamily: 'Montserrat, sans-serif', fontSize: 12, color: 'var(--ink-3)', lineHeight: 1.5 }}>Preview is for placement only — our art team confirms sizing &amp; ink colors before printing. Transparent PNGs print cleanest.</p>
          </div>

          {/* ---------- RIGHT: controls ---------- */}
          <div className="ch-controls-col" style={{ display: 'flex', flexDirection: 'column', gap: 30 }}>

            {/* 1 — garment */}
            <section>
              <SectionLabel step="1">Garment Options</SectionLabel>
              <div className="ch-garment-tabs" style={{ display: 'grid', gridTemplateColumns: 'repeat(5, minmax(0, 1fr))', gap: 8 }}>
                {CH_GARMENT_OPTS.map(opt => (
                  <GarmentTab key={opt.id} opt={opt} active={opt.id === garmentId} onClick={() => selectGarment(opt)} />
                ))}
              </div>
            </section>

            {/* 2 — design: upload, build in the studio, or generate with AI */}
            <section>
              <SectionLabel step="2">Your design</SectionLabel>
              <UploadZone artwork={artwork} fileName={fileName} onFile={(d, n) => { setArtwork(d); setFileName(n); setStudioDoc(null); resetPlacement(); }} onClear={() => { setArtwork(null); setFileName(''); setStudioDoc(null); resetPlacement(); }} />
              <div className="ch-studio-launch" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10, marginTop: 10 }}>
                <button onClick={() => { setStudioTab('add'); setStudioOpen(true); }}
                  style={{ cursor: 'pointer', padding: '13px 14px', borderRadius: 8, border: '2px solid var(--vintage-navy)', background: '#fff', textAlign: 'left', boxShadow: 'var(--shadow-sm)' }}>
                  <span style={{ display: 'block', fontFamily: 'Oswald, sans-serif', fontWeight: 700, fontSize: 14.5, textTransform: 'uppercase', color: 'var(--vintage-navy)' }}>{studioDoc ? 'Edit Your Design' : 'Design It Yourself'}</span>
                  <span style={{ display: 'block', marginTop: 3, fontFamily: 'Montserrat, sans-serif', fontSize: 11.5, lineHeight: 1.4, color: 'var(--ink-3)' }}>Add text in print-ready fonts, curve it, layer your art</span>
                </button>
                <button onClick={() => { setStudioTab('ai'); setStudioOpen(true); }}
                  style={{ cursor: 'pointer', padding: '13px 14px', borderRadius: 8, border: '2px solid var(--grizzly-gold)', background: '#fff', textAlign: 'left', boxShadow: 'var(--shadow-sm)' }}>
                  <span style={{ display: 'block', fontFamily: 'Oswald, sans-serif', fontWeight: 700, fontSize: 14.5, textTransform: 'uppercase', color: 'var(--vintage-navy)' }}>&#10024; Design With AI</span>
                  <span style={{ display: 'block', marginTop: 3, fontFamily: 'Montserrat, sans-serif', fontSize: 11.5, lineHeight: 1.4, color: 'var(--ink-3)' }}>Describe your idea — get a print-ready design you can edit</span>
                </button>
              </div>
              {artwork && (
                <div className="ch-placement-card" style={{ marginTop: 12, padding: '14px 16px', background: '#fff', border: '1px solid var(--line)', borderRadius: 8 }}>
                  <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: 12 }}>
                    <span style={{ fontFamily: 'Oswald, sans-serif', fontWeight: 700, fontSize: 13, textTransform: 'uppercase', letterSpacing: '.04em', color: 'var(--ink)' }}>Print size &amp; position</span>
                    {(artScale !== 1 || artOffsetY !== 0) && (
                      <button onClick={resetPlacement} style={{ background: 'none', border: 'none', cursor: 'pointer', padding: 0, fontFamily: 'Oswald, sans-serif', fontWeight: 600, fontSize: 11.5, textTransform: 'uppercase', letterSpacing: '.04em', color: 'var(--marathon-blue)' }}>Reset</button>
                    )}
                  </div>
                  <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: 4 }}>
                    <span style={{ fontFamily: 'Oswald, sans-serif', fontWeight: 600, fontSize: 12, textTransform: 'uppercase', letterSpacing: '.04em', color: 'var(--ink-2)' }}>Size</span>
                    <span style={{ fontFamily: 'Montserrat, sans-serif', fontSize: 12, fontVariantNumeric: 'tabular-nums', color: 'var(--ink-3)' }}>{Math.round(artScale * 100)}%</span>
                  </div>
                  <input type="range" min="0.5" max="2" step="0.05" value={artScale} onChange={e => setArtScale(parseFloat(e.target.value))} aria-label="Print size" style={{ width: '100%', accentColor: 'var(--chowdahead-red)', display: 'block' }} />
                  <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', margin: '12px 0 4px' }}>
                    <span style={{ fontFamily: 'Oswald, sans-serif', fontWeight: 600, fontSize: 12, textTransform: 'uppercase', letterSpacing: '.04em', color: 'var(--ink-2)' }}>Position</span>
                    <span style={{ fontFamily: 'Montserrat, sans-serif', fontSize: 12, fontVariantNumeric: 'tabular-nums', color: 'var(--ink-3)' }}>{artOffsetY === 0 ? 'Centered' : (artOffsetY < 0 ? 'Up ' : 'Down ') + Math.round(Math.abs(artOffsetY) * 100) + '%'}</span>
                  </div>
                  <input type="range" min="-0.15" max="0.15" step="0.01" value={artOffsetY} onChange={e => setArtOffsetY(parseFloat(e.target.value))} aria-label="Print vertical position" style={{ width: '100%', accentColor: 'var(--chowdahead-red)', display: 'block' }} />
                  <span style={{ display: 'block', marginTop: 8, fontFamily: 'Montserrat, sans-serif', fontSize: 11.5, lineHeight: 1.45, color: 'var(--ink-3)' }}>Watch the live preview — your size and position are saved with the mockup we receive, and our art team confirms exact placement before printing.</span>
                </div>
              )}
            </section>

            {/* 3 — color */}
            <section>
              <SectionLabel step="3" hint={color.name}>Color Options</SectionLabel>
              <div className="ch-color-swatches" style={{ display: 'flex', flexWrap: 'wrap', gap: 12 }}>
                {colors.map((c, i) => (
                  <ColorSwatch key={c.name} c={c} active={i === colorIdx} onClick={() => setColorIdx(i)} />
                ))}
              </div>
            </section>

            {/* 4 — quantity */}
            <section>
              <SectionLabel step="4" hint={`${totalQty} total`}>Total Quantity</SectionLabel>
              <div className="ch-quantity-grid" style={{ display: 'grid', gridTemplateColumns: 'repeat(5, minmax(0, 1fr))', gap: 8 }}>
                {quantityRows.map(opt => {
                  const active = opt.id === garmentId;
                  const hasQty = opt.qty > 0;
                  return (
                    <label
                      key={opt.id}
                      style={{
                        display: 'block', minWidth: 0, padding: '10px 12px',
                        background: active || hasQty ? 'var(--paper-2)' : '#fff',
                        border: active ? '2px solid var(--vintage-navy)' : '1px solid var(--line)',
                        borderRadius: 6, transition: 'all .12s',
                        boxShadow: active ? '2px 2px 0 var(--vintage-navy)' : 'none',
                        transform: active ? 'translate(-1px,-1px)' : 'none',
                      }}>
                      <span style={{ display: 'block', marginBottom: 8, fontFamily: 'Oswald, sans-serif', fontWeight: 700, fontSize: 13.5, textTransform: 'uppercase', color: 'var(--ink)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{opt.name}</span>
                      <input
                        type="number"
                        inputMode="numeric"
                        min="0"
                        max="9999"
                        step="1"
                        value={opt.qty || ''}
                        placeholder="0"
                        onChange={e => {
                          const nextQty = Math.max(0, Math.min(9999, parseInt(e.target.value, 10) || 0));
                          setQuantities(q => ({ ...q, [opt.id]: nextQty }));
                        }}
                        aria-label={`${opt.name} total quantity`}
                        style={{ display: 'block', width: '100%', padding: '10px 9px', border: '1px solid var(--line-strong)', borderRadius: 6, background: '#fff', fontFamily: 'Oswald, sans-serif', fontWeight: 700, fontSize: 20, color: 'var(--ink)', fontVariantNumeric: 'tabular-nums' }}
                      />
                    </label>
                  );
                })}
              </div>
              <span style={{ display: 'block', marginTop: 10, fontFamily: 'Montserrat, sans-serif', fontSize: 12.5, lineHeight: 1.45, color: 'var(--ink-3)' }}>Enter quantities for any garment options you want quoted. The cards stay visible while you switch garments; our team will confirm sizing before printing.</span>
            </section>
          </div>
        </div>

        {/* ---------- GET PRICING CTA ---------- */}
        <div className="ch-price-bar" style={{ marginTop: 34, background: 'var(--vintage-navy)', borderRadius: 10, boxShadow: 'var(--shadow)', overflow: 'hidden' }}>
          <div className="ch-price-content" style={{ padding: '22px 24px', display: 'flex', alignItems: 'center', gap: 28, flexWrap: 'wrap' }}>
            <div>
              <div style={{ fontFamily: 'Oswald, sans-serif', fontWeight: 600, fontSize: 12, letterSpacing: '.1em', textTransform: 'uppercase', color: 'rgba(247,244,236,.6)' }}>Custom pricing</div>
              <div style={{ fontFamily: 'Montserrat, sans-serif', fontSize: 15, lineHeight: 1.55, color: 'rgba(247,244,236,.85)' }}>
                Submit your design, garment color, and quantities and our team will follow up with pricing and next steps.
              </div>
            </div>
            <div className="ch-price-actions" style={{ marginLeft: 'auto', display: 'flex', alignItems: 'center', gap: 12, flexWrap: 'wrap' }}>
              <Button variant="primary" size="lg" onClick={() => setQuoteOpen(true)}>
                Get Pricing <Icon name="arrowRight" size={18} color="#fff" />
              </Button>
            </div>
          </div>
        </div>

        <div style={{ marginTop: 40 }}><Reassurance /></div>

        <div className="ch-info-card" style={{ marginTop: 28, background: '#fff', border: '1px solid var(--line)', borderRadius: 10, padding: '26px 28px' }}>
          <h3 style={{ margin: '0 0 16px', fontFamily: 'Oswald, sans-serif', fontWeight: 700, fontSize: 17, textTransform: 'uppercase', letterSpacing: '.02em', color: 'var(--ink)' }}>How we keep it fast &amp; affordable</h3>
          <ul style={{ margin: 0, padding: 0, listStyle: 'none', display: 'flex', flexDirection: 'column', gap: 14 }}>
            {[
              ['Premium garments only', 'We don\u2019t cut corners on blanks \u2014 we stock and print exclusively on premium-quality garments, with special pricing to keep those better blanks affordable.'],
              ['Limited stocked colors', 'We carry a curated selection of garment colors we keep in stock. Sticking to what\u2019s on our shelves lets us print your order fast and keep your costs down.'],
              ['Front-center chest printing only', 'We print on the front center chest area only. Keeping every job to one standard print location keeps production costs low and gets your order out the door quickly.'],
            ].map(([t, s]) => (
              <li key={t} style={{ display: 'flex', gap: 13, alignItems: 'flex-start' }}>
                <span style={{ flex: 'none', marginTop: 2, width: 22, height: 22, borderRadius: 999, background: 'var(--kelly-green)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}><Icon name="check" size={14} color="#fff" /></span>
                <span style={{ fontFamily: 'Montserrat, sans-serif', fontSize: 14, lineHeight: 1.55, color: 'var(--ink-2)' }}>
                  <strong style={{ color: 'var(--ink)' }}>{t}.</strong> {s}
                </span>
              </li>
            ))}
          </ul>
        </div>

        <div className="ch-info-card" style={{ marginTop: 28, background: '#fff', border: '1px solid var(--line)', borderRadius: 10, padding: '26px 28px' }}>
          <h3 style={{ margin: '0 0 12px', fontFamily: 'Oswald, sans-serif', fontWeight: 700, fontSize: 17, textTransform: 'uppercase', letterSpacing: '.02em', color: 'var(--ink)' }}>How Do I Create Art?</h3>
          <p style={{ margin: '0 0 18px', fontFamily: 'Montserrat, sans-serif', fontSize: 14, lineHeight: 1.6, color: 'var(--ink-2)' }}>
            You don't need finished artwork — our built-in <strong>Design Studio</strong> (step 2 above) lets you add text in real print fonts, arch and layer it, upload whatever art you have, or describe your idea and let AI generate a print-ready design you can keep editing. Prefer outside tools? These work great too. If you are making more than 72 t-shirts, we can help with the art — submit the form blank or send whatever you have so we can help guide the design.
          </p>
          <div className="ch-tools-grid" style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(185px, 1fr))', gap: 12 }}>
            {[
              ['Canva', 'https://www.canva.com/', 'Easy templates for beginners'],
              ['Kittl', 'https://www.kittl.com/', 'Great for vintage-style graphics'],
              ['Adobe Express', 'https://www.adobe.com/express/', 'Quick social and merch designs'],
              ['Figma', 'https://www.figma.com/', 'Flexible layout and vector tools'],
              ['VistaCreate', 'https://create.vista.com/', 'Ready-made design templates'],
              ['Fiverr', 'https://www.fiverr.com/', 'Hire a freelance designer'],
              ['ChatGPT', 'https://chatgpt.com/', 'Use it for ideas, copy, and prompts'],
            ].map(([name, href, desc]) => (
              <a key={name} href={href} target="_blank" rel="noopener noreferrer" style={{ display: 'block', padding: '15px 16px', background: 'var(--paper-2)', border: '1px solid var(--line)', borderRadius: 8, textDecoration: 'none', color: 'var(--ink)' }}>
                <span style={{ display: 'block', fontFamily: 'Oswald, sans-serif', fontWeight: 700, fontSize: 15, textTransform: 'uppercase', letterSpacing: '.02em', color: 'var(--dark-royal)' }}>{name}</span>
                <span style={{ display: 'block', marginTop: 4, fontFamily: 'Montserrat, sans-serif', fontSize: 12.5, lineHeight: 1.45, color: 'var(--ink-2)' }}>{desc}</span>
              </a>
            ))}
          </div>
        </div>

        <section className="ch-seo-copy" aria-labelledby="custom-apparel-printing-heading" style={{ marginTop: 28, marginBottom: 48, background: 'var(--paper-2)', border: '1px solid var(--line)', borderRadius: 10, padding: '28px 30px' }}>
          <h2 id="custom-apparel-printing-heading" style={{ margin: '0 0 14px', fontFamily: 'Oswald, sans-serif', fontWeight: 700, fontSize: 21, lineHeight: 1.18, textTransform: 'uppercase', letterSpacing: '.02em', color: 'var(--ink)' }}>Custom apparel printing near Boston</h2>
          <p style={{ margin: '0 0 14px', fontFamily: 'Montserrat, sans-serif', fontSize: 15, lineHeight: 1.7, color: 'var(--ink-2)' }}>
            Chowdaheadz offers professional custom apparel printing for businesses, bands, schools, and organizations. Based in Woburn, MA—just north of Boston—we’ve been New England’s trusted choice for high-quality custom merchandise for over 20 years. While we love our local roots, we ship nationwide.
          </p>
          <p style={{ margin: '0 0 14px', fontFamily: 'Montserrat, sans-serif', fontSize: 15, lineHeight: 1.7, color: 'var(--ink-2)' }}>
            Whether you need custom t-shirts, ladies tees, hoodies, or hats, we’ve got you covered.
          </p>
          <p style={{ margin: 0, fontFamily: 'Montserrat, sans-serif', fontSize: 15, lineHeight: 1.7, color: 'var(--ink-2)' }}>
            Ready to get started? Our minimum order is just 12 pieces. Fill out the pricing form above and let’s get rolling!
          </p>
        </section>
      </div>

      {/* toast */}
      {toast && (
        <div className="ch-toast" style={{ position: 'fixed', left: '50%', bottom: 28, transform: 'translateX(-50%)', zIndex: 90, background: 'var(--kelly-green)', color: '#fff', padding: '13px 22px', borderRadius: 8, boxShadow: 'var(--shadow-lg)', fontFamily: 'Oswald, sans-serif', fontWeight: 600, fontSize: 15, textTransform: 'uppercase', letterSpacing: '.02em', display: 'flex', alignItems: 'center', gap: 10 }}>
          <Icon name="check" size={20} color="#fff" /> {toast}
        </div>
      )}

      <DesignStudio
        open={studioOpen}
        initialDoc={studioDoc}
        initialTab={studioTab}
        garmentColor={color}
        onClose={() => setStudioOpen(false)}
        onApply={({ dataUrl, doc }) => {
          setArtwork(dataUrl);
          setFileName('chowdaheadz-studio-design.png');
          setStudioDoc(doc);
          setStudioOpen(false);
          setToast('Design applied to your garment!');
        }}
      />
      <QuoteModal open={quoteOpen} onClose={() => setQuoteOpen(false)} summary={summary} sizeSummary={quantitySummary}
        onSent={({ fields }) => { setCustomerInfo(fields); setQuoteOpen(false); setPage('sizes'); }}
        uploadCtx={{
          baseSrc: color.img,
          artwork,
          printZone: garment.printZone || (typeof CH_TEE_PRINT !== 'undefined' ? CH_TEE_PRINT : { left: '34%', top: '24%', width: '32%', height: '33%' }),
          strings: color.strings,
          artScale,
          artOffsetY,
          artworkName: fileName,
          garmentName: garment.name,
          colorName: color.name,
          sizeBreakdown: quantityBreakdown,
          sizeSummary: quantitySummary,
        }} />
    </div>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<CustomShop />);
