// Product Manager — admin creates products with up to 8 images, detailed description, dual pricing
// Consumer sees retail only, Owner sees both retail + wholesale
// getManagedProducts, saveManagedProduct, deleteManagedProduct are defined in firebase-init.jsx (Firestore)

// ═══════════════════════════════════════════════════════════
// ADMIN: Product Editor — create/edit with 8 images + description + dual price
// ═══════════════════════════════════════════════════════════
function ProductEditor({ product, onSave, onCancel }) {
  const empty = { id: '', brand: '', name_kr: '', code: '', retail: '', wholesale: '', sizes: '', colors_kr: '', season: '', parts: '', description: '', features: '', images: [] };
  const [form, setForm] = React.useState(product || empty);
  const [err, setErr] = React.useState('');

  const f = (k, v) => setForm(prev => ({ ...prev, [k]: v }));

  const handleImages = async (e) => {
    const files = Array.from(e.target.files);
    const current = form.images || [];
    if (current.length + files.length > 8) { setErr('이미지는 최대 8장까지 가능합니다'); return; }
    setErr('');
    const newImgs = [];
    for (const file of files) {
      const b64 = await fileToBase64(file);
      newImgs.push({ data: b64, name: file.name });
    }
    f('images', [...current, ...newImgs]);
    e.target.value = '';
  };

  const removeImage = (idx) => {
    f('images', form.images.filter((_, i) => i !== idx));
  };

  const moveImage = (idx, dir) => {
    const imgs = [...form.images];
    const target = idx + dir;
    if (target < 0 || target >= imgs.length) return;
    [imgs[idx], imgs[target]] = [imgs[target], imgs[idx]];
    f('images', imgs);
  };

  const submit = () => {
    if (!form.name_kr || !form.retail) { setErr('상품명과 판매가는 필수입니다'); return; }
    const p = {
      ...form,
      id: form.id || 'P-' + Date.now(),
      retail: Number(form.retail) || 0,
      wholesale: Number(form.wholesale) || 0,
      createdAt: form.createdAt || new Date().toISOString(),
      updatedAt: new Date().toISOString(),
    };
    onSave(p);
  };

  return (
    <div style={{ padding: 28 }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
        <div>
          <div className="mono" style={{ fontSize: 10, color: 'var(--wu-mute)' }}>PRODUCT EDITOR</div>
          <div className="display" style={{ fontSize: 28, marginTop: 2 }}>{product ? '상품 수정' : '신규 상품 등록'}</div>
        </div>
        <div style={{ display: 'flex', gap: 6 }}>
          <button onClick={onCancel} className="wu-btn ghost" style={{ fontSize: 11, padding: '8px 14px' }}>취소</button>
          <button onClick={submit} className="wu-btn lime" style={{ fontSize: 11, padding: '8px 14px' }}>💾 저장</button>
        </div>
      </div>
      {err && <div className="kr" style={{ fontSize: 12, color: 'var(--wu-orange)', marginTop: 8 }}>⚠ {err}</div>}

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 20, marginTop: 20 }}>
        {/* Left: form fields */}
        <div>
          <div className="display" style={{ fontSize: 16, marginBottom: 12 }}>기본 정보</div>
          {[
            ['상품명 *', 'name_kr', 'text', '매드독 쿨링 팬 반팔'],
            ['브랜드', 'brand', 'text', 'MADDOG'],
            ['SKU 코드', 'code', 'text', 'MD6MUAWT111'],
          ].map(([l, k, t, ph]) => (
            <div key={k} style={{ marginBottom: 12 }}>
              <div className="mono" style={{ fontSize: 10, color: 'var(--wu-mute)', marginBottom: 4 }}>{l}</div>
              <input value={form[k]} onChange={e => f(k, e.target.value)} type={t} placeholder={ph} className="kr"
                style={{ width: '100%', padding: '10px 12px', border: '1px solid var(--wu-line)', background: 'var(--wu-bg)', fontSize: 14, fontWeight: 600, outline: 0 }} />
            </div>
          ))}

          <div className="display" style={{ fontSize: 16, marginTop: 20, marginBottom: 12 }}>가격 정보</div>
          <div style={{ padding: 14, background: 'var(--wu-ink)', color: 'var(--wu-paper)', marginBottom: 16 }}>
            <div className="mono" style={{ fontSize: 9, color: 'var(--wu-lime)' }}>💡 점주는 공급가+판매가 모두, 일반회원은 판매가만 표시됩니다</div>
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
            <div>
              <div className="mono" style={{ fontSize: 10, color: 'var(--wu-mute)', marginBottom: 4 }}>👁 판매가 * (원)</div>
              <input value={form.retail} onChange={e => f('retail', e.target.value)} type="number" placeholder="53800" className="mono"
                style={{ width: '100%', padding: '10px 12px', border: '1px solid var(--wu-line)', background: 'var(--wu-bg)', fontSize: 16, fontWeight: 700, outline: 0 }} />
            </div>
            <div>
              <div className="mono" style={{ fontSize: 10, color: 'var(--wu-mute)', marginBottom: 4 }}>🔒 공급가 (원) · 점주전용</div>
              <input value={form.wholesale} onChange={e => f('wholesale', e.target.value)} type="number" placeholder="36500" className="mono"
                style={{ width: '100%', padding: '10px 12px', border: '1px solid var(--wu-lime)', background: 'rgba(214,255,61,0.08)', fontSize: 16, fontWeight: 700, outline: 0 }} />
            </div>
          </div>
          {form.retail && form.wholesale && Number(form.retail) > 0 && (
            <div className="mono" style={{ fontSize: 11, color: 'var(--wu-mute)', marginTop: 6 }}>
              마진 {Math.round(((Number(form.retail) - Number(form.wholesale)) / Number(form.retail)) * 100)}% · ₩{(Number(form.retail) - Number(form.wholesale)).toLocaleString()}
            </div>
          )}

          <div className="display" style={{ fontSize: 16, marginTop: 20, marginBottom: 12 }}>옵션 정보</div>
          {[
            ['사이즈', 'sizes', 'M-L, XL-2XL, 3XL-4XL'],
            ['색상', 'colors_kr', '블랙, 네이비'],
            ['시즌', 'season', '26SS / 봄·여름'],
            ['부위', 'parts', '상의 / 아우터'],
          ].map(([l, k, ph]) => (
            <div key={k} style={{ marginBottom: 10 }}>
              <div className="mono" style={{ fontSize: 10, color: 'var(--wu-mute)', marginBottom: 4 }}>{l}</div>
              <input value={form[k]} onChange={e => f(k, e.target.value)} placeholder={ph} className="kr"
                style={{ width: '100%', padding: '8px 12px', border: '1px solid var(--wu-line)', background: 'var(--wu-bg)', fontSize: 13, outline: 0 }} />
            </div>
          ))}
        </div>

        {/* Right: images + description */}
        <div>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 12 }}>
            <div className="display" style={{ fontSize: 16 }}>상품 이미지 ({(form.images || []).length}/8)</div>
            <label className="wu-btn" style={{ fontSize: 11, padding: '6px 12px', cursor: 'pointer' }}>
              📷 추가
              <input type="file" accept="image/*" multiple onChange={handleImages} style={{ display: 'none' }} />
            </label>
          </div>

          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 6, marginBottom: 16 }}>
            {(form.images || []).map((img, i) => (
              <div key={i} style={{ position: 'relative', aspectRatio: '1/1', background: 'var(--wu-bg)', border: '1px solid var(--wu-line)', overflow: 'hidden' }}>
                <img src={img.data} style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
                {i === 0 && <span className="mono" style={{ position: 'absolute', top: 4, left: 4, fontSize: 8, padding: '2px 4px', background: 'var(--wu-lime)', color: 'var(--wu-ink)', fontWeight: 700 }}>대표</span>}
                <div style={{ position: 'absolute', bottom: 2, right: 2, display: 'flex', gap: 2 }}>
                  {i > 0 && <button onClick={() => moveImage(i, -1)} style={{ width: 20, height: 20, background: 'rgba(0,0,0,0.7)', color: '#fff', border: 0, fontSize: 10, cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>←</button>}
                  {i < (form.images || []).length - 1 && <button onClick={() => moveImage(i, 1)} style={{ width: 20, height: 20, background: 'rgba(0,0,0,0.7)', color: '#fff', border: 0, fontSize: 10, cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>→</button>}
                  <button onClick={() => removeImage(i)} style={{ width: 20, height: 20, background: 'rgba(200,0,0,0.8)', color: '#fff', border: 0, fontSize: 10, cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>✕</button>
                </div>
              </div>
            ))}
            {(form.images || []).length < 8 && (
              <label style={{ aspectRatio: '1/1', border: '2px dashed var(--wu-line)', display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer', flexDirection: 'column', gap: 4 }}>
                <span style={{ fontSize: 24, opacity: 0.4 }}>+</span>
                <span className="mono" style={{ fontSize: 9, color: 'var(--wu-mute)' }}>추가</span>
                <input type="file" accept="image/*" multiple onChange={handleImages} style={{ display: 'none' }} />
              </label>
            )}
          </div>

          <div className="display" style={{ fontSize: 16, marginBottom: 8 }}>상세 설명</div>
          <textarea value={form.description} onChange={e => f('description', e.target.value)}
            placeholder="상품에 대한 상세 설명을 입력하세요.&#10;&#10;예: 2025년 대히트 쿨링팬 베스트의 반팔 버전으로, 한층 더 시원해진 2026년형 쿨링 팬 셔츠."
            className="kr" rows={6}
            style={{ width: '100%', padding: 12, border: '1px solid var(--wu-line)', background: 'var(--wu-bg)', fontSize: 13, fontFamily: 'Pretendard', lineHeight: 1.6, resize: 'vertical', outline: 0 }} />

          <div className="display" style={{ fontSize: 16, marginTop: 16, marginBottom: 8 }}>주요 특징 (줄바꿈으로 구분)</div>
          <textarea value={form.features} onChange={e => f('features', e.target.value)}
            placeholder="반팔 구조로 팔까지 전달되는 강력한 쿨링 효과&#10;4중 배출 시스템으로 열기와 습기 빠른 배출&#10;5포켓 구성으로 뛰어난 수납력"
            className="kr" rows={4}
            style={{ width: '100%', padding: 12, border: '1px solid var(--wu-line)', background: 'var(--wu-bg)', fontSize: 13, fontFamily: 'Pretendard', lineHeight: 1.6, resize: 'vertical', outline: 0 }} />
        </div>
      </div>
    </div>
  );
}

// ═══════════════════════════════════════════════════════════
// ADMIN: Product List + Manager
// ═══════════════════════════════════════════════════════════
function AdminProductManager({ onBack }) {
  const [products, setProducts] = React.useState([]);
  const [editing, setEditing] = React.useState(null); // null=list, 'new'=create, product=edit
  const [msg, setMsg] = React.useState(null);

  const load = async () => { const p = await getManagedProducts(); setProducts(p); };
  React.useEffect(() => { load(); }, []);

  const flash = (t) => { setMsg(t); setTimeout(() => setMsg(null), 2500); };

  const handleSave = async (p) => {
    await saveManagedProduct(p);
    await load();
    setEditing(null);
    flash('상품 저장 완료');
  };

  const handleDelete = async (id) => {
    await deleteManagedProduct(id);
    await load();
    flash('상품 삭제됨');
  };

  if (editing !== null) {
    return <ProductEditor product={editing === 'new' ? null : editing} onSave={handleSave} onCancel={() => setEditing(null)} />;
  }

  return (
    <div style={{ padding: 28 }}>
      {msg && <div style={{ position: 'fixed', top: 16, right: 16, zIndex: 999, padding: '10px 18px', background: 'var(--wu-lime)', color: 'var(--wu-ink)', fontFamily: 'Pretendard', fontSize: 13, fontWeight: 700, boxShadow: '0 8px 24px rgba(0,0,0,0.2)' }}>{msg}</div>}

      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end' }}>
        <div>
          <div className="mono" style={{ fontSize: 10, color: 'var(--wu-mute)' }}>ADMIN · PRODUCT MANAGER</div>
          <div className="display" style={{ fontSize: 28, marginTop: 2 }}>상품 관리</div>
          <div className="kr" style={{ fontSize: 12, color: 'var(--wu-mute)', marginTop: 4 }}>이미지 8장 · 상세설명 · 공급가/판매가 등록</div>
        </div>
        <button onClick={() => setEditing('new')} className="wu-btn lime" style={{ fontSize: 12, padding: '10px 18px' }}>+ 신규 상품 등록</button>
      </div>

      {products.length > 0 ? (
        <div style={{ marginTop: 20, display: 'grid', gap: 12 }}>
          {products.map(p => (
            <div key={p.id} style={{ background: 'var(--wu-paper)', border: '1px solid var(--wu-line)', display: 'flex', overflow: 'hidden' }}>
              {/* Thumbnail */}
              <div style={{ width: 120, height: 120, flexShrink: 0, background: 'var(--wu-bg)' }}>
                {p.images && p.images[0] ? (
                  <img src={p.images[0].data} style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
                ) : (
                  <div className="wu-placeholder" style={{ width: '100%', height: '100%' }}><span className="label">NO IMG</span></div>
                )}
              </div>
              <div style={{ flex: 1, padding: '12px 16px', display: 'flex', alignItems: 'center', gap: 20 }}>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                    <span className="mono" style={{ fontSize: 9, padding: '2px 6px', background: 'var(--wu-ink)', color: 'var(--wu-lime)', fontWeight: 700 }}>{p.brand || '—'}</span>
                    {p.season && <span className="mono" style={{ fontSize: 9, padding: '2px 6px', background: 'var(--wu-bg)', border: '1px solid var(--wu-line)' }}>{p.season}</span>}
                    <span className="mono" style={{ fontSize: 9, color: 'var(--wu-mute)' }}>📷 {(p.images || []).length}/8</span>
                  </div>
                  <div className="kr" style={{ fontSize: 15, fontWeight: 700, marginTop: 6 }}>{p.name_kr}</div>
                  <div className="mono" style={{ fontSize: 10, color: 'var(--wu-mute)', marginTop: 2 }}>{p.code || 'SKU 없음'}</div>
                </div>
                <div style={{ textAlign: 'right', flexShrink: 0 }}>
                  <div className="mono" style={{ fontSize: 10, color: 'var(--wu-mute)' }}>👁 판매가</div>
                  <div className="display" style={{ fontSize: 18 }}>₩{(p.retail || 0).toLocaleString()}</div>
                  {p.wholesale > 0 && (
                    <>
                      <div className="mono" style={{ fontSize: 10, color: 'var(--wu-lime)', marginTop: 4 }}>🔒 공급가</div>
                      <div className="mono" style={{ fontSize: 14, fontWeight: 700, color: 'var(--wu-ink)' }}>₩{p.wholesale.toLocaleString()}</div>
                    </>
                  )}
                </div>
                <div style={{ display: 'flex', flexDirection: 'column', gap: 4, flexShrink: 0 }}>
                  <button onClick={() => setEditing(p)} className="wu-btn" style={{ fontSize: 10, padding: '6px 10px' }}>✏ 수정</button>
                  <button onClick={() => handleDelete(p.id)} style={{ padding: '6px 10px', fontSize: 10, fontWeight: 700, fontFamily: 'Archivo', background: 'var(--wu-bg)', border: '1px solid #C44', color: '#C44', cursor: 'pointer', borderRadius: 999 }}>🗑 삭제</button>
                </div>
              </div>
            </div>
          ))}
        </div>
      ) : (
        <div style={{ marginTop: 20, padding: '60px 20px', background: 'var(--wu-paper)', border: '2px dashed var(--wu-line)', textAlign: 'center' }}>
          <div style={{ fontSize: 40, marginBottom: 12 }}>📦</div>
          <div className="display" style={{ fontSize: 18, color: 'var(--wu-mute)' }}>등록된 상품이 없습니다</div>
          <div className="kr" style={{ fontSize: 12, color: 'var(--wu-mute)', marginTop: 6 }}>"+ 신규 상품 등록" 버튼으로 시작하세요</div>
        </div>
      )}
    </div>
  );
}

// ═══════════════════════════════════════════════════════════
// CONSUMER / OWNER: Product Detail View (role-aware pricing)
// ═══════════════════════════════════════════════════════════
function ProductDetailView({ product, userRole, onBack }) {
  const [imgIdx, setImgIdx] = React.useState(0);
  const imgs = product.images || [];
  const features = (product.features || '').split('\n').filter(Boolean);

  return (
    <div className="wu wu-scroll" style={{ height: '100%', overflow: 'auto', background: 'var(--wu-bg)', paddingBottom: 100 }}>
      <div style={{ padding: 'calc(env(safe-area-inset-top, 20px) + 12px) 16px 8px', display: 'flex', justifyContent: 'space-between' }}>
        <button onClick={onBack} style={{ fontSize: 18, cursor: 'pointer' }}>←</button>
        <div style={{ display: 'flex', gap: 6 }}>
          <button style={{ width: 32, height: 32, borderRadius: 999, background: '#fff', border: '1px solid var(--wu-line)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>♡</button>
          <button style={{ width: 32, height: 32, borderRadius: 999, background: '#fff', border: '1px solid var(--wu-line)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>↗</button>
        </div>
      </div>

      {/* Main image */}
      <div style={{ margin: '8px 16px', position: 'relative', background: 'var(--wu-bg)' }}>
        {imgs.length > 0 ? (
          <img src={imgs[imgIdx].data} style={{ width: '100%', aspectRatio: '4/5', objectFit: 'cover', display: 'block' }} />
        ) : (
          <div className="wu-placeholder" style={{ width: '100%', aspectRatio: '4/5' }}><span className="label">NO IMAGE</span></div>
        )}
        {imgs.length > 1 && (
          <div style={{ position: 'absolute', bottom: 10, left: '50%', transform: 'translateX(-50%)', display: 'flex', gap: 4 }}>
            {imgs.map((_, i) => <button key={i} onClick={() => setImgIdx(i)} style={{ width: 6, height: 6, borderRadius: 999, background: i === imgIdx ? 'var(--wu-ink)' : 'rgba(0,0,0,0.2)', border: 0, cursor: 'pointer', padding: 0 }} />)}
          </div>
        )}
      </div>

      {/* Thumbnails */}
      {imgs.length > 1 && (
        <div className="wu-scroll" style={{ display: 'flex', gap: 6, padding: '0 16px', overflowX: 'auto', marginBottom: 16 }}>
          {imgs.map((img, i) => (
            <button key={i} onClick={() => setImgIdx(i)} style={{ width: 56, height: 56, flexShrink: 0, border: i === imgIdx ? '2px solid var(--wu-ink)' : '1px solid var(--wu-line)', padding: 0, cursor: 'pointer', overflow: 'hidden' }}>
              <img src={img.data} style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
            </button>
          ))}
        </div>
      )}

      {/* Info */}
      <div style={{ padding: '0 16px' }}>
        <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
          {product.brand && <span className="mono" style={{ fontSize: 9, padding: '2px 6px', background: 'var(--wu-ink)', color: 'var(--wu-lime)', fontWeight: 700 }}>{product.brand}</span>}
          {product.season && <span className="mono" style={{ fontSize: 9, padding: '2px 6px', background: 'var(--wu-bg)', border: '1px solid var(--wu-line)' }}>{product.season}</span>}
        </div>
        <div className="kr" style={{ fontSize: 20, fontWeight: 700, marginTop: 10 }}>{product.name_kr}</div>
        {product.code && <div className="mono" style={{ fontSize: 11, color: 'var(--wu-mute)', marginTop: 4 }}>{product.code}</div>}

        {/* PRICING — role-aware */}
        <div style={{ marginTop: 16, padding: 16, background: userRole === 'owner' ? 'var(--wu-ink)' : 'var(--wu-paper)', color: userRole === 'owner' ? 'var(--wu-paper)' : 'var(--wu-ink)', border: '1px solid var(--wu-line)' }}>
          {userRole === 'owner' ? (
            <>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
                <div className="mono" style={{ fontSize: 10, color: 'var(--wu-lime)' }}>🔒 공급가 · WHOLESALE</div>
                <div className="display" style={{ fontSize: 24, color: 'var(--wu-lime)' }}>₩{(product.wholesale || 0).toLocaleString()}</div>
              </div>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginTop: 8 }}>
                <div className="mono" style={{ fontSize: 10, color: 'var(--wu-mute)' }}>👁 판매가 · RETAIL</div>
                <div className="mono" style={{ fontSize: 16, fontWeight: 700 }}>₩{(product.retail || 0).toLocaleString()}</div>
              </div>
              {product.wholesale > 0 && product.retail > 0 && (
                <div className="mono" style={{ fontSize: 10, color: 'var(--wu-mute)', marginTop: 8, paddingTop: 8, borderTop: '1px dashed #2A2A26' }}>
                  마진 {Math.round(((product.retail - product.wholesale) / product.retail) * 100)}% · ₩{(product.retail - product.wholesale).toLocaleString()}
                </div>
              )}
            </>
          ) : (
            <>
              <div className="mono" style={{ fontSize: 10, color: 'var(--wu-mute)' }}>판매가</div>
              <div className="display" style={{ fontSize: 28, marginTop: 2 }}>₩{(product.retail || 0).toLocaleString()}</div>
            </>
          )}
        </div>

        {/* Options */}
        {(product.sizes || product.colors_kr) && (
          <div style={{ marginTop: 16 }}>
            {product.sizes && (
              <div style={{ marginBottom: 10 }}>
                <div className="mono" style={{ fontSize: 10, color: 'var(--wu-mute)', marginBottom: 6 }}>사이즈</div>
                <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
                  {product.sizes.split(',').map(s => <span key={s} style={{ padding: '6px 12px', border: '1px solid var(--wu-ink)', fontSize: 12, fontFamily: 'JetBrains Mono', fontWeight: 600 }}>{s.trim()}</span>)}
                </div>
              </div>
            )}
            {product.colors_kr && (
              <div>
                <div className="mono" style={{ fontSize: 10, color: 'var(--wu-mute)', marginBottom: 6 }}>색상</div>
                <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
                  {product.colors_kr.split(',').map(c => <span key={c} className="kr" style={{ padding: '6px 12px', border: '1px solid var(--wu-line)', fontSize: 12, fontWeight: 600 }}>{c.trim()}</span>)}
                </div>
              </div>
            )}
          </div>
        )}

        {/* Description */}
        {product.description && (
          <div style={{ marginTop: 20 }}>
            <div className="display" style={{ fontSize: 14, marginBottom: 8 }}>상세 설명</div>
            <div className="kr" style={{ fontSize: 13, lineHeight: 1.8, color: 'var(--wu-ink)', whiteSpace: 'pre-wrap' }}>{product.description}</div>
          </div>
        )}

        {/* Features */}
        {features.length > 0 && (
          <div style={{ marginTop: 20 }}>
            <div className="display" style={{ fontSize: 14, marginBottom: 8 }}>주요 특징</div>
            {features.map((f, i) => (
              <div key={i} className="kr" style={{ display: 'flex', gap: 10, padding: '8px 0', borderBottom: '1px solid var(--wu-line)', fontSize: 13 }}>
                <span className="mono" style={{ color: 'var(--wu-lime)', fontSize: 10, marginTop: 2 }}>✔</span>
                <span>{f}</span>
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  );
}

// ═══════════════════════════════════════════════════════════
// CONSUMER/OWNER: Product List (browsing, role-aware)
// ═══════════════════════════════════════════════════════════
function ManagedProductList({ userRole, onSelect }) {
  const [products, setProducts] = React.useState([]);
  React.useEffect(() => { getManagedProducts().then(setProducts); }, []);

  if (products.length === 0) return null;

  return (
    <div style={{ padding: '0 16px', marginTop: 20 }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 12 }}>
        <div>
          <div className="display" style={{ fontSize: 18 }}>MANAGED PRODUCTS</div>
          <div className="kr mono" style={{ fontSize: 10, color: 'var(--wu-mute)' }}>관리자 등록 상품 · {products.length}건</div>
        </div>
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
        {products.map(p => (
          <button key={p.id} onClick={() => onSelect(p)} style={{ textAlign: 'left', cursor: 'pointer', background: 'none', padding: 0 }}>
            <div style={{ position: 'relative' }}>
              {p.images && p.images[0] ? (
                <img src={p.images[0].data} style={{ width: '100%', aspectRatio: '4/5', objectFit: 'cover', display: 'block' }} />
              ) : (
                <div className="wu-placeholder" style={{ width: '100%', aspectRatio: '4/5' }}><span className="label">{p.code || 'NEW'}</span></div>
              )}
              {p.brand && <span className="mono" style={{ position: 'absolute', top: 8, left: 8, fontSize: 9, padding: '2px 6px', background: 'var(--wu-ink)', color: 'var(--wu-lime)', fontWeight: 700 }}>{p.brand}</span>}
            </div>
            <div style={{ marginTop: 8 }}>
              <div className="kr" style={{ fontSize: 13, fontWeight: 700 }}>{p.name_kr}</div>
              <div className="display" style={{ fontSize: 14, marginTop: 4 }}>₩{(p.retail || 0).toLocaleString()}</div>
              {userRole === 'owner' && p.wholesale > 0 && (
                <div className="mono" style={{ fontSize: 10, color: 'var(--wu-lime)', marginTop: 2 }}>🔒 공급 ₩{p.wholesale.toLocaleString()}</div>
              )}
            </div>
          </button>
        ))}
      </div>
    </div>
  );
}

Object.assign(window, { ProductEditor, AdminProductManager, ProductDetailView, ManagedProductList });
