/* eslint-disable @next/next/no-img-element */
import Link from "next/link";
import PrintReportButton from "@/components/reports/PrintReportButton";
import ReportFilters from "@/components/reports/ReportFilters";
import ExternalExpenseManager from "@/components/reports/ExternalExpenseManager";
import Badge from "@/components/ui/Badge";
import Card from "@/components/ui/Card";
import { monthOptions, periodRange } from "@/lib/dateRange";
import { getFinancialStatementReport } from "@/lib/financialStatementReport";
import { getOrderBusinessReport } from "@/lib/orderBusinessReport";
import { getProfitReport } from "@/lib/profitReport";
import { calculateProfitAccounting } from "@/lib/profitAccounting";
import { shopRepository } from "@/lib/repositories/shopRepository";
import { resolveShopScope, restrictedShopIds } from "@/lib/storeScope";
import { APP_TIME_ZONE, dateKeyInTimeZone, SHOPEE_WALLET_TIME_ZONE } from "@/lib/walletAccountingDate";
import { getCurrentUser } from "@/lib/currentUser";
import { BUSINESS_EXPENSE_SCOPE_ID } from "@/lib/externalExpenses";

export const dynamic = "force-dynamic";

type SearchParams = Promise<Record<string, string | string[] | undefined>>;
type ReportTab = "summary" | "daily_income" | "products" | "sales" | "expenses" | "losses";
type ProductView = "best" | "high_profit" | "low_profit" | "missing_hpp";
type ProfitView = "estimated" | "realized";
type SalesStatus = "all" | "completed" | "to_ship" | "shipping" | "return" | "cancelled" | "unpaid";
type BusinessReport = Awaited<ReturnType<typeof getOrderBusinessReport>>;
type ProfitReport = Awaited<ReturnType<typeof getProfitReport>>;
type FinancialReport = Awaited<ReturnType<typeof getFinancialStatementReport>>;
type ProductPerformance = BusinessReport["products"]["bestSellers"][number];
type ProfitDetail = ProfitReport["details"]["realized"][number];
type StoreProfitBreakdown = {
  shopId: string;
  shopName: string;
  releasedIncome: number;
  income: number;
  hppAwal: number;
  hppAdjustment: number;
  hppFinal: number;
  profitBeforeAds: number;
  settlementAds: number;
  walletAds: number;
  totalAds: number;
  adsBudget: number;
  adsBudgetResult: number;
  afterAds: number;
  inventoryLoss: number;
  externalExpenses: number;
  netProfit: number;
  adsShare: number | null;
  status: "UNTUNG" | "IKLAN_TINGGI" | "IKLAN_OVER" | "HPP_BONCOS" | "BONCOS_RETUR" | "BONCOS_IKLAN" | "BONCOS_OPERASIONAL";
};

const REPORT_TABS: Array<{ value: ReportTab; label: string; icon: string }> = [
  { value: "summary", label: "Ringkasan", icon: "📊" },
  { value: "daily_income", label: "Pemasukan Harian", icon: "💵" },
  { value: "products", label: "Produk Terlaris", icon: "🏆" },
  { value: "sales", label: "Data Penjualan", icon: "📝" },
  { value: "expenses", label: "Pengeluaran", icon: "💸" },
  { value: "losses", label: "Kerugian", icon: "⚠️" },
];

const SALES_STATUSES: Array<{ value: SalesStatus; label: string; statuses: string[] | null }> = [
  { value: "all", label: "Semua status", statuses: null },
  { value: "completed", label: "Selesai / cair", statuses: ["COMPLETED"] },
  { value: "to_ship", label: "Perlu dikirim", statuses: ["READY_TO_SHIP", "PROCESSED"] },
  { value: "shipping", label: "Sedang dikirim", statuses: ["SHIPPED", "TO_CONFIRM_RECEIVE"] },
  { value: "return", label: "Retur", statuses: ["TO_RETURN", "RETURNED"] },
  { value: "cancelled", label: "Batal", statuses: ["CANCELLED", "IN_CANCEL"] },
  { value: "unpaid", label: "Belum dibayar", statuses: ["UNPAID", "PENDING", "INVOICE_PENDING"] },
];

function firstParam(value: string | string[] | undefined) {
  return Array.isArray(value) ? value[0] : value;
}

function money(value: number | null | undefined) {
  const amount = Math.round(value || 0);
  return `${amount < 0 ? "-" : ""}Rp${Math.abs(amount).toLocaleString("id-ID")}`;
}

function dateLabel(value: string | Date | null, timeZone = APP_TIME_ZONE) {
  if (!value) return "-";
  const date = typeof value === "string" && /^\d{4}-\d{2}-\d{2}$/.test(value) ? new Date(`${value}T12:00:00+07:00`) : new Date(value);
  return new Intl.DateTimeFormat("id-ID", { day: "numeric", month: "short", year: "numeric", timeZone }).format(date);
}

function dateTimeLabel(value: string | Date | null, timeZone = APP_TIME_ZONE) {
  if (!value) return "-";
  return new Intl.DateTimeFormat("id-ID", {
    day: "numeric",
    month: "short",
    year: "numeric",
    hour: "2-digit",
    minute: "2-digit",
    timeZone,
  }).format(new Date(value));
}

function reportDateKey(value: Date | null, timeZone = APP_TIME_ZONE) {
  if (!value) return null;
  return dateKeyInTimeZone(value, timeZone);
}

function selectedTab(value: string | undefined): ReportTab {
  return REPORT_TABS.some((tab) => tab.value === value) ? value as ReportTab : "summary";
}

function selectedProductView(value: string | undefined): ProductView {
  return ["best", "high_profit", "low_profit", "missing_hpp"].includes(value || "") ? value as ProductView : "best";
}

function selectedProfitView(value: string | undefined): ProfitView {
  return value === "realized" ? "realized" : "estimated";
}

function selectedSalesStatus(value: string | undefined): SalesStatus {
  return SALES_STATUSES.some((status) => status.value === value) ? value as SalesStatus : "all";
}

function statusTone(status: string | null) {
  if (status === "COMPLETED") return "success" as const;
  if (["CANCELLED", "IN_CANCEL", "TO_RETURN", "RETURNED"].includes(status || "")) return "danger" as const;
  if (["READY_TO_SHIP", "PROCESSED"].includes(status || "")) return "warning" as const;
  if (["SHIPPED", "TO_CONFIRM_RECEIVE"].includes(status || "")) return "info" as const;
  return "neutral" as const;
}

function statusLabel(status: string | null) {
  const labels: Record<string, string> = {
    COMPLETED: "Selesai",
    READY_TO_SHIP: "Perlu dikirim",
    PROCESSED: "Diproses",
    SHIPPED: "Sedang dikirim",
    TO_CONFIRM_RECEIVE: "Menunggu diterima",
    TO_RETURN: "Proses retur",
    RETURNED: "Retur",
    DELIVERY_FAILED: "Pengiriman gagal",
    CANCELLED: "Batal",
    IN_CANCEL: "Proses batal",
    UNPAID: "Belum dibayar",
    PENDING: "Tertunda",
    INVOICE_PENDING: "Menunggu pembayaran",
  };
  return status ? labels[status] || status : "-";
}

function groupDailyIncome(rows: ProfitDetail[], timeZone = APP_TIME_ZONE) {
  const days = new Map<string, {
    date: string;
    orderSns: Set<string>;
    itemCount: number;
    income: number;
    hpp: number;
    profit: number;
    missingHppItems: number;
    rows: ProfitDetail[];
  }>();
  for (const row of rows) {
    const date = reportDateKey(row.date, timeZone);
    if (!date) continue;
    const day = days.get(date) || { date, orderSns: new Set<string>(), itemCount: 0, income: 0, hpp: 0, profit: 0, missingHppItems: 0, rows: [] };
    day.orderSns.add(row.orderSn);
    day.itemCount += row.quantity;
    day.income += row.income || 0;
    if (row.hpp === null) day.missingHppItems += row.quantity;
    else day.hpp += row.hpp;
    if (row.profit !== null) day.profit += row.profit;
    day.rows.push(row);
    days.set(date, day);
  }
  return Array.from(days.values()).map((day) => ({ ...day, orders: day.orderSns.size })).sort((a, b) => b.date.localeCompare(a.date));
}

export default async function ReportsPage({ searchParams }: { searchParams: SearchParams }) {
  const params = await searchParams;
  const current = await getCurrentUser();
  const shops = current ? await shopRepository.findScopeOptionsForUser(current) : [];
  const activeShopId = resolveShopScope(firstParam(params.shop_id), shops);
  const shopIds = restrictedShopIds(current?.role, activeShopId, shops);
  const months = monthOptions();
  const defaultReportPeriod = months[0]?.value || "30d";
  const period = firstParam(params.period) || defaultReportPeriod;
  const q = firstParam(params.q) || null;
  const tab = selectedTab(firstParam(params.tab));
  const productView = selectedProductView(firstParam(params.product_view));
  const profitView = selectedProfitView(firstParam(params.profit_view));
  const salesStatus = selectedSalesStatus(firstParam(params.sales_status));
  const selectedStatusConfig = SALES_STATUSES.find((item) => item.value === salesStatus) || SALES_STATUSES[0];
  const { dateFrom, dateTo } = periodRange(period, firstParam(params.date_from) || null, firstParam(params.date_to) || null);
  const fromDate = new Date(`${dateFrom}T00:00:00+07:00`);
  const toDate = new Date(`${dateTo}T23:59:59.999+07:00`);

  // Each tab loads only the data it renders. The three source reports are expensive
  // and must not all run for a product list or a wallet-expense page.
  const [businessResult, profitResult, financialResult] = await Promise.all([
    ["summary", "products", "sales"].includes(tab) ? getOrderBusinessReport({
      shopId: activeShopId,
      shopIds,
      dateFrom: fromDate,
      dateTo: toDate,
      search: q,
      statuses: tab === "sales" ? selectedStatusConfig.statuses : tab === "products" ? ["READY_TO_SHIP", "PROCESSED", "SHIPPED", "TO_CONFIRM_RECEIVE", "COMPLETED"] : null,
    }) : Promise.resolve(null),
    ["summary", "daily_income"].includes(tab) ? getProfitReport({ shopId: activeShopId, shopIds, dateFrom: fromDate, dateTo: toDate, search: q }) : Promise.resolve(null),
    ["summary", "sales", "expenses", "losses"].includes(tab) || (tab === "daily_income" && profitView === "realized")
      ? getFinancialStatementReport({ shopId: activeShopId, shopIds, expenseOwnerIds: current ? [current.ownerId || current.id] : [], dateFrom: fromDate, dateTo: toDate, search: q })
      : Promise.resolve(null),
  ]);
  // The JSX branches below only read the corresponding report when its tab is active.
  const business = businessResult as BusinessReport;
  const profit = profitResult as ProfitReport;
  const financial = financialResult as FinancialReport;

  const shopNameById = new Map(shops.map((shop) => [shop.shopId, shop.shopName || shop.shopId]));
  const settledItems = (profit?.details.realized || []).filter((row) => row.incomeSource === "settlement");
  const estimatedDetailsByDate = new Map(groupDailyIncome(profit?.details.estimated || [], APP_TIME_ZONE).map((row) => [row.date, row]));
  const realizedDetailsByDate = new Map(groupDailyIncome(profit?.details.realized || [], SHOPEE_WALLET_TIME_ZONE).map((row) => [row.date, row]));
  const activeProfitSummary = profitView === "estimated" ? profit?.estimated : profit?.realized;
  const activeProfitDetailsByDate = profitView === "estimated" ? estimatedDetailsByDate : realizedDetailsByDate;
  const activeProfitDays = (profit?.daily || []).filter((row) => profitView === "estimated" ? row.estimatedOrders > 0 : row.realizedOrders > 0);
  const activeProfitLabel = profitView === "estimated" ? "Estimasi profit" : "Profit order";
  const settledItemQuantity = settledItems.reduce((sum, row) => sum + row.quantity, 0);
  const knownFinalHpp = settledItems.reduce((sum, row) => sum + (row.hpp || 0), 0);
  const knownInitialHpp = settledItems
    .filter((row) => row.hpp !== null)
    .reduce((sum, row) => sum + (row.hppAwal ?? row.hpp ?? 0), 0);
  const knownIncome = settledItems.filter((row) => row.hpp !== null).reduce((sum, row) => sum + (row.income || 0), 0);
  const knownItemProfit = knownIncome - knownFinalHpp;
  const partialOrderItemProfit = knownItemProfit - (profit?.realized.profit || 0);
  const missingFinalHppItems = settledItems.filter((row) => row.hpp === null).reduce((sum, row) => sum + row.quantity, 0);
  const unresolvedIncome = Math.max(0, (financial?.settlements.netReleased || 0) - knownIncome);
  const settlementAdsExpense = (financial?.settlements.expenseRows || [])
    .filter((row) => row.key.endsWith(":marketing_credit"))
    .reduce((sum, row) => sum + row.amount, 0);
  const accounting = calculateProfitAccounting({ confirmedIncome: knownIncome, initialHpp: knownInitialHpp, finalHpp: knownFinalHpp, settlementAds: settlementAdsExpense, walletAds: financial?.settlements.walletMarketingExpense || 0, inventoryLoss: financial?.returns.inventoryLoss || 0, externalProfitExpenses: financial?.externalExpenses.profitExpense || 0 });
  const { hppAdjustment, totalAdsExpense, netSettlementIncome, initialHppProfit, profitBeforeAds, adsBudget, adsBudgetResult, afterMarketingProfit, netProfit: calculatedNetProfit } = accounting;
  const storeProfitBase = new Map<string, { releasedIncome: number; income: number; hppAwal: number; hppFinal: number; settlementAds: number; walletAds: number; inventoryLoss: number; externalExpenses: number }>();
  const storeProfitEntry = (shopId: string) => {
    const entry = storeProfitBase.get(shopId) || { releasedIncome: 0, income: 0, hppAwal: 0, hppFinal: 0, settlementAds: 0, walletAds: 0, inventoryLoss: 0, externalExpenses: 0 };
    storeProfitBase.set(shopId, entry);
    return entry;
  };
  for (const row of financial?.settlements.rows || []) storeProfitEntry(row.shopId).releasedIncome += row.net;
  for (const row of settledItems) {
    if (row.hpp === null) continue;
    const entry = storeProfitEntry(row.shopId);
    entry.income += row.income || 0;
    entry.hppAwal += row.hppAwal ?? row.hpp;
    entry.hppFinal += row.hpp;
  }
  for (const row of financial?.settlements.expenseRows || []) {
    if (row.key.endsWith(":marketing_credit")) storeProfitEntry(row.shopId).settlementAds += row.amount;
    if (row.key.endsWith(":wallet_ads")) storeProfitEntry(row.shopId).walletAds += row.amount;
  }
  for (const row of financial?.returns.rows || []) {
    if (row.hppLoss === null) continue;
    storeProfitEntry(row.shopId).inventoryLoss += row.hppLoss;
  }
  for (const row of financial?.externalExpenses.rows || []) {
    // Business-wide overhead appears once in the total P&L; do not arbitrarily
    // assign it to a store in the per-store comparison.
    if (row.affectsProfit && row.shopId !== BUSINESS_EXPENSE_SCOPE_ID) storeProfitEntry(row.shopId).externalExpenses += row.amount;
  }
  const storeProfitRows: StoreProfitBreakdown[] = Array.from(storeProfitBase, ([shopId, row]) => {
    const shopAccounting = calculateProfitAccounting({ confirmedIncome: row.income, initialHpp: row.hppAwal, finalHpp: row.hppFinal, settlementAds: row.settlementAds, walletAds: row.walletAds, inventoryLoss: row.inventoryLoss, externalProfitExpenses: row.externalExpenses });
    const hppAdjustmentByShop = shopAccounting.hppAdjustment;
    const profitBeforeAdsByShop = shopAccounting.profitBeforeAds;
    const totalAdsByShop = shopAccounting.totalAdsExpense;
    const adsBudgetByShop = shopAccounting.adsBudget;
    const adsBudgetResultByShop = shopAccounting.adsBudgetResult;
    const afterAds = shopAccounting.afterMarketingProfit;
    const netProfit = shopAccounting.netProfit;
    const adsShare = adsBudgetByShop > 0 ? (totalAdsByShop / adsBudgetByShop) * 100 : totalAdsByShop > 0 ? null : 0;
    const status: StoreProfitBreakdown["status"] = profitBeforeAdsByShop < 0
      ? "HPP_BONCOS"
      : netProfit < 0 && adsBudgetResultByShop < 0
        ? "BONCOS_IKLAN"
        : netProfit < 0 && row.externalExpenses > 0 && afterAds - row.inventoryLoss >= 0
          ? "BONCOS_OPERASIONAL"
        : netProfit < 0
          ? "BONCOS_RETUR"
          : adsBudgetResultByShop < 0
            ? "IKLAN_OVER"
          : adsShare !== null && adsShare >= 80
            ? "IKLAN_TINGGI"
            : "UNTUNG";
    return {
      shopId,
      shopName: shopNameById.get(shopId) || shopId,
      releasedIncome: row.releasedIncome,
      income: row.income,
      hppAwal: row.hppAwal,
      hppAdjustment: hppAdjustmentByShop,
      hppFinal: row.hppFinal,
      profitBeforeAds: profitBeforeAdsByShop,
      settlementAds: row.settlementAds,
      walletAds: row.walletAds,
      totalAds: totalAdsByShop,
      adsBudget: adsBudgetByShop,
      adsBudgetResult: adsBudgetResultByShop,
      afterAds,
      inventoryLoss: row.inventoryLoss,
      externalExpenses: row.externalExpenses,
      netProfit,
      adsShare,
      status,
    };
  }).filter((row) => row.releasedIncome !== 0 || row.income !== 0 || row.totalAds !== 0 || row.inventoryLoss !== 0).sort((a, b) => a.netProfit - b.netProfit);
  const hppCoverage = settledItemQuantity === 0
    ? 100
    : Math.round(((settledItemQuantity - missingFinalHppItems) / settledItemQuantity) * 100);
  const expenseByOrder = new Map((financial?.settlements.rows || []).map((row) => [row.key, row]));
  const summary = business?.summary;
  const averageOrder = summary?.totalOrders ? summary.omzet / summary.totalOrders : 0;

  const exportParams = new URLSearchParams({ shop_id: activeShopId || "all", date_from: dateFrom, date_to: dateTo });
  if (q) exportParams.set("q", q);
  if (tab === "summary" || tab === "daily_income") exportParams.set("report", "profit");
  if (tab === "daily_income") exportParams.set("mode", profitView);
  if (tab === "expenses") exportParams.set("report", "expenses");
  if (tab === "losses") exportParams.set("report", "losses");

  function hrefFor(nextTab: ReportTab, options?: { productView?: ProductView; profitView?: ProfitView; salesStatus?: SalesStatus }) {
    const query = new URLSearchParams({ shop_id: activeShopId || "all", period, tab: nextTab });
    if (period === "custom") {
      query.set("date_from", dateFrom);
      query.set("date_to", dateTo);
    }
    if (q) query.set("q", q);
    if (nextTab === "daily_income") query.set("profit_view", options?.profitView || profitView);
    if (nextTab === "products") query.set("product_view", options?.productView || productView);
    if (nextTab === "sales") query.set("sales_status", options?.salesStatus || salesStatus);
    return `/reports?${query.toString()}`;
  }

  function profitPdfHref(from: string, to: string) {
    const query = new URLSearchParams({ shop_id: activeShopId || "all", report: "profit", mode: profitView, date_from: from, date_to: to });
    if (q) query.set("q", q);
    return `/api/reports/pdf?${query.toString()}`;
  }

  const productRows = productView === "high_profit"
    ? (business?.products.highProfit || []).filter((row) => !row.missingHpp && !row.missingIncome)
    : productView === "low_profit"
      ? (business?.products.lowProfit || []).filter((row) => !row.missingHpp && !row.missingIncome)
      : productView === "missing_hpp"
        ? business?.products.missingHpp || []
        : business?.products.bestSellers || [];
  const highestProfitProduct = business?.products.highProfit[0] || null;
  const lowestProfitProduct = business?.products.lowProfit[0] || null;

  return (
    <div className="report-page space-y-4">
      <section className="flex flex-wrap items-start justify-between gap-3">
        <div>
          <div className="muted-label">Keuangan & analitik</div>
          <h1 className="page-title mt-1">Laporan Bisnis</h1>
          <p className="mt-1 text-sm text-slate-500">{dateLabel(dateFrom)} – {dateLabel(dateTo)} · {activeShopId ? shopNameById.get(activeShopId) : "Semua toko"}</p>
        </div>
        <div className="report-no-print flex flex-wrap gap-2">
          <a className="ui-button ui-button-primary" href={tab === "daily_income" ? profitPdfHref(dateFrom, dateTo) : `/api/reports/export?${exportParams.toString()}`}>{tab === "daily_income" ? "Unduh PDF" : "Ekspor CSV"}</a>
          <PrintReportButton />
        </div>
      </section>

      <div className="report-no-print">
        <ReportFilters key={`${activeShopId || "all"}:${period}:${dateFrom}:${dateTo}:${q || ""}`} basePath="/reports" shops={shops} activeShopId={activeShopId} period={period} dateFrom={dateFrom} dateTo={dateTo} defaultPeriod={defaultReportPeriod} q={q} includeSearch months={months} />
      </div>

      <nav className="report-tabs report-no-print" aria-label="Bagian laporan">
        {REPORT_TABS.map((item) => (
          <a aria-current={tab === item.value ? "page" : undefined} className={`report-tab ${tab === item.value ? "is-active" : ""}`} href={hrefFor(item.value)} key={item.value}>
            <span aria-hidden="true">{item.icon}</span>{item.label}
          </a>
        ))}
      </nav>

      {tab === "summary" ? (
        <div className="space-y-4">
          <section className="report-kpi-grid" aria-label="Ringkasan keuangan">
            <ReportMetric label="Omzet selesai" value={money(financial.settlements.grossRevenue)} hint={`${financial.settlements.orders} settlement`} />
            <ReportMetric label="Dana cair bersih" value={money(financial.settlements.netReleased)} hint="Setelah potongan Shopee" tone="emerald" />
            <ReportMetric label="Dana dengan HPP terisi" value={money(knownIncome)} hint={unresolvedIncome ? `${money(unresolvedIncome)} belum masuk laba` : "Seluruh dana terhitung"} />
            <ReportMetric label="HPP Final terhitung" value={money(knownFinalHpp)} hint={`${hppCoverage}% cakupan item`} />
            <ReportMetric label="Belanja iklan tercatat" value={money(totalAdsExpense)} hint={`${money(settlementAdsExpense)} sudah dipotong di settlement · ${money(financial.settlements.walletMarketingExpense)} dari wallet`} />
            <ReportMetric label="Laba setelah penyesuaian iklan" value={money(afterMarketingProfit)} hint={afterMarketingProfit < 0 ? `Boncos ${money(Math.abs(afterMarketingProfit))}` : "Iklan settlement tidak dikurangi dua kali"} tone={afterMarketingProfit < 0 ? "rose" : "emerald"} />
            <ReportMetric label="Profit riil bersih" value={money(calculatedNetProfit)} hint={missingFinalHppItems ? `${missingFinalHppItems} item belum dihitung` : "Setelah iklan dan kerugian"} tone={calculatedNetProfit < 0 ? "rose" : "emerald"} />
            <ReportMetric label="Kerugian retur & gagal kirim" value={money(financial.returns.totalImpact)} hint={`${money(financial.returns.settlementLoss)} sudah pada dana cair; ${money(financial.returns.inventoryLoss)} HPP inventori`} tone={financial.returns.items ? "rose" : "neutral"} />
          </section>

          {missingFinalHppItems > 0 ? (
            <section className="report-alert is-warning">
              <div><b>Laba belum final.</b> Ada {missingFinalHppItems} item settlement tanpa HPP Final. Angka laba hanya memakai item yang HPP Final-nya sudah terisi.</div>
              <Link className="ui-button ui-button-secondary report-no-print" href={`/products?shop_id=${activeShopId || "all"}&filter=hpp_missing`}>Lengkapi HPP Final</Link>
            </section>
          ) : null}

          <div className="grid gap-4 xl:grid-cols-2">
            <Card className="report-statement" title="Laporan Laba Rugi" description="Basis pesanan selesai yang settlement-nya sudah tersedia.">
              <div className="mb-4 flex flex-wrap gap-2"><Badge tone="success">Berbasis dana cair bersih</Badge><Badge tone={hppCoverage === 100 ? "success" : "warning"}>HPP Final {hppCoverage}%</Badge><Badge tone="info">Iklan settlement sudah masuk potongan</Badge></div>
              <StatementSection title="Pendapatan">
                <StatementRow label="Omzet bruto transaksi selesai" value={financial.settlements.grossRevenue} />
                <StatementRow label="Potongan marketplace" value={-financial.settlements.deductions} tone="danger" />
                {financial.settlements.additions > 0 ? <StatementRow label="Kredit / subsidi marketplace" value={financial.settlements.additions} tone="success" /> : null}
                <StatementRow label="Pendapatan bersih setelah potongan" value={financial.settlements.netReleased} strong tone="success" />
              </StatementSection>
              <StatementSection title="Harga Pokok Penjualan">
                <StatementRow label="Pendapatan bersih item dengan HPP lengkap" value={netSettlementIncome} note={`${unresolvedIncome ? `${money(unresolvedIncome)} belum masuk basis profit karena HPP kosong. ` : ""}${money(settlementAdsExpense)} iklan settlement sudah tercakup dalam potongan dan dana cair.`} />
                <StatementRow label="Harga supplier (HPP Awal)" value={-knownInitialHpp} note="Informasi biaya dasar barang; tidak dipakai sebagai profit final" tone="danger" />
                <StatementRow label="Dana bersih setelah HPP Awal" value={initialHppProfit} note="Pembanding setelah seluruh potongan settlement; belum memperhitungkan selisih ke HPP Final." tone={initialHppProfit < 0 ? "danger" : "success"} />
                <StatementRow label="Selisih HPP Awal → HPP Final" value={-hppAdjustment} note={`Total HPP Final setelah penyesuaian: ${money(knownFinalHpp)}`} tone={hppAdjustment > 0 ? "danger" : hppAdjustment < 0 ? "success" : "neutral"} />
                <StatementRow label="Profit order setelah HPP Final" value={profitBeforeAds} strong tone={profitBeforeAds < 0 ? "danger" : "success"} />
              </StatementSection>
              <StatementSection title="Pengeluaran & Kerugian">
                <StatementRow label="Iklan otomatis dari settlement (sudah terpotong)" value={settlementAdsExpense} note="Informasi saja: sudah mengurangi dana settlement dan tidak dipotong lagi dari laba." />
                <StatementRow label="Auto top-up/autodebet wallet (pengurang tambahan)" value={-financial.settlements.walletMarketingExpense} note="Pengeluaran Shopee Ads dari Saldo Penjual setelah settlement cair." tone="danger" />
                <StatementRow label="Total belanja iklan tercatat" value={totalAdsExpense} note="Metode settlement + wallet; total informasi, bukan pengurang tambahan seluruhnya." />
                <StatementRow label="Pos biaya dari selisih HPP" value={adsBudget} note="Selisih HPP Awal menuju HPP Final untuk iklan, packing, dan penyesuaian lain" />
                <StatementRow label="Selisih pos HPP terhadap belanja iklan" value={adsBudgetResult} note={`${adsBudgetResult < 0 ? `Belanja iklan tercatat melebihi pos biaya ${money(Math.abs(adsBudgetResult))}` : `Sisa pos biaya ${money(adsBudgetResult)}`}. Indikator anggaran ini tidak dikurangi lagi dari laba.`} tone={adsBudgetResult < 0 ? "danger" : "success"} />
                <StatementRow label="Laba setelah penyesuaian iklan" value={afterMarketingProfit} note="Profit order + pos biaya selisih HPP − autodebet wallet. Iklan settlement sudah tercakup di pendapatan bersih." strong tone={afterMarketingProfit < 0 ? "danger" : "success"} />
                <StatementRow label="Pengeluaran operasional eksternal" value={-financial.externalExpenses.profitExpense} note="Gaji, sewa, utilitas, packing, dan pengeluaran lain yang ditandai mengurangi laba" tone={financial.externalExpenses.profitExpense > 0 ? "danger" : "neutral"} />
                <StatementRow label="Dikurangi: HPP barang retur & gagal kirim" value={-financial.returns.inventoryLoss} note="Dihitung sebagai kerugian inventori" tone="danger" />
                <StatementRow label="Profit riil bersih terhitung" value={calculatedNetProfit} note="Laba setelah penyesuaian iklan, pengeluaran eksternal terpilih, dan kerugian inventori; item tanpa HPP belum dihitung" strong tone={calculatedNetProfit < 0 ? "danger" : "success"} />
              </StatementSection>
              <p className="mt-4 text-[11px] leading-5 text-slate-500">Profit order = dana settlement bersih setelah potongan Shopee − HPP Final. Iklan otomatis yang sudah dipotong sebelum dana cair hanya ditampilkan untuk informasi/anggaran; yang dikurangi lagi adalah autodebet wallet, lalu kerugian inventori dan pengeluaran eksternal. Angka belum final selama HPP item kosong.</p>
            </Card>

            <Card className="report-statement" title="Laporan Arus Kas" description="Metode langsung berdasarkan uang marketplace yang benar-benar dilepas.">
              <div className="mb-4 flex flex-wrap gap-2"><Badge tone="info">Kas terpantau dari Shopee</Badge><Badge tone="warning">Saldo rekening belum terhubung</Badge></div>
              <StatementSection title="Aktivitas operasional">
                <StatementRow label="Penerimaan kas bersih dari Shopee" value={financial.settlements.netReleased} />
                <StatementRow label="Top up / autodebet Shopee Ads" value={-financial.settlements.walletMarketingExpense} />
                <StatementRow label="Pengeluaran kas eksternal" value={-financial.externalExpenses.cashOutflow} note="Semua catatan biaya di luar Shopee, termasuk pembelian bahan/stok" tone={financial.externalExpenses.cashOutflow > 0 ? "danger" : "neutral"} />
                <StatementRow label="Kenaikan kas yang terpantau" value={financial.settlements.netReleased - financial.settlements.walletMarketingExpense - financial.externalExpenses.cashOutflow} strong />
              </StatementSection>
              <StatementSection title="Informasi non-kas">
                <StatementRow label="HPP Final barang terjual" value={knownFinalHpp} note="Mengurangi laba, bukan otomatis arus kas pada tanggal settlement" />
                <StatementRow label="Dampak settlement retur" value={financial.returns.settlementLoss} note="Sudah tercermin di settlement jika Shopee memotongnya" />
              </StatementSection>
              <p className="mt-4 text-[11px] leading-5 text-slate-500">Saldo awal dan saldo akhir belum ditampilkan karena Sellfin belum terhubung ke rekening kas. Angka ini sengaja tidak diisi Rp0 agar tidak menyesatkan.</p>
            </Card>
          </div>

          <StoreProfitBreakdownTable rows={storeProfitRows} />
          <StorePerformance rows={business.salesByShop} />
        </div>
      ) : null}

      {tab === "daily_income" ? (
        <section className="space-y-4">
          <div className="report-profit-toolbar report-no-print">
            <div className="report-subtabs" aria-label="Jenis profit harian">
              <ProductViewLink active={profitView === "estimated"} href={hrefFor("daily_income", { profitView: "estimated" })}>Estimasi profit</ProductViewLink>
              <ProductViewLink active={profitView === "realized"} href={hrefFor("daily_income", { profitView: "realized" })}>Profit riil</ProductViewLink>
            </div>
            <a className="ui-button ui-button-primary" href={profitPdfHref(dateFrom, dateTo)}>Unduh semua tanggal (PDF)</a>
          </div>

          <div className="report-kpi-grid is-four">
            <ReportMetric label={activeProfitLabel} value={money(activeProfitSummary.profit)} hint={`${activeProfitSummary.confirmedOrders}/${activeProfitSummary.orders} order lengkap`} tone={activeProfitSummary.profit < 0 ? "rose" : profitView === "realized" ? "emerald" : "neutral"} />
            {profitView === "realized" ? <ReportMetric label="Profit riil bersih" value={money(calculatedNetProfit)} hint="Setelah iklan dan HPP retur/gagal kirim" tone={calculatedNetProfit < 0 ? "rose" : "emerald"} /> : null}
            <ReportMetric label={profitView === "estimated" ? "Order masuk" : "Order selesai"} value={activeProfitSummary.orders.toLocaleString("id-ID")} hint={`${activeProfitSummary.quantity} item`} />
            <ReportMetric label={profitView === "estimated" ? "Estimasi dana" : "Dana riil"} value={money(activeProfitSummary.income)} hint={`${activeProfitSummary.incomeCoverage}% data dana tersedia`} tone="emerald" />
            <ReportMetric label="HPP Final + packing" value={money(activeProfitSummary.hpp)} hint={`${activeProfitSummary.hppCoverage}% item lengkap`} />
          </div>

          {profitView === "realized" ? <section className="report-alert is-info"><div><b>Bedakan hasil order dan profit bersih.</b> Profit order lengkap {money(profit.realized.profit)} tidak memasukkan seluruh order yang masih memiliki item tanpa HPP. Basis profit item terhitung {money(knownItemProfit)}{partialOrderItemProfit !== 0 ? `, termasuk ${money(partialOrderItemProfit)} dari item ber-HPP pada order parsial` : ""}. Profit riil bersih terhitung {money(calculatedNetProfit)} mengikuti rekonsiliasi pos selisih HPP dengan iklan aktual serta kerugian retur. Iklan wallet tidak dibagi ke barang tanpa bukti alokasi.</div></section> : null}
          <Card title={`${activeProfitLabel} Harian`} description={profitView === "estimated" ? "Berdasarkan tanggal order masuk. Semua order dan produk estimasi dapat dibuka di bawah." : "Berdasarkan tanggal dana masuk Saldo Penjual. Angka per barang adalah hasil order sebelum penyesuaian iklan wallet/retur; lihat profit bersih di atas."}>
            <div className="space-y-2">
              {activeProfitDays.map((row) => {
                const day = activeProfitDetailsByDate.get(row.date);
                const orders = profitView === "estimated" ? row.estimatedOrders : row.realizedOrders;
                const income = profitView === "estimated" ? row.estimatedIncome : row.realizedIncome;
                const hpp = profitView === "estimated" ? row.estimatedHpp : row.realizedHpp;
                const dailyProfit = profitView === "estimated" ? row.estimatedProfit : row.realizedProfit;
                const unconfirmed = profitView === "estimated" ? row.estimatedUnconfirmed : row.realizedUnconfirmed;
                return <details className="report-day report-profit-day" key={row.date}>
                  <summary>
                    <div className="report-day-date"><span aria-hidden="true">📅</span><div><strong>{dateLabel(row.date)}</strong><small>{orders} order · {day?.itemCount || 0} item</small></div></div>
                    <div className={`report-profit-block is-${profitView === "estimated" ? "estimate" : "realized"}`}><div className="report-profit-block-label"><span>{activeProfitLabel}</span>{unconfirmed > 0 ? <em>{unconfirmed} belum lengkap</em> : <em className="is-complete">Lengkap</em>}</div><strong className={dailyProfit < 0 ? "text-rose-700" : profitView === "estimated" ? "text-cyan-700" : "text-emerald-700"}>{money(dailyProfit)}</strong><small>Dana {money(income)} · HPP Final {money(hpp)}</small></div>
                    <a className="ui-button ui-button-secondary report-day-download" href={profitPdfHref(row.date, row.date)}>Unduh PDF</a>
                    <span className="report-day-chevron" aria-hidden="true">⌄</span>
                  </summary>
                  {day ? <><div className="overflow-x-auto border-t border-slate-200 dark:border-slate-800"><table className="report-table min-w-[980px]"><thead><tr><th>Produk</th><th>Order / toko</th><th className="text-right">Qty</th><th className="text-right">{profitView === "estimated" ? "Estimasi dana" : "Dana riil"}</th><th className="text-right">HPP Final</th><th className="text-right">{activeProfitLabel}</th></tr></thead><tbody>{day.rows.map((item) => <tr key={item.key}><td><ProductIdentity imageUrl={item.imageUrl} name={item.itemName} detail={`${item.modelName || "Tanpa variasi"} · ${item.platformSku}`} /></td><td><Link className="font-mono text-xs font-bold text-emerald-700 hover:underline" href={`/orders?shop_id=${item.shopId}&q=${encodeURIComponent(item.orderSn)}`}>{item.orderSn}</Link><div className="mt-1 text-xs text-slate-500">{shopNameById.get(item.shopId) || item.shopId}</div></td><td className="text-right font-semibold">{item.quantity}</td><td className="text-right">{item.income === null ? <MissingValue text="Belum tersedia" /> : money(item.income)}</td><td className="text-right">{item.hpp === null ? <MissingValue text="Belum diisi" /> : money(item.hpp)}</td><td className={`text-right font-bold ${item.profit !== null && item.profit < 0 ? "text-rose-700" : profitView === "estimated" ? "text-cyan-700" : "text-emerald-700"}`}>{item.profit === null ? "-" : money(item.profit)}</td></tr>)}</tbody></table></div>{day.missingHppItems > 0 ? <div className="bg-amber-50 px-4 py-2 text-xs font-semibold text-amber-800 dark:bg-amber-950/30 dark:text-amber-300">{day.missingHppItems} item belum punya HPP Final; {activeProfitLabel.toLowerCase()} hari ini belum lengkap.</div> : null}</> : <div className="border-t border-slate-200 px-4 py-5 text-sm text-slate-500 dark:border-slate-800">Order terdata, tetapi rincian produknya belum tersedia.</div>}
                </details>;
              })}
              {activeProfitDays.length > 0 ? <div className="report-profit-total"><div className="report-day-date"><span aria-hidden="true">∑</span><div><strong>Total keseluruhan</strong><small>{dateLabel(dateFrom)} – {dateLabel(dateTo)}</small></div></div><div className={`report-profit-block is-${profitView === "estimated" ? "estimate" : "realized"}`}><div className="report-profit-block-label"><span>{activeProfitLabel}</span>{activeProfitSummary.unconfirmedOrders > 0 ? <em>{activeProfitSummary.unconfirmedOrders} belum lengkap</em> : <em className="is-complete">Lengkap</em>}</div><strong className={activeProfitSummary.profit < 0 ? "text-rose-700" : profitView === "estimated" ? "text-cyan-700" : "text-emerald-700"}>{money(activeProfitSummary.profit)}</strong><small>{activeProfitSummary.orders} order · Dana {money(activeProfitSummary.income)} · HPP Final {money(activeProfitSummary.hpp)}</small></div><a className="ui-button ui-button-primary report-no-print" href={profitPdfHref(dateFrom, dateTo)}>Unduh PDF</a><span aria-hidden="true" /></div> : null}
              {activeProfitDays.length === 0 ? <Empty title={`Belum ada ${activeProfitLabel.toLowerCase()}`} text="Tidak ada order pada toko dan periode ini." /> : null}
            </div>
          </Card>
        </section>
      ) : null}

      {tab === "products" ? (
        <section className="space-y-3">
          <section className="report-alert is-info"><div><b>Produk terlaris dihitung dari order valid yang dibuat pada periode ini.</b> Order batal, retur, dan belum dibayar tidak ikut. Urutan profit hanya memuat SKU dengan dana dan HPP Final lengkap; ini bukan laba bersih setelah iklan wallet.</div></section>
          <div className="report-subtabs report-no-print">
            <ProductViewLink active={productView === "best"} href={hrefFor("products", { productView: "best" })}>Terlaris</ProductViewLink>
            <ProductViewLink active={productView === "high_profit"} href={hrefFor("products", { productView: "high_profit" })}>Profit tertinggi</ProductViewLink>
            <ProductViewLink active={productView === "low_profit"} href={hrefFor("products", { productView: "low_profit" })}>Profit terendah</ProductViewLink>
            <ProductViewLink active={productView === "missing_hpp"} href={hrefFor("products", { productView: "missing_hpp" })}>HPP Final kosong</ProductViewLink>
          </div>
          <div className="grid gap-3 md:grid-cols-2" aria-label="Produk dengan profit tertinggi dan terendah">
            <ProductProfitHighlight
              title="Profit tertinggi"
              product={highestProfitProduct}
              emptyText="Belum ada produk dengan settlement dan HPP Final lengkap."
              tone="emerald"
              href={hrefFor("products", { productView: "high_profit" })}
            />
            <ProductProfitHighlight
              title="Profit terendah"
              product={lowestProfitProduct}
              emptyText="Belum ada produk dengan settlement dan HPP Final lengkap."
              tone="rose"
              href={hrefFor("products", { productView: "low_profit" })}
            />
          </div>
          <div className="report-kpi-grid is-four">
            <ReportMetric label="Order valid dibuat" value={summary.totalOrders.toLocaleString("id-ID")} hint={`${summary.quantitySold} item dipesan`} />
            <ReportMetric label="GMV" value={money(summary.omzet)} hint={`Rata-rata ${money(averageOrder)}`} />
            <ReportMetric label="Produk ditampilkan" value={productRows.length.toLocaleString("id-ID")} hint="Maksimal 50 SKU" />
            <ReportMetric label="HPP Final kosong" value={summary.missingHppItems.toLocaleString("id-ID")} hint={`${summary.hppCoverage}% cakupan`} tone={summary.missingHppItems ? "rose" : "emerald"} />
          </div>
          <ProductTable rows={productRows} shopId={activeShopId} />
        </section>
      ) : null}

      {tab === "sales" ? (
        <section className="space-y-3">
          <section className="report-alert is-info"><div><b>Patokan tanggal di tab ini adalah saat order dibuat.</b> Order yang belum memiliki tanggal dana masuk masih dapat menampilkan estimasi dana dan profit; jangan dibaca sebagai uang cair. Profit per order belum memuat iklan wallet dan kerugian retur periode.</div></section>
          <div className="report-subtabs report-no-print" aria-label="Filter status penjualan">
            {SALES_STATUSES.map((item) => <ProductViewLink active={salesStatus === item.value} href={hrefFor("sales", { salesStatus: item.value })} key={item.value}>{item.label}</ProductViewLink>)}
          </div>
          <div className="grid gap-3 sm:grid-cols-2 xl:grid-cols-4" aria-label="Kategori dampak penjualan">
            <ReportMetric label="Pengembalian" value={`${business.salesImpact.returns.orders} order`} hint={business.salesImpact.returns.refund === null ? "Nilai refund belum tersedia dari settlement" : `Refund tercatat ${money(business.salesImpact.returns.refund)} · ${business.salesImpact.returns.refundKnownOrders} order memiliki nilai`} tone={business.salesImpact.returns.orders ? "rose" : "neutral"} />
            <ReportMetric label="Selisih ongkir" value={business.salesImpact.shipping.difference === null ? "Belum tersedia" : money(business.salesImpact.shipping.difference)} hint={`${business.salesImpact.shipping.ordersWithData} order punya data actual ongkir & subsidi`} tone={(business.salesImpact.shipping.difference || 0) > 0 ? "rose" : "emerald"} />
            <ReportMetric label="Penyesuaian Shopee" value={business.salesImpact.adjustments.amount === null ? "Belum tersedia" : money(business.salesImpact.adjustments.amount)} hint={`${business.salesImpact.adjustments.ordersWithData} order mengirim field total_adjustment_amount`} tone={(business.salesImpact.adjustments.amount || 0) < 0 ? "rose" : "neutral"} />
            <ReportMetric label="Belum cair" value={money(business.salesImpact.notPaidOut.gross)} hint={`${business.salesImpact.notPaidOut.orders} order non-batal belum punya tanggal pelepasan dana`} tone={business.salesImpact.notPaidOut.orders ? "rose" : "neutral"} />
            <ReportMetric label="COD" value={money(business.salesImpact.cod.gross)} hint={`${business.salesImpact.cod.orders} order dengan metode Cash on Delivery`} />
            <ReportMetric label="COD batal" value={`${business.salesImpact.codCancelled.orders} order`} hint={`GMV tercatat ${money(business.salesImpact.codCancelled.gross)} · COD berstatus batal/proses batal`} tone={business.salesImpact.codCancelled.orders ? "rose" : "neutral"} />
            <ReportMetric label="Gagal kirim" value={`${business.salesImpact.deliveryFailed.orders} order`} hint={`Nilai order saat ini ${money(business.salesImpact.deliveryFailed.gross)} · status logistik gagal`} tone={business.salesImpact.deliveryFailed.orders ? "rose" : "neutral"} />
            <ReportMetric label="Barang hilang" value={`${business.salesImpact.lost.orders} order`} hint={business.salesImpact.lost.compensation === null ? "Kompensasi belum tersedia di data Shopee" : `${money(business.salesImpact.lost.compensation)} kompensasi tercatat pada ${business.salesImpact.lost.compensationKnownOrders} order`} tone={business.salesImpact.lost.orders ? "rose" : "neutral"} />
          </div>
          <section className="report-alert is-info"><div><b>Angka detail mengikuti data yang Shopee kirimkan.</b> “Belum tersedia” berarti field terkait tidak ada di data settlement tersimpan. Kategori dapat tumpang tindih—misalnya COD juga dapat belum cair atau batal—dan kartu ini adalah rincian/referensi, bukan potongan laba tambahan. Dana, pengembalian, ongkir, dan penyesuaian yang sudah masuk settlement tidak dihitung ulang.</div></section>
          <Card title="Daftar order" description={`Menampilkan ${business.orderDetails.length ? `1–${business.orderDetails.length}` : "0"} dari ${summary.totalOrders} order dibuat. Gunakan status untuk memisahkan order aktif, selesai, retur, dan batal.`}>
            <div className="overflow-x-auto">
              <table className="report-table min-w-[1480px]">
                <thead><tr><th>Detail pesanan</th><th>Tgl dibuat</th><th>Tgl dana masuk</th><th>Platform / metode</th><th className="text-right">Bruto order</th><th className="text-right">Potongan Shopee</th><th className="text-right">Dana Shopee</th><th className="text-right">HPP Final</th><th className="text-right">Profit order</th><th>Status kini</th><th>Aksi</th></tr></thead>
                <tbody>{business.orderDetails.map((order) => {
                  const statement = expenseByOrder.get(`${order.shopId}:${order.orderSn}`);
                  return <tr className="align-top" key={`${order.shopId}:${order.orderSn}`}><td><div className="min-w-[300px]"><Link className="font-mono text-xs font-bold text-emerald-700 hover:underline" href={`/orders?shop_id=${order.shopId}&q=${encodeURIComponent(order.orderSn)}`}>{order.orderSn}</Link><div className="mt-1 text-xs text-slate-500">{order.shopName} · {order.buyerName}</div><div className="mt-2 space-y-1.5">{order.items.map((item, index) => <div className="flex items-center gap-2" key={`${item.sku}:${index}`}>{item.imageUrl ? <img alt="" className="h-8 w-8 rounded-md border border-slate-200 object-cover" src={item.imageUrl} /> : <span className="h-8 w-8 rounded-md border border-dashed border-slate-300" />}<div className="min-w-0"><div className="max-w-[260px] truncate text-xs font-semibold">{item.itemName || "Produk"}</div><div className="font-mono text-[10px] text-slate-400">{item.modelName || item.sku} · {item.quantity}x</div></div></div>)}</div></div></td><td>{dateTimeLabel(order.createTime)}</td><td>{dateTimeLabel(order.releaseTime, SHOPEE_WALLET_TIME_ZONE)}</td><td><Badge tone="warning">Shopee</Badge>{/cash\s*on\s*delivery|\bcod\b/i.test(order.paymentMethod || "") ? <div className="mt-1"><Badge tone="info">COD</Badge></div> : null}<div className="mt-2 text-xs text-slate-500">{order.shippingCarrier}</div>{order.logisticsStatus === "LOGISTICS_DELIVERY_FAILED" ? <div className="mt-1"><Badge tone="danger">Gagal kirim</Badge></div> : null}{order.lostSignal ? <div className="mt-1"><Badge tone="danger">Indikasi barang hilang</Badge></div> : null}</td><td className="text-right font-semibold">{money(order.amount)}</td><td className="text-right">{statement ? money(statement.deductions) : order.platformFees ? money(order.platformFees) : "-"}</td><td className="text-right font-semibold">{order.income === null ? "Belum tersedia" : <>{money(order.income)}<div className={`mt-1 text-[10px] ${order.releaseTime ? "text-emerald-700" : "text-cyan-700"}`}>{order.releaseTime ? "Cair" : "Estimasi · belum cair"}</div></>}</td><td className="text-right">{order.missingHppItems ? <MissingValue text={`${order.missingHppItems} item kosong`} /> : money(order.hppFinal)}</td><td className={`text-right font-bold ${order.profit !== null && order.profit < 0 ? "text-rose-700" : order.releaseTime ? "text-emerald-700" : "text-cyan-700"}`}>{order.profit === null ? "-" : <>{money(order.profit)}<div className="mt-1 text-[10px] font-medium">{order.releaseTime ? "Order cair" : "Estimasi"}</div></>}</td><td><Badge tone={order.riskLate ? "danger" : statusTone(order.status)}>{order.riskLate ? "Risiko terlambat" : statusLabel(order.status)}</Badge></td><td><Link className="ui-button ui-button-secondary" href={`/orders?shop_id=${order.shopId}&q=${encodeURIComponent(order.orderSn)}`}>Buka</Link></td></tr>;
                })}</tbody>
              </table>
              {business.orderDetails.length === 0 ? <Empty title="Data tidak ditemukan" text="Ubah status, toko, periode, atau kata pencarian." /> : null}
            </div>
          </Card>
        </section>
      ) : null}

      {tab === "expenses" ? (
        <section className="space-y-4">
          <section className="report-alert is-info"><div><b>Satu halaman untuk semua uang keluar.</b> Pengeluaran eksternal yang Anda catat tampil bersama potongan dan iklan Shopee, tetapi sumbernya tetap dipisahkan. Jangan catat ulang iklan Shopee karena sudah disinkronkan otomatis.</div></section>
          <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3 2xl:grid-cols-6">
            <ReportMetric label="Potongan Shopee" value={money(financial.settlements.deductions)} hint={`${financial.settlements.orders} settlement`} tone="rose" />
            <ReportMetric label="Iklan Shopee" value={money(financial.settlements.marketingExpense)} hint="Settlement + Saldo Penjual" tone="rose" />
            <ReportMetric label="Platform & logistik" value={money(financial.settlements.platformExpense)} hint="Komisi, layanan, proses, ongkir" tone="rose" />
            <ReportMetric label="Kredit / subsidi" value={money(financial.settlements.additions)} hint="Dari marketplace" tone="emerald" />
            <ReportMetric label="Kas eksternal" value={money(financial.externalExpenses.cashOutflow)} hint="Semua catatan biaya luar Shopee" tone="rose" />
            <ReportMetric label="Beban eksternal laba" value={money(financial.externalExpenses.profitExpense)} hint="Catatan yang ditandai kurangi laba" tone="rose" />
          </div>

          <ExternalExpenseManager
            defaultDate={dateTo}
            rows={financial.externalExpenses.rows}
          />

          <Card title="Biaya dari Shopee" description="Ringkasan biaya hasil sinkronisasi settlement dan transaksi Saldo Penjual. Nilai merah adalah pengeluaran; hijau adalah kredit atau subsidi.">
            {financial.settlements.feeBreakdown.length ? <div className="grid gap-2 sm:grid-cols-2 xl:grid-cols-3">{financial.settlements.feeBreakdown.map((row) => <div className="flex min-w-0 items-center justify-between gap-3 rounded-xl border border-slate-100 bg-slate-50/70 p-3 dark:border-slate-800 dark:bg-slate-950/40" key={row.key}><div className="min-w-0"><div className="truncate text-sm font-semibold">{row.label}</div><div className="mt-1 text-[11px] text-slate-500">{row.group}</div></div><strong className={`shrink-0 tabular-nums ${row.amount < 0 ? "text-emerald-700" : "text-rose-700"}`}>{row.amount < 0 ? "+" : "-"}{money(Math.abs(row.amount))}</strong></div>)}</div> : <Empty title="Belum ada biaya Shopee" text="Tidak ada settlement atau transaksi wallet pada periode dan toko ini." />}
          </Card>

          <Card title="Rincian transaksi Shopee" description={`Menampilkan ${Math.min(financial.settlements.expenseRows.length, 250)} dari ${financial.settlements.expenseRows.length} potongan, kredit, dan transaksi iklan yang tersinkron.`}>
            <div className="overflow-x-auto">
              <table className="report-table min-w-[760px]"><thead><tr><th>Tanggal</th><th>Order / toko</th><th>Kategori</th><th>Sumber</th><th className="text-right">Nilai</th></tr></thead><tbody>{financial.settlements.expenseRows.slice(0, 250).map((row) => <tr key={row.key}><td className="whitespace-nowrap">{dateLabel(row.date, SHOPEE_WALLET_TIME_ZONE)}</td><td>{row.orderSn === "Transaksi wallet" ? <span className="font-semibold text-slate-600">Transaksi wallet</span> : <Link className="font-mono text-xs font-bold text-emerald-700 hover:underline" href={`/orders?shop_id=${row.shopId}&q=${encodeURIComponent(row.orderSn)}`}>{row.orderSn}</Link>}<div className="mt-1 text-xs text-slate-500">{row.shopName}</div></td><td className="font-semibold">{row.category}</td><td><Badge tone={row.amount < 0 ? "success" : row.group === "Pemasaran" ? "warning" : "neutral"}>{row.amount < 0 ? "Kredit" : row.group}</Badge></td><td className={`text-right font-bold tabular-nums ${row.amount < 0 ? "text-emerald-700" : "text-rose-700"}`}>{row.amount < 0 ? "+" : "-"}{money(Math.abs(row.amount))}</td></tr>)}</tbody></table>
              {financial.settlements.expenseRows.length === 0 ? <Empty title="Tidak ada transaksi pengeluaran Shopee" text="Biaya eksternal yang Anda catat tetap tersedia di atas." /> : null}
            </div>
          </Card>
        </section>
      ) : null}

      {tab === "losses" ? (
        <section className="space-y-4">
          <div className="report-kpi-grid is-four">
            <ReportMetric label="Retur & gagal kirim" value={financial.returns.orders.toLocaleString("id-ID")} hint={`${financial.returns.items} item terdampak`} tone={financial.returns.orders ? "rose" : "neutral"} />
            <ReportMetric label="Kerugian HPP Awal" value={money(financial.returns.inventoryLoss)} hint="Biaya supplier untuk barang terdampak" tone={financial.returns.inventoryLoss ? "rose" : "neutral"} />
            <ReportMetric label="Dampak settlement" value={money(financial.returns.settlementLoss)} hint="Refund dan ongkir balik" />
            <ReportMetric label="Total dampak kerugian" value={money(financial.returns.totalImpact)} hint={financial.returns.missingHppItems ? `${financial.returns.missingHppItems} item HPP Awal kosong` : "HPP Awal lengkap"} tone={financial.returns.totalImpact ? "rose" : "neutral"} />
          </div>
          {financial.returns.missingHppItems > 0 ? <section className="report-alert is-warning"><div><b>Valuasi kerugian belum lengkap.</b> {financial.returns.missingHppItems} barang retur/gagal kirim belum mempunyai HPP Awal (harga supplier).</div><Link className="ui-button ui-button-secondary report-no-print" href={`/products?shop_id=${activeShopId || "all"}&product_keys=${encodeURIComponent(Array.from(new Set(financial.returns.rows.filter((row) => row.unitHpp === null && row.itemId).map((row) => `${row.shopId}:${row.itemId}:${row.modelId || "0"}`))).join(","))}`}>Isi HPP Awal barang terdampak</Link></section> : null}
          <Card title="Barang Retur & Pengiriman Gagal" description="Setiap baris adalah barang terdampak. Dampak settlement yang sudah mengurangi dana cair tidak dikurangi dua kali pada laba-rugi.">
            <div className="overflow-x-auto">
              <table className="report-table min-w-[1160px]"><thead><tr><th>Barang</th><th>Order / toko</th><th>Tanggal</th><th>Status</th><th className="text-right">Qty terdampak</th><th className="text-right">HPP Awal / unit</th><th className="text-right">Kerugian HPP Awal</th><th className="text-right">Dampak settlement</th><th className="text-right">Total dampak</th></tr></thead><tbody>{financial.returns.rows.map((row) => <tr key={row.key}><td><ProductIdentity imageUrl={row.imageUrl} name={row.itemName} detail={`${row.modelName || "Tanpa variasi"} · ${row.platformSku}${row.masterSku ? ` · ${row.masterSku}` : ""}`} /></td><td><Link className="font-mono text-xs font-bold text-emerald-700 hover:underline" href={`/orders?shop_id=${row.shopId}&q=${encodeURIComponent(row.orderSn)}`}>{row.orderSn}</Link><div className="mt-1 text-xs text-slate-500">{row.shopName}</div></td><td>{dateTimeLabel(row.date)}</td><td><Badge tone="danger">{statusLabel(row.status)}</Badge></td><td className="text-right font-bold">{row.quantity}</td><td className="text-right">{row.unitHpp === null ? <MissingValue text="Belum diisi" /> : money(row.unitHpp)}</td><td className="text-right font-bold text-rose-700">{row.hppLoss === null ? "-" : money(row.hppLoss)}</td><td className="text-right">{money(row.settlementImpact)}</td><td className="text-right font-bold text-rose-700">{row.totalImpact === null ? "-" : money(row.totalImpact)}</td></tr>)}</tbody></table>
              {financial.returns.rows.length === 0 ? <Empty title="Tidak ada kerugian" text="Tidak ada retur atau pengiriman gagal pada toko dan periode ini." /> : null}
            </div>
          </Card>
        </section>
      ) : null}
    </div>
  );
}

function StatementSection({ title, children }: { title: string; children: React.ReactNode }) {
  return <div className="mt-4 first:mt-0"><div className="border-b border-slate-200 pb-2 text-[10px] font-bold uppercase tracking-[0.08em] text-slate-500 dark:border-slate-800">{title}</div><div>{children}</div></div>;
}

function StatementRow({ label, value, textValue, note, strong = false, muted = false, tone = "neutral" }: { label: string; value?: number; textValue?: string; note?: string; strong?: boolean; muted?: boolean; tone?: "neutral" | "success" | "danger" }) {
  const valueTone = tone === "success" ? "text-emerald-700" : tone === "danger" ? "text-rose-700" : "text-slate-950 dark:text-white";
  return <div className={`flex items-start justify-between gap-4 border-b border-slate-100 py-3 dark:border-slate-800 ${strong ? "bg-slate-50 px-3 dark:bg-slate-950" : ""}`}><div><div className={`${strong ? "font-bold" : "font-medium"} ${muted ? "text-slate-500" : "text-slate-700 dark:text-slate-200"}`}>{label}</div>{note ? <div className="mt-0.5 text-[11px] text-slate-400">{note}</div> : null}</div><strong className={`whitespace-nowrap ${valueTone}`}>{textValue || money(value)}</strong></div>;
}

function ReportMetric({ label, value, hint, tone = "neutral" }: { label: string; value: string; hint: string; tone?: "neutral" | "emerald" | "rose" }) {
  const color = tone === "emerald" ? "text-emerald-700" : tone === "rose" ? "text-rose-700" : "text-slate-950 dark:text-white";
  return <div className="report-kpi"><div className="summary-label">{label}</div><div className={`summary-value ${color}`}>{value}</div><div className="summary-hint">{hint}</div></div>;
}

function ProductTable({ rows, shopId }: { rows: ProductPerformance[]; shopId: string | null }) {
  return <Card title="Performa Produk" description="Profit per unit = profit order dibagi jumlah terjual. Margin dihitung dari profit order terhadap dana settlement teralokasi. Biaya iklan wallet belum dibagi ke setiap SKU.">
    <div className="overflow-x-auto">
      <table className="report-table min-w-[1320px]">
        <thead><tr><th>Produk / toko</th><th>SKU</th><th className="text-right">Terjual</th><th className="text-right">GMV</th><th className="text-right">Dana settlement</th><th className="text-right">HPP Final</th><th className="text-right">Profit / unit</th><th className="text-right">Margin</th><th className="text-right">Total profit order</th><th>Kualitas data</th></tr></thead>
        <tbody>{rows.map((row) => {
          const complete = row.missingHpp === 0 && row.missingIncome === 0 && row.quantity > 0;
          const unitProfit = complete ? row.profitEstimate / row.quantity : null;
          const margin = complete && row.income > 0 ? row.profitEstimate / row.income * 100 : null;
          return <tr key={row.key}>
            <td><ProductIdentity imageUrl={row.imageUrl} name={row.productName} detail={row.shopName} /></td>
            <td><Link className="font-mono text-xs font-semibold text-emerald-700 hover:underline" href={`/products?shop_id=${shopId || row.shopId}&q=${encodeURIComponent(row.sku)}`}>{row.sku}</Link></td>
            <td className="text-right font-bold">{row.quantity}</td>
            <td className="text-right">{money(row.omzet)}</td>
            <td className="text-right">{row.missingIncome ? <MissingValue text="Belum lengkap" /> : money(row.income)}</td>
            <td className="text-right">{money(row.hpp)}</td>
            <td className={`text-right font-bold ${unitProfit === null ? "text-slate-400" : unitProfit < 0 ? "text-rose-700" : "text-emerald-700"}`}>{unitProfit === null ? "—" : money(unitProfit)}</td>
            <td className={`text-right font-semibold ${margin === null ? "text-slate-400" : margin < 0 ? "text-rose-700" : "text-emerald-700"}`}>{margin === null ? "—" : `${margin.toFixed(1)}%`}</td>
            <td className={`text-right font-bold ${row.profitEstimate < 0 ? "text-rose-700" : "text-emerald-700"}`}>{money(row.profitEstimate)}</td>
            <td><Badge tone={row.missingHpp || row.missingIncome ? "warning" : "success"}>{row.missingHpp ? `${row.missingHpp} HPP Final kosong` : row.missingIncome ? `${row.missingIncome} settlement kosong` : "Lengkap"}</Badge></td>
          </tr>;
        })}</tbody>
      </table>
      {rows.length === 0 ? <Empty title="Tidak ada produk" text="Tidak ada produk pada kategori dan periode ini." /> : null}
    </div>
  </Card>;
}

function StoreProfitBreakdownTable({ rows }: { rows: StoreProfitBreakdown[] }) {
  const sum = (select: (row: StoreProfitBreakdown) => number) => rows.reduce((total, row) => total + select(row), 0);
  const statusLabel = (status: StoreProfitBreakdown["status"]) => ({
    UNTUNG: "Untung",
    IKLAN_TINGGI: "Iklan tinggi",
    IKLAN_OVER: "Iklan over",
    HPP_BONCOS: "HPP boncos",
    BONCOS_RETUR: "Boncos retur",
    BONCOS_IKLAN: "Boncos · iklan over",
    BONCOS_OPERASIONAL: "Boncos · operasional",
  })[status];
  const statusTone = (status: StoreProfitBreakdown["status"]): "success" | "warning" | "danger" => status === "UNTUNG" ? "success" : status === "IKLAN_TINGGI" ? "warning" : "danger";
  return (
    <Card title="Sumber Profit & Boncos per Toko" description="Dana cair penuh dan basis yang sudah punya HPP dipisahkan. Baris paling boncos ditampilkan paling atas.">
      <div className="mb-3 text-xs text-slate-500">Iklan settlement sudah terpotong dari dana cair; total iklan dipakai untuk membaca belanja dan batas anggaran, bukan dikurangi ulang. Hanya autodebet wallet yang dikurangi lagi dari profit.</div>
      <div className="overflow-x-auto">
        <table className="report-table min-w-[2050px]">
          <thead><tr><th>Toko</th><th className="text-right">Dana cair total</th><th className="text-right">Dana dengan HPP</th><th className="text-right">Harga supplier (HPP Awal)</th><th className="text-right">Pos biaya selisih HPP</th><th className="text-right">HPP Final</th><th className="text-right">Profit order setelah HPP Final</th><th className="text-right">Iklan settlement (sudah terpotong)</th><th className="text-right">Iklan wallet (pengurang tambahan)</th><th className="text-right">Total iklan (info)</th><th className="text-right">Hasil pos biaya</th><th className="text-right">Laba setelah penyesuaian</th><th className="text-right">Retur/gagal (HPP Awal)</th><th className="text-right">Beban eksternal</th><th className="text-right">Profit riil terhitung</th><th className="text-right">Iklan / pos biaya</th><th>Status</th></tr></thead>
          <tbody>{rows.map((row) => (
            <tr key={row.shopId}>
              <td><div className="font-semibold">{row.shopName}</div><div className="mt-1 font-mono text-[10px] text-slate-400">{row.shopId}</div>{row.releasedIncome > row.income ? <div className="mt-1 text-[10px] font-semibold text-amber-700">{money(row.releasedIncome - row.income)} belum ber-HPP</div> : null}</td>
              <td className="text-right font-semibold">{money(row.releasedIncome)}</td>
              <td className="text-right font-semibold">{money(row.income)}</td>
              <td className="text-right text-rose-700">{money(-row.hppAwal)}</td>
              <td className="text-right font-bold text-emerald-700">{money(row.adsBudget)}</td>
              <td className="text-right text-rose-700">{money(-row.hppFinal)}</td>
              <td className={`text-right font-bold ${row.profitBeforeAds < 0 ? "text-rose-700" : "text-emerald-700"}`}>{money(row.profitBeforeAds)}</td>
              <td className="text-right font-bold text-slate-600">{money(row.settlementAds)}</td>
              <td className={`text-right font-bold ${row.walletAds > 0 ? "text-rose-700" : "text-emerald-700"}`}>{money(-row.walletAds)}</td>
              <td className="text-right font-bold text-slate-600">{money(row.totalAds)}</td>
              <td className={`text-right font-bold ${row.adsBudgetResult < 0 ? "text-rose-700" : "text-emerald-700"}`}>{money(row.adsBudgetResult)}</td>
              <td className={`text-right font-bold ${row.afterAds < 0 ? "text-rose-700" : "text-emerald-700"}`}>{money(row.afterAds)}</td>
              <td className="text-right text-rose-700">{money(-row.inventoryLoss)}</td>
              <td className="text-right text-rose-700">{money(-row.externalExpenses)}</td>
              <td className={`text-right font-bold ${row.netProfit < 0 ? "text-rose-700" : "text-emerald-700"}`}>{money(row.netProfit)}</td>
              <td className={`text-right font-bold ${row.adsShare === null || row.adsShare >= 100 ? "text-rose-700" : row.adsShare >= 80 ? "text-amber-700" : "text-slate-700"}`}>{row.adsShare === null ? "Tidak ada batas" : `${Math.round(row.adsShare)}%`}</td>
              <td><Badge tone={statusTone(row.status)}>{statusLabel(row.status)}</Badge></td>
            </tr>
          ))}</tbody>
          {rows.length > 0 ? <tfoot><tr className="border-t-2 border-slate-300 bg-slate-50 font-bold dark:border-slate-700 dark:bg-slate-900">
            <td>Total semua toko</td>
            <td className="text-right">{money(sum((row) => row.releasedIncome))}</td>
            <td className="text-right">{money(sum((row) => row.income))}</td>
            <td className="text-right">{money(-sum((row) => row.hppAwal))}</td>
            <td className="text-right">{money(sum((row) => row.adsBudget))}</td>
            <td className="text-right">{money(-sum((row) => row.hppFinal))}</td>
            <td className="text-right">{money(sum((row) => row.profitBeforeAds))}</td>
            <td className="text-right">{money(sum((row) => row.settlementAds))}</td>
            <td className="text-right">{money(-sum((row) => row.walletAds))}</td>
            <td className="text-right">{money(sum((row) => row.totalAds))}</td>
            <td className="text-right">{money(sum((row) => row.adsBudgetResult))}</td>
            <td className="text-right">{money(sum((row) => row.afterAds))}</td>
            <td className="text-right">{money(-sum((row) => row.inventoryLoss))}</td>
            <td className="text-right">{money(-sum((row) => row.externalExpenses))}</td>
            <td className="text-right">{money(sum((row) => row.netProfit))}</td>
            <td className="text-right">—</td><td>—</td>
          </tr></tfoot> : null}
        </table>
        {rows.length === 0 ? <Empty title="Belum ada basis profit per toko" text="Belum ada settlement dengan HPP Final atau transaksi iklan pada periode ini." /> : null}
      </div>
    </Card>
  );
}

function StorePerformance({ rows }: { rows: BusinessReport["salesByShop"] }) {
  return <Card title="Order masuk per Toko" description="Bagian ini memakai tanggal order dibuat, bukan tanggal dana cair. Lihat tabel profit per toko di atas untuk transaksi settlement periode ini."><div className="overflow-x-auto"><table className="report-table min-w-[680px]"><thead><tr><th>Toko</th><th className="text-right">Order dibuat</th><th className="text-right">GMV order</th><th className="text-right">Kini selesai</th><th className="text-right">Kini batal / retur</th></tr></thead><tbody>{rows.map((row) => <tr key={row.shopId}><td className="font-semibold">{row.shopName}</td><td className="text-right">{row.orders}</td><td className="text-right font-semibold">{money(row.omzet)}</td><td className="text-right text-emerald-700">{row.completed}</td><td className="text-right text-rose-700">{row.cancelled}</td></tr>)}</tbody></table>{rows.length === 0 ? <Empty title="Belum ada order baru" text="Pada periode ini tidak ada order baru; settlement dari order lama tetap tampil pada bagian profit di atas." /> : null}</div></Card>;
}

function ProductProfitHighlight({ title, product, emptyText, tone, href }: {
  title: string;
  product: ProductPerformance | null;
  emptyText: string;
  tone: "emerald" | "rose";
  href: string;
}) {
  const valueTone = tone === "rose" ? "text-rose-700" : "text-emerald-700";
  const borderTone = tone === "rose" ? "border-rose-200 bg-rose-50/60" : "border-emerald-200 bg-emerald-50/60";
  return <Link className={`block rounded-2xl border p-4 transition hover:shadow-sm ${borderTone}`} href={href}>
    <div className="text-xs font-bold uppercase tracking-wide text-slate-500">{title}</div>
    {product ? <div className="mt-2 flex items-start justify-between gap-4">
      <div className="flex min-w-0 items-center gap-3">
        {product.imageUrl ? <img alt="" className="h-12 w-12 shrink-0 rounded-lg border border-white object-cover" src={product.imageUrl} /> : null}
        <div className="min-w-0"><div className="line-clamp-2 font-bold text-slate-900">{product.productName}</div><div className="mt-1 truncate text-xs text-slate-500">{product.shopName} · SKU {product.sku} · {product.quantity} terjual</div></div>
      </div>
      <div className="shrink-0 text-right"><strong className={`block text-lg tabular-nums ${valueTone}`}>{money(product.profitEstimate)}</strong><span className="text-[11px] text-slate-600">{money(product.profitEstimate / product.quantity)} / unit</span></div>
    </div> : <p className="mt-2 text-sm text-slate-500">{emptyText}</p>}
    <div className="mt-2 text-[11px] text-slate-500">Profit order setelah HPP Final, sebelum penyesuaian iklan wallet · Lihat daftar →</div>
  </Link>;
}

function ProductIdentity({ imageUrl, name, detail }: { imageUrl: string | null; name: string; detail?: string }) {
  return <div className="flex min-w-[280px] items-center gap-3">{imageUrl ? <img alt="" className="h-11 w-11 shrink-0 rounded-lg border border-slate-200 object-cover" src={imageUrl} /> : <div className="h-11 w-11 shrink-0 rounded-lg border border-dashed border-slate-300" />}<div className="min-w-0"><div className="line-clamp-2 font-semibold">{name}</div>{detail ? <div className="mt-1 max-w-[380px] truncate font-mono text-[10px] text-slate-400">{detail}</div> : null}</div></div>;
}

function ProductViewLink({ active, href, children }: { active: boolean; href: string; children: React.ReactNode }) {
  return <a aria-current={active ? "page" : undefined} className={`rounded-lg border px-3 py-2 text-xs font-semibold ${active ? "border-slate-950 bg-slate-950 text-white dark:border-emerald-400 dark:bg-emerald-400 dark:text-slate-950" : "border-slate-200 bg-white text-slate-600 hover:bg-slate-50 dark:border-slate-700 dark:bg-slate-900 dark:text-slate-300"}`} href={href}>{children}</a>;
}

function MissingValue({ text }: { text: string }) {
  return <span className="text-xs font-semibold text-amber-700">{text}</span>;
}

function Empty({ title, text }: { title: string; text: string }) {
  return <div className="py-12 text-center"><div className="font-semibold text-slate-700 dark:text-slate-200">{title}</div><div className="mt-1 text-sm text-slate-500">{text}</div></div>;
}
