/* Free Resource — the 3-Week Reset signup section.
   Sits between Pricing and Coach Bio.
   Two paths: "Get the Plan" (basic email capture) or "Build It For Me"
   (calculator + personalized macros baked into the delivered plan). */

const FreeResource = () => {
  const [modal, setModal] = React.useState(null); // null | 'basic' | 'custom'

  return (
    <>
      <section id="reset">
        <div className="wrap">
          <div className="m-1 m-gap" style={{
            display: 'grid',
            gridTemplateColumns: '1.2fr 1fr',
            gap: 72,
            alignItems: 'center',
          }}>
            {/* Left: the pitch */}
            <div>
              <div className="eyebrow">Free Resource</div>
              <h2 className="h-section" style={{ marginTop: 12 }}>Not sure yet?<br/>Run this first.</h2>
              <div className="rule" />
              <p style={{ fontSize: 18, lineHeight: 1.55, color: 'var(--fg)', maxWidth: '54ch', marginTop: 28, fontWeight: 500 }}>
                A free three-week training and nutrition framework you can run on your own. No commitment. No pressure. If you finish it, you&apos;ll know whether you&apos;re ready for the full coaching version — and so will I.
              </p>

              <ul style={{
                listStyle: 'none',
                padding: 0,
                margin: '36px 0 0',
                display: 'flex',
                flexDirection: 'column',
                gap: 14,
              }}>
                {[
                  ['01', 'A real 3-week training program', 'Three sessions a week. Programmed sets, reps, and progression rules. Not generic.'],
                  ['02', 'On intensity — how hard to lift', 'RPE explained. Most plans skip this. We don\u2019t. You\u2019ll know exactly how hard to push.'],
                  ['03', 'Set your own macros', 'The formula, taught simply. Or let us calculate for you (see below).'],
                  ['04', 'A self-tracking template', 'The same habit our paying clients build. The Reset is where you learn it.'],
                ].map(([n, t, b]) => (
                  <li key={n} style={{
                    display: 'grid',
                    gridTemplateColumns: 'auto 1fr',
                    gap: 18,
                    paddingBottom: 14,
                    borderBottom: '1px solid var(--border)',
                  }}>
                    <div style={{
                      fontFamily: 'var(--font-mono)',
                      fontSize: 14,
                      fontWeight: 500,
                      color: 'var(--accent)',
                      letterSpacing: '0.05em',
                    }}>{n}</div>
                    <div>
                      <div style={{
                        fontFamily: 'var(--font-headline)',
                        fontWeight: 600,
                        fontSize: 15,
                        textTransform: 'uppercase',
                        letterSpacing: '0.02em',
                        color: 'var(--fg)',
                        marginBottom: 4,
                      }}>{t}</div>
                      <div style={{ fontSize: 13, color: 'var(--fg-2)', lineHeight: 1.5 }}>{b}</div>
                    </div>
                  </li>
                ))}
              </ul>
            </div>

            {/* Right: visual + dual CTA */}
            <div>
              <ResetMock />

              <div style={{ marginTop: 24, display: 'flex', flexDirection: 'column', gap: 8 }}>
                <button
                  onClick={() => setModal('basic')}
                  className="btn btn-primary"
                  style={{ padding: '15px 24px', fontSize: 13, width: '100%', justifyContent: 'center' }}
                >
                  Get The Reset <span style={{ marginLeft: 4 }}>→</span>
                </button>

                <button
                  onClick={() => setModal('custom')}
                  style={{
                    width: '100%',
                    padding: '15px 24px',
                    fontFamily: 'var(--font-body)',
                    fontSize: 13,
                    fontWeight: 600,
                    textTransform: 'uppercase',
                    letterSpacing: '0.1em',
                    background: 'transparent',
                    color: 'var(--fg)',
                    border: '1px solid var(--border-strong)',
                    borderRadius: 6,
                    cursor: 'pointer',
                    transition: 'border 200ms cubic-bezier(.16,1,.3,1)',
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    gap: 8,
                  }}
                  onMouseEnter={e => e.currentTarget.style.borderColor = 'var(--fg)'}
                  onMouseLeave={e => e.currentTarget.style.borderColor = 'var(--border-strong)'}
                >
                  Build It For Me <span style={{ color: 'var(--accent)' }}>→</span>
                </button>

                <div style={{ marginTop: 8, fontSize: 11, color: 'var(--fg-3)', lineHeight: 1.6, textAlign: 'center' }}>
                  Both options send you the same plan.<br/>
                  <strong style={{ color: 'var(--fg)', fontWeight: 600 }}>Build It For Me</strong> personalizes your macros into the PDF.
                </div>
              </div>
            </div>
          </div>
        </div>
      </section>

      <ResetModal mode={modal} onClose={() => setModal(null)} />
    </>
  );
};

// --- Visual: stylized Reset cover mock ---
const ResetMock = () => (
  <div style={{ position: 'relative', perspective: 1000 }}>
    {/* Back stack — sense of depth */}
    <div style={{
      position: 'absolute',
      inset: 0,
      background: 'var(--rxr-haze)',
      border: '1px solid var(--border)',
      borderRadius: 6,
      transform: 'rotate(-2deg) translate(-12px, 12px)',
      zIndex: 1,
    }} />
    <div style={{
      position: 'absolute',
      inset: 0,
      background: 'var(--rxr-haze)',
      border: '1px solid var(--border)',
      borderRadius: 6,
      transform: 'rotate(2deg) translate(-6px, 6px)',
      zIndex: 2,
    }} />

    {/* Front cover */}
    <div style={{
      position: 'relative',
      zIndex: 3,
      background: '#fff',
      border: '1px solid var(--border)',
      borderRadius: 6,
      padding: '36px 32px',
      aspectRatio: '8.5 / 11',
      display: 'flex',
      flexDirection: 'column',
      boxShadow: '0 12px 28px rgba(17,20,24,0.12), 0 2px 4px rgba(17,20,24,0.06)',
    }}>
      <div style={{
        display: 'flex',
        alignItems: 'center',
        gap: 10,
        paddingBottom: 14,
        borderBottom: '1px solid var(--border)',
      }}>
        <img src="./assets/logo-icon.svg" width="28" height="28" />
        <div>
          <div style={{ fontFamily: 'var(--font-display)', fontSize: 13, letterSpacing: '0.02em', color: 'var(--fg)' }}>REP BY REP</div>
          <div style={{ fontSize: 7, color: 'var(--accent)', letterSpacing: '0.3em', fontWeight: 600, marginTop: 2 }}>EARNED EVERY DAY</div>
        </div>
      </div>

      <div style={{ flex: 1, display: 'flex', flexDirection: 'column', justifyContent: 'center', paddingTop: 24 }}>
        <div style={{
          fontSize: 9,
          fontWeight: 600,
          letterSpacing: '0.32em',
          textTransform: 'uppercase',
          color: 'var(--accent)',
          marginBottom: 14,
        }}>
          The 3-Week Reset
        </div>
        <div style={{
          fontFamily: 'var(--font-display)',
          fontSize: 48,
          lineHeight: 0.9,
          letterSpacing: '-0.01em',
          textTransform: 'uppercase',
          color: 'var(--fg)',
        }}>
          BUILD<br/>THE BASE.
        </div>
        <div style={{
          fontFamily: 'var(--font-headline)',
          fontWeight: 600,
          fontSize: 13,
          textTransform: 'uppercase',
          letterSpacing: '0.02em',
          color: 'var(--fg-2)',
          marginTop: 14,
        }}>
          A free starting framework
        </div>
        <div style={{ width: 48, height: 2, background: 'var(--accent)', margin: '20px 0' }} />
        <div style={{ fontSize: 12, color: 'var(--fg-2)', lineHeight: 1.55, maxWidth: '32ch' }}>
          Three weeks. Three sessions a week.<br/>The numbers. The intensity. The tracking.
        </div>
      </div>

      <div style={{
        paddingTop: 14,
        borderTop: '1px solid var(--border)',
        display: 'flex',
        justifyContent: 'space-between',
        fontSize: 8,
        letterSpacing: '0.22em',
        textTransform: 'uppercase',
        fontWeight: 600,
        color: 'var(--fg-3)',
      }}>
        <span>Free Resource</span>
        <span style={{ color: 'var(--accent)' }}>EARNED EVERY DAY</span>
      </div>
    </div>
  </div>
);

// --- Modal: handles both basic and custom-macro flows ---
const ResetModal = ({ mode, onClose }) => {
  const [name, setName] = React.useState('');
  const [email, setEmail] = React.useState('');
  const [bw, setBw] = React.useState('');
  const [units, setUnits] = React.useState('lb');
  const [heightFt, setHeightFt] = React.useState('');
  const [heightIn, setHeightIn] = React.useState('');
  const [activity, setActivity] = React.useState('moderate');
  const [goal, setGoal] = React.useState('recomp');
  const [age, setAge] = React.useState('');
  const [sex, setSex] = React.useState('male');
  const [submitted, setSubmitted] = React.useState(false);

  React.useEffect(() => {
    if (!mode) {
      setTimeout(() => {
        setName(''); setEmail(''); setBw(''); setUnits('lb');
        setActivity('moderate'); setGoal('recomp');
        setAge(''); setSex('male'); setHeightFt(''); setHeightIn('');
        setSubmitted(false);
      }, 300);
    }
  }, [mode]);

  React.useEffect(() => {
    document.body.style.overflow = mode ? 'hidden' : '';
    return () => { document.body.style.overflow = ''; };
  }, [mode]);

  const isCustom = mode === 'custom';
  const emailValid = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
  const heightTotalIn = (+heightFt || 0) * 12 + (+heightIn || 0);
  const numericValid = isCustom
    ? (bw && +bw > 50 && age && +age > 14 && heightFt && heightTotalIn > 36)
    : true;
  const valid = name && emailValid && numericValid;

  // Macro calculation (Mifflin-St Jeor + activity multiplier)
  // Must be called unconditionally for hook order; gated inside the callback.
  const macros = React.useMemo(() => {
    if (!isCustom || !valid) return null;
    const weightLb = units === 'lb' ? +bw : +bw * 2.20462;
    const weightKg = weightLb / 2.20462;
    const heightCm = heightTotalIn * 2.54;
    const ageN = +age;
    const bmr = sex === 'male'
      ? 10 * weightKg + 6.25 * heightCm - 5 * ageN + 5
      : 10 * weightKg + 6.25 * heightCm - 5 * ageN - 161;
    const mult = { sedentary: 1.2, light: 1.375, moderate: 1.55, active: 1.725 }[activity];
    let tdee = bmr * mult;
    if (goal === 'cut') tdee -= 350;
    if (goal === 'lean-bulk') tdee += 200;
    const cals = Math.round(tdee / 10) * 10;
    const protein = Math.round(weightLb);
    const fat = Math.round((cals * 0.27) / 9);
    const carbs = Math.round((cals - protein * 4 - fat * 9) / 4);
    return { cals, protein, carbs, fat, weightLb: Math.round(weightLb) };
  }, [isCustom, valid, bw, units, heightTotalIn, age, sex, activity, goal]);

  if (!mode) return null;

  return (
    <div
      role="dialog"
      aria-modal="true"
      style={{
        position: 'fixed', inset: 0, zIndex: 1000,
        background: 'rgba(17,20,24,0.85)',
        display: 'flex', alignItems: 'flex-start', justifyContent: 'center',
        padding: '60px 24px', overflowY: 'auto',
        animation: 'rxrFadeIn 200ms cubic-bezier(.16,1,.3,1)',
      }}
      onClick={e => { if (e.target === e.currentTarget) onClose(); }}
    >
      <div style={{
        background: '#fff', borderRadius: 6,
        maxWidth: isCustom ? 720 : 540, width: '100%',
        position: 'relative',
        animation: 'rxrSlideUp 300ms cubic-bezier(.16,1,.3,1)',
      }}>
        <button
          onClick={onClose}
          aria-label="Close"
          style={{
            position: 'absolute', top: 18, right: 18,
            background: 'transparent', border: 0, cursor: 'pointer',
            color: 'var(--fg-3)', padding: 8, borderRadius: 4,
            transition: 'all 150ms cubic-bezier(.16,1,.3,1)',
            display: 'flex', zIndex: 10,
          }}
          onMouseEnter={e => { e.currentTarget.style.background = 'var(--rxr-haze)'; e.currentTarget.style.color = 'var(--fg)'; }}
          onMouseLeave={e => { e.currentTarget.style.background = 'transparent'; e.currentTarget.style.color = 'var(--fg-3)'; }}
        >
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round">
            <line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/>
          </svg>
        </button>

        {!submitted ? (
          <>
            <div style={{ padding: '32px 40px 24px', borderBottom: '1px solid var(--border)' }}>
              <div style={{ fontSize: 11, fontWeight: 600, letterSpacing: '0.22em', textTransform: 'uppercase', color: 'var(--accent)' }}>
                The 3-Week Reset
              </div>
              <h2 style={{
                fontFamily: 'var(--font-display)', fontSize: 32, lineHeight: 1,
                letterSpacing: '-0.01em', color: 'var(--fg)',
                margin: '10px 0 0',
              }}>
                {isCustom ? 'Personalized — for you.' : 'Where do we send it?'}
              </h2>
              <div style={{ fontSize: 14, color: 'var(--fg-2)', marginTop: 10, lineHeight: 1.5 }}>
                {isCustom
                  ? 'Tell us a few things about you. We\u2019ll calculate your macros and bake them into the plan we send.'
                  : 'Email us where to send the plan. No follow-up sales emails — you can subscribe to Field Notes separately if you want them.'}
              </div>
            </div>

            <div style={{ padding: 32 }}>
              <div style={{ display: 'grid', gridTemplateColumns: isCustom ? '1fr 1fr' : '1fr', gap: 14 }}>
                <RxField label="First Name" value={name} onChange={setName} />
                <RxField label="Email" type="email" value={email} onChange={setEmail} />

                {isCustom && (
                  <>
                    <RxFieldUnits label="Bodyweight" value={bw} onChange={setBw} units={units} onUnitChange={setUnits} options={['lb', 'kg']} />
                    <HeightField labelFt="Height" ft={heightFt} setFt={setHeightFt} inches={heightIn} setIn={setHeightIn} />
                    <RxField label="Age" type="number" value={age} onChange={setAge} />
                    <RxSelect label="Sex" value={sex} onChange={setSex} options={[['male','Male'],['female','Female']]} />
                    <RxSelect label="Activity level" value={activity} onChange={setActivity} options={[
                      ['sedentary', 'Sedentary — desk job, no training'],
                      ['light', 'Light — 1–3 sessions/week'],
                      ['moderate', 'Moderate — 3–5 sessions/week'],
                      ['active', 'Active — 5–7 sessions/week + steps'],
                    ]} />
                    <RxSelect label="Primary goal" value={goal} onChange={setGoal} options={[
                      ['recomp', 'Recomp — change body comp'],
                      ['cut', 'Cut — lose body fat'],
                      ['lean-bulk', 'Lean bulk — gain muscle'],
                      ['maintain', 'Maintain — stay where I am'],
                    ]} />
                  </>
                )}
              </div>

              {isCustom && macros && (
                <div style={{
                  marginTop: 24,
                  padding: '18px 22px',
                  background: 'var(--rxr-charcoal)',
                  color: '#fff',
                  borderRadius: 6,
                }}>
                  <div style={{ fontSize: 10, fontWeight: 600, letterSpacing: '0.22em', textTransform: 'uppercase', color: 'var(--rxr-sapphire-tint)' }}>
                    Your starting numbers
                  </div>
                  <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 16, marginTop: 14 }}>
                    {[
                      ['Calories', macros.cals, ''],
                      ['Protein', macros.protein, 'g'],
                      ['Carbs', macros.carbs, 'g'],
                      ['Fat', macros.fat, 'g'],
                    ].map(([k, v, u]) => (
                      <div key={k}>
                        <div style={{ fontSize: 9, fontWeight: 600, letterSpacing: '0.22em', textTransform: 'uppercase', color: 'rgba(255,255,255,0.5)' }}>{k}</div>
                        <div style={{ fontFamily: 'var(--font-mono)', fontSize: 24, fontWeight: 500, letterSpacing: '-0.01em', marginTop: 4 }}>
                          {v}<span style={{ fontFamily: 'var(--font-body)', fontSize: 11, color: 'rgba(255,255,255,0.55)', marginLeft: 2 }}>{u}</span>
                        </div>
                      </div>
                    ))}
                  </div>
                  <div style={{ fontSize: 11, color: 'rgba(255,255,255,0.55)', marginTop: 12, lineHeight: 1.5 }}>
                    These are your starting point. We\u2019ll explain how to use them inside the plan, and the math behind the numbers.
                  </div>
                </div>
              )}

              <div style={{
                marginTop: 24,
                display: 'flex',
                justifyContent: 'space-between',
                alignItems: 'center',
                gap: 14,
                flexWrap: 'wrap',
              }}>
                <div style={{ fontSize: 11, color: 'var(--fg-3)', letterSpacing: '0.1em', lineHeight: 1.5 }}>
                  We never sell your email. Unsubscribe with one click.
                </div>
                <button
                  onClick={async () => { if (!valid) return; await window.rxrMailerLite(email, name, window.MAILERLITE_GROUPS.reset); setSubmitted(true); }}
                  disabled={!valid}
                  className="btn btn-primary"
                  style={{
                    padding: '14px 24px',
                    opacity: !valid ? 0.4 : 1,
                    cursor: !valid ? 'not-allowed' : 'pointer',
                  }}
                >
                  Send Me The Plan →
                </button>
              </div>
            </div>
          </>
        ) : (
          <div style={{ padding: 40, textAlign: 'center' }}>
            <div style={{
              width: 48, height: 48, borderRadius: 24,
              background: 'var(--rxr-volt)',
              display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
              color: '#fff', marginBottom: 20,
            }}>
              <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><polyline points="20 6 9 17 4 12"/></svg>
            </div>
            <div style={{
              fontFamily: 'var(--font-display)', fontSize: 32, lineHeight: 1,
              letterSpacing: '-0.01em', color: 'var(--fg)', marginBottom: 12,
            }}>
              {name.toUpperCase()}, IT&apos;S ON ITS WAY.
            </div>
            <div style={{ fontSize: 15, color: 'var(--fg-2)', lineHeight: 1.6, maxWidth: '44ch', margin: '0 auto' }}>
              {isCustom
                ? `Your personalized Reset plan — with your starting macros baked in — is on its way to ${email}. Check your inbox in the next few minutes.`
                : `The Reset plan is on its way to ${email}. Check your inbox in the next few minutes.`}
            </div>
            <div style={{
              marginTop: 28,
              padding: '14px 18px',
              background: 'var(--rxr-sapphire-wash)',
              borderLeft: '2px solid var(--accent)',
              fontSize: 13,
              color: 'var(--fg)',
              lineHeight: 1.55,
              textAlign: 'left',
              maxWidth: 440,
              margin: '28px auto 0',
            }}>
              <strong>Tip:</strong> If you don&apos;t see it, check your spam folder or Promotions tab. Drag it to your inbox so the next note doesn&apos;t get lost.
            </div>
            <button onClick={onClose} className="btn btn-primary" style={{ marginTop: 24, padding: '12px 22px' }}>
              Got It →
            </button>
          </div>
        )}
      </div>
    </div>
  );
};

// --- Small form primitives ---
const RxField = ({ label, type = 'text', value, onChange }) => (
  <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
    <label style={{ fontSize: 10, fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.18em', color: 'var(--fg-3)' }}>{label}</label>
    <input
      type={type}
      value={value}
      onChange={e => onChange(e.target.value)}
      style={{
        fontFamily: 'var(--font-body)', fontSize: 14,
        padding: '11px 12px', borderRadius: 6,
        border: '1px solid var(--border-strong)',
        background: '#fff', color: 'var(--fg)',
      }}
    />
  </div>
);

const RxFieldUnits = ({ label, value, onChange, units, onUnitChange, options }) => (
  <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
    <label style={{ fontSize: 10, fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.18em', color: 'var(--fg-3)' }}>{label}</label>
    <div style={{ display: 'flex', gap: 8 }}>
      <input
        type="number"
        value={value}
        onChange={e => onChange(e.target.value)}
        style={{
          flex: 1,
          fontFamily: 'var(--font-mono)', fontSize: 14,
          padding: '11px 12px', borderRadius: 6,
          border: '1px solid var(--border-strong)',
          background: '#fff', color: 'var(--fg)',
        }}
      />
      <select
        value={units}
        onChange={e => onUnitChange(e.target.value)}
        style={{
          fontFamily: 'var(--font-mono)', fontSize: 13,
          padding: '11px 12px', borderRadius: 6,
          border: '1px solid var(--border-strong)',
          background: '#fff', color: 'var(--fg)',
        }}
      >
        {options.map(o => <option key={o} value={o}>{o}</option>)}
      </select>
    </div>
  </div>
);

const HeightField = ({ labelFt, ft, setFt, inches, setIn }) => (
  <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
    <label style={{ fontSize: 10, fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.18em', color: 'var(--fg-3)' }}>{labelFt}</label>
    <div style={{ display: 'flex', gap: 8 }}>
      <div style={{ position: 'relative', flex: 1 }}>
        <input
          type="number"
          value={ft}
          onChange={e => setFt(e.target.value)}
          placeholder="5"
          style={{
            width: '100%',
            fontFamily: 'var(--font-mono)', fontSize: 14,
            padding: '11px 36px 11px 12px', borderRadius: 6,
            border: '1px solid var(--border-strong)',
            background: '#fff', color: 'var(--fg)',
          }}
        />
        <span style={{
          position: 'absolute', right: 12, top: '50%', transform: 'translateY(-50%)',
          fontFamily: 'var(--font-mono)', fontSize: 12, color: 'var(--fg-3)', pointerEvents: 'none',
        }}>ft</span>
      </div>
      <div style={{ position: 'relative', flex: 1 }}>
        <input
          type="number"
          value={inches}
          onChange={e => setIn(e.target.value)}
          placeholder="7"
          style={{
            width: '100%',
            fontFamily: 'var(--font-mono)', fontSize: 14,
            padding: '11px 36px 11px 12px', borderRadius: 6,
            border: '1px solid var(--border-strong)',
            background: '#fff', color: 'var(--fg)',
          }}
        />
        <span style={{
          position: 'absolute', right: 12, top: '50%', transform: 'translateY(-50%)',
          fontFamily: 'var(--font-mono)', fontSize: 12, color: 'var(--fg-3)', pointerEvents: 'none',
        }}>in</span>
      </div>
    </div>
  </div>
);

const RxSelect = ({ label, value, onChange, options }) => (
  <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
    <label style={{ fontSize: 10, fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.18em', color: 'var(--fg-3)' }}>{label}</label>
    <select
      value={value}
      onChange={e => onChange(e.target.value)}
      style={{
        fontFamily: 'var(--font-body)', fontSize: 14,
        padding: '11px 12px', borderRadius: 6,
        border: '1px solid var(--border-strong)',
        background: '#fff', color: 'var(--fg)',
      }}
    >
      {options.map(([v, l]) => <option key={v} value={v}>{l}</option>)}
    </select>
  </div>
);

Object.assign(window, { FreeResource });
