/* designer.jsx — Chowdaheadz Custom Shop: the full t-shirt designer tool. */

/* ---------------- DATA ---------------- */
const CH_PRICING = window.CH_CUSTOM_PRICING || {};
const CH_DEFAULT_TIERS = [
  { min: 1, max: 11, label: '1–11' },
  { min: 12, max: 23, label: '12–23' },
  { min: 24, max: 49, label: '24–49' },
  { min: 50, max: 99, label: '50–99' },
  { min: 100, max: Infinity, label: '100+' },
];
const CH_DEFAULT_GARMENT_PRICES = {
  tee: [22, 18, 15, 13, 11],
  ladies: [22, 18, 15, 13, 11],
  long: [27, 23, 20, 18, 16],
  hoodie: [44, 39, 35, 32, 29],
  hat: [26, 23, 20, 18, 16],
};

// quantity tiers — index aligns with each garment's price array
const CH_TIERS = CH_PRICING.tiers || CH_DEFAULT_TIERS;
const CH_GARMENT_PRICES = { ...CH_DEFAULT_GARMENT_PRICES, ...(CH_PRICING.garmentPrices || {}) };

function chPricesFor(garmentId) {
  const prices = CH_GARMENT_PRICES[garmentId] || CH_DEFAULT_GARMENT_PRICES[garmentId];
  return CH_TIERS.map((tier, idx) => {
    const price = prices && prices[idx];
    return typeof price === 'number' ? price : 0;
  });
}

const CH_COLOR = {
  gray:        { name: 'Gray', hex: '#A7A9AC' },
  charcoal:    { name: 'Charcoal', hex: '#3A3D42' },
  heatherNavy: { name: 'Heather Navy', hex: '#2C3A57' },
  kelly:       { name: 'Kelly Green', hex: '#009048' },
  military:    { name: 'Military Green', hex: '#565B3C' },
  navy:        { name: 'Navy', hex: '#18243C' },
  black:       { name: 'Black', hex: '#191919' },
  white:       { name: 'White', hex: '#FFFFFF' },
};
const CH_ALL_COLORS = [CH_COLOR.gray, CH_COLOR.charcoal, CH_COLOR.heatherNavy, CH_COLOR.kelly, CH_COLOR.military, CH_COLOR.navy];

const CH_GARMENT_OPTS = [
  {
    id: 'tee', name: 'T-Shirt', sub: 'Classic 5.3oz cotton', prices: chPricesFor('tee'),
    colors: [
      { ...CH_COLOR.gray, img: 'assets/shirts/tee-gray.jpg' },
      { ...CH_COLOR.charcoal, img: 'assets/shirts/tee-charcoal.jpg' },
      { ...CH_COLOR.heatherNavy, img: 'assets/shirts/tee-heathernavy.jpg' },
      { ...CH_COLOR.kelly, img: 'assets/shirts/tee-kelly.jpg' },
      { ...CH_COLOR.military, img: 'assets/shirts/tee-military.jpg' },
      { ...CH_COLOR.navy, img: 'assets/shirts/tee-navy.jpg' },
    ],
  },
  {
    id: 'ladies', name: 'Ladies', sub: 'Ladies fit tee', prices: chPricesFor('ladies'),
    colors: [
      { ...CH_COLOR.gray, img: 'assets/shirts/LT-GY-Flat.jpg' },
      { ...CH_COLOR.charcoal, img: 'assets/shirts/LT-CC-Flat.jpg' },
      { ...CH_COLOR.heatherNavy, img: 'assets/shirts/LT-HB-Flat.jpg' },
      { ...CH_COLOR.kelly, img: 'assets/shirts/LT-GN-Flat.jpg' },
      { ...CH_COLOR.navy, img: 'assets/shirts/LT-NY-Flat.jpg' },
    ],
  },
  {
    id: 'long', name: 'Long Sleeve', sub: 'Cozy cotton long-sleeve', prices: chPricesFor('long'),
    printZone: { left: '35%', top: '23.5%', width: '30%', height: '30%' },
    colors: [
      { ...CH_COLOR.charcoal, img: 'assets/shirts/ls-charcoal.jpg' },
      { ...CH_COLOR.gray, img: 'assets/shirts/ls-gray.jpg' },
      { ...CH_COLOR.navy, img: 'assets/shirts/ls-navy.jpg' },
    ],
  },
  {
    id: 'hoodie', name: 'Hoodie', sub: 'Heavyweight fleece pullover', prices: chPricesFor('hoodie'),
    printZone: { left: '36%', top: '34%', width: '28%', height: '26%' },
    colors: [
      { ...CH_COLOR.charcoal, img: 'assets/shirts/hoodie-charcoal.png', strings: 'assets/shirts/hoodie-charcoal-strings.png' },
      { ...CH_COLOR.gray, img: 'assets/shirts/hoodie-gray.png', strings: 'assets/shirts/hoodie-gray-strings.png' },
      { ...CH_COLOR.heatherNavy, img: 'assets/shirts/hoodie-heathernavy.png', strings: 'assets/shirts/hoodie-heathernavy-strings.png' },
      { ...CH_COLOR.military, img: 'assets/shirts/hoodie-military.png', strings: 'assets/shirts/hoodie-military-strings.png' },
    ],
  },
  {
    id: 'hat', name: 'Hat', sub: 'Performance 5-panel cap', prices: chPricesFor('hat'),
    printZone: { left: '30%', top: '27%', width: '40%', height: '28%' },
    colors: [
      { ...CH_COLOR.black, img: 'assets/shirts/hat-black.jpg' },
      { ...CH_COLOR.gray, img: 'assets/shirts/hat-gray.jpg' },
      { ...CH_COLOR.navy, img: 'assets/shirts/hat-navy.jpg' },
      { ...CH_COLOR.white, img: 'assets/shirts/hat-white.jpg' },
    ],
  },
];

const CH_COLORS = CH_ALL_COLORS;

function tierIndexFor(qty) {
  for (let i = CH_TIERS.length - 1; i >= 0; i--) {
    if (qty >= CH_TIERS[i].min) return i;
  }
  return 0;
}

function chFmt(n) {
  return '$' + n.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
}
function chFmtShort(n) {
  return '$' + (Number.isInteger(n) ? n : n.toFixed(2));
}

/* ---------------- SMALL PIECES ---------------- */

function SectionLabel({ step, children, hint }) {
  return (
    <div style={{ display: 'flex', alignItems: 'baseline', gap: 10, marginBottom: 14 }}>
      <span style={{
        fontFamily: 'Oswald, sans-serif', fontWeight: 700, fontSize: 13, lineHeight: 1,
        width: 24, height: 24, borderRadius: 999, background: 'var(--vintage-navy)', color: '#fff',
        display: 'inline-flex', alignItems: 'center', justifyContent: 'center', flex: 'none',
      }}>{step}</span>
      <h3 style={{ margin: 0, fontFamily: 'Oswald, sans-serif', fontWeight: 700, fontSize: 18, textTransform: 'uppercase', letterSpacing: '.02em', color: 'var(--ink)' }}>{children}</h3>
      {hint && <span style={{ marginLeft: 'auto', fontFamily: 'Montserrat, sans-serif', fontSize: 12.5, color: 'var(--ink-3)' }}>{hint}</span>}
    </div>
  );
}

function GarmentTab({ opt, active, onClick }) {
  const [hover, setHover] = React.useState(false);
  return (
    <button onClick={onClick} onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)}
      style={{
        flex: 1, textAlign: 'left', cursor: 'pointer', padding: '10px 12px',
        background: active ? 'var(--paper-2)' : '#fff',
        border: active ? '2px solid var(--vintage-navy)' : '1px solid var(--line)',
        borderRadius: 6, transition: 'all .12s', minWidth: 0,
        boxShadow: active ? '2px 2px 0 var(--vintage-navy)' : (hover ? 'var(--shadow-sm)' : 'none'),
        transform: active ? 'translate(-1px,-1px)' : 'none',
      }}>
      <div style={{ fontFamily: 'Oswald, sans-serif', fontWeight: 700, fontSize: 13.5, textTransform: 'uppercase', color: 'var(--ink)', whiteSpace: 'nowrap' }}>{opt.name}</div>
    </button>
  );
}

function ColorSwatch({ c, active, onClick }) {
  const isWhite = c.hex.toUpperCase() === '#FFFFFF';
  return (
    <button onClick={onClick} title={c.name} aria-label={c.name}
      style={{
        width: 40, height: 40, borderRadius: 999, cursor: 'pointer', padding: 0, flex: 'none',
        background: c.hex,
        border: isWhite ? '1px solid var(--line-strong)' : 'none',
        boxShadow: active ? '0 0 0 2px #fff, 0 0 0 4px var(--vintage-navy)' : 'inset 0 0 0 1px rgba(0,0,0,.08)',
        transition: 'box-shadow .12s, transform .12s',
        transform: active ? 'scale(1.06)' : 'none',
      }} />
  );
}

/* ---------------- UPLOAD ZONE ---------------- */
function UploadZone({ artwork, fileName, onFile, onClear }) {
  const inputRef = React.useRef(null);
  const [drag, setDrag] = React.useState(false);

  const handleFiles = (files) => {
    const f = files && files[0];
    if (!f || !f.type.startsWith('image/')) return;
    const reader = new FileReader();
    reader.onload = ev => onFile(ev.target.result, f.name);
    reader.readAsDataURL(f);
  };

  if (artwork) {
    return (
      <div style={{ display: 'flex', alignItems: 'center', gap: 14, padding: 14, border: '1px solid var(--line)', borderRadius: 8, background: '#fff' }}>
        <div style={{ width: 56, height: 56, borderRadius: 6, background: 'var(--paper-2)', backgroundImage: 'repeating-conic-gradient(#fff 0% 25%, #efe9db 0% 50%)', backgroundSize: '14px 14px', flex: 'none', display: 'flex', alignItems: 'center', justifyContent: 'center', overflow: 'hidden', border: '1px solid var(--line)' }}>
          <img src={artwork} alt="" style={{ maxWidth: '100%', maxHeight: '100%', objectFit: 'contain' }} />
        </div>
        <div style={{ minWidth: 0, flex: 1 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
            <Icon name="check" size={16} color="var(--kelly-green)" />
            <span style={{ fontFamily: 'Oswald, sans-serif', fontWeight: 600, fontSize: 14, color: 'var(--ink)', textTransform: 'uppercase' }}>Art uploaded</span>
          </div>
          <div style={{ fontFamily: 'Montserrat, sans-serif', fontSize: 12.5, color: 'var(--ink-3)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{fileName}</div>
        </div>
        <button onClick={() => { onClear(); if (inputRef.current) inputRef.current.value = ''; }}
          style={{ background: 'none', border: '1px solid var(--line-strong)', borderRadius: 6, cursor: 'pointer', padding: '8px 12px', fontFamily: 'Oswald, sans-serif', fontWeight: 600, fontSize: 12.5, textTransform: 'uppercase', color: 'var(--ink-2)', display: 'flex', alignItems: 'center', gap: 6 }}>
          <Icon name="refresh" size={15} /> Replace
        </button>
        <input ref={inputRef} type="file" accept="image/*" style={{ display: 'none' }} onChange={e => handleFiles(e.target.files)} />
      </div>
    );
  }

  return (
    <div
      onClick={() => inputRef.current && inputRef.current.click()}
      onDragOver={e => { e.preventDefault(); setDrag(true); }}
      onDragLeave={() => setDrag(false)}
      onDrop={e => { e.preventDefault(); setDrag(false); handleFiles(e.dataTransfer.files); }}
      style={{
        cursor: 'pointer', borderRadius: 8, padding: '22px 18px', textAlign: 'center',
        border: drag ? '2px dashed var(--dark-royal)' : '2px dashed var(--line-strong)',
        background: drag ? 'rgba(0,36,144,.04)' : 'var(--paper-2)', transition: 'all .12s',
      }}>
      <div style={{ width: 42, height: 42, borderRadius: 999, background: 'var(--vintage-navy)', margin: '0 auto 10px', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
        <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="#fff" strokeWidth="2.25" strokeLinecap="round" strokeLinejoin="round"><path d="M12 17V3" /><path d="m6 9 6-6 6 6" /><path d="M5 21h14" /></svg>
      </div>
      <div style={{ fontFamily: 'Oswald, sans-serif', fontWeight: 700, fontSize: 15, textTransform: 'uppercase', color: 'var(--ink)' }}>Drop your design here</div>
      <div style={{ fontFamily: 'Montserrat, sans-serif', fontSize: 12.5, color: 'var(--ink-3)', marginTop: 4 }}>Upload whatever you have, or leave it blank — we will respond back to discuss your art before moving forward.</div>
      <div style={{ fontFamily: 'Montserrat, sans-serif', fontSize: 12.5, color: 'var(--ink-3)', marginTop: 3 }}>or <span style={{ color: 'var(--marathon-blue)', fontWeight: 600 }}>browse files</span> &middot; PNG, JPG or SVG &middot; transparent PNG works best</div>
      <input ref={inputRef} type="file" accept="image/*" style={{ display: 'none' }} onChange={e => handleFiles(e.target.files)} />
    </div>
  );
}

/* ---------------- QUOTE MODAL ---------------- */
function QuoteModal({ open, onClose, summary, sizeSummary, uploadCtx, onSent }) {
  const [status, setStatus] = React.useState('form'); // form | sending | sent | error
  const [errMsg, setErrMsg] = React.useState('');
  const [result, setResult] = React.useState(null);
  const saved = React.useMemo(() => (typeof loadLeadContact === 'function' ? loadLeadContact() : {}), [open]);
  React.useEffect(() => { if (open) { setStatus('form'); setErrMsg(''); setResult(null); } }, [open]);
  if (!open) return null;

  const submit = async (e) => {
    e.preventDefault();
    setStatus('sending');
    try {
      const f = e.target.elements;
      const fields = {
        name: (f.cust_name && f.cust_name.value) || '',
        email: (f.cust_email && f.cust_email.value) || '',
        phone: (f.cust_phone && f.cust_phone.value) || '',
        company: (f.cust_company && f.cust_company.value) || '',
        town: (f.cust_town && f.cust_town.value) || '',
        notes: (f.cust_notes && f.cust_notes.value) || '',
        summary: summary,
        sizeSummary: sizeSummary || (uploadCtx && uploadCtx.sizeSummary) || '',
      };
      const r = await submitQuote({ ...fields, uploadCtx });
      setResult(r);
      setStatus('sent');
      if (onSent) onSent({ fields, result: r });
    } catch (err) {
      setErrMsg((err && err.message) || 'Something went wrong sending your request.');
      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' }}>Get Pricing</span>
          <button onClick={onClose} style={{ background: 'none', border: 'none', cursor: '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)' }}>Got it — we're on it!</h3>
            <p style={{ margin: 0, fontFamily: 'Montserrat, sans-serif', fontSize: 14.5, color: 'var(--ink-2)', lineHeight: 1.6 }}>A real New Englandah from our Woburn shop will email your pricing within one business day.{result && result.mockupUrl ? ' Your mockup and artwork are saved to our system.' : ''} Thanks for going custom!</p>
            <div style={{ marginTop: 22 }}><Button variant="dark" onClick={onClose}>Close</Button></div>
          </div>
        ) : status === 'error' ? (
          <div style={{ padding: '36px 28px', textAlign: 'center' }}>
            <div style={{ width: 58, height: 58, borderRadius: 999, background: 'var(--chowdahead-red)', margin: '0 auto 16px', display: 'flex', alignItems: 'center', justifyContent: 'center' }}><Icon name="x" size={30} color="#fff" /></div>
            <h3 style={{ margin: '0 0 8px', fontFamily: 'Oswald, sans-serif', fontWeight: 700, fontSize: 20, textTransform: 'uppercase', color: 'var(--ink)' }}>Couldn't send your files</h3>
            <p style={{ margin: '0 0 8px', fontFamily: 'Montserrat, sans-serif', fontSize: 13.5, color: 'var(--ink-2)', lineHeight: 1.6 }}>{errMsg}</p>
            <div style={{ marginTop: 18, display: 'flex', gap: 10, justifyContent: 'center' }}>
              <Button variant="outline" onClick={onClose}>Close</Button>
              <Button variant="primary" onClick={() => setStatus('form')}>Try again</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 }}>Want it dialed in — exact ink colors, rush dates, or a big bulk run? Send the details and we'll come back with custom pricing.</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)' }}>Quantity:</strong> {sizeSummary}</div>}
            </div>
            <label style={{ display: 'block', marginBottom: 14 }}>
              <span style={labelTxt}>Name</span>
              <input name="cust_name" type="text" required defaultValue={saved.name || ''} placeholder="Tom from Southie" style={fieldStyle} />
            </label>
            <label style={{ display: 'block', marginBottom: 14 }}>
              <span style={labelTxt}>Email</span>
              <input name="cust_email" type="email" required defaultValue={saved.email || ''} placeholder="you@email.com" style={fieldStyle} />
            </label>
            <label style={{ display: 'block', marginBottom: 14 }}>
              <span style={labelTxt}>Phone (optional)</span>
              <input name="cust_phone" type="tel" defaultValue={saved.phone || ''} placeholder="(617) 555-0142" style={fieldStyle} />
            </label>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12, marginBottom: 14 }}>
              <label style={{ display: 'block' }}>
                <span style={labelTxt}>Company / Team (optional)</span>
                <input name="cust_company" type="text" defaultValue={saved.company || ''} placeholder="Woburn Little League" style={fieldStyle} />
              </label>
              <label style={{ display: 'block' }}>
                <span style={labelTxt}>City / Town (optional)</span>
                <input name="cust_town" type="text" defaultValue={saved.town || ''} placeholder="Woburn, MA" style={fieldStyle} />
              </label>
            </div>
            <label style={{ display: 'block', marginBottom: 20 }}>
              <span style={labelTxt}>Notes</span>
              <textarea name="cust_notes" rows={3} placeholder="Need 'em by a certain date? Specific ink colors? Tell us here." style={{ ...fieldStyle, resize: 'vertical' }} />
            </label>
            <Button variant="primary" size="lg" full disabled={status === 'sending'}>
              {status === 'sending' ? 'Sending…' : <React.Fragment>Get Pricing <Icon name="arrowRight" size={18} color="#fff" /></React.Fragment>}
            </Button>
          </form>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { CH_TIERS, CH_GARMENT_OPTS, CH_COLORS, tierIndexFor, chFmt, chFmtShort, SectionLabel, GarmentTab, ColorSwatch, UploadZone, QuoteModal });
