// === Main app shell ===
const { useState: useStateApp, useEffect: useEffectApp } = React;

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "theme": "light"
}/*EDITMODE-END*/;

function App() {
  const [route, setRoute] = useStateApp("dashboard");
  const [products, setProducts] = useStateApp(window.MOCK.PRODUCTS);
  const [orders, setOrders] = useStateApp(window.MOCK.ORDERS);
  const [detailId, setDetailId] = useStateApp(null);
  const [sidebarOpen, setSidebarOpen] = useStateApp(false);
  const [tweaksOpen, setTweaksOpen] = useStateApp(false);

  // 데이터 소스: mock(샘플) vs live(네이버 실제). loading/error는 별도.
  const [productsSource, setProductsSource] = useStateApp("mock");
  const [productsLoading, setProductsLoading] = useStateApp(false);
  const [productsError, setProductsError] = useStateApp(null);
  const [productsMeta, setProductsMeta] = useStateApp(null);

  const loadNaverProducts = (opts) => {
    setProductsLoading(true);
    setProductsError(null);
    return window.API.naverFetchProducts({ page: 1, size: 100, ...(opts || {}) })
      .then(({ products: live, ...meta }) => {
        setProducts(live);
        setProductsSource("live");
        setProductsMeta(meta);
        window.toast && window.toast(`네이버 상품 ${live.length}개 불러옴 (전체 ${meta.totalElements}개)`);
      })
      .catch(err => {
        console.error("[naverFetchProducts]", err);
        setProductsError(err.message);
        window.toast && window.toast("네이버 상품 조회 실패: " + err.message);
      })
      .finally(() => setProductsLoading(false));
  };

  // 마운트 시 자격증명 있으면 자동 로드
  useEffectApp(() => {
    if (window.API.naverConfigured()) {
      loadNaverProducts();
    }
  }, []);

  // Theme tweak
  const [tweaks, setTweak] = window.useTweaks ? window.useTweaks(TWEAK_DEFAULTS) : [TWEAK_DEFAULTS, () => {}];

  useEffectApp(() => {
    document.documentElement.setAttribute("data-theme", tweaks.theme);
  }, [tweaks.theme]);

  // Tweaks panel host registration
  useEffectApp(() => {
    const handler = (e) => {
      if (!e.data || typeof e.data !== "object") return;
      if (e.data.type === "__activate_edit_mode") setTweaksOpen(true);
      if (e.data.type === "__deactivate_edit_mode") setTweaksOpen(false);
    };
    window.addEventListener("message", handler);
    window.parent.postMessage({ type: "__edit_mode_available" }, "*");
    return () => window.removeEventListener("message", handler);
  }, []);

  const navItems = [
    { key: "dashboard", label: "대시보드", icon: window.I.Dashboard },
    { key: "products", label: "상품 관리", icon: window.I.Box, badge: products.filter(p => p.status === "outofstock").length || null },
    { key: "bulk", label: "일괄 가격 수정", icon: window.I.Tag },
    { key: "orders", label: "주문/판매 내역", icon: window.I.ShoppingCart, badge: orders.filter(o => o.status === "paid").length || null },
    { key: "shipping", label: "로젠 송장 출력", icon: window.I.Truck },
    { key: "isvm", label: "ISVM 상품 연동", icon: window.I.Plug },
    { key: "settings", label: "API 설정", icon: window.I.Settings },
  ];

  const goto = (k) => { setRoute(k); setSidebarOpen(false); window.scrollTo(0, 0); };
  const openDetail = (pid) => setDetailId(pid);
  const closeDetail = () => setDetailId(null);

  const titleMap = {
    dashboard: "대시보드", products: "상품 관리", bulk: "일괄 가격 수정",
    orders: "주문/판매 내역", shipping: "로젠 송장 출력", isvm: "ISVM 상품 연동",
    settings: "API 설정"
  };

  return (
    <div className="app" data-screen-label={titleMap[route]}>
      {/* Sidebar */}
      <aside className={"sidebar " + (sidebarOpen ? "open" : "")}>
        <div className="sidebar-header">
          <div className="logo-mark">N</div>
          <div>
            <div className="brand-name">스마트팜</div>
            <div className="brand-sub">스마트스토어 관리</div>
          </div>
        </div>
        <div className="nav-section">
          <div className="nav-label">메뉴</div>
          {navItems.map(it => {
            const Icon = it.icon;
            return (
              <button key={it.key} className={"nav-item " + (route === it.key ? "active" : "")} onClick={() => goto(it.key)}>
                <Icon size={16} className="nav-icon" />
                <span>{it.label}</span>
                {it.badge != null && <span className="nav-badge">{it.badge}</span>}
              </button>
            );
          })}
          <div className="nav-label" style={{ marginTop: 12 }}>설정</div>
          <button className="nav-item">
            <window.I.Bell size={16} className="nav-icon" />
            <span>알림</span>
            <span className="nav-badge" style={{ background: "var(--danger-soft)", color: "var(--danger)" }}>3</span>
          </button>
          <button className="nav-item">
            <window.I.Settings size={16} className="nav-icon" />
            <span>스토어 설정</span>
          </button>
        </div>
        <div className="sidebar-footer">
          <div className="avatar">SF</div>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: 12, fontWeight: 600 }}>스마트팜</div>
            <div className="text-xs muted">smartfarm@store.kr</div>
          </div>
          <button className="btn btn-icon btn-sm btn-ghost"
                  onClick={() => setTweak({ theme: tweaks.theme === "dark" ? "light" : "dark" })}>
            {tweaks.theme === "dark" ? <window.I.Sun size={14} /> : <window.I.Moon size={14} />}
          </button>
        </div>
      </aside>

      {/* Main */}
      <div className="main">
        <header className="topbar no-print">
          <button className="btn btn-icon btn-ghost mobile-toggle" onClick={() => setSidebarOpen(o => !o)}>
            <window.I.Menu size={16} />
          </button>
          <div className="crumbs">
            <span className="muted">스마트스토어</span>
            <window.I.ChevronRight size={12} className="crumb-sep" />
            <span style={{ fontWeight: 600 }}>{titleMap[route]}</span>
          </div>
          <div className="topbar-spacer" />
          <div className="row gap-2 hide-mobile">
            {productsSource === "live" ? (
              <span className="badge badge-success badge-dot">
                네이버 라이브
                {productsMeta && ` · ${products.length}/${productsMeta.totalElements}`}
              </span>
            ) : productsLoading ? (
              <span className="badge">불러오는 중...</span>
            ) : productsError ? (
              <span className="badge badge-danger" title={productsError}>네이버 연결 실패</span>
            ) : (
              <span className="badge">샘플 데이터 (자격증명 없음)</span>
            )}
            <button className="btn btn-icon btn-ghost btn-sm">
              <window.I.Bell size={14} />
            </button>
          </div>
        </header>

        {route === "dashboard" && <window.Dashboard goto={goto} />}
        {route === "products" && <window.ProductsScreen products={products} setProducts={setProducts} goto={goto} openDetail={openDetail}
                                                       productsSource={productsSource} productsLoading={productsLoading}
                                                       productsError={productsError} productsMeta={productsMeta}
                                                       reloadProducts={loadNaverProducts} />}
        {route === "bulk" && <window.BulkEditScreen products={products} setProducts={setProducts} productsSource={productsSource} />}
        {route === "orders" && <window.OrdersScreen orders={orders} setOrders={setOrders} goto={goto} />}
        {route === "shipping" && <window.ShippingScreen orders={orders} setOrders={setOrders} />}
        {route === "isvm" && <window.ISVMScreen products={products} setProducts={setProducts} goto={goto} />}
        {route === "settings" && <window.SettingsScreen />}
      </div>

      {detailId && <window.ProductDetail productId={detailId} products={products} setProducts={setProducts} onClose={closeDetail} />}

      <ToastHost />

      {/* Tweaks panel */}
      {tweaksOpen && window.TweaksPanel && (
        <window.TweaksPanel onClose={() => setTweaksOpen(false)} title="Tweaks">
          <window.TweakSection title="테마">
            <window.TweakRadio label="모드" value={tweaks.theme} onChange={v => setTweak({ theme: v })}
              options={[{ value: "light", label: "라이트" }, { value: "dark", label: "다크" }]} />
          </window.TweakSection>
        </window.TweaksPanel>
      )}
    </div>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<App />);
