/* eslint-disable @next/next/no-img-element */
import Link from "next/link";
import Badge from "@/components/ui/Badge";
import Card from "@/components/ui/Card";
import ReportFilters from "@/components/reports/ReportFilters";
import HistoricalReconcile from "@/components/finance/HistoricalReconcile";
import { monthOptions, periodRange } from "@/lib/dateRange";
import { getFinancialStatementReport } from "@/lib/financialStatementReport";
import { calculateProfitAccounting } from "@/lib/profitAccounting";
import { getProfitReport } from "@/lib/profitReport";
import { shopRepository } from "@/lib/repositories/shopRepository";
import { resolveShopScope, restrictedShopIds } from "@/lib/storeScope";
import { getCurrentUser } from "@/lib/currentUser";

export const dynamic = "force-dynamic";

type SearchParams = Promise<Record<string, string | string[] | undefined>>;
type DetailMode = "estimated" | "in_transit" | "realized";
type ProfitReport = Awaited<ReturnType<typeof getProfitReport>>;
type ProfitDetailRow = ProfitReport["details"]["estimated"][number];
type ProfitPanelRow = {
  label: string;
  value: string | number;
  hint: string;
  href?: string;
  active?: boolean;
};

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 itemMargin(profit: number | null, income: number | null) {
  return profit !== null && income !== null && income > 0 ? (profit / income) * 100 : null;
}

function percent(value: number) {
  return `${Math.round(value)}%`;
}

function dateLabel(value: string | Date | null) {
  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", { weekday: "short", day: "numeric", month: "short", year: "numeric" }).format(date);
}

function detailMode(value: string | undefined): DetailMode | null {
  return value === "estimated" || value === "in_transit" || value === "realized" ? value : null;
}

function statusLabel(status: string | null) {
  if (status === "COMPLETED") return "Selesai";
  if (status === "SHIPPED") return "Dikirim";
  if (status === "TO_CONFIRM_RECEIVE") return "Menunggu diterima";
  if (status === "READY_TO_SHIP") return "Siap diproses";
  if (status === "PROCESSED") return "Diproses";
  return status || "-";
}

function statusTone(status: string | null) {
  if (status === "COMPLETED") return "success" as const;
  if (status === "READY_TO_SHIP" || status === "PROCESSED") return "warning" as const;
  return "neutral" as const;
}

export default async function FinancePage({ 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 period = firstParam(params.period) || "today";
  const selectedDetail = detailMode(firstParam(params.detail));
  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`);
  const [profit, financial] = await Promise.all([
    getProfitReport({ shopId: activeShopId, shopIds, dateFrom: fromDate, dateTo: toDate }),
    getFinancialStatementReport({ shopId: activeShopId, shopIds, expenseOwnerIds: current ? [current.ownerId || current.id] : [], dateFrom: fromDate, dateTo: toDate }),
  ]);
  const estimated = profit.estimated;
  const inTransit = profit.inTransit;
  const realized = profit.realized;
  const exportParams = new URLSearchParams({ shop_id: activeShopId || "all", date_from: dateFrom, date_to: dateTo, report: "profit" });
  const estimatedMargin = estimated.confirmedIncome > 0 ? (estimated.profit / estimated.confirmedIncome) * 100 : 0;
  const inTransitMargin = inTransit.confirmedIncome > 0 ? (inTransit.profit / inTransit.confirmedIncome) * 100 : 0;
  const realizedMargin = realized.confirmedIncome > 0 ? (realized.profit / realized.confirmedIncome) * 100 : 0;
  const confirmedItems = profit.details.realized.filter((row) => row.incomeSource === "settlement" && row.hpp !== null);
  const settlementAds = financial.settlements.expenseRows.filter((row) => row.key.endsWith(":marketing_credit")).reduce((sum, row) => sum + row.amount, 0);
  const accounting = calculateProfitAccounting({
    confirmedIncome: confirmedItems.reduce((sum, row) => sum + (row.income || 0), 0),
    initialHpp: confirmedItems.reduce((sum, row) => sum + (row.hppAwal ?? row.hpp ?? 0), 0),
    finalHpp: confirmedItems.reduce((sum, row) => sum + (row.hpp || 0), 0),
    settlementAds,
    walletAds: financial.settlements.walletMarketingExpense,
    inventoryLoss: financial.returns.inventoryLoss,
    externalProfitExpenses: financial.externalExpenses.profitExpense,
  });
  const knownItemProfit = confirmedItems.reduce((sum, row) => sum + (row.income || 0) - (row.hpp || 0), 0);
  const partialOrderItemProfit = knownItemProfit - realized.profit;
  const shopNameById = new Map(shops.map((shop) => [shop.shopId, shop.shopName || shop.shopId]));
  const missingHppProductKeys = Array.from(new Set(
    [...profit.details.estimated, ...profit.details.inTransit, ...profit.details.realized]
      .filter((row) => row.hpp === null && row.itemId)
      .map((row) => `${row.shopId}:${row.itemId}:${row.modelId || "0"}`),
  ));
  const hppRepairParams = new URLSearchParams({
    shop_id: activeShopId || "all",
  });
  if (missingHppProductKeys.length > 0) hppRepairParams.set("product_keys", missingHppProductKeys.join(","));
  const hppRepairHref = `/products?${hppRepairParams.toString()}`;

  function financeHref(nextDetail: DetailMode | null) {
    const query = new URLSearchParams({ shop_id: activeShopId || "all", period });
    if (period === "custom") {
      query.set("date_from", dateFrom);
      query.set("date_to", dateTo);
    }
    if (nextDetail) query.set("detail", nextDetail);
    return `/finance?${query.toString()}${nextDetail ? "#rincian-barang" : ""}`;
  }

  return (
    <div className="space-y-5">
      <section className="flex flex-wrap items-center justify-between gap-3">
        <div><h1 className="page-title">Profit</h1><p className="mt-1 text-sm text-slate-500">Estimasi mengikuti order masuk; hasil pesanan mengikuti dana masuk Saldo Penjual. Profit bersih setelah iklan ditampilkan terpisah.</p></div>
        <div className="flex gap-2"><Link className="ui-button ui-button-secondary" href={`/products?shop_id=${encodeURIComponent(activeShopId || "all")}&filter=hpp_missing`}>Lengkapi HPP</Link><a className="ui-button ui-button-primary" href={`/api/reports/export?${exportParams.toString()}`}>Ekspor CSV</a></div>
      </section>

      <ReportFilters key={`${activeShopId || "all"}:${period}:${dateFrom}:${dateTo}`} basePath="/finance" shops={shops} activeShopId={activeShopId} period={period} dateFrom={dateFrom} dateTo={dateTo} defaultPeriod="today" months={monthOptions()} />

      {activeShopId && activeShopId !== "all" && <HistoricalReconcile shopId={activeShopId} />}

      <Card title="Rekonsiliasi profit riil bersih" description="Basis toko dan periode sama dengan Laporan. Profit order dipisahkan dari penyesuaian iklan dan kerugian retur.">
        <div className="grid gap-x-6 sm:grid-cols-2 lg:grid-cols-6">
          <FinanceMetric label="Profit item dengan HPP terisi" value={knownItemProfit} />
          <FinanceMetric label="Iklan settlement (sudah terpotong)" value={settlementAds} />
          <FinanceMetric label="Iklan wallet (pengurang tambahan)" value={financial.settlements.walletMarketingExpense} />
          <FinanceMetric label="Pos biaya selisih HPP" value={accounting.adsBudget} />
          <FinanceMetric label="Biaya eksternal" value={financial.externalExpenses.profitExpense} />
          <FinanceMetric label="Profit riil bersih" value={accounting.netProfit} emphasis />
        </div>
        <p className="mt-2 text-xs text-slate-500">Profit order = dana settlement bersih setelah potongan Shopee − HPP Final. Iklan settlement sudah termasuk dalam potongan tersebut dan tidak dikurangi lagi; autodebet wallet dikurangi sebagai pengeluaran setelah dana cair. Profit bersih juga merekonsiliasi pos biaya dari selisih HPP Awal–Final dan kerugian inventori. Profit order lengkap {money(realized.profit)} tidak memasukkan seluruh order yang masih memiliki item tanpa HPP; {partialOrderItemProfit !== 0 ? `${money(partialOrderItemProfit)} berasal dari item dengan HPP terisi dalam order parsial. ` : ""}</p>
      </Card>

      <div className="grid gap-5 xl:grid-cols-3">
        <ProfitPanel eyebrow="ORDER MASUK" title="Estimasi profit" description="Untuk keputusan operasional hari ini" tone="estimate" rows={[{ label: "Order valid", value: estimated.orders, hint: `${estimated.quantity} item · Lihat barang →`, href: financeHref("estimated"), active: selectedDetail === "estimated" }, { label: "Estimasi dana Shopee", value: estimated.orders ? money(estimated.income) : "Belum ada", hint: estimated.provisionalIncomeOrders ? `${estimated.provisionalIncomeOrders} masih pakai nilai bruto` : estimated.orders ? "Settlement terdata" : "Menunggu order valid" }, { label: "Basis dana terkonfirmasi", value: estimated.orders ? money(estimated.confirmedIncome) : "Belum ada", hint: `${estimated.confirmedOrders} order lengkap` }, { label: "HPP Final + packing", value: estimated.orders ? money(estimated.hpp) : "Belum ada", hint: estimated.orders ? `${percent(estimated.hppCoverage)} coverage item` : "Belum ada item" }]} profit={estimated.profit} margin={estimatedMargin} coverage={estimated.profitCoverage} orders={estimated.orders} unconfirmed={estimated.unconfirmedOrders} />
        <ProfitPanel eyebrow="DALAM PENGIRIMAN" title="Uang berjalan" description="Snapshot SHIPPED; berkurang otomatis saat order selesai" tone="transit" profitLabel="Potensi profit" rows={[{ label: "Pesanan sedang dikirim", value: inTransit.orders, hint: `${inTransit.quantity} item · Lihat barang →`, href: financeHref("in_transit"), active: selectedDetail === "in_transit" }, { label: "Dana berjalan", value: inTransit.orders ? money(inTransit.income) : "Belum ada", hint: inTransit.provisionalIncomeOrders ? `${inTransit.provisionalIncomeOrders} masih memakai nilai order` : inTransit.orders ? "Estimasi dana Shopee tersedia" : "Tidak ada barang dalam pengiriman" }, { label: "Dana dengan HPP lengkap", value: inTransit.orders ? money(inTransit.confirmedIncome) : "Belum ada", hint: `${inTransit.confirmedOrders}/${inTransit.orders} order lengkap` }, { label: "HPP Final + packing", value: inTransit.orders ? money(inTransit.hpp) : "Belum ada", hint: inTransit.orders ? `${percent(inTransit.hppCoverage)} coverage item` : "Belum ada item" }]} profit={inTransit.profit} margin={inTransitMargin} coverage={inTransit.profitCoverage} orders={inTransit.orders} unconfirmed={inTransit.unconfirmedOrders} />
        <ProfitPanel eyebrow="DANA MASUK" title="Profit riil" description="Realisasi berdasarkan tanggal transaksi Saldo Penjual" tone="realized" rows={[{ label: "Settlement masuk", value: realized.orders, hint: `${realized.quantity} item · Lihat barang →`, href: financeHref("realized"), active: selectedDetail === "realized" }, { label: "Dana settlement", value: realized.orders ? money(realized.income) : "Belum ada", hint: realized.orders ? `${percent(realized.incomeCoverage)} coverage` : "Menunggu transaksi Saldo Penjual" }, { label: "Basis dana terkonfirmasi", value: realized.orders ? money(realized.confirmedIncome) : "Belum ada", hint: `${realized.confirmedOrders} order lengkap` }, { label: "HPP Final + packing", value: realized.orders ? money(realized.hpp) : "Belum ada", hint: realized.orders ? `${percent(realized.hppCoverage)} coverage item` : "Belum ada settlement" }]} profit={realized.profit} margin={realizedMargin} coverage={realized.profitCoverage} orders={realized.orders} unconfirmed={realized.unconfirmedOrders} />
      </div>

      {selectedDetail ? (
        <ProfitItemDetails
          closeHref={financeHref(null)}
          estimatedHref={financeHref("estimated")}
          estimatedQuantity={estimated.quantity}
          inTransitHref={financeHref("in_transit")}
          inTransitQuantity={inTransit.quantity}
          mode={selectedDetail}
          realizedHref={financeHref("realized")}
          realizedQuantity={realized.quantity}
          rows={selectedDetail === "in_transit" ? profit.details.inTransit : profit.details[selectedDetail]}
          shopNameById={shopNameById}
          summary={selectedDetail === "estimated" ? estimated : selectedDetail === "in_transit" ? inTransit : realized}
        />
      ) : null}

      {estimated.orders === 0 && inTransit.orders === 0 && realized.orders === 0 ? (
        <section className="rounded-2xl border border-slate-200 bg-slate-50 p-4 text-sm font-bold text-slate-700">Belum ada order valid, barang dalam pengiriman, atau transaksi Saldo Penjual. Sinkronisasi live akan memeriksa ulang otomatis.</section>
      ) : estimated.unconfirmedOrders > 0 || inTransit.unconfirmedOrders > 0 || realized.unconfirmedOrders > 0 ? (
        <section className="grid gap-3 rounded-2xl border border-amber-200 bg-amber-50 p-4 sm:grid-cols-[1fr_auto] sm:items-center">
          <div><div className="font-black text-amber-950">Angka profit belum 100% lengkap</div><p className="mt-1 text-sm text-amber-800">{estimated.unconfirmedOrders} estimasi dan {inTransit.unconfirmedOrders} dalam pengiriman belum lengkap. {realized.missingIncomeOrders === 0 ? `Seluruh ${realized.orders} settlement periode ini sudah bernominal; ${realized.unconfirmedOrders} order realisasi tertahan karena HPP atau detail barang.` : `${realized.unconfirmedOrders} realisasi tertahan karena dana settlement, HPP Final, atau detail barang.`} {realized.missingItemDetailsOrders > 0 ? `${realized.missingItemDetailsOrders} order belum memiliki rincian barang Shopee; buka order dari rincian untuk memuat ulang detailnya. ` : ""}Sellfin tidak menebak nilai yang kosong.</p></div>
          {missingHppProductKeys.length > 0 ? <Link className="rounded-xl bg-amber-900 px-4 py-2.5 text-center text-sm font-black text-white hover:bg-amber-800" href={hppRepairHref}>Perbaiki {missingHppProductKeys.length} HPP</Link> : <Link className="rounded-xl bg-amber-900 px-4 py-2.5 text-center text-sm font-black text-white hover:bg-amber-800" href={financeHref(realized.unconfirmedOrders > 0 ? "realized" : inTransit.unconfirmedOrders > 0 ? "in_transit" : "estimated")}>{realized.missingItemDetailsOrders > 0 ? `Periksa ${realized.missingItemDetailsOrders} order` : "Lihat rincian"}</Link>}
        </section>
      ) : <section className="rounded-2xl border border-emerald-200 bg-emerald-50 p-4 text-sm font-bold text-emerald-900">Semua order pada periode ini sudah memiliki data dana dan HPP lengkap.</section>}

      <Card title="Profit harian: estimasi vs hasil order" description="Estimasi dicatat saat order masuk; hasil order saat uang masuk Saldo Penjual. Hasil order belum mencakup iklan wallet/retur, sehingga berbeda dari profit riil bersih di atas.">
        <div className="overflow-x-auto">
          <table className="w-full min-w-[1040px] text-sm">
            <thead className="bg-slate-50 text-left text-[11px] font-black uppercase tracking-wide text-slate-500"><tr><th className="rounded-l-xl px-3 py-3">Tanggal</th><th className="px-3 py-3 text-right">Order masuk</th><th className="px-3 py-3 text-right">Est. dana</th><th className="px-3 py-3 text-right">HPP Final</th><th className="px-3 py-3 text-right">Est. profit</th><th className="px-3 py-3 text-right">Order selesai</th><th className="px-3 py-3 text-right">Dana riil</th><th className="px-3 py-3 text-right">HPP Final</th><th className="rounded-r-xl px-3 py-3 text-right">Profit order</th></tr></thead>
            <tbody>{profit.daily.map((row) => <tr className="border-b border-slate-100" key={row.date}><td className="px-3 py-4 font-bold text-slate-950">{dateLabel(row.date)}</td><td className="px-3 py-4 text-right"><b>{row.estimatedOrders}</b>{row.estimatedUnconfirmed ? <div className="text-[11px] font-semibold text-amber-700">{row.estimatedUnconfirmed} belum lengkap</div> : null}</td><td className="px-3 py-4 text-right font-semibold">{money(row.estimatedIncome)}</td><td className="px-3 py-4 text-right">{money(row.estimatedHpp)}</td><td className={`px-3 py-4 text-right font-black ${row.estimatedProfit < 0 ? "text-rose-700" : "text-cyan-700"}`}>{money(row.estimatedProfit)}</td><td className="px-3 py-4 text-right"><b>{row.realizedOrders}</b>{row.realizedUnconfirmed ? <div className="text-[11px] font-semibold text-amber-700">{row.realizedUnconfirmed} belum lengkap</div> : null}</td><td className="px-3 py-4 text-right font-semibold">{money(row.realizedIncome)}</td><td className="px-3 py-4 text-right">{money(row.realizedHpp)}</td><td className={`px-3 py-4 text-right font-black ${row.realizedProfit < 0 ? "text-rose-700" : "text-emerald-700"}`}>{money(row.realizedProfit)}</td></tr>)}</tbody>
          </table>
          {profit.daily.length === 0 ? <div className="py-10 text-center text-sm text-slate-500">Belum ada aktivitas keuangan pada periode ini.</div> : null}
        </div>
      </Card>

      <Card title="Rekonsiliasi settlement Shopee" description="Hanya transaksi yang masuk Saldo Penjual pada periode ini, bukan tanggal order dibuat."><div className="grid gap-x-6 sm:grid-cols-2 lg:grid-cols-4"><FinanceMetric label="Omzet bruto settlement" value={financial.settlements.grossRevenue} /><FinanceMetric label="Potongan dari order" value={financial.settlements.deductions} /><FinanceMetric label="Kredit / subsidi order" value={financial.settlements.additions} /><FinanceMetric label="Dana cair" value={financial.settlements.netReleased} emphasis /></div><p className="mt-2 text-xs text-slate-500">Omzet bruto − potongan order + kredit order = dana cair. Top-up iklan dari wallet adalah transaksi terpisah, bukan potongan order kedua.</p></Card>
    </div>
  );
}

function ProfitPanel({ eyebrow, title, description, tone, profitLabel = "Profit", rows, profit, margin, coverage, orders, unconfirmed }: { eyebrow: string; title: string; description: string; tone: "estimate" | "transit" | "realized"; profitLabel?: string; rows: ProfitPanelRow[]; profit: number; margin: number; coverage: number; orders: number; unconfirmed: number }) {
  const displayTitle = tone === "realized" ? "Profit order terealisasi" : title;
  const displayDescription = tone === "realized" ? "Dana settlement − HPP Final; iklan wallet dan retur ada pada profit bersih di atas" : description;
  return <section className={`profit-panel is-${tone}`}>
    <div className="profit-panel-heading">
      <div>
        <div className="profit-panel-eyebrow">{eyebrow}</div>
        <h2>{displayTitle}</h2>
        <p>{displayDescription}</p>
      </div>
      <Badge tone={orders === 0 ? "neutral" : unconfirmed ? "warning" : "success"}>{orders === 0 ? "Belum ada data" : `${coverage}% lengkap`}</Badge>
    </div>
    <div className="profit-panel-total">
      <div><span>{tone === "realized" ? "Profit order" : profitLabel}</span><strong>{orders === 0 ? "Belum ada" : money(profit)}</strong></div>
      <div className="text-right"><span>Margin</span><strong>{orders === 0 ? "—" : `${margin.toFixed(1)}%`}</strong></div>
    </div>
    <div className="profit-panel-rows">{rows.map((row) => row.href ? <Link aria-current={row.active ? "location" : undefined} className={`profit-panel-row is-link ${row.active ? "is-active" : ""}`} href={row.href} key={row.label}><div><div>{row.label}</div><small>{row.hint}</small></div><strong>{row.value}</strong></Link> : <div className="profit-panel-row" key={row.label}><div><div>{row.label}</div><small>{row.hint}</small></div><strong>{row.value}</strong></div>)}</div>
    {unconfirmed > 0 ? <div className="profit-panel-note">{unconfirmed} order belum dihitung karena data belum lengkap.</div> : null}
  </section>;
}

function ProfitItemDetails({ mode, rows, summary, shopNameById, estimatedHref, estimatedQuantity, inTransitHref, inTransitQuantity, realizedHref, realizedQuantity, closeHref }: {
  mode: DetailMode;
  rows: ProfitDetailRow[];
  summary: ProfitReport["estimated"];
  shopNameById: Map<string, string>;
  estimatedHref: string;
  estimatedQuantity: number;
  inTransitHref: string;
  inTransitQuantity: number;
  realizedHref: string;
  realizedQuantity: number;
  closeHref: string;
}) {
  const estimatedMode = mode === "estimated";
  const inTransitMode = mode === "in_transit";
  const detailTitle = estimatedMode ? "Barang dari order valid" : inTransitMode ? "Barang sedang dalam pengiriman" : "Barang dari order selesai";
  const detailDescription = inTransitMode
    ? `${summary.quantity.toLocaleString("id-ID")} item dari ${summary.orders.toLocaleString("id-ID")} pesanan yang saat ini masih dikirim.`
    : `${summary.quantity.toLocaleString("id-ID")} item dari ${summary.orders.toLocaleString("id-ID")} pesanan pada toko dan periode yang dipilih.`;
  const orderedRows = [...rows].sort((a, b) => Number(a.profit !== null) - Number(b.profit !== null));
  return (
    <section className="scroll-mt-4 overflow-hidden rounded-2xl border border-slate-200 bg-white shadow-sm" id="rincian-barang">
      <div className="flex flex-wrap items-start justify-between gap-4 border-b border-slate-200 px-4 py-4 sm:px-5">
        <div>
          <div className="text-xs font-black uppercase tracking-[0.12em] text-emerald-700">Rincian barang</div>
          <h2 className="mt-1 text-lg font-black text-slate-950">{detailTitle}</h2>
          <p className="mt-1 text-sm text-slate-500">{detailDescription}</p>
        </div>
        <Link className="ui-button ui-button-secondary" href={closeHref}>Tutup rincian</Link>
      </div>
      <nav className="flex gap-1 overflow-x-auto border-b border-slate-200 bg-slate-50 px-4 py-2" aria-label="Jenis rincian profit">
        <Link aria-current={estimatedMode ? "page" : undefined} className={`whitespace-nowrap rounded-lg px-3 py-2 text-xs font-bold ${estimatedMode ? "bg-slate-950 text-white" : "text-slate-600 hover:bg-white"}`} href={estimatedHref}>Order masuk · {estimatedQuantity.toLocaleString("id-ID")} item</Link>
        <Link aria-current={inTransitMode ? "page" : undefined} className={`whitespace-nowrap rounded-lg px-3 py-2 text-xs font-bold ${inTransitMode ? "bg-slate-950 text-white" : "text-slate-600 hover:bg-white"}`} href={inTransitHref}>Dalam pengiriman · {inTransitQuantity.toLocaleString("id-ID")} item</Link>
        <Link aria-current={mode === "realized" ? "page" : undefined} className={`whitespace-nowrap rounded-lg px-3 py-2 text-xs font-bold ${mode === "realized" ? "bg-slate-950 text-white" : "text-slate-600 hover:bg-white"}`} href={realizedHref}>Order selesai · {realizedQuantity.toLocaleString("id-ID")} item</Link>
      </nav>
      <div className="overflow-x-auto">
        <table className="w-full min-w-[1160px] text-left text-sm">
          <thead className="bg-slate-50 text-[10px] font-black uppercase tracking-[0.08em] text-slate-500">
            <tr><th className="px-4 py-3">Barang</th><th className="px-4 py-3">Pesanan & toko</th><th className="px-4 py-3 text-right">Jumlah</th><th className="px-4 py-3 text-right">{estimatedMode ? "Estimasi dana" : inTransitMode ? "Dana berjalan" : "Dana riil"}</th><th className="px-4 py-3 text-right">HPP Final</th><th className="px-4 py-3 text-right">Profit</th><th className="px-4 py-3 text-right">Margin</th></tr>
          </thead>
          <tbody className="divide-y divide-slate-100">
            {orderedRows.map((row) => {
              const margin = itemMargin(row.profit, row.income);
              return <tr className="align-middle hover:bg-slate-50/80" key={row.key}>
                <td className="px-4 py-3">
                  <div className="flex min-w-[330px] items-center gap-3">
                    {row.imageUrl ? <img alt="" className="h-12 w-12 shrink-0 rounded-lg border border-slate-200 object-cover" src={row.imageUrl} /> : <div className="h-12 w-12 shrink-0 rounded-lg border border-dashed border-slate-300" />}
                    <div className="min-w-0"><div className={`line-clamp-2 font-bold ${row.itemDetailMissing ? "text-amber-900" : "text-slate-950"}`}>{row.itemName}</div><div className="mt-1 truncate text-xs text-slate-500">{row.itemDetailMissing ? "Shopee belum mengirim item_list untuk order ini" : `${row.modelName || "Tanpa variasi"} · ${row.platformSku}`}</div>{row.masterSku ? <div className="mt-0.5 truncate font-mono text-[10px] font-semibold text-emerald-700">Master: {row.masterSku}</div> : row.itemDetailMissing ? null : <div className="mt-0.5 text-[10px] font-semibold text-amber-700">Master SKU belum dipetakan</div>}</div>
                  </div>
                </td>
                <td className="px-4 py-3"><Link className="font-mono text-xs font-bold text-slate-950 hover:text-emerald-700 hover:underline" href={`/orders?shop_id=${encodeURIComponent(row.shopId)}&q=${encodeURIComponent(row.orderSn)}`}>{row.orderSn}</Link><div className="mt-1 text-xs text-slate-500">{shopNameById.get(row.shopId) || row.shopId}</div><div className="mt-1 flex items-center gap-2"><Badge tone={statusTone(row.status)}>{statusLabel(row.status)}</Badge><span className="text-[10px] text-slate-400">{dateLabel(row.date)}</span></div></td>
                <td className="px-4 py-3 text-right">{row.itemDetailMissing ? <><div className="font-semibold text-amber-700">Belum diketahui</div><div className="mt-1 text-[10px] text-slate-400">Jumlah item belum termuat</div></> : <><div className="font-black">×{row.quantity}</div><div className="mt-1 text-[10px] text-slate-400">{money(row.unitPrice)} / item</div></>}</td>
                <td className="px-4 py-3 text-right"><div className={row.income === null ? "font-semibold text-amber-700" : "font-bold text-slate-900"}>{row.income === null ? "Belum tersedia" : money(row.income)}</div><div className="mt-1 text-[10px] text-slate-400">{row.itemDetailMissing ? "Total dana order · belum terbagi per barang" : row.incomeSource === "gross_provisional" ? "Masih memakai bruto" : row.incomeSource === "settlement" ? "Alokasi settlement" : "Settlement kosong"}</div></td>
                <td className="px-4 py-3 text-right">{row.itemDetailMissing
                  ? <Link className="text-xs font-bold text-amber-700 hover:underline" href={`/orders?shop_id=${encodeURIComponent(row.shopId)}&q=${encodeURIComponent(row.orderSn)}`}>Buka order untuk muat ulang</Link>
                  : row.hpp === null
                    ? <Link className="text-xs font-bold text-amber-700 hover:underline" href={`/products?shop_id=${encodeURIComponent(row.shopId)}&product_keys=${encodeURIComponent(`${row.shopId}:${row.itemId}:${row.modelId || "0"}`)}`}>Isi HPP</Link>
                    : <><div className="font-bold">{money(row.hpp)}</div><div className="mt-1 text-[10px] text-slate-400">{money(row.unitHpp)} × {row.quantity}</div></>}</td>
                <td className={`px-4 py-3 text-right font-black ${row.profit === null ? "text-amber-700" : row.profit < 0 ? "text-rose-700" : "text-emerald-700"}`}>{row.profit === null ? "Belum lengkap" : money(row.profit)}</td>
                <td className="px-4 py-3 text-right" title="Margin barang = profit ÷ dana/pendapatan barang × 100%. Belum mengurangi iklan dan kerugian.">
                  {margin === null
                    ? <span className="text-xs font-semibold text-slate-400">{row.profit === null || row.income === null ? "Belum lengkap" : "—"}</span>
                    : <><span className={`inline-flex rounded-full px-2.5 py-1 text-xs font-black ${margin < 0 ? "bg-rose-50 text-rose-700" : "bg-emerald-50 text-emerald-700"}`}>{margin.toLocaleString("id-ID", { minimumFractionDigits: 1, maximumFractionDigits: 1 })}%</span><div className="mt-1 text-[10px] text-slate-400">dari dana barang</div></>}
                </td>
              </tr>;
            })}
          </tbody>
        </table>
        {rows.length === 0 ? <div className="py-10 text-center text-sm text-slate-500">Tidak ada barang pada periode ini.</div> : null}
      </div>
      <div className="border-t border-slate-200 bg-slate-50 px-4 py-3 text-xs text-slate-500">Dana per barang dialokasikan proporsional dari nilai item dalam satu pesanan. Margin = profit barang ÷ dana barang × 100%; belum mengurangi iklan dan kerugian retur. Total dana tetap mengikuti settlement pesanan.</div>
    </section>
  );
}

function FinanceMetric({ label, value, emphasis = false }: { label: string; value: number; emphasis?: boolean }) { return <div className="flex items-center justify-between gap-4 border-b border-slate-100 py-3 text-sm"><span className="text-slate-500">{label}</span><span className={emphasis ? "font-bold text-slate-950" : "font-semibold text-slate-700"}>{money(value)}</span></div>; }
