/* =========================================================================
   Morning Mob — register interest
   No payment is taken. Visitors leave their contact details to register
   interest in the tee, and we reach out when it's ready. This view
   repurposes the former checkout route (still keyed 'checkout' in the app).
   ========================================================================= */

/* Register-interest submissions are forwarded to a Google Form. The form has
   Name / Email / Note / "interested in?" questions — but the last is a
   multiple-choice field, which only accepts its preset options, so we fold the
   tee selection (and newsletter opt-in) into the free-text Note instead. That
   way nothing a visitor tells us is ever dropped. Field IDs come from the
   form's HTML (the `entry.NNN` names). Update GFORM if the form is rebuilt. */
const GFORM = {
  action: 'https://docs.google.com/forms/d/e/1FAIpQLSfW0g0D2EE47ywzVMDIaAkeXRusW0Nudn71nvRZMdNONJM_JA/formResponse',
  name: 'entry.1771799390',
  email: 'entry.296265152',
  note: 'entry.2126383156',
};

function sendToGoogleForm(f, items) {
  const interest = (items || [])
    .map((it) => it.product.name
      + (it.colour ? ' — ' + it.colour : '')
      + (it.size ? ' / ' + it.size : '')
      + (it.qty ? ' ×' + it.qty : ''))
    .join('; ');
  const note = [
    f.note && f.note.trim(),
    interest && 'Interested in: ' + interest,
    'Newsletter: ' + (f.news ? 'yes' : 'no'),
  ].filter(Boolean).join('\n');

  const body = new URLSearchParams();
  body.append(GFORM.name, f.name.trim());
  body.append(GFORM.email, f.email.trim());
  body.append(GFORM.note, note);

  // no-cors: Google's endpoint doesn't return CORS headers, so we can't read
  // the response — but the submission is still recorded. Failures are swallowed
  // so a network hiccup never blocks the visitor's confirmation screen.
  fetch(GFORM.action, {
    method: 'POST',
    mode: 'no-cors',
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
    body: body.toString(),
  }).catch(() => {});
}

function Field({ label, value, onChange, type = 'text', placeholder, error, half, autoComplete, textarea }) {
  const [focus, setFocus] = useState(false);
  const base = { width: '100%', padding: textarea ? '12px 14px' : '0 14px', background: '#fff', borderRadius: 0, outline: 'none',
    border: '1px solid ' + (error ? 'var(--rust)' : focus ? 'var(--hairline-strong)' : 'var(--hairline)'),
    fontFamily: 'var(--font-sans)', fontSize: 14, fontWeight: 300, color: 'var(--ink)' };
  return (
    <label style={{ display: 'block', gridColumn: half ? 'span 1' : '1 / -1' }}>
      <span style={{ display: 'block', fontFamily: 'var(--font-sans)', fontSize: 11, fontWeight: 400,
        letterSpacing: '1.5px', textTransform: 'uppercase', color: 'var(--muted)', marginBottom: 8 }}>{label}</span>
      {textarea ? (
        <textarea value={value} onChange={(e) => onChange(e.target.value)} placeholder={placeholder} rows={3}
          onFocus={() => setFocus(true)} onBlur={() => setFocus(false)} style={{ ...base, resize: 'vertical', lineHeight: 1.5 }} />
      ) : (
        <input value={value} onChange={(e) => onChange(e.target.value)} type={type} placeholder={placeholder}
          autoComplete={autoComplete} onFocus={() => setFocus(true)} onBlur={() => setFocus(false)} style={{ ...base, height: 46 }} />
      )}
      {error && <span style={{ display: 'block', fontFamily: 'var(--font-sans)', fontSize: 11, fontWeight: 300, color: 'var(--rust)', marginTop: 6 }}>{error}</span>}
    </label>
  );
}

/* The tees the visitor has flagged interest in — no totals, no payment. */
function InterestSummary({ items }) {
  return (
    <aside style={{ background: 'var(--surface-soft)', padding: 28, position: 'sticky', top: 96, alignSelf: 'start' }}>
      <Eyebrow color="var(--ink)" style={{ display: 'block', marginBottom: 20 }}>You're interested in</Eyebrow>
      {items.map((it) => (
        <div key={it.product.id + (it.size || '') + (it.colour || '')} style={{ display: 'flex', gap: 14, paddingBottom: 18, marginBottom: 18, borderBottom: '1px solid var(--hairline)' }}>
          <div style={{ width: 56, flex: 'none' }}><Photo id={'sum-' + it.product.id + '-' + (it.colour || '')} src={itemThumb(it)} label="" /></div>
          <div style={{ flex: 1 }}>
            <h3 style={{ fontFamily: 'var(--font-serif)', fontSize: 15, fontWeight: 400, color: 'var(--ink)', margin: 0 }}>{it.product.name}</h3>
            <div style={{ fontFamily: 'var(--font-sans)', fontSize: 11, fontWeight: 300, color: 'var(--muted)', marginTop: 4 }}>{[it.colour, it.size && 'Size ' + it.size, 'Qty ' + it.qty].filter(Boolean).join(' · ')}</div>
          </div>
          <span style={{ fontFamily: 'var(--font-sans)', fontSize: 13, fontWeight: 300, color: 'var(--body)', whiteSpace: 'nowrap' }}>{money(it.product.price)}</span>
        </div>
      ))}
      <p style={{ fontFamily: 'var(--font-sans)', fontSize: 11, fontWeight: 300, color: 'var(--muted)', margin: 0, lineHeight: 1.6, letterSpacing: '0.3px' }}>
        No payment is taken here. Register your interest and we'll be in touch — nothing else in between.</p>
    </aside>
  );
}

function Checkout({ items, onDone, onShop, go }) {
  const [f, setF] = useState({ name: '', email: '', note: '', news: true });
  const [errs, setErrs] = useState({});
  const [done, setDone] = useState(false);
  const set = (k) => (v) => setF((p) => ({ ...p, [k]: v }));

  if (done) return <Confirmation email={f.email} onShop={onShop} go={go} />;

  if (items.length === 0) {
    return (
      <div style={{ maxWidth: 640, margin: '0 auto', padding: '96px 28px', textAlign: 'center' }}>
        <h1 style={{ fontFamily: 'var(--font-serif)', fontSize: 32, fontWeight: 400, color: 'var(--ink)', margin: 0 }}>Nothing saved yet</h1>
        <p style={{ marginTop: 16, color: 'var(--body)' }}>Add the tee to register your interest.</p>
        <button onClick={onShop} style={primaryBtn}>Shop the tee</button>
      </div>
    );
  }

  const submit = () => {
    const e = {};
    if (!f.name.trim()) e.name = 'Required';
    if (!f.email.trim()) e.email = 'Required';
    else if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(f.email)) e.email = 'Enter a valid email';
    setErrs(e);
    if (Object.keys(e).length) return;
    sendToGoogleForm(f, items);
    setDone(true);
    onDone();
    window.scrollTo(0, 0);
  };

  return (
    <div style={{ maxWidth: 'var(--content-max)', margin: '0 auto', padding: '40px 28px 96px' }}>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 36 }}>
        <h1 style={{ fontFamily: 'var(--font-serif)', fontSize: 28, fontWeight: 400, color: 'var(--ink)', margin: 0 }}>Register interest</h1>
        <button onClick={onShop} style={{ fontFamily: 'var(--font-sans)', fontSize: 11, fontWeight: 400, letterSpacing: '1px',
          textTransform: 'uppercase', color: 'var(--muted)', background: 'none', border: 'none', cursor: 'pointer' }}>Continue shopping</button>
      </div>

      <div className="mm-checkout" style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: 64, alignItems: 'start' }}>
        <div>
          <p style={{ color: 'var(--body)', margin: '0 0 28px', maxWidth: 460, lineHeight: 1.6 }}>
            We're not taking payment on the site right now. Leave your details to register your interest and we'll be in touch — no payment, no spam.</p>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
            <Field label="Name" value={f.name} onChange={set('name')} error={errs.name} autoComplete="name" />
            <Field label="Email address" value={f.email} onChange={set('email')} type="email" placeholder="you@example.com" error={errs.email} autoComplete="email" />
            <Field label="Anything you'd like us to know (optional)" value={f.note} onChange={set('note')} textarea placeholder="Size you're after, a question, or just hello." />
            <label style={{ gridColumn: '1 / -1', display: 'flex', alignItems: 'center', gap: 10, cursor: 'pointer' }}>
              <input type="checkbox" checked={f.news} onChange={(e) => set('news')(e.target.checked)} style={{ width: 16, height: 16, accentColor: '#000' }} />
              <span style={{ fontFamily: 'var(--font-sans)', fontSize: 13, fontWeight: 300, color: 'var(--body)' }}>Also keep me on the list for new arrivals and the occasional note from the studio.</span>
            </label>
          </div>

          <div style={{ display: 'flex', alignItems: 'center', marginTop: 36 }}>
            <button onClick={submit} style={{ ...primaryBtn, marginLeft: 'auto', marginTop: 0, width: 'auto', padding: '0 40px' }}>Register interest</button>
          </div>
        </div>

        <InterestSummary items={items} />
      </div>
    </div>
  );
}

function Confirmation({ email, onShop, go }) {
  return (
    <div style={{ maxWidth: 640, margin: '0 auto', padding: '96px 28px', textAlign: 'center' }}>
      <div style={{ width: 56, height: 56, margin: '0 auto 28px', border: '1px solid var(--hairline-strong)', display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'var(--success)' }}>
        <Icon name="check" size={26} stroke={1.4} />
      </div>
      <Eyebrow color="var(--success)">Interest registered</Eyebrow>
      <h1 style={{ fontFamily: 'var(--font-serif)', fontSize: 36, fontWeight: 400, color: 'var(--ink)', margin: '16px 0 0', lineHeight: 1.15 }}>Thank you.</h1>
      <p style={{ marginTop: 20, color: 'var(--body)', maxWidth: 440, marginInline: 'auto' }}>
        You're on the list. We'll be in touch at {email || 'your inbox'} about the Mocha Mode Tee and what comes next — and nothing else in between.</p>
      <div style={{ display: 'flex', gap: 16, justifyContent: 'center', marginTop: 36, flexWrap: 'wrap' }}>
        <button onClick={onShop} style={{ ...primaryBtn, marginTop: 0, width: 'auto', padding: '0 32px' }}>Continue shopping</button>
        <a href="https://www.instagram.com/morning_mob/" target="_blank" rel="noopener noreferrer" style={{ ...ghostBtn, marginTop: 0, width: 'auto', padding: '0 32px', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', textDecoration: 'none' }}>Follow @morning_mob</a>
      </div>
    </div>
  );
}

const primaryBtn = { height: 48, marginTop: 32, background: 'var(--ink)', color: '#fff', border: 'none',
  fontFamily: 'var(--font-sans)', fontSize: 11, fontWeight: 400, letterSpacing: '2px', textTransform: 'uppercase', cursor: 'pointer' };
const ghostBtn = { height: 48, background: 'none', color: 'var(--ink)', border: '1px solid var(--ink)',
  fontFamily: 'var(--font-sans)', fontSize: 11, fontWeight: 400, letterSpacing: '2px', textTransform: 'uppercase', cursor: 'pointer' };

Object.assign(window, { Checkout, primaryBtn, ghostBtn });
