// Store owner dashboard screens (desktop + mobile)
const { leaderboard, messages } = WU_DATA;

// ────────────────────────────────────────────────────
// OWNER STORE MAP — 점주 매장 지도 (카카오맵)
// ────────────────────────────────────────────────────
function OwnerStoreMap() {
  const mapRef = React.useRef(null);
  const mapObjRef = React.useRef(null);
  const markersRef = React.useRef([]);
  const [realStores, setRealStores] = React.useState([]);
  const [mapReady, setMapReady] = React.useState(false);
  const [selected, setSelected] = React.useState(null);
  const [search, setSearch] = React.useState('');
  const [activeRegion, setActiveRegion] = React.useState('전체');

  const REGIONS = ['전체', '서울', '경기', '인천', '부산', '대구', '대전', '광주', '울산', '충북', '충남', '전북', '전남', '경북', '경남', '강원', '제주'];

  React.useEffect(() => {
    if (typeof getAllStores === 'function') getAllStores().then(s => setRealStores(s)).catch(() => {});
  }, []);

  React.useEffect(() => {
    const apiKey = localStorage.getItem('wu-kakao-key');
    if (!apiKey || !mapRef.current) return;
    const init = () => {
      try {
        if (window.kakao && window.kakao.maps) window.kakao.maps.load(() => setMapReady(true));
      } catch(e) {}
    };
    if (window.kakao && window.kakao.maps) { init(); return; }
    if (document.getElementById('kakao-map-script')) { setTimeout(init, 500); return; }
    const s = document.createElement('script');
    s.id = 'kakao-map-script';
    s.src = 'https://dapi.kakao.com/v2/maps/sdk.js?appkey=' + apiKey + '&libraries=services&autoload=false';
    s.onload = init;
    document.head.appendChild(s);
  }, []);

  // 마커 생성 — 한 번만
  React.useEffect(() => {
    if (!mapReady || !mapRef.current || !realStores.length) return;
    try {
      const map = new kakao.maps.Map(mapRef.current, { center: new kakao.maps.LatLng(36.5, 127.0), level: 13 });
      map.addControl(new kakao.maps.ZoomControl(), kakao.maps.ControlPosition.RIGHT);
      mapObjRef.current = map;
      if (kakao.maps.services && kakao.maps.services.Geocoder) {
        const gc = new kakao.maps.services.Geocoder();
        const ps = new kakao.maps.services.Places();
        const newMarkers = [];
        const _clean = (addr) => {
          if (!addr) return '';
          let c = addr.trim().replace(/\([^)]*\)/g, '').trim();
          c = c.replace(/\s+(?:\d+층|\d+F|B\d+F?|\d+호|\d+동\s*\d*호?|지하\s*\d*층?).*$/i, '').trim();
          c = c.replace(/(\d+[-−]\d+)\s+.+$/, '$1').trim();
          c = c.replace(/,.*$/, '').trim();
          return c;
        };
        const addMk = (st, lat, lng) => {
          const pos = new kakao.maps.LatLng(lat, lng);
          const mk = new kakao.maps.Marker({ map, position: pos, title: st.name });
          kakao.maps.event.addListener(mk, 'click', () => setSelected(st));
          newMarkers.push({ marker: mk, store: st });
          markersRef.current = [...newMarkers];
        };
        realStores.forEach(st => {
          if (!st.address) return;
          const raw = st.address.trim();
          const clean = _clean(raw);
          try {
            gc.addressSearch(raw, (r1, s1) => {
              if (s1 === kakao.maps.services.Status.OK) { addMk(st, r1[0].y, r1[0].x); return; }
              if (clean && clean !== raw) {
                gc.addressSearch(clean, (r2, s2) => {
                  if (s2 === kakao.maps.services.Status.OK) { addMk(st, r2[0].y, r2[0].x); return; }
                  ps.keywordSearch(st.name + ' ' + clean, (r3, s3) => {
                    if (s3 === kakao.maps.services.Status.OK && r3.length) { addMk(st, r3[0].y, r3[0].x); return; }
                    ps.keywordSearch(clean, (r4, s4) => {
                      if (s4 === kakao.maps.services.Status.OK && r4.length) addMk(st, r4[0].y, r4[0].x);
                    });
                  });
                });
              } else {
                ps.keywordSearch(st.name + ' ' + raw, (r3, s3) => {
                  if (s3 === kakao.maps.services.Status.OK && r3.length) { addMk(st, r3[0].y, r3[0].x); return; }
                  ps.keywordSearch(raw, (r4, s4) => {
                    if (s4 === kakao.maps.services.Status.OK && r4.length) addMk(st, r4[0].y, r4[0].x);
                  });
                });
              }
            });
          } catch(e) {}
        });
      }
    } catch(e) {}
  }, [mapReady, realStores]);

  // 검색/필터 변경 시 마커 show/hide
  React.useEffect(() => {
    if (!markersRef.current.length || !mapObjRef.current) return;
    const q = search.trim().toLowerCase();
    let visibleBounds = null;
    try { visibleBounds = new kakao.maps.LatLngBounds(); } catch(e) {}
    let visCount = 0;

    markersRef.current.forEach(({ marker, store }) => {
      const addr = (store.address || '').toLowerCase();
      const name = (store.name || '').toLowerCase();
      const regionMatch = activeRegion === '전체' || addr.includes(activeRegion);
      const searchMatch = !q || name.includes(q) || addr.includes(q) || (store.storeId || '').toLowerCase().includes(q);
      const visible = regionMatch && searchMatch;

      if (visible) {
        marker.setMap(mapObjRef.current);
        if (visibleBounds) { try { visibleBounds.extend(marker.getPosition()); } catch(e) {} }
        visCount++;
      } else {
        marker.setMap(null);
      }
    });

    if (visCount > 0 && visibleBounds && mapObjRef.current) {
      try {
        if (visCount === 1) {
          mapObjRef.current.setCenter(visibleBounds.getSouthWest());
          mapObjRef.current.setLevel(5);
        } else {
          mapObjRef.current.setBounds(visibleBounds);
        }
      } catch(e) {}
    }
  }, [search, activeRegion, markersRef.current.length]);

  const handleRegion = (r) => { setActiveRegion(r); setSearch(''); setSelected(null); };

  const filteredCount = search || activeRegion !== '전체'
    ? realStores.filter(s => {
        const addr = (s.address || '').toLowerCase();
        const name = (s.name || '').toLowerCase();
        const q = search.trim().toLowerCase();
        return (activeRegion === '전체' || addr.includes(activeRegion)) && (!q || name.includes(q) || addr.includes(q));
      }).length
    : realStores.length;

  return (
    <div style={{ padding: 28 }}>
      <div className="display" style={{ fontSize: 22, marginBottom: 4 }}>매장 지도</div>
      <div className="mono" style={{ fontSize: 11, color: 'var(--wu-mute)', marginBottom: 16 }}>전국 {realStores.length}개 매장</div>

      {/* 검색 + 필터 */}
      <div style={{ display: 'flex', gap: 8, marginBottom: 12 }}>
        <div style={{ flex: 1, background: '#fff', borderRadius: 999, padding: '8px 14px', display: 'flex', alignItems: 'center', gap: 8, border: '1px solid var(--wu-line)' }}>
          <svg width="14" height="14" viewBox="0 0 20 20" fill="none" stroke="currentColor" strokeWidth="2"><circle cx="9" cy="9" r="6"/><path d="M14 14l4 4"/></svg>
          <input value={search} onChange={e => { setSearch(e.target.value); setActiveRegion('전체'); }} placeholder="지역·매장 검색" className="kr" style={{ border: 'none', outline: 'none', fontSize: 13, flex: 1, background: 'transparent' }} />
          {search && <button onClick={() => { setSearch(''); setActiveRegion('전체'); }} style={{ background: 'none', border: 'none', cursor: 'pointer', fontSize: 14, color: 'var(--wu-mute)', padding: 0 }}>✕</button>}
        </div>
      </div>
      <div style={{ display: 'flex', gap: 6, flexWrap: 'nowrap', overflowX: 'auto', marginBottom: 12, paddingBottom: 4 }}>
        {REGIONS.map(r => {
          const isActive = activeRegion === r && !search;
          const label = r === '전체' ? '전체 ' + filteredCount : r;
          return (
            <button key={r} onClick={() => handleRegion(r)} style={{ background: isActive ? 'var(--wu-ink)' : '#fff', color: isActive ? 'var(--wu-paper)' : 'var(--wu-ink)', padding: '6px 12px', borderRadius: 999, fontSize: 11, fontWeight: 600, border: '1px solid var(--wu-line)', cursor: 'pointer', whiteSpace: 'nowrap', flexShrink: 0 }} className="kr">{label}</button>
          );
        })}
      </div>
      {(search || activeRegion !== '전체') && (
        <div className="kr" style={{ fontSize: 12, color: 'var(--wu-mute)', marginBottom: 8 }}>검색 결과 {filteredCount}개</div>
      )}

      <div style={{ position: 'relative', width: '100%', height: 500, border: '1px solid var(--wu-line)', overflow: 'hidden' }}>
        <div ref={mapRef} style={{ width: '100%', height: '100%' }} />
        {!localStorage.getItem('wu-kakao-key') && (
          <div style={{ position: 'absolute', inset: 0, display: 'flex', alignItems: 'center', justifyContent: 'center', background: '#E9E5DC' }}>
            <div className="kr" style={{ fontSize: 14, color: 'var(--wu-mute)', textAlign: 'center' }}>카카오맵 API 키가 설정되지 않았습니다</div>
          </div>
        )}
      </div>
      {selected && (
        <div style={{ marginTop: 16, padding: 16, background: 'var(--wu-paper)', border: '1px solid var(--wu-line)', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <div style={{ flex: 1 }}>
            <div style={{ display: 'flex', gap: 8, alignItems: 'center', marginBottom: 8 }}>
              <span className="kr" style={{ fontSize: 18, fontWeight: 700 }}>{selected.name}</span>
              {selected.storeId && <span className="mono" style={{ fontSize: 10, color: 'var(--wu-mute)', background: 'var(--wu-bg)', padding: '2px 6px', borderRadius: 4 }}>{selected.storeId}</span>}
            </div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 4 }}>
              <svg width="13" height="13" viewBox="0 0 20 20" fill="none" stroke="var(--wu-mute)" strokeWidth="1.8"><path d="M10 2C6.7 2 4 4.7 4 8c0 5 6 10 6 10s6-5 6-10c0-3.3-2.7-6-6-6z"/><circle cx="10" cy="8" r="2"/></svg>
              <span className="kr" style={{ fontSize: 13, color: 'var(--wu-ink)' }}>{selected.address || '주소 없음'}</span>
            </div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
              <svg width="13" height="13" viewBox="0 0 20 20" fill="none" stroke="var(--wu-mute)" strokeWidth="1.8"><path d="M3 4h4l2 3-2.5 2.5a11.4 11.4 0 005 5L14 12l3 2v4a1 1 0 01-1 1A16 16 0 012 5a1 1 0 011-1z"/></svg>
              <span className="mono" style={{ fontSize: 13, color: 'var(--wu-ink)' }}>{selected.mobile || selected.phone || '번호 없음'}</span>
            </div>
          </div>
          <button onClick={() => setSelected(null)} style={{ fontSize: 11, background: 'none', border: '1px solid var(--wu-line)', padding: '6px 12px', cursor: 'pointer', flexShrink: 0 }}>닫기</button>
        </div>
      )}
    </div>
  );
}

// ────────────────────────────────────────────────────
// OWNER PRODUCT LIST — 발행 상품 열람 (IndexedDB)
// ────────────────────────────────────────────────────
function OwnerProductList() {
  const [items, setItems] = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const [search, setSearch] = React.useState('');

  React.useEffect(() => {
    if (typeof getPublished === 'function') {
      getPublished().then(list => { setItems(list); setLoading(false); }).catch(() => setLoading(false));
    } else { setLoading(false); }
  }, []);

  const filtered = search
    ? items.filter(p => {
        const q = search.toLowerCase();
        const ps = p.parsed || {};
        return (p.title || '').toLowerCase().includes(q) || (ps.brand || '').toLowerCase().includes(q) || (ps.code || '').toLowerCase().includes(q) || (ps.kr || '').toLowerCase().includes(q);
      })
    : items;

  return (
    <div style={{ padding: 28 }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 20 }}>
        <div>
          <div className="mono" style={{ fontSize: 10, color: 'var(--wu-mute)' }}>PARTNER · CATALOG</div>
          <div className="display" style={{ fontSize: 28, marginTop: 2 }}>상품 카탈로그</div>
        </div>
        <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
          <div style={{ background: '#fff', border: '1px solid var(--wu-line)', borderRadius: 999, padding: '8px 14px', display: 'flex', alignItems: 'center', gap: 8, width: 250 }}>
            <svg width="13" height="13" viewBox="0 0 20 20" fill="none" stroke="currentColor" strokeWidth="2"><circle cx="9" cy="9" r="6"/><path d="M14 14l4 4"/></svg>
            <input value={search} onChange={e => setSearch(e.target.value)} placeholder="상품명 · 브랜드 검색" className="kr" style={{ border: 'none', outline: 'none', fontSize: 12, flex: 1, background: 'transparent' }} />
          </div>
          <div className="mono" style={{ fontSize: 11, color: 'var(--wu-mute)' }}>총 {filtered.length}건</div>
        </div>
      </div>

      {loading ? (
        <div style={{ padding: '60px 20px', textAlign: 'center' }}><div className="kr" style={{ fontSize: 14, color: 'var(--wu-mute)' }}>로딩 중...</div></div>
      ) : filtered.length === 0 ? (
        <div style={{ padding: '60px 20px', textAlign: 'center', background: 'var(--wu-paper)', border: '2px dashed var(--wu-line)' }}>
          <div style={{ fontSize: 40, marginBottom: 8 }}>📦</div>
          <div className="kr" style={{ fontSize: 14, color: 'var(--wu-mute)' }}>{search ? '검색 결과가 없습니다' : '발행된 상품이 없습니다'}</div>
        </div>
      ) : (
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(200px, 1fr))', gap: 16 }}>
          {filtered.map(p => {
            const ps = p.parsed || {};
            const photo = (p.photos || [])[0];
            const title = p.title || ps.kr || ps.name || '상품';
            const brand = ps.brand || '';
            const retail = ps.retail ? (typeof ps.retail === 'number' ? ps.retail.toLocaleString() : String(ps.retail).replace(/[^\d,]/g,'')) : '';
            const wholesale = ps.wholesale ? (typeof ps.wholesale === 'number' ? ps.wholesale.toLocaleString() : String(ps.wholesale).replace(/[^\d,]/g,'')) : '';
            return (
              <div key={p.id} style={{ background: 'var(--wu-paper)', border: '1px solid var(--wu-line)', overflow: 'hidden' }}>
                <div style={{ width: '100%', aspectRatio: '4/5', background: '#E9E5DC', overflow: 'hidden' }}>
                  {photo ? <img src={photo} style={{ width: '100%', height: '100%', objectFit: 'cover' }} /> : <div style={{ width: '100%', height: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center' }}><span className="mono" style={{ fontSize: 9, color: 'var(--wu-mute)' }}>NO IMG</span></div>}
                </div>
                <div style={{ padding: '12px 14px' }}>
                  {brand && <div className="mono" style={{ fontSize: 9, color: 'var(--wu-mute)', letterSpacing: '0.06em' }}>{brand}</div>}
                  <div className="kr" style={{ fontSize: 14, fontWeight: 700, marginTop: 2, lineHeight: 1.3 }}>{title}</div>
                  <div style={{ display: 'flex', gap: 10, marginTop: 8 }}>
                    {retail && <div><div className="mono" style={{ fontSize: 9, color: 'var(--wu-mute)' }}>소매가</div><div className="mono" style={{ fontSize: 13, fontWeight: 700 }}>{retail}원</div></div>}
                    {wholesale && <div><div className="mono" style={{ fontSize: 9, color: 'var(--wu-orange)' }}>공급가</div><div className="mono" style={{ fontSize: 13, fontWeight: 700, color: 'var(--wu-orange)' }}>{wholesale}원</div></div>}
                  </div>
                </div>
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
}

// ────────────────────────────────────────────────────
// OWNER DASHBOARD (desktop)
// ────────────────────────────────────────────────────
function OwnerDashboard() {
  const [page, setPage] = React.useState('dashboard');
  return (
    <div className="wu" style={{ height: '100%', background: 'var(--wu-bg)', display: 'flex', overflow: 'hidden' }}>
      {/* Sidebar */}
      <div style={{ width: 220, background: 'var(--wu-ink)', color: 'var(--wu-paper)', padding: '24px 18px', display: 'flex', flexDirection: 'column', flexShrink: 0 }}>
        <WuLogo size={22} color="var(--wu-paper)" />
        <div className="mono" style={{ fontSize: 9, color: 'var(--wu-mute)', marginTop: 6, letterSpacing: '0.1em' }}>PARTNER CONSOLE · v4.2</div>

        <div style={{ marginTop: 28, display: 'flex', flexDirection: 'column', gap: 2 }}>
          {[
            ['dashboard', 'DASHBOARD', '대시보드'],
            ['catalog', 'CATALOG', '상품 카탈로그'],
            ['announce', 'ANNOUNCE', '공지 · 공급가'],
            ['messages', 'MESSAGES', '메시지', 2],
            ['leaderboard', 'LEADERBOARD', '판매 랭킹'],
            ['store', 'STORE', '내 매장 정보'],
          ].map(([id, k, kr, badge]) => (
            <button key={id} onClick={() => setPage(id)} style={{ padding: '9px 12px', borderRadius: 6, background: page === id ? 'var(--wu-orange)' : 'transparent', color: page === id ? '#fff' : '#B8B3A8', display: 'flex', alignItems: 'center', justifyContent: 'space-between', border: 'none', cursor: 'pointer', textAlign: 'left', width: '100%' }}>
              <div>
                <div className="mono" style={{ fontSize: 9, fontWeight: 600, letterSpacing: '0.08em' }}>{k}</div>
                <div className="kr" style={{ fontSize: 12, fontWeight: 600, marginTop: 1 }}>{kr}</div>
              </div>
              {badge && <span style={{ background: 'var(--wu-orange)', color: '#fff', fontSize: 9, padding: '2px 5px', fontFamily: 'JetBrains Mono', fontWeight: 700 }}>{badge}</span>}
            </button>
          ))}
        </div>

        <div style={{ flex: 1 }} />
        <div style={{ padding: 12, background: '#1A1A17', borderLeft: '3px solid var(--wu-orange)', borderRadius: '0 4px 4px 0' }}>
          <div className="mono" style={{ fontSize: 9, color: 'var(--wu-orange)' }}>● APPROVED PARTNER</div>
          <div className="kr" style={{ fontSize: 12, fontWeight: 700, marginTop: 4 }}>성수점 · 김민재</div>
          <div className="mono" style={{ fontSize: 9, color: 'var(--wu-mute)', marginTop: 2 }}>STORE ID · 001</div>
        </div>
      </div>

      {/* Main content */}
      <div className="wu-scroll" style={{ flex: 1, overflow: 'auto' }}>
        {/* Top bar */}
        <div style={{ padding: '18px 28px', display: 'flex', alignItems: 'center', justifyContent: 'space-between', borderBottom: '1px solid var(--wu-line)', background: 'var(--wu-bg)', position: 'sticky', top: 0, zIndex: 10 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
            <div className="mono" style={{ fontSize: 10, color: 'var(--wu-mute)' }}>TODAY · 2026.04.21 · TUE</div>
            <div style={{ width: 1, height: 14, background: 'var(--wu-line)' }} />
            <div className="kr" style={{ fontSize: 12, color: 'var(--wu-ink)' }}>날씨: 맑음 18° · 매장 유동인구 +12%</div>
          </div>
          <div style={{ display: 'flex', gap: 8 }}>
            <button className="wu-btn ghost" style={{ fontSize: 11, padding: '8px 14px' }}>+ 공지 작성</button>
            <button className="wu-btn" style={{ fontSize: 11, padding: '8px 14px' }}>+ 주문하기</button>
          </div>
        </div>

        {/* 내 매장 정보 — 카카오맵 */}
        {page === 'store' && <OwnerStoreMap />}

        {/* 상품 카탈로그 — 발행 상품 */}
        {page === 'catalog' && <OwnerProductList />}

        {page !== 'store' && page !== 'catalog' && <div style={{ padding: 28 }}>
          {/* Welcome + stats */}
          <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', marginBottom: 20 }}>
            <div>
              <div className="mono" style={{ fontSize: 10, color: 'var(--wu-mute)' }}>GOOD AFTERNOON</div>
              <div className="display" style={{ fontSize: 40, lineHeight: 1 }}>김민재 점장님</div>
              <div className="kr" style={{ fontSize: 13, color: 'var(--wu-mute)', marginTop: 4 }}>오늘도 좋은 하루 되세요 ✦ 확인해야 할 항목 3건이 있어요.</div>
            </div>
          </div>

          {/* Stat row */}
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 12, marginBottom: 20 }}>
            {[
              { l: '이번 주 매출', v: '₩12.4M', d: '+18%', good: true },
              { l: '판매 수량', v: '428', sub: '지난주 362' },
              { l: '재고 경고', v: '7', sub: '품목', accent: 'orange' },
              { l: '미확인 공지', v: '3', sub: '본사', accent: 'lime' },
            ].map(s => (
              <div key={s.l} style={{ background: s.accent === 'lime' ? 'var(--wu-lime)' : 'var(--wu-paper)', border: '1px solid var(--wu-line)', padding: 16 }}>
                <div className="mono" style={{ fontSize: 9, color: s.accent === 'lime' ? 'var(--wu-ink)' : 'var(--wu-mute)', letterSpacing: '0.08em' }}>{s.l.toUpperCase()}</div>
                <div style={{ display: 'flex', alignItems: 'baseline', gap: 8, marginTop: 10 }}>
                  <div className="display" style={{ fontSize: 30, lineHeight: 1 }}>{s.v}</div>
                  {s.d && <div className="mono" style={{ fontSize: 11, color: s.good ? '#2a8f3c' : 'var(--wu-ink)', fontWeight: 700 }}>{s.d}</div>}
                </div>
                {s.sub && <div className="kr" style={{ fontSize: 11, color: s.accent === 'lime' ? 'var(--wu-ink)' : 'var(--wu-mute)', marginTop: 4 }}>{s.sub}</div>}
              </div>
            ))}
          </div>

          {/* 2-col: announcements + leaderboard */}
          <div style={{ display: 'grid', gridTemplateColumns: '1.3fr 1fr', gap: 16 }}>
            <div style={{ background: 'var(--wu-paper)', border: '1px solid var(--wu-line)' }}>
              <div style={{ padding: '14px 16px', borderBottom: '1px solid var(--wu-line)', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                <div className="display" style={{ fontSize: 16 }}>PINNED · 본사 공지</div>
                <span className="mono" style={{ fontSize: 10, color: 'var(--wu-mute)' }}>{WU_DATA.announcements.length} ITEMS</span>
              </div>
              {WU_DATA.announcements.map((a, i) => (
                <div key={a.id} style={{ padding: '14px 16px', borderBottom: i < WU_DATA.announcements.length - 1 ? '1px solid var(--wu-line)' : 'none', display: 'flex', gap: 14, alignItems: 'flex-start' }}>
                  <div style={{ width: 40, flexShrink: 0, textAlign: 'center' }}>
                    <div style={{ background: a.type === 'PRICE' ? 'var(--wu-lime)' : a.type === 'DROP' ? 'var(--wu-ink)' : a.type === 'EVENT' ? 'var(--wu-orange)' : '#E3DFD6', color: a.type === 'DROP' ? 'var(--wu-paper)' : a.type === 'EVENT' ? '#fff' : 'var(--wu-ink)', padding: '4px 0', fontSize: 9, fontFamily: 'JetBrains Mono', fontWeight: 700 }}>
                      {a.type}
                    </div>
                    {a.pinned && <div className="mono" style={{ fontSize: 9, color: 'var(--wu-orange)', marginTop: 4 }}>📌 PIN</div>}
                  </div>
                  <div style={{ flex: 1 }}>
                    <div className="kr" style={{ fontSize: 13, fontWeight: 700 }}>{a.title}</div>
                    <div className="kr" style={{ fontSize: 11, color: 'var(--wu-mute)', marginTop: 4 }}>{a.body}</div>
                    <div className="mono" style={{ fontSize: 9, color: 'var(--wu-mute)', marginTop: 6, letterSpacing: '0.05em' }}>{a.date}</div>
                  </div>
                </div>
              ))}
            </div>

            <div style={{ background: 'var(--wu-ink)', color: 'var(--wu-paper)' }}>
              <div style={{ padding: '14px 16px', borderBottom: '1px solid #1A1A17', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                <div className="display" style={{ fontSize: 16, color: 'var(--wu-lime)' }}>LEADERBOARD</div>
                <span className="mono" style={{ fontSize: 10, color: 'var(--wu-mute)' }}>THIS WEEK</span>
              </div>
              {leaderboard.map(r => (
                <div key={r.rank} style={{ padding: '12px 16px', borderBottom: '1px solid #1A1A17', display: 'flex', alignItems: 'center', gap: 12 }}>
                  <div className="display" style={{ fontSize: 26, width: 32, color: r.rank === 1 ? 'var(--wu-lime)' : 'rgba(255,255,255,0.3)' }}>{String(r.rank).padStart(2, '0')}</div>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div className="kr" style={{ fontSize: 12, fontWeight: 600 }}>{r.kr}</div>
                    <div className="mono" style={{ fontSize: 9, color: 'var(--wu-mute)', marginTop: 2 }}>{r.sku}</div>
                  </div>
                  <div style={{ textAlign: 'right' }}>
                    <div className="mono" style={{ fontSize: 13, fontWeight: 700 }}>{r.units}</div>
                    <div className="mono" style={{ fontSize: 9, color: r.delta > 0 ? 'var(--wu-lime)' : 'var(--wu-orange)' }}>{r.delta > 0 ? '+' : ''}{r.delta}%</div>
                  </div>
                </div>
              ))}
            </div>
          </div>
        </div>}
      </div>
    </div>
  );
}

// ────────────────────────────────────────────────────
// OWNER CATALOG (wholesale prices)
// ────────────────────────────────────────────────────
function OwnerCatalog() {
  return (
    <div className="wu" style={{ height: '100%', background: 'var(--wu-bg)', display: 'flex', flexDirection: 'column' }}>
      {/* Header */}
      <div style={{ padding: '20px 28px', background: 'var(--wu-paper)', borderBottom: '1px solid var(--wu-line)' }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <div>
            <div className="mono" style={{ fontSize: 10, color: 'var(--wu-mute)' }}>PARTNER / CATALOG</div>
            <div className="display" style={{ fontSize: 32, marginTop: 4 }}>상품 카탈로그</div>
          </div>
          <div style={{ display: 'flex', gap: 8 }}>
            <div style={{ background: 'var(--wu-bg)', border: '1px solid var(--wu-line)', borderRadius: 999, padding: '8px 16px', display: 'flex', alignItems: 'center', gap: 8, width: 220 }}>
              <svg width="13" height="13" viewBox="0 0 20 20" fill="none" stroke="currentColor" strokeWidth="2"><circle cx="9" cy="9" r="6"/><path d="M14 14l4 4"/></svg>
              <span className="kr" style={{ fontSize: 12, color: 'var(--wu-mute)' }}>SKU · 품명 검색</span>
            </div>
            <button className="wu-btn" style={{ fontSize: 11, padding: '8px 14px' }}>↓ 공급가표 다운로드</button>
          </div>
        </div>
        <div style={{ display: 'flex', gap: 6, marginTop: 14, flexWrap: 'wrap' }}>
          {['전체 296', '신상 18', '자켓 42', '팬츠 58', '셔츠 74', '부츠 22', '액세서리 82', '재고 부족 7'].map((f, i) => (
            <WuChip key={f} active={i === 0}>{f}</WuChip>
          ))}
        </div>
      </div>

      {/* Catalog table */}
      <div className="wu-scroll" style={{ flex: 1, overflow: 'auto', padding: 28 }}>
        <div style={{ background: 'var(--wu-paper)', border: '1px solid var(--wu-line)' }}>
          <div style={{ display: 'grid', gridTemplateColumns: '56px 2fr 1fr 1fr 1fr 1fr 90px', padding: '10px 16px', background: '#EFEBE2', borderBottom: '1px solid var(--wu-line)' }}>
            {['', 'SKU · 품명', '소매가', '공급가', '마진', '재고 상태', '주문'].map(h => (
              <div key={h} className="mono" style={{ fontSize: 9, color: 'var(--wu-mute)', letterSpacing: '0.08em', fontWeight: 700 }}>{h.toUpperCase()}</div>
            ))}
          </div>
          {WU_DATA.newDrops.map((p, i) => {
            const margin = Math.round(((p.retail - p.wholesale) / p.retail) * 100);
            return (
              <div key={p.id} style={{ display: 'grid', gridTemplateColumns: '56px 2fr 1fr 1fr 1fr 1fr 90px', padding: '12px 16px', borderBottom: i < WU_DATA.newDrops.length - 1 ? '1px solid var(--wu-line)' : 'none', alignItems: 'center' }}>
                <div style={{ width: 40, height: 40 }}><WuPhoto label="" ratio="1/1" tint={p.colors[0]} /></div>
                <div>
                  <div className="kr" style={{ fontSize: 13, fontWeight: 700 }}>{p.kr} {p.tag && <span className="wu-tag" style={{ marginLeft: 6, background: p.tag === 'NEW' ? 'var(--wu-lime)' : 'var(--wu-ink)', color: p.tag === 'NEW' ? 'var(--wu-ink)' : '#fff', fontSize: 9 }}>{p.tag}</span>}</div>
                  <div className="mono" style={{ fontSize: 10, color: 'var(--wu-mute)', marginTop: 2 }}>{p.code}</div>
                </div>
                <div className="mono" style={{ fontSize: 13, color: 'var(--wu-mute)' }}>{wuPrice(p.retail)}</div>
                <div className="mono display" style={{ fontSize: 15 }}>{wuPrice(p.wholesale)}</div>
                <div className="mono" style={{ fontSize: 12, color: 'var(--wu-ink)', fontWeight: 700 }}>{margin}%</div>
                <div>
                  <span style={{ fontFamily: 'JetBrains Mono', fontSize: 10, fontWeight: 700, padding: '3px 7px', background: p.stock === 'LOW' ? 'var(--wu-orange)' : p.stock === 'NEW' ? 'var(--wu-lime)' : p.stock === 'RESTOCK' ? 'var(--wu-ink)' : '#E3DFD6', color: p.stock === 'LOW' || p.stock === 'RESTOCK' ? '#fff' : 'var(--wu-ink)' }}>
                    {p.stock}
                  </span>
                </div>
                <button className="wu-btn" style={{ fontSize: 10, padding: '6px 10px' }}>담기 +</button>
              </div>
            );
          })}
        </div>

        {/* Price update banner */}
        <div style={{ marginTop: 20, background: 'var(--wu-lime)', padding: '14px 16px', display: 'flex', alignItems: 'center', gap: 14 }}>
          <div style={{ width: 32, height: 32, borderRadius: 999, background: 'var(--wu-ink)', color: 'var(--wu-lime)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <svg width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="currentColor" strokeWidth="2"><path d="M1 7l3 3 9-9"/></svg>
          </div>
          <div style={{ flex: 1 }}>
            <div className="kr" style={{ fontSize: 13, fontWeight: 700 }}>겨울 자켓 공급가가 오늘부터 -12% 인하되었어요.</div>
            <div className="kr mono" style={{ fontSize: 10, color: 'var(--wu-ink)', opacity: 0.6, marginTop: 2 }}>적용: 11.15 00:00 – 11.22 23:59 · 최소 발주 20pcs</div>
          </div>
          <button style={{ padding: '8px 14px', fontSize: 11, fontWeight: 700, fontFamily: 'Archivo', background: 'var(--wu-ink)', color: 'var(--wu-lime)', borderRadius: 999, textTransform: 'uppercase' }}>자세히 →</button>
        </div>
      </div>
    </div>
  );
}

// ────────────────────────────────────────────────────
// OWNER MESSAGES
// ────────────────────────────────────────────────────
function OwnerMessages() {
  const msgs = [
    { id: 1, type: 'HQ', sender: 'HQ', subject: 'Winter jacket price update', preview: 'Price reduced by 12%', time: '14:22', unread: true },
    { id: 2, type: 'HQ', sender: 'HQ MD', subject: 'Spring 2026 lineup', preview: 'New catalog available', time: '11:05', unread: true },
    { id: 3, type: 'PEER', sender: 'Store A', subject: 'Tent stock inquiry', preview: 'Do you have 3p tents?', time: 'Yesterday', unread: false },
    { id: 4, type: 'PEER', sender: 'Store B', subject: 'Weekly sales share', preview: 'Sharing this week results', time: '04.18', unread: false },
  ];
  return (
    <div className="wu" style={{ height: '100%', background: 'var(--wu-bg)', display: 'flex' }}>
      <div style={{ width: 300, background: 'var(--wu-paper)', borderRight: '1px solid var(--wu-line)', display: 'flex', flexDirection: 'column', flexShrink: 0 }}>
        <div style={{ padding: '20px 18px 12px' }}>
          <div className="mono" style={{ fontSize: 10, color: 'var(--wu-mute)' }}>PARTNER / MESSAGES</div>
          <div className="display" style={{ fontSize: 24, marginTop: 2 }}>MESSAGES</div>
        </div>
        <div style={{ flex: 1, overflow: 'auto' }} className="wu-scroll">
          {msgs.map((m, i) => (
            <div key={m.id} style={{ padding: '14px 18px', borderTop: '1px solid var(--wu-line)', background: i === 0 ? 'var(--wu-bg)' : 'transparent', cursor: 'pointer' }}>
              <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                  <span style={{ background: m.type === 'HQ' ? 'var(--wu-ink)' : 'var(--wu-orange)', color: '#fff', padding: '2px 6px', fontSize: 9, fontFamily: 'JetBrains Mono', fontWeight: 700 }}>{m.type}</span>
                  {m.unread && <div style={{ width: 6, height: 6, borderRadius: 999, background: 'var(--wu-orange)' }} />}
                </div>
                <span className="mono" style={{ fontSize: 9, color: 'var(--wu-mute)' }}>{m.time}</span>
              </div>
              <div className="kr" style={{ fontSize: 12, fontWeight: m.unread ? 800 : 600, marginTop: 6 }}>{m.subject}</div>
              <div className="kr" style={{ fontSize: 11, color: 'var(--wu-mute)', marginTop: 4 }}>{m.preview}</div>
            </div>
          ))}
        </div>
      </div>
      <div style={{ flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
        <div style={{ textAlign: 'center' }}>
          <div style={{ fontSize: 48, marginBottom: 12 }}>✉</div>
          <div className="kr" style={{ fontSize: 14, color: 'var(--wu-mute)' }}>Select a message</div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { OwnerDashboard, OwnerCatalog, OwnerMessages, OwnerProductList });
