// === ISVM 검색 → 네이버 등록 (real API) ===
const { useState: useStateIS, useMemo: useMemoIS, useEffect: useEffectIS } = React;

function ISVMScreen({ products, setProducts, goto }) {
  const [keyword, setKeyword] = useStateIS("");
  const [sort, setSort] = useStateIS("sales");
  const [limit, setLimit] = useStateIS(20);
  const [results, setResults] = useStateIS([]);
  const [loading, setLoading] = useStateIS(false);
  const [error, setError] = useStateIS("");
  const [health, setHealth] = useStateIS(null);
  const [selected, setSelected] = useStateIS(new Set());
  const [registerForm, setRegisterForm] = useStateIS(null);
  const [naverPreview, setNaverPreview] = useStateIS(null);
  const [registered, setRegistered] = useStateIS(new Set());
  const [creds, setCreds] = useStateIS(window.API.loadCreds());

  useEffectIS(() => {
    window.API.isvmHealth().then(setHealth);
  }, []);

  const doSearch = async () => {
    if (!keyword.trim()) { window.toast("검색어를 입력하세요"); return; }
    setLoading(true); setError(""); setResults([]); setSelected(new Set());
    try {
      const data = await window.API.isvmSearch({ keyword: keyword.trim(), limit: parseInt(limit) || 20, sort });
      setResults(data);
      window.toast(`${data.length}개 상품 검색 완료`);
    } catch (e) {
      const isCors = String(e.message || e).includes("Failed to fetch") || String(e.message || e).includes("NetworkError");
      setError(isCors
        ? "ISVM 서버에 직접 연결할 수 없습니다 (CORS). 데모용 샘플 데이터를 표시합니다."
        : `검색 실패: ${e.message}`);
      // Fallback demo data so UI is testable from any origin
      setResults(generateDemoResults(keyword.trim()));
    } finally {
      setLoading(false);
    }
  };

  const toggleOne = (code) => {
    const s = new Set(selected);
    s.has(code) ? s.delete(code) : s.add(code);
    setSelected(s);
  };

  const openRegister = (item) => {
    setRegisterForm({
      product_code: item.product_code,
      name: item.name,
      brand: item.brand || "",
      purchase_price: item.purchase_price,
      // 권장 마진 60%
      sale_price: Math.round((item.purchase_price * 1.6) / 10) * 10,
      image_url: item.image_url,
      stock: 50,
      desc: `${item.name}\n\n공급사: ${item.brand || "-"} · ISVM 코드: ${item.product_code}`,
      leafCategoryId: "50000000",
      baseFee: 3000,
    });
  };

  const previewNaverPayload = () => {
    const p = window.API.buildNaverProductPayload({
      product_code: registerForm.product_code,
      name: registerForm.name,
      brand: registerForm.brand,
      desc: registerForm.desc,
      image_url: registerForm.image_url,
      salePrice: parseInt(registerForm.sale_price) || 0,
      stock: parseInt(registerForm.stock) || 0,
    }, {
      leafCategoryId: registerForm.leafCategoryId,
      baseFee: parseInt(registerForm.baseFee) || 3000,
    });
    setNaverPreview(p);
  };

  const submitRegister = async () => {
    // For real submission you must POST through your own backend proxy.
    // Here we simulate success and add to local product list.
    const newId = "P" + (10300 + products.length);
    const newProduct = {
      id: newId,
      name: registerForm.name,
      category: "fashion", // user can re-categorize after; or auto-map by leafCategoryId
      price: parseInt(registerForm.sale_price) || 0,
      costPrice: parseInt(registerForm.purchase_price) || 0,
      stock: parseInt(registerForm.stock) || 0,
      sales30d: 0, rating: 0, reviews: 0,
      status: "active", views30d: 0,
      sku: registerForm.product_code,
      brand: registerForm.brand || "ISVM",
      tone: parseInt(registerForm.product_code, 10) % 9 || 0,
      desc: registerForm.desc,
      image_url: registerForm.image_url,
    };
    setProducts(prev => [...prev, newProduct]);
    setRegistered(prev => new Set(prev).add(registerForm.product_code));
    setRegisterForm(null);
    setNaverPreview(null);
    window.toast(`'${newProduct.name.slice(0, 24)}…' 등록 (시뮬레이션)`);
  };

  const corsWarning = error && error.includes("CORS");

  return (
    <div className="page">
      <div className="page-header" style={{ display: "flex", alignItems: "flex-end", gap: 16 }}>
        <div style={{ flex: 1 }}>
          <h1 className="page-title">ISVM → 네이버 스마트스토어 연동</h1>
          <p className="page-desc">ISVM 도매 사이트에서 상품을 검색하고 네이버 스마트스토어에 등록합니다</p>
        </div>
        <button className="btn" onClick={() => goto("settings")}>
          <window.I.Settings size={14} /> API 설정
        </button>
      </div>

      {/* Connection bar */}
      <div className="card" style={{ marginBottom: 12 }}>
        <div className="card-body" style={{ padding: 14, display: "flex", alignItems: "center", gap: 16, flexWrap: "wrap" }}>
          <div className="row gap-3">
            <div style={{ width: 36, height: 36, borderRadius: 8, background: "linear-gradient(135deg, #6366f1, #8b5cf6)", color: "white", display: "flex", alignItems: "center", justifyContent: "center", fontWeight: 700 }}>IS</div>
            <div>
              <div style={{ fontWeight: 600, fontSize: 13 }}>ISVM Crawler API</div>
              <div className="text-xs muted">{window.API.ISVM_BASE}</div>
            </div>
            <span className={"badge badge-dot " + (health === true ? "badge-success" : health === false ? "badge-danger" : "")}>
              {health === true ? "연결됨" : health === false ? "연결 실패" : "확인 중..."}
            </span>
          </div>
          <window.I.ChevronRight size={20} className="muted" />
          <div className="row gap-3">
            <div style={{ width: 36, height: 36, borderRadius: 8, background: "var(--accent)", color: "white", display: "flex", alignItems: "center", justifyContent: "center", fontWeight: 800 }}>N</div>
            <div>
              <div style={{ fontWeight: 600, fontSize: 13 }}>네이버 커머스 API</div>
              <div className="text-xs muted">
                {creds.naver_client_id
                  ? `client_id: ${creds.naver_client_id.slice(0, 6)}••••••`
                  : "자격증명 미설정"}
              </div>
            </div>
            <span className={"badge badge-dot " + (creds.naver_client_id && creds.proxy_url ? "badge-success" : "badge-warn")}>
              {creds.naver_client_id && creds.proxy_url ? "프록시 연결" : "프록시 필요"}
            </span>
          </div>
        </div>
      </div>

      {/* Search bar */}
      <div className="toolbar">
        <div className="input-with-icon" style={{ flex: 1, maxWidth: 480 }}>
          <window.I.Search size={14} className="input-icon" />
          <input className="input" placeholder="ISVM 키워드 검색 (예: 동관터미널, 티셔츠)..."
                 value={keyword} onChange={e => setKeyword(e.target.value)}
                 onKeyDown={e => e.key === "Enter" && doSearch()} />
        </div>
        <div className="seg">
          <button className={"seg-btn " + (sort === "sales" ? "active" : "")} onClick={() => setSort("sales")}>판매량순</button>
          <button className={"seg-btn " + (sort === "relevance" ? "active" : "")} onClick={() => setSort("relevance")}>관련도순</button>
        </div>
        <select className="select" style={{ width: 90 }} value={limit} onChange={e => setLimit(e.target.value)}>
          {[10, 20, 50, 100].map(n => <option key={n} value={n}>{n}개</option>)}
        </select>
        <button className="btn btn-primary" onClick={doSearch} disabled={loading}>
          {loading ? "검색 중..." : <><window.I.Search size={14} /> 검색</>}
        </button>
      </div>

      {error && (
        <div style={{ padding: "10px 14px", borderRadius: 8, marginBottom: 12,
                      background: corsWarning ? "rgba(245, 158, 11, 0.1)" : "var(--danger-soft)",
                      border: `1px solid ${corsWarning ? "var(--warning)" : "var(--danger)"}`,
                      fontSize: 13 }}>
          <strong>{corsWarning ? "⚠️ CORS 차단" : "❌ 오류"}:</strong> {error}
          {corsWarning && (
            <div className="text-xs muted" style={{ marginTop: 4 }}>
              ISVM 서버에 이 도메인을 화이트리스트에 등록하거나, 자체 백엔드를 통해 프록시하세요.
            </div>
          )}
        </div>
      )}

      {results.length === 0 && !loading && !error && (
        <div className="card">
          <div className="empty">
            <window.I.Search size={32} className="empty-icon" />
            <div style={{ marginBottom: 4 }}>키워드를 입력하고 검색하세요</div>
            <div className="text-sm">ISVM 도매 사이트의 실시간 매입가/이미지가 조회됩니다</div>
          </div>
        </div>
      )}

      {results.length > 0 && (
        <>
          <div className="row gap-2 muted" style={{ marginBottom: 8, fontSize: 12 }}>
            <span>검색 결과 {results.length}개</span>
            <span>·</span>
            <span>선택: {selected.size}</span>
            {selected.size > 0 && (
              <button className="btn btn-sm right" onClick={() => setSelected(new Set())}>선택 해제</button>
            )}
          </div>
          <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(260px, 1fr))", gap: 12 }}>
            {results.map(item => {
              const isReg = registered.has(item.product_code) || products.some(p => p.sku === item.product_code);
              const margin = ((item.purchase_price * 1.6 - item.purchase_price) / (item.purchase_price * 1.6) * 100).toFixed(0);
              return (
                <div key={item.product_code} className="card" style={{ display: "flex", flexDirection: "column" }}>
                  <div style={{ position: "relative", aspectRatio: "1", background: "var(--bg-elev)" }}>
                    {item.image_url
                      ? <img src={item.image_url} alt="" style={{ width: "100%", height: "100%", objectFit: "cover" }}
                             onError={e => { e.target.style.display = "none"; }} />
                      : <ProductThumb tone={parseInt(item.product_code) % 9} name={item.name} size="100%" radius={0} />}
                    <span style={{ position: "absolute", top: 8, left: 8, background: "rgba(0,0,0,0.7)", color: "white", fontSize: 10, padding: "2px 6px", borderRadius: 4, fontFamily: "monospace" }}>
                      {item.product_code}
                    </span>
                    {isReg && (
                      <span style={{ position: "absolute", top: 8, right: 8 }} className="badge badge-success">
                        <window.I.Check size={11} /> 등록됨
                      </span>
                    )}
                  </div>
                  <div style={{ padding: 12, flex: 1, display: "flex", flexDirection: "column" }}>
                    <div style={{ fontSize: 13, fontWeight: 500, lineHeight: 1.4, marginBottom: 4 }}>{item.name}</div>
                    <div className="text-xs muted" style={{ marginBottom: 8 }}>{item.brand || "-"}</div>
                    <div style={{ flex: 1 }} />
                    <div className="row" style={{ justifyContent: "space-between", marginBottom: 8 }}>
                      <div>
                        <div className="text-xs muted">매입가</div>
                        <div className="tabular" style={{ fontWeight: 600 }}>{formatKRW(item.purchase_price)}</div>
                      </div>
                      <div style={{ textAlign: "right" }}>
                        <div className="text-xs muted">권장 판매가 (마진 {margin}%)</div>
                        <div className="tabular text-sm" style={{ color: "var(--accent)" }}>
                          {formatKRW(Math.round(item.purchase_price * 1.6 / 10) * 10)}
                        </div>
                      </div>
                    </div>
                    <button className={"btn " + (isReg ? "" : "btn-primary")} disabled={isReg} onClick={() => openRegister(item)}>
                      {isReg ? <><window.I.Check size={14} /> 이미 등록됨</> : <><window.I.Plus size={14} /> 네이버 등록</>}
                    </button>
                  </div>
                </div>
              );
            })}
          </div>
        </>
      )}

      {/* Register modal */}
      {registerForm && (
        <Modal open={true} onClose={() => { setRegisterForm(null); setNaverPreview(null); }} size="lg" title="네이버 스마트스토어 상품 등록"
               footer={<>
                 <button className="btn btn-ghost" onClick={previewNaverPayload}>
                   <window.I.Eye size={14} /> API 페이로드 미리보기
                 </button>
                 <div className="right" />
                 <button className="btn" onClick={() => { setRegisterForm(null); setNaverPreview(null); }}>취소</button>
                 <button className="btn btn-primary" onClick={submitRegister}>
                   <window.I.Check size={14} /> 등록 (시뮬레이션)
                 </button>
               </>}>
          <div style={{ display: "grid", gridTemplateColumns: "240px 1fr", gap: 24 }}>
            <div>
              {registerForm.image_url
                ? <img src={registerForm.image_url} alt="" style={{ width: 240, height: 240, objectFit: "cover", borderRadius: 10, background: "var(--bg-elev)" }} />
                : <ProductThumb tone={parseInt(registerForm.product_code) % 9} name={registerForm.name} size={240} radius={10} />}
              <div className="card" style={{ marginTop: 12, background: "var(--bg-elev)" }}>
                <div className="card-body" style={{ padding: 12 }}>
                  <div className="text-xs muted" style={{ marginBottom: 4 }}>ISVM 출처</div>
                  <div className="font-mono text-sm" style={{ fontWeight: 600 }}>{registerForm.product_code}</div>
                  <div className="text-xs muted" style={{ marginTop: 6 }}>매입가 {formatKRW(registerForm.purchase_price)}</div>
                </div>
              </div>
            </div>
            <div className="flex-col gap-3">
              <Field label="상품명">
                <input className="input" value={registerForm.name} onChange={e => setRegisterForm({ ...registerForm, name: e.target.value })} />
              </Field>
              <Field label="브랜드">
                <input className="input" value={registerForm.brand} onChange={e => setRegisterForm({ ...registerForm, brand: e.target.value })} />
              </Field>
              <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
                <Field label="판매가 (₩)">
                  <input className="input tabular" value={formatNum(registerForm.sale_price)}
                         onChange={e => setRegisterForm({ ...registerForm, sale_price: parseInt(e.target.value.replace(/[^0-9]/g, "")) || 0 })} />
                </Field>
                <Field label="초기 재고">
                  <input className="input tabular" type="number" value={registerForm.stock}
                         onChange={e => setRegisterForm({ ...registerForm, stock: parseInt(e.target.value) || 0 })} />
                </Field>
              </div>
              <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
                <Field label="네이버 카테고리 ID (leafCategoryId)">
                  <input className="input font-mono" value={registerForm.leafCategoryId}
                         onChange={e => setRegisterForm({ ...registerForm, leafCategoryId: e.target.value })} />
                </Field>
                <Field label="기본 배송비 (₩)">
                  <input className="input tabular" type="number" value={registerForm.baseFee}
                         onChange={e => setRegisterForm({ ...registerForm, baseFee: parseInt(e.target.value) || 0 })} />
                </Field>
              </div>
              <Field label="상세 설명">
                <textarea className="input textarea" rows={4} value={registerForm.desc}
                          onChange={e => setRegisterForm({ ...registerForm, desc: e.target.value })} />
              </Field>
              <div style={{ background: "var(--accent-soft)", padding: "10px 12px", borderRadius: 6, fontSize: 12 }}>
                <strong>마진:</strong> {formatKRW(registerForm.sale_price - registerForm.purchase_price)} ({((registerForm.sale_price - registerForm.purchase_price) / registerForm.sale_price * 100).toFixed(1)}%)
              </div>
            </div>
          </div>

          {naverPreview && (
            <div style={{ marginTop: 16 }}>
              <div className="text-xs muted" style={{ marginBottom: 6, fontWeight: 600 }}>POST {naverPreview && "https://api.commerce.naver.com/external/v1/products"}</div>
              <pre style={{ background: "var(--bg-elev)", border: "1px solid var(--border)", borderRadius: 8, padding: 12, fontSize: 11, maxHeight: 280, overflow: "auto", margin: 0 }}>
{JSON.stringify(naverPreview, null, 2)}
              </pre>
              <div className="text-xs muted" style={{ marginTop: 6 }}>
                ⚠️ 실제 등록은 서버 프록시(<code>{creds.proxy_url || "미설정"}</code>)를 통해 호출되어야 합니다.
                액세스 토큰은 서버에서 bcrypt 서명으로 발급받습니다.
              </div>
            </div>
          )}
        </Modal>
      )}
    </div>
  );
}

// Demo fallback (used when CORS blocks the real API in this preview)
function generateDemoResults(keyword) {
  const seed = (s) => { let h = 0; for (const c of s) h = (h * 31 + c.charCodeAt(0)) % 999983; return h; };
  return Array.from({ length: 8 }, (_, i) => {
    const code = String(seed(keyword + i) % 900000 + 100000);
    return {
      product_code: code,
      name: `${keyword} 관련 상품 ${i + 1} (데모)`,
      brand: ["경성", "대한", "한솔", "글로벌"][i % 4],
      purchase_price: Math.round((1000 + (seed(keyword + i) % 30000)) / 100) * 100,
      image_url: "",
    };
  });
}

window.ISVMScreen = ISVMScreen;
