// === Product detail viewer ===
function ProductDetail({ productId, products, setProducts, onClose }) {
  const product = products.find(p => p.id === productId);
  if (!product) return null;
  const cat = window.MOCK.CATEGORIES.find(c => c.id === product.category);
  const [tab, setTab] = useState("overview");
  const margin = ((product.price - product.costPrice) / product.price * 100).toFixed(1);

  const update = (patch) => setProducts(prev => prev.map(p => p.id === product.id ? { ...p, ...patch } : p));

  return (
    <Modal open={true} onClose={onClose} size="xl" title={
      <div className="row gap-3">
        <span style={{ fontSize: 11, color: "var(--text-subtle)", fontFamily: "monospace" }}>{product.sku}</span>
        <span>{product.name}</span>
      </div>
    } footer={
      <>
        <a className="btn btn-ghost" target="_blank" rel="noreferrer" href="https://smartstore.naver.com">
          <window.I.ExternalLink size={14} /> 스마트스토어에서 보기
        </a>
        <div className="right" />
        <button className="btn" onClick={onClose}>닫기</button>
        <button className="btn btn-primary" onClick={() => { toast("저장되었습니다"); onClose(); }}>
          <window.I.Check size={14} /> 변경사항 저장
        </button>
      </>
    }>
      <div style={{ display: "grid", gridTemplateColumns: "320px 1fr", gap: 24 }} className="dash-grid">
        {/* Left: gallery */}
        <div>
          <div style={{ position: "relative" }}>
            <ProductThumb tone={product.tone} name={product.name} size={320} radius={10} />
            <span className="badge badge-success" style={{ position: "absolute", top: 12, left: 12 }}>
              <StatusBadge status={product.status} />
            </span>
          </div>
          <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 6, marginTop: 8 }}>
            {[0, 1, 2, 3].map(i => (
              <ProductThumb key={i} tone={(product.tone + i) % window.MOCK.TONES.length} name={product.name} size={72} />
            ))}
          </div>
          <div className="card" style={{ marginTop: 16 }}>
            <div className="card-body" style={{ padding: 14 }}>
              <div className="text-xs muted">현재 판매가</div>
              <div style={{ fontSize: 22, fontWeight: 700, marginTop: 2 }} className="tabular">{formatKRW(product.price)}</div>
              <div className="row gap-3" style={{ marginTop: 6 }}>
                <span className="text-xs muted">원가 <strong className="tabular" style={{ color: "var(--text)" }}>{formatKRW(product.costPrice)}</strong></span>
                <span className="text-xs">·</span>
                <span className="text-xs muted">마진율 <strong style={{ color: "var(--accent)" }}>{margin}%</strong></span>
              </div>
              <div className="divider" style={{ margin: "12px 0" }} />
              <div className="row gap-3" style={{ alignItems: "flex-start" }}>
                <div style={{ flex: 1 }}>
                  <div className="text-xs muted">평점</div>
                  <div className="row gap-2" style={{ marginTop: 2 }}>
                    <window.I.Star size={14} fill="#f59e0b" stroke="#f59e0b" />
                    <strong>{product.rating}</strong>
                    <span className="text-xs muted">({formatNum(product.reviews)})</span>
                  </div>
                </div>
                <div style={{ flex: 1 }}>
                  <div className="text-xs muted">조회수 (30일)</div>
                  <div style={{ marginTop: 2, fontWeight: 600 }}>{formatNum(product.views30d)}</div>
                </div>
              </div>
            </div>
          </div>
        </div>

        {/* Right: details */}
        <div>
          <div className="row gap-2" style={{ marginBottom: 12, fontSize: 12 }}>
            <span className="badge">{cat?.icon} {cat?.name}</span>
            <span className="badge">{product.brand}</span>
          </div>

          <div className="seg" style={{ marginBottom: 16 }}>
            {[
              ["overview", "기본정보"],
              ["pricing", "가격/재고"],
              ["desc", "상세설명"],
              ["sales", "판매통계"],
            ].map(([k, l]) => (
              <button key={k} className={"seg-btn " + (tab === k ? "active" : "")} onClick={() => setTab(k)}>{l}</button>
            ))}
          </div>

          {tab === "overview" && (
            <div className="flex-col gap-4">
              <Field label="상품명">
                <input className="input" value={product.name} onChange={e => update({ name: e.target.value })} />
              </Field>
              <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
                <Field label="카테고리">
                  <select className="select" value={product.category} onChange={e => update({ category: e.target.value })}>
                    {window.MOCK.CATEGORIES.map(c => <option key={c.id} value={c.id}>{c.name}</option>)}
                  </select>
                </Field>
                <Field label="브랜드">
                  <input className="input" value={product.brand} onChange={e => update({ brand: e.target.value })} />
                </Field>
              </div>
              <Field label="SKU">
                <input className="input font-mono" value={product.sku} onChange={e => update({ sku: e.target.value })} />
              </Field>
              <Field label="상품 상태">
                <div className="seg">
                  <button className={"seg-btn " + (product.status === "active" ? "active" : "")} onClick={() => update({ status: "active" })}>판매중</button>
                  <button className={"seg-btn " + (product.status === "paused" ? "active" : "")} onClick={() => update({ status: "paused" })}>판매중지</button>
                  <button className={"seg-btn " + (product.status === "outofstock" ? "active" : "")} onClick={() => update({ status: "outofstock" })}>품절</button>
                </div>
              </Field>
            </div>
          )}

          {tab === "pricing" && (
            <div className="flex-col gap-4">
              <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
                <Field label="판매가 (₩)">
                  <input className="input tabular" type="text" value={formatNum(product.price)}
                         onChange={e => update({ price: parseInt(e.target.value.replace(/[^0-9]/g, "")) || 0 })} />
                </Field>
                <Field label="원가 (₩)">
                  <input className="input tabular" type="text" value={formatNum(product.costPrice)}
                         onChange={e => update({ costPrice: parseInt(e.target.value.replace(/[^0-9]/g, "")) || 0 })} />
                </Field>
              </div>
              <div className="card" style={{ background: "var(--bg-elev)" }}>
                <div className="card-body" style={{ padding: 14 }}>
                  <div className="row" style={{ justifyContent: "space-between" }}>
                    <span className="text-sm muted">개당 마진</span>
                    <strong className="tabular">{formatKRW(product.price - product.costPrice)} ({margin}%)</strong>
                  </div>
                  <div className="row" style={{ justifyContent: "space-between", marginTop: 6 }}>
                    <span className="text-sm muted">30일 예상 매출</span>
                    <strong className="tabular">{formatKRW(product.price * product.sales30d)}</strong>
                  </div>
                </div>
              </div>
              <Field label="재고 수량">
                <input className="input tabular" type="number" value={product.stock}
                       onChange={e => update({ stock: parseInt(e.target.value) || 0 })} />
              </Field>
            </div>
          )}

          {tab === "desc" && (
            <Field label="상품 상세 설명">
              <textarea className="input textarea" rows={10} value={product.desc} onChange={e => update({ desc: e.target.value })} />
            </Field>
          )}

          {tab === "sales" && (
            <div className="flex-col gap-4">
              <div className="stat-grid" style={{ gridTemplateColumns: "1fr 1fr 1fr" }}>
                <div className="stat-tile">
                  <div className="stat-label">30일 판매량</div>
                  <div className="stat-value">{product.sales30d}<span style={{ fontSize: 14, fontWeight: 500, marginLeft: 4 }}>건</span></div>
                </div>
                <div className="stat-tile">
                  <div className="stat-label">30일 매출</div>
                  <div className="stat-value" style={{ fontSize: 18 }}>{formatKRW(product.price * product.sales30d)}</div>
                </div>
                <div className="stat-tile">
                  <div className="stat-label">전환율</div>
                  <div className="stat-value">{(product.sales30d / product.views30d * 100).toFixed(1)}<span style={{ fontSize: 14, fontWeight: 500 }}>%</span></div>
                </div>
              </div>
              <div className="card">
                <div className="card-header"><div className="card-title">최근 14일 판매 추이</div></div>
                <div className="card-body" style={{ padding: 16 }}>
                  <MiniSpark data={Array.from({ length: 14 }, () => Math.round(product.sales30d / 30 * (0.7 + Math.random() * 0.6)))} height={80} />
                </div>
              </div>
            </div>
          )}
        </div>
      </div>
    </Modal>
  );
}

function Field({ label, children }) {
  return (
    <div>
      <div className="text-xs muted" style={{ marginBottom: 6, fontWeight: 500 }}>{label}</div>
      {children}
    </div>
  );
}

window.ProductDetail = ProductDetail;
