// ── Size Guide — slide-in panel from the right ───────────────────────

// Worldwide average body measurements (what the wearer measures, not the garment)
const UPPER_IN = [
  { size: 'XS',   chest: '31–33', shoulder: '15.5', sleeve: '31–32' },
  { size: 'S',    chest: '34–36', shoulder: '16.5', sleeve: '32–33' },
  { size: 'M',    chest: '37–39', shoulder: '17.5', sleeve: '33–33.5' },
  { size: 'L',    chest: '40–42', shoulder: '18.5', sleeve: '33.5–34' },
  { size: 'XL',   chest: '43–45', shoulder: '19.5', sleeve: '34–34.5' },
  { size: 'XXL',  chest: '46–48', shoulder: '20.5', sleeve: '34.5–35' },
  { size: 'XXXL', chest: '49–51', shoulder: '21.5', sleeve: '35–35.5' },
];
const UPPER_CM = [
  { size: 'XS',   chest: '79–84',   shoulder: '40', sleeve: '79–81' },
  { size: 'S',    chest: '86–91',   shoulder: '42', sleeve: '81–84' },
  { size: 'M',    chest: '94–99',   shoulder: '44', sleeve: '84–85' },
  { size: 'L',    chest: '102–107', shoulder: '47', sleeve: '85–86' },
  { size: 'XL',   chest: '109–114', shoulder: '50', sleeve: '86–88' },
  { size: 'XXL',  chest: '117–122', shoulder: '52', sleeve: '88–89' },
  { size: 'XXXL', chest: '124–130', shoulder: '55', sleeve: '89–90' },
];

const LOWER_IN = [
  { size: 'XS',   waist: '25–27', hips: '31–33', inseam: '28–29' },
  { size: 'S',    waist: '28–30', hips: '34–36', inseam: '29–30' },
  { size: 'M',    waist: '31–33', hips: '37–39', inseam: '30–31' },
  { size: 'L',    waist: '34–36', hips: '40–42', inseam: '31–32' },
  { size: 'XL',   waist: '37–39', hips: '43–45', inseam: '31–32' },
  { size: 'XXL',  waist: '40–43', hips: '46–48', inseam: '32' },
  { size: 'XXXL', waist: '44–47', hips: '49–52', inseam: '32' },
];
const LOWER_CM = [
  { size: 'XS',   waist: '64–69',   hips: '79–84',   inseam: '71–74' },
  { size: 'S',    waist: '71–76',   hips: '86–91',   inseam: '74–76' },
  { size: 'M',    waist: '79–84',   hips: '94–99',   inseam: '76–79' },
  { size: 'L',    waist: '86–91',   hips: '102–107', inseam: '79–81' },
  { size: 'XL',   waist: '94–99',   hips: '109–114', inseam: '79–81' },
  { size: 'XXL',  waist: '102–109', hips: '117–122', inseam: '81' },
  { size: 'XXXL', waist: '112–119', hips: '124–132', inseam: '81' },
];

function SizeGuide({ product, onClose }) {
  const [unit, setUnit] = React.useState('in');
  const [tab, setTab] = React.useState('upper');

  const upperRows = unit === 'in' ? UPPER_IN : UPPER_CM;
  const lowerRows = unit === 'in' ? LOWER_IN : LOWER_CM;

  React.useEffect(() => {
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    document.addEventListener('keydown', onKey);
    document.body.style.overflow = 'hidden';
    return () => {
      document.removeEventListener('keydown', onKey);
      document.body.style.overflow = '';
    };
  }, [onClose]);

  function SizeTable({ headers, rows }) {
    return (
      <div style={{ overflowX: 'auto' }}>
        <table style={{
          width: '100%', borderCollapse: 'collapse',
          fontFamily: 'var(--font-mono)', fontSize: 11,
          letterSpacing: '.1em',
        }}>
          <thead>
            <tr style={{ borderBottom: '.5px solid var(--line)' }}>
              {headers.map(h => (
                <th key={h} style={{
                  padding: '10px 12px', textAlign: 'left',
                  color: 'var(--fg-3)', fontWeight: 400,
                  textTransform: 'uppercase', letterSpacing: '.18em',
                  whiteSpace: 'nowrap',
                }}>{h}</th>
              ))}
            </tr>
          </thead>
          <tbody>
            {rows.map((r, i) => (
              <tr key={r.size} style={{
                borderBottom: '.5px solid var(--line)',
                background: i % 2 === 0 ? 'transparent' : 'color-mix(in srgb, var(--fg) 2%, transparent)',
              }}>
                <td style={{ padding: '14px 12px', color: 'var(--fg)', fontWeight: 600 }}>{r.size}</td>
                {Object.entries(r).filter(([k]) => k !== 'size').map(([k, v]) => (
                  <td key={k} style={{ padding: '14px 12px', color: 'var(--fg-2)' }}>{v}</td>
                ))}
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    );
  }

  return (
    <div style={{
      position: 'fixed', inset: 0, zIndex: 900,
      display: 'flex', justifyContent: 'flex-end',
    }}>
      {/* Backdrop */}
      <div onClick={onClose} style={{
        position: 'absolute', inset: 0,
        background: 'rgba(10,10,10,.55)',
        backdropFilter: 'blur(4px)',
        WebkitBackdropFilter: 'blur(4px)',
        animation: 'sg-fade-in .22s ease',
      }} />

      {/* Panel */}
      <div style={{
        position: 'relative', zIndex: 1,
        width: '100%', maxWidth: 520,
        background: 'var(--bg)',
        borderLeft: '.5px solid var(--line)',
        overflowY: 'auto',
        animation: 'sg-slide-in .28s cubic-bezier(.22,.72,.36,1)',
        display: 'flex', flexDirection: 'column',
      }}>

        {/* Header */}
        <div style={{
          display: 'flex', alignItems: 'center', justifyContent: 'space-between',
          padding: '28px 32px 24px',
          borderBottom: '.5px solid var(--line)',
          position: 'sticky', top: 0,
          background: 'var(--bg)', zIndex: 2,
        }}>
          <div>
            <div className="eyebrow" style={{ marginBottom: 6 }}>◇ &nbsp; Sizing</div>
            <h2 className="display" style={{ fontSize: 32, margin: 0 }}>
              <em>Size guide</em>
            </h2>
          </div>
          <button onClick={onClose} aria-label="Close size guide"
            style={{
              width: 44, height: 44,
              border: '.5px solid var(--line-2)',
              color: 'var(--fg-2)',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              fontSize: 18,
              transition: 'border-color .15s, color .15s',
            }}
            onMouseEnter={e => { e.currentTarget.style.borderColor = 'var(--fg)'; e.currentTarget.style.color = 'var(--fg)'; }}
            onMouseLeave={e => { e.currentTarget.style.borderColor = 'var(--line-2)'; e.currentTarget.style.color = 'var(--fg-2)'; }}>
            ×
          </button>
        </div>

        {/* Tabs + Unit toggle in one bar */}
        <div style={{
          display: 'flex', alignItems: 'center', justifyContent: 'space-between',
          borderBottom: '.5px solid var(--line)',
          padding: '0 32px',
          position: 'sticky', top: 97, background: 'var(--bg)', zIndex: 2,
        }}>
          <div style={{ display: 'flex' }}>
            {[['upper', 'Upper Body'], ['lower', 'Lower Body']].map(([t, label]) => (
              <button key={t} onClick={() => setTab(t)}
                className="mono"
                style={{
                  padding: '16px 0', marginRight: 28,
                  color: tab === t ? 'var(--fg)' : 'var(--fg-3)',
                  borderBottom: tab === t ? '1px solid var(--fg)' : '1px solid transparent',
                  transition: 'color .15s',
                  fontSize: 11, letterSpacing: '.12em',
                }}>
                {label}
              </button>
            ))}
          </div>
          <div style={{
            display: 'flex',
            border: '.5px solid var(--line-2)',
            overflow: 'hidden',
          }}>
            {['in', 'cm'].map(u => (
              <button key={u} onClick={() => setUnit(u)}
                className="mono"
                style={{
                  padding: '6px 14px',
                  background: unit === u ? 'var(--fg)' : 'transparent',
                  color: unit === u ? 'var(--bg)' : 'var(--fg-2)',
                  transition: 'all .15s',
                  fontSize: 10, letterSpacing: '.1em',
                }}>
                {u}
              </button>
            ))}
          </div>
        </div>

        <div style={{ padding: '28px 32px', flex: 1 }}>

          {tab === 'upper' && (
            <div>
              <p style={{
                fontSize: 12, color: 'var(--fg-3)',
                fontFamily: 'var(--font-mono)', letterSpacing: '.04em',
                lineHeight: 1.65, marginTop: 0, marginBottom: 22,
              }}>
                All measurements are your body measurements, not the garment. Measure your chest — that determines your size.
              </p>

              <SizeTable
                headers={['SIZE', `CHEST (${unit})`, `SHOULDER (${unit})`, `SLEEVE (${unit})`]}
                rows={upperRows}
              />

              <div style={{
                marginTop: 20, padding: 16,
                background: 'var(--surf)',
                borderLeft: '2px solid var(--line-2)',
              }}>
                <div className="mono" style={{ color: 'var(--fg-2)', lineHeight: 1.75, fontSize: 10.5 }}>
                  <strong style={{ color: 'var(--fg)' }}>Chest</strong> — tape around the fullest part of your chest, just under the arms, parallel to the floor.<br />
                  <strong style={{ color: 'var(--fg)' }}>Shoulder</strong> — bony tip of left shoulder across your back to the right shoulder tip.<br />
                  <strong style={{ color: 'var(--fg)' }}>Sleeve</strong> — center back of neck, over shoulder, down to your wrist bone.<br />
                  Leather has minimal stretch — if between sizes, size up.
                </div>
              </div>
            </div>
          )}

          {tab === 'lower' && (
            <div>
              <p style={{
                fontSize: 12, color: 'var(--fg-3)',
                fontFamily: 'var(--font-mono)', letterSpacing: '.04em',
                lineHeight: 1.65, marginTop: 0, marginBottom: 22,
              }}>
                Reference lower body measurements. These correspond to the same size label as your upper body.
              </p>

              <SizeTable
                headers={['SIZE', `WAIST (${unit})`, `HIPS (${unit})`, `INSEAM (${unit})`]}
                rows={lowerRows}
              />

              <div style={{
                marginTop: 20, padding: 16,
                background: 'var(--surf)',
                borderLeft: '2px solid var(--line-2)',
              }}>
                <div className="mono" style={{ color: 'var(--fg-2)', lineHeight: 1.75, fontSize: 10.5 }}>
                  <strong style={{ color: 'var(--fg)' }}>Waist</strong> — around your natural waist, approximately one inch above the navel.<br />
                  <strong style={{ color: 'var(--fg)' }}>Hips</strong> — around the fullest part of your hips, 7–9 inches below the waist.<br />
                  <strong style={{ color: 'var(--fg)' }}>Inseam</strong> — from the crotch seam down to the ankle bone.
                </div>
              </div>
            </div>
          )}

          {/* Contact footer */}
          <div style={{
            marginTop: 32, padding: '20px 24px',
            border: '.5px solid var(--line)',
            display: 'flex', justifyContent: 'space-between',
            alignItems: 'center', gap: 20, flexWrap: 'wrap',
          }}>
            <div>
              <div className="display" style={{ fontSize: 18 }}>
                <em>Need help?</em>
              </div>
            </div>
            <button className="btn ghost sm"
              onClick={() => window.location.href = `mailto:${(window.CONTACT || {}).email || ''}`}>
              Contact us <span className="arrow">→</span>
            </button>
          </div>
        </div>
      </div>

      <style>{`
        @keyframes sg-fade-in  { from { opacity:0 }              to { opacity:1 } }
        @keyframes sg-slide-in { from { transform:translateX(100%) } to { transform:translateX(0) } }
      `}</style>
    </div>
  );
}

Object.assign(window, { SizeGuide });
