// EwoooC - 主應用

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "sidebarCollapsed": false,
  "sidebarTheme": "light",
  "density": "comfortable",
  "cardStyle": "shadow",
  "buttonStyle": "gradient",
  "page": "dashboard",
  "campaignHero": "dotted"
}/*EDITMODE-END*/;

const MomoApp = ({ tweaks, setTweak, fixedPage, label }) => {
  const [cmdOpen, setCmdOpen] = React.useState(false);
  const [editProduct, setEditProduct] = React.useState(null);
  const [priceProduct, setPriceProduct] = React.useState(null);

  const page = fixedPage || tweaks.page;

  // Cmd+K 開啟命令面板
  React.useEffect(() => {
    const onKey = (e) => {
      if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 'k') {
        e.preventDefault();
        setCmdOpen(true);
      }
      if (e.key === 'Escape') {
        setCmdOpen(false);
        setEditProduct(null);
        setPriceProduct(null);
      }
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, []);

  return (
    <div className="momo-app" style={{
      position: 'absolute', inset: 0,
      display: 'flex',
      overflow: 'hidden',
    }}>
      <Sidebar
        active={page}
        onNavigate={(id) => setTweak && setTweak('page', id)}
        collapsed={tweaks.sidebarCollapsed}
        sidebarTheme={tweaks.sidebarTheme}
      />
      <div style={{ flex: 1, display: 'flex', flexDirection: 'column', minWidth: 0, minHeight: 0 }}>
        <Topbar
          onToggleSidebar={() => setTweak && setTweak('sidebarCollapsed', !tweaks.sidebarCollapsed)}
          onOpenCmd={() => setCmdOpen(true)}
        />
        {label && (
          <div style={{
            padding: '6px 24px',
            background: 'var(--momo-primary-50)',
            borderBottom: '1px solid var(--momo-primary-100)',
            fontSize: 11, fontWeight: 600,
            color: 'var(--momo-primary-700)',
            letterSpacing: '0.06em', textTransform: 'uppercase',
          }}>{label}</div>
        )}
        <main className="momo-scroll" style={{
          flex: 1, overflowY: 'auto', minHeight: 0,
          padding: tweaks.density === 'compact' ? '20px 24px' : '28px 32px',
          background: 'var(--momo-bg-body)',
        }}>
          {page === 'dashboard' && (
            <DashboardPage density={tweaks.density} onProductClick={setPriceProduct} />
          )}
          {page === 'campaigns' && (
            <CampaignsPage density={tweaks.density} heroVariant={tweaks.campaignHero} />
          )}
          {page === 'analytics-sales' && <AnalyticsSalesPage />}
          {['analytics-daily','analytics-growth','analytics-monthly','analytics'].includes(page) && (
            <EmptyPage page={page} />
          )}
          {page === 'orders' && (
            <OrdersPage density={tweaks.density} cardStyle={tweaks.cardStyle} buttonStyle={tweaks.buttonStyle} />
          )}
          {page === 'products' && (
            <ProductsPage density={tweaks.density} cardStyle={tweaks.cardStyle} buttonStyle={tweaks.buttonStyle}
              onEditProduct={setEditProduct} />
          )}
          {!['dashboard','orders','products','campaigns','analytics-sales','analytics-daily','analytics-growth','analytics-monthly','analytics'].includes(page) && (
            <EmptyPage page={page} />
          )}
        </main>
      </div>

      <CommandPalette
        open={cmdOpen}
        onClose={() => setCmdOpen(false)}
        onNavigate={(id) => setTweak && setTweak('page', id)}
      />
      <ProductEditModal
        open={!!editProduct}
        product={editProduct}
        onClose={() => setEditProduct(null)}
        buttonStyle={tweaks.buttonStyle}
      />
      <PriceHistoryModal
        open={!!priceProduct}
        product={priceProduct}
        onClose={() => setPriceProduct(null)}
      />
    </div>
  );
};

const EmptyPage = ({ page }) => {
  const labels = {
    inventory: '庫存管理', members: '會員管理', marketing: '行銷活動',
    analytics: '分析報表', settings: '系統設定',
    'analytics-daily':   '當日業績',
    'analytics-growth':  '成長分析',
    'analytics-monthly': '月份總表數據分析',
    outofstock: '廠商缺貨', ai: 'AI 助手', cloud: '雲端匯入',
  };
  return (
    <div>
      <PageHeader title={labels[page] || '頁面'} subtitle="此頁面尚在規劃中" />
      <Card style={{ padding: 64, textAlign: 'center' }}>
        <div style={{
          width: 64, height: 64,
          borderRadius: '50%',
          background: 'var(--momo-primary-100)',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          margin: '0 auto 16px',
          color: 'var(--momo-primary)',
        }}>
          <Icon name="sparkle" size={28} />
        </div>
        <div style={{ fontSize: 16, fontWeight: 700, color: 'var(--momo-text-primary)', marginBottom: 6 }}>
          {labels[page]} 即將推出
        </div>
        <div style={{ fontSize: 13, color: 'var(--momo-text-secondary)', marginBottom: 20 }}>
          此區尚未建置示意內容，歡迎在 Tweaks 切換到其他頁面預覽。
        </div>
        <Button variant="gradient">通知我上線時間</Button>
      </Card>
    </div>
  );
};

window.MomoApp = MomoApp;
window.TWEAK_DEFAULTS = TWEAK_DEFAULTS;
