// Shared UI primitives for workup
const { useState, useEffect, useRef, useMemo } = React;

// ── 에러 바운더리 — 화면 오류 시 팝업 + 뒤로가기 ──
class WuErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false, error: null, errorInfo: null };
  }
  static getDerivedStateFromError(error) {
    return { hasError: true, error };
  }
  componentDidCatch(error, errorInfo) {
    this.setState({ errorInfo });
    console.error('WuErrorBoundary caught:', error, errorInfo);
  }
  render() {
    if (this.state.hasError) {
      const err = this.state.error;
      const info = this.state.errorInfo;
      const goBack = this.props.onBack;
      return React.createElement('div', {
        style: { height: '100%', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', background: 'var(--wu-bg)', padding: 24 }
      },
        React.createElement('div', {
          style: { width: '100%', maxWidth: 400, background: 'var(--wu-paper)', border: '1px solid var(--wu-line)', boxShadow: '0 8px 32px rgba(0,0,0,0.12)', overflow: 'hidden', borderRadius: 8 }
        },
          // 헤더
          React.createElement('div', {
            style: { padding: '16px 20px', background: 'var(--wu-ink)', color: '#fff', display: 'flex', alignItems: 'center', gap: 10 }
          },
            React.createElement('span', { style: { fontSize: 20 } }, '⚠️'),
            React.createElement('div', null,
              React.createElement('div', {
                style: { fontSize: 16, fontWeight: 700, fontFamily: 'Pretendard' }
              }, '화면 표시 오류'),
              React.createElement('div', {
                style: { fontSize: 11, color: 'var(--wu-mute)', marginTop: 2, fontFamily: 'JetBrains Mono' }
              }, 'RENDER ERROR')
            )
          ),
          // 에러 메시지
          React.createElement('div', {
            style: { padding: '16px 20px' }
          },
            React.createElement('div', {
              style: { fontSize: 12, color: '#C44', fontWeight: 700, fontFamily: 'Pretendard', marginBottom: 8 }
            }, '오류 내용:'),
            React.createElement('div', {
              style: { padding: 12, background: '#FFF5F5', border: '1px solid #FCC', borderRadius: 6, fontSize: 12, fontFamily: 'JetBrains Mono', color: '#333', lineHeight: 1.5, maxHeight: 120, overflow: 'auto', wordBreak: 'break-all' }
            }, err ? err.toString() : 'Unknown error'),
            info && info.componentStack && React.createElement('details', {
              style: { marginTop: 8 }
            },
              React.createElement('summary', {
                style: { fontSize: 11, color: 'var(--wu-mute)', cursor: 'pointer', fontFamily: 'Pretendard' }
              }, '상세 스택 보기'),
              React.createElement('pre', {
                style: { fontSize: 10, color: '#666', marginTop: 4, maxHeight: 150, overflow: 'auto', whiteSpace: 'pre-wrap', wordBreak: 'break-all', background: 'var(--wu-bg)', padding: 8, borderRadius: 4 }
              }, info.componentStack)
            )
          ),
          // 버튼
          React.createElement('div', {
            style: { padding: '12px 20px 16px', display: 'flex', gap: 8 }
          },
            goBack && React.createElement('button', {
              onClick: goBack,
              style: { flex: 1, padding: '12px', fontSize: 14, fontWeight: 700, fontFamily: 'Pretendard', background: 'var(--wu-ink)', color: '#fff', border: 'none', cursor: 'pointer', borderRadius: 6 }
            }, '← 뒤로가기'),
            React.createElement('button', {
              onClick: function() { location.reload(); },
              style: { flex: 1, padding: '12px', fontSize: 14, fontWeight: 700, fontFamily: 'Pretendard', background: 'var(--wu-orange)', color: '#fff', border: 'none', cursor: 'pointer', borderRadius: 6 }
            }, '↻ 새로고침')
          )
        )
      );
    }
    return this.props.children;
  }
}
window.WuErrorBoundary = WuErrorBoundary;

// Logo — workup wordmark
function WuLogo({ size = 22, color = 'var(--wu-ink)', accent = 'var(--wu-orange)' }) {
  return (
    <div style={{ display: 'inline-flex', alignItems: 'center', gap: 0, lineHeight: 1 }}>
      <span style={{ fontFamily: 'Pretendard', fontSize: size, fontWeight: 900, letterSpacing: '-0.04em', color }}>워크</span>
      <span style={{ fontFamily: 'Pretendard', fontSize: size, fontWeight: 900, letterSpacing: '-0.04em', background: accent, color: '#fff', padding: '2px 6px 2px 5px', borderRadius: 4, marginLeft: 2 }}>업</span>
    </div>
  );
}

// Striped product placeholder
function WuPhoto({ label = 'PRODUCT', dark = false, ratio = '1/1', children, style, tint }) {
  return (
    <div className={'wu-placeholder' + (dark ? ' dark' : '')} style={{ aspectRatio: ratio, width: '100%', background: tint, ...style }}>
      {children || <span className="label">{label}</span>}
    </div>
  );
}

// Chip / pill
function WuChip({ active, children, onClick, dark = false }) {
  return (
    <button onClick={onClick} className="kr" style={{
      padding: '8px 14px', borderRadius: 999, fontSize: 13, fontWeight: 600,
      whiteSpace: 'nowrap',
      background: active ? (dark ? 'var(--wu-lime)' : 'var(--wu-ink)') : (dark ? '#1C1C19' : '#fff'),
      color: active ? (dark ? 'var(--wu-ink)' : 'var(--wu-paper)') : (dark ? '#B8B3A8' : 'var(--wu-ink)'),
      border: dark ? 'none' : (active ? 'none' : '1px solid var(--wu-line)'),
    }}>{children}</button>
  );
}

// Price formatter
function wuPrice(n) { return '₩' + n.toLocaleString('ko-KR'); }

// Product card — variant A: editorial, big type
function WuProductCard({ p, variant = 'A', onFav, faved, dark = false, onClick }) {
  if (variant === 'A') {
    return (
      <div style={{ position: 'relative', cursor: onClick ? 'pointer' : 'default' }} onClick={onClick}>
        <WuPhoto label={p.code} ratio="4/5" tint={p.colors?.[0] ? `linear-gradient(160deg, ${p.colors[0]}22, ${p.colors[0]}55)` : undefined} />
        {p.tag && <span className="wu-tag" style={{ position: 'absolute', top: 10, left: 10, background: p.tag === 'NEW' ? 'var(--wu-lime)' : p.tag === 'HOT' ? 'var(--wu-orange)' : 'var(--wu-ink)', color: p.tag === 'NEW' ? 'var(--wu-ink)' : '#fff' }}>{p.tag}</span>}
        <button onClick={onFav} style={{ position: 'absolute', top: 10, right: 10, width: 32, height: 32, borderRadius: 999, background: faved ? 'var(--wu-ink)' : 'rgba(255,255,255,0.9)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <svg width="14" height="14" viewBox="0 0 14 14" fill={faved ? 'var(--wu-lime)' : 'none'} stroke={faved ? 'var(--wu-lime)' : 'var(--wu-ink)'} strokeWidth="1.6"><path d="M7 12L2 7.5a2.8 2.8 0 014-4l1 1 1-1a2.8 2.8 0 014 4L7 12z"/></svg>
        </button>
        <div style={{ marginTop: 10, display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', gap: 8 }}>
          <div>
            <div className="kr" style={{ fontSize: 13, fontWeight: 600 }}>{p.kr}</div>
            <div className="mono" style={{ fontSize: 10, color: 'var(--wu-mute)', marginTop: 2 }}>{p.code}</div>
          </div>
          <div className="display" style={{ fontSize: 15 }}>{wuPrice(p.retail)}</div>
        </div>
        <div style={{ display: 'flex', gap: 3, marginTop: 6 }}>
          {p.colors?.map((c, i) => <div key={i} style={{ width: 10, height: 10, borderRadius: 999, background: c, border: '1px solid rgba(0,0,0,0.08)' }} />)}
        </div>
      </div>
    );
  }
  // variant B: mono / catalog strip
  if (variant === 'B') {
    return (
      <div style={{ display: 'flex', gap: 12, padding: 10, background: 'var(--wu-paper)', border: '1px solid var(--wu-line)' }}>
        <div style={{ width: 72, flexShrink: 0 }}><WuPhoto label="" ratio="1/1" tint={p.colors?.[0]} /></div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
            <div className="mono" style={{ fontSize: 10, color: 'var(--wu-mute)' }}>{p.code}</div>
            {p.tag && <span className="mono" style={{ fontSize: 9, letterSpacing: '0.06em', color: p.tag === 'NEW' ? 'var(--wu-orange)' : 'var(--wu-ink)' }}>● {p.tag}</span>}
          </div>
          <div className="kr" style={{ fontSize: 14, fontWeight: 600, marginTop: 4 }}>{p.kr}</div>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginTop: 8 }}>
            <div style={{ display: 'flex', gap: 3 }}>
              {p.colors?.map((c, i) => <div key={i} style={{ width: 10, height: 10, borderRadius: 999, background: c, border: '1px solid rgba(0,0,0,0.08)' }} />)}
            </div>
            <div className="display" style={{ fontSize: 14 }}>{wuPrice(p.retail)}</div>
          </div>
        </div>
      </div>
    );
  }
  // variant C: poster — full bleed with overlay
  return (
    <div style={{ position: 'relative', background: 'var(--wu-ink)', color: 'var(--wu-paper)' }}>
      <WuPhoto label={p.code} ratio="3/4" dark tint={p.colors?.[0] ? `linear-gradient(180deg, ${p.colors[0]}55, #0E0E0C)` : undefined} />
      <div style={{ position: 'absolute', inset: 0, display: 'flex', flexDirection: 'column', justifyContent: 'space-between', padding: 12 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between' }}>
          {p.tag && <span className="wu-tag lime">{p.tag}</span>}
          <span className="mono" style={{ fontSize: 10, color: 'rgba(255,255,255,0.7)' }}>{p.code}</span>
        </div>
        <div>
          <div className="display" style={{ fontSize: 24, color: 'var(--wu-lime)', lineHeight: 1 }}>{p.en}</div>
          <div className="kr" style={{ fontSize: 12, marginTop: 4, opacity: 0.8 }}>{p.kr}</div>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginTop: 10 }}>
            <div style={{ display: 'flex', gap: 3 }}>
              {p.colors?.map((c, i) => <div key={i} style={{ width: 10, height: 10, borderRadius: 999, background: c, border: '1px solid rgba(255,255,255,0.3)' }} />)}
            </div>
            <div className="mono" style={{ fontSize: 13, fontWeight: 600 }}>{wuPrice(p.retail)}</div>
          </div>
        </div>
      </div>
    </div>
  );
}

// Bottom tab bar — 무신사 스타일 하단 고정
function WuTabBar({ active = 'home', onChange, variant = 'pill', dark = false }) {
  const tabs = [
    { id: 'shop', kr: '검색',
      svg: (c, w) => <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth={w} strokeLinecap="round" strokeLinejoin="round"><circle cx="11" cy="11" r="7"/><path d="M21 21l-4.35-4.35"/></svg> },
    { id: 'map', kr: '매장',
      svg: (c, w) => <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth={w} strokeLinecap="round" strokeLinejoin="round"><path d="M3 7l3-4h12l3 4"/><path d="M3 7v13h18V7"/><path d="M9 20v-7h6v7"/></svg> },
    { id: 'board', kr: '게시판',
      svg: (c, w) => <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth={w} strokeLinecap="round" strokeLinejoin="round"><path d="M4 4h16v3H4zm0 6h16v3H4zm0 6h10v3H4z"/></svg> },
    { id: 'home', kr: '홈',
      svg: (c, w) => <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth={w} strokeLinecap="round" strokeLinejoin="round"><path d="M3 10.5L12 3l9 7.5V21H3V10.5z"/></svg> },
    { id: 'wishlist', kr: '좋아요',
      svg: (c, w) => <svg width="20" height="20" viewBox="0 0 24 24" fill={active === 'wishlist' ? c : 'none'} stroke={c} strokeWidth={w} strokeLinecap="round" strokeLinejoin="round"><path d="M12 21C12 21 3 13.5 3 8.5 3 5.42 5.42 3 8.5 3c1.74 0 3.41.81 4.5 2.09C14.09 3.81 15.76 3 17.5 3 20.58 3 23 5.42 23 8.5 23 13.5 12 21 12 21z"/></svg> },
    { id: 'me', kr: '마이',
      svg: (c, w) => <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth={w} strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="8" r="4"/><path d="M4 21a8 8 0 0116 0"/></svg> },
  ];
  return (
    <div style={{ position: 'absolute', bottom: 0, left: 0, right: 0, background: '#fff', borderTop: '1px solid #E5E5E5', display: 'flex', paddingBottom: 'env(safe-area-inset-bottom, 8px)', zIndex: 40 }}>
      {tabs.map(t => {
        const isActive = active === t.id;
        const color = isActive ? '#1A1A1A' : '#999';
        const weight = isActive ? 2 : 1.5;
        return (
          <button key={t.id} onClick={() => onChange?.(t.id)} style={{ flex: 1, padding: '8px 0 4px', display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 3, background: 'none', border: 'none', cursor: 'pointer' }}>
            {t.svg(color, weight)}
            <span className="kr" style={{ fontSize: 9, fontWeight: isActive ? 700 : 400, color, letterSpacing: '-0.02em' }}>{t.kr}</span>
          </button>
        );
      })}
    </div>
  );
}

Object.assign(window, { WuLogo, WuPhoto, WuChip, WuProductCard, WuTabBar, wuPrice });
