// ── JT Atelier — Post-delivery Survey ────────────────────────────────
// Reached from the delivered email: /survey?ref=ORDER_REF&p=PRODUCT_ID
// Ten questions feeding marketing / QC / product / pricing. On submit,
// rewards a 15% code (THANKYOU15) and thanks the customer.

const SURVEY_QUESTIONS = [
  { id: 'heard',      type: 'single', q: 'How did you hear about JT Atelier?',
    options: ['Instagram', 'TikTok', 'Google search', 'Friend / referral', 'Press / blog', 'Other'] },
  { id: 'why',        type: 'multi',  q: 'What made you buy this jacket?',
    options: ['Design / style', 'Leather quality', 'Made-to-order / bespoke', 'Price', 'Brand story', 'Reviews', 'Other'] },
  { id: 'quality',    type: 'stars',  q: 'Rate the quality of your jacket.' },
  { id: 'fit',        type: 'single', q: 'How was the fit?',
    options: ['Too small', 'Slightly snug', 'Perfect', 'Slightly loose', 'Too big'] },
  { id: 'nps',        type: 'scale',  q: 'How likely are you to recommend us to a friend?', min: 0, max: 10 },
  { id: 'delivery',   type: 'stars',  q: 'How was delivery & packaging?' },
  { id: 'expectation',type: 'single', q: 'Did the jacket match the website photos & description?',
    options: ['Much better', 'Better', 'As expected', 'Worse', 'Much worse'] },
  { id: 'next',       type: 'multi',  q: 'What should we offer next?',
    options: ['More colours', "Women's range", 'Accessories (bags / belts / wallets)', 'Coats / outerwear', 'Seasonal lines', 'More customization', 'Other'] },
  { id: 'price',      type: 'single', q: 'How was the price for the value you received?',
    options: ['Great value', 'Fair', 'Slightly expensive', 'Too expensive'] },
  { id: 'open',       type: 'text',   q: 'Anything else you would like to share?' },
];

function Survey() {
  const params = new URLSearchParams(window.location.search);
  const orderRef  = params.get('ref') || '';
  const productId = params.get('p') || '';

  const [answers, setAnswers] = React.useState({});
  const [consent, setConsent] = React.useState(false);
  const [status, setStatus]   = React.useState('idle'); // idle | sending | done | error
  const [errMsg, setErrMsg]   = React.useState('');

  React.useEffect(() => { window.scrollTo({ top: 0, behavior: 'instant' }); }, []);

  const set = (id, val) => setAnswers(a => ({ ...a, [id]: val }));
  const toggleMulti = (id, opt) => setAnswers(a => {
    const cur = Array.isArray(a[id]) ? a[id] : [];
    return { ...a, [id]: cur.includes(opt) ? cur.filter(x => x !== opt) : [...cur, opt] };
  });

  const submit = () => {
    setStatus('sending'); setErrMsg('');
    fetch('/api/admin?a=survey_submit', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ order_ref: orderRef, product_id: productId, answers: { ...answers, consent } }),
    })
      .then(r => r.json())
      .then(d => {
        if (d && d.ok) setStatus('done');
        else { setStatus('error'); setErrMsg((d && d.error) || 'Something went wrong.'); }
      })
      .catch(() => { setStatus('error'); setErrMsg('Network error — please try again.'); });
  };

  const card = {
    background: 'var(--bg)', minHeight: '100vh',
    padding: 'clamp(48px,8vw,96px) clamp(20px,6vw,80px) 80px',
  };
  const qWrap = {
    borderBottom: '.5px solid var(--line)', padding: 'clamp(22px,3vw,34px) 0',
  };
  const qLabel = {
    fontFamily: 'var(--font-display, Georgia, serif)', fontStyle: 'italic',
    fontSize: 'clamp(16px,2.2vw,21px)', color: 'var(--fg)', marginBottom: 16, lineHeight: 1.35,
  };
  const opt = (active) => ({
    fontFamily: 'var(--font-mono)', fontSize: 12, letterSpacing: '.04em',
    padding: '9px 16px', cursor: 'pointer', borderRadius: 2,
    border: active ? '1px solid var(--fg)' : '.5px solid var(--line)',
    color: active ? 'var(--fg)' : 'var(--fg-3)',
    background: active ? 'color-mix(in srgb,var(--fg) 7%,transparent)' : 'transparent',
    transition: 'all .15s',
  });

  if (status === 'done') {
    return (
      <main style={card}>
        <div style={{ maxWidth: 560, margin: '0 auto', textAlign: 'center' }}>
          <div className="eyebrow" style={{ marginBottom: 22 }}>◇ &nbsp; Thank you</div>
          <h1 className="display" style={{ fontSize: 'clamp(38px,7vw,68px)', lineHeight: .95, margin: 0 }}>
            <em>Merci.</em>
          </h1>
          <p style={{ fontFamily: 'var(--font-mono)', fontSize: 13, lineHeight: 1.9, color: 'var(--fg-3)', margin: '24px 0 28px' }}>
            Your feedback shapes every piece we make next. As our thanks, here is <strong style={{ color: 'var(--fg)' }}>15% off</strong> your next order.
          </p>
          <div style={{ display: 'inline-block', border: '1px dashed var(--gold,#c6a86b)', padding: '14px 28px', borderRadius: 4 }}>
            <div style={{ fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '.2em', textTransform: 'uppercase', color: 'var(--fg-3)', marginBottom: 6 }}>Use at checkout</div>
            <div style={{ fontFamily: 'var(--font-display, Georgia, serif)', fontSize: 26, letterSpacing: '.08em', color: 'var(--fg)' }}>THANKYOU15</div>
          </div>
          {productId ? (
            <div style={{ marginTop: 36 }}>
              <a href={'/product/' + encodeURIComponent(productId)} className="btn">Leave a review <span className="arrow">→</span></a>
            </div>
          ) : null}
        </div>
      </main>
    );
  }

  return (
    <main style={card}>
      <div style={{ maxWidth: 680, margin: '0 auto' }}>
        <div className="eyebrow" style={{ marginBottom: 22 }}>◇ &nbsp; Your feedback</div>
        <h1 className="display" style={{ fontSize: 'clamp(40px,7vw,80px)', lineHeight: .92, margin: '0 0 14px', letterSpacing: '-.02em' }}>
          <em>Tell us.</em>
        </h1>
        <p style={{ fontFamily: 'var(--font-mono)', fontSize: 12, letterSpacing: '.05em', lineHeight: 1.85, color: 'var(--fg-3)', maxWidth: 460, margin: '0 0 8px' }}>
          A 30-second survey on the piece you just received. Complete it for <strong style={{ color: 'var(--fg)' }}>15% off</strong> your next order.
        </p>

        {SURVEY_QUESTIONS.map((Q, i) => (
          <div key={Q.id} style={qWrap}>
            <div style={qLabel}><span style={{ fontFamily: 'var(--font-mono)', fontStyle: 'normal', fontSize: 11, color: 'var(--fg-3)', marginRight: 10 }}>{String(i + 1).padStart(2, '0')}</span>{Q.q}</div>

            {(Q.type === 'single' || Q.type === 'multi') && (
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
                {Q.options.map(o => {
                  const active = Q.type === 'multi'
                    ? Array.isArray(answers[Q.id]) && answers[Q.id].includes(o)
                    : answers[Q.id] === o;
                  return (
                    <button key={o} style={opt(active)}
                      onClick={() => Q.type === 'multi' ? toggleMulti(Q.id, o) : set(Q.id, o)}>{o}</button>
                  );
                })}
              </div>
            )}

            {Q.type === 'stars' && (
              <div style={{ display: 'flex', gap: 8 }}>
                {[1, 2, 3, 4, 5].map(n => (
                  <button key={n} onClick={() => set(Q.id, n)}
                    style={{ background: 'none', border: 'none', cursor: 'pointer', fontSize: 26, lineHeight: 1, color: (answers[Q.id] || 0) >= n ? 'var(--gold,#c6a86b)' : 'var(--line)', padding: 0 }}>★</button>
                ))}
              </div>
            )}

            {Q.type === 'scale' && (
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
                {Array.from({ length: Q.max - Q.min + 1 }, (_, k) => Q.min + k).map(n => (
                  <button key={n} onClick={() => set(Q.id, n)}
                    style={{ width: 38, height: 38, cursor: 'pointer', borderRadius: 2, fontFamily: 'var(--font-mono)', fontSize: 12,
                      border: answers[Q.id] === n ? '1px solid var(--fg)' : '.5px solid var(--line)',
                      background: answers[Q.id] === n ? 'var(--fg)' : 'transparent',
                      color: answers[Q.id] === n ? 'var(--bg)' : 'var(--fg-3)', transition: 'all .15s' }}>{n}</button>
                ))}
              </div>
            )}

            {Q.type === 'text' && (
              <textarea rows={3} value={answers[Q.id] || ''} onChange={e => set(Q.id, e.target.value)}
                placeholder="Optional — we read every word."
                style={{ width: '100%', boxSizing: 'border-box', background: 'transparent', border: '.5px solid var(--line)', color: 'var(--fg)', fontFamily: 'var(--font-mono)', fontSize: 13, padding: '12px 14px', outline: 'none', resize: 'vertical' }} />
            )}
          </div>
        ))}

        <label style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '20px 0', cursor: 'pointer' }}>
          <input type="checkbox" checked={consent} onChange={e => setConsent(e.target.checked)} />
          <span style={{ fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--fg-3)', letterSpacing: '.03em' }}>You may feature my feedback (anonymously) in your marketing.</span>
        </label>

        {status === 'error' && <div style={{ color: 'var(--gold,#c6a86b)', fontFamily: 'var(--font-mono)', fontSize: 12, marginBottom: 14 }}>{errMsg}</div>}

        <button className="btn" disabled={status === 'sending'} onClick={submit} style={{ opacity: status === 'sending' ? .6 : 1 }}>
          {status === 'sending' ? 'Submitting…' : 'Submit & get 15% off'} <span className="arrow">→</span>
        </button>
        <div style={{ fontFamily: 'var(--font-mono)', fontSize: 10, color: 'var(--fg-3)', opacity: .6, marginTop: 16 }}>
          Order {orderRef || '—'} · Your answers are anonymous and used only to improve our products.
        </div>
      </div>
    </main>
  );
}

Object.assign(window, { Survey });
