import Link from "next/link";
import Badge from "@/components/ui/Badge";
import Card from "@/components/ui/Card";
import PageHeader from "@/components/ui/PageHeader";
import { redirect } from "next/navigation";
import { periodRange } from "@/lib/dateRange";
import { getOrderBusinessReport } from "@/lib/orderBusinessReport";
import { getProfitReport } from "@/lib/profitReport";
import { shopRepository } from "@/lib/repositories/shopRepository";
import { firstSearchParam, resolveShopScope, restrictedShopIds } from "@/lib/storeScope";
import { getCurrentUser } from "@/lib/currentUser";


export const dynamic = "force-dynamic";

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

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

function periodLabel(dateFrom: string, dateTo: string) {
  return dateFrom === dateTo ? `pada ${new Intl.DateTimeFormat("id-ID", { day: "numeric", month: "long" }).format(new Date(`${dateFrom}T12:00:00+07:00`))}` : `pada ${dateFrom} sampai ${dateTo}`;
}

type SearchParams = Promise<Record<string, string | string[] | undefined>>;

export default async function DashboardPage({ searchParams }: { searchParams: SearchParams }) {
  const params = await searchParams;
  const current = await getCurrentUser();
  const requestedShopId = firstSearchParam(params.shop_id);
  if (current?.role === "super_admin" && (!requestedShopId || requestedShopId === "all")) redirect("/admin");

  const shops = current ? await shopRepository.findScopeOptionsForUser(current) : [];
  const shopId = resolveShopScope(firstSearchParam(params.shop_id), shops);
  const shopIds = restrictedShopIds(current?.role, shopId, shops);
  const period = firstSearchParam(params.period) || "today";
  const { dateFrom, dateTo } = periodRange(period, firstSearchParam(params.date_from) || null, firstSearchParam(params.date_to) || null);
  const rangeStart = new Date(`${dateFrom}T00:00:00+07:00`);
  const rangeEnd = new Date(`${dateTo}T23:59:59.999+07:00`);
  const [report, allReport, profit] = await Promise.all([
    getOrderBusinessReport({ shopId, shopIds, dateFrom: rangeStart, dateTo: rangeEnd }),
    getOrderBusinessReport({ shopId, shopIds }),
    getProfitReport({ shopId, shopIds, dateFrom: rangeStart, dateTo: rangeEnd }),
  ]);

  const estimated = profit.estimated;
  const realized = profit.realized;
  const operations = allReport.summary;
  const scopeParam = shopId || "all";
  const activeShopLabel = shopId ? shops.find((shop) => shop.shopId === shopId)?.shopName || `Toko ${shopId}` : `semua toko${shops.length ? ` (${shops.length} toko)` : ""}`;
  const printQueue = operations.waitingTracking + operations.needPrint + operations.printedWaitingDispatch;
  // riskLate adalah penanda pada order yang sudah berada di salah satu antrean di atas,
  // sehingga tidak boleh dijumlahkan lagi sebagai pekerjaan terpisah.
  const attention = operations.incoming + printQueue + operations.readyToShip;
  const syncHealthy = operations.latestSyncSuccess === true;
  const syncLabel = operations.latestSyncSuccess === null ? "Belum ada riwayat sync" : `${syncHealthy ? "Sync terakhir" : "Sync gagal"} · ${dateTime(operations.latestSyncAt)}`;
  const estimatedValue = estimated.orders === 0 ? "Belum ada transaksi" : estimated.confirmedOrders === 0 ? "Belum dihitung" : money(estimated.profit);
  const realizedValue = realized.orders === 0 ? "Belum ada settlement" : realized.confirmedOrders === 0 ? "Belum dihitung" : money(realized.profit);
  const inTransit = profit.inTransit;

  return (
    <div className="space-y-6">
      <PageHeader eyebrow="Operasional" title="Ringkasan" description={`Kondisi bisnis ${activeShopLabel} · ${dateFrom} sampai ${dateTo}.`} actions={<>
        <Link href={`/logs?shop_id=${encodeURIComponent(scopeParam)}`} title={operations.latestSyncMessage || undefined}><Badge tone={syncHealthy ? "success" : "warning"}>{syncLabel}</Badge></Link>
        <Link className="ui-button ui-button-secondary" href={`/finance?shop_id=${encodeURIComponent(scopeParam)}&date_from=${dateFrom}&date_to=${dateTo}`}>Laporan profit</Link>
        <Link className="ui-button ui-button-primary" href={`/orders?shop_id=${encodeURIComponent(scopeParam)}&status=incoming`}>Proses pesanan</Link>
      </>} />
      <details className="scope-toolbar group/filter">
        <summary className="flex cursor-pointer list-none items-center justify-between gap-3 text-[13px] font-semibold text-slate-700 dark:text-slate-200"><span>Filter toko & periode <span className="ml-2 font-normal text-slate-500">{dateFrom} — {dateTo}</span></span><span aria-hidden="true" className="text-lg transition-transform group-open/filter:rotate-180">⌄</span></summary>
        <form className="mt-4 grid gap-3 border-t border-slate-200 pt-4 sm:grid-cols-2 xl:grid-cols-[1.2fr_180px_1fr_1fr_auto] xl:items-end dark:border-slate-800">
          <label><span className="muted-label">Toko</span><select className="mt-1.5 w-full rounded-lg border border-slate-200 bg-white px-3 py-2.5 text-[13px]" name="shop_id" defaultValue={shopId || ""}><option value="">Semua toko</option>{shops.map((shop) => <option key={shop.shopId} value={shop.shopId}>{shop.shopName || shop.shopId}{shop.connected ? "" : " · historis"}</option>)}</select></label>
          <label><span className="muted-label">Periode</span><select className="mt-1.5 w-full rounded-lg border border-slate-200 bg-white px-3 py-2.5 text-[13px]" name="period" defaultValue={period}><option value="today">Hari ini</option><option value="yesterday">Kemarin</option><option value="7d">7 hari terakhir</option><option value="30d">30 hari terakhir</option><option value="custom">Rentang tanggal</option></select></label>
          <label><span className="muted-label">Dari</span><input className="mt-1.5 w-full rounded-lg border border-slate-200 bg-white px-3 py-2.5 text-[13px]" name="date_from" type="date" defaultValue={dateFrom} /></label>
          <label><span className="muted-label">Sampai</span><input className="mt-1.5 w-full rounded-lg border border-slate-200 bg-white px-3 py-2.5 text-[13px]" name="date_to" type="date" defaultValue={dateTo} /></label>
          <button className="ui-button ui-button-primary" type="submit">Terapkan</button>
        </form>
      </details>
      {operations.latestSyncSuccess === false ? <div role="status" className="flex flex-wrap items-center justify-between gap-3 rounded-xl border border-amber-200 bg-amber-50 px-4 py-3 text-xs leading-5 text-amber-950 dark:border-amber-900 dark:bg-amber-950/30 dark:text-amber-200"><span><strong>Sinkronisasi terakhir gagal · {dateTime(operations.latestSyncAt)}.</strong> Ringkasan ini memakai data yang tersimpan; transaksi terbaru mungkin belum masuk.</span><Link className="shrink-0 font-bold underline" href={`/logs?shop_id=${encodeURIComponent(scopeParam)}`}>Lihat penyebab →</Link></div> : null}

      <section aria-label="Kondisi bisnis pada periode" className="grid gap-3 sm:grid-cols-2 xl:grid-cols-4">
        <MetricCard label="Order valid masuk" value={estimated.orders} hint={`${report.summary.quantitySold} item · ${estimated.orders ? `${estimated.confirmedOrders}/${estimated.orders} estimasi lengkap` : `belum ada order ${periodLabel(dateFrom, dateTo)}`}`} accent="slate" href={`/orders?shop_id=${scopeParam}&status=all`} />
        <MetricCard label="Estimasi profit" value={estimatedValue} hint="Berdasarkan tanggal order dibuat; gunakan untuk memantau pesanan baru." accent="cyan" href={`/finance?shop_id=${scopeParam}&period=${period}&detail=estimated#rincian-barang`} />
        <MetricCard label="Dana settlement masuk" value={realized.orders ? money(realized.income) : "Belum ada settlement"} hint={`${realized.orders} order selesai · periode pilihan`} accent="amber" href={`/finance?shop_id=${scopeParam}&period=${period}&detail=realized#rincian-barang`} />
        <MetricCard label="Profit order terealisasi" value={realizedValue} hint={realized.orders ? `${realized.confirmedOrders}/${realized.orders} lengkap · sebelum iklan wallet & retur` : "Settlement dikurangi HPP Final."} accent="emerald" href={`/finance?shop_id=${scopeParam}&period=${period}&detail=realized#rincian-barang`} />
      </section>

      <section aria-label="Tren profit dan prioritas hari ini" className="grid items-start gap-5 xl:grid-cols-[minmax(0,1.8fr)_minmax(280px,0.85fr)]">
        <Card title="Pergerakan profit harian" description="Estimasi mengikuti tanggal order dibuat. Profit terealisasi mengikuti tanggal settlement masuk.">
          <ProfitTrendChart rows={profit.daily} dateFrom={dateFrom} dateTo={dateTo} detailHref={`/finance?shop_id=${encodeURIComponent(scopeParam)}&date_from=${dateFrom}&date_to=${dateTo}&detail=realized#rincian-barang`} />
        </Card>
        <Card title="Prioritas hari ini" description="Antrean operasional saat ini; tidak dibatasi periode laporan.">
          <Link href={`/orders?shop_id=${scopeParam}&status=incoming`} className="flex items-center justify-between rounded-xl border border-amber-200 bg-amber-50 p-4 hover:bg-amber-100"><span><span className="block text-xs font-semibold text-amber-900">Perlu diproses</span><span className="mt-1 block text-[11px] text-amber-800">{operations.riskLate} berisiko terlambat</span></span><strong className="text-2xl text-amber-900">{attention}</strong></Link>
          <div className="mt-3 space-y-1 divide-y divide-slate-100">
            <CompactMetric label="Dalam pengiriman" value={`${operations.shipped} order`} hint={`Dana berjalan saat ini ${money(inTransit.income)}`} />
            <CompactMetric label="Settlement selesai" value={`${operations.completed} order`} hint="Riwayat semua tanggal" />
            <CompactMetric label="Batal / retur / masalah" value={`${operations.cancelled} order`} hint="Perlu ditinjau bila ada kerugian" warning={operations.cancelled > 0} />
          </div>
          <div className="mt-3 grid grid-cols-2 gap-2">
            <Link className="rounded-lg border border-slate-200 px-3 py-2.5 text-center text-xs font-semibold text-slate-700 hover:bg-slate-50" href={`/orders?shop_id=${scopeParam}&status=print_queue`}>Menunggu cetak · {printQueue}</Link>
            <Link className="rounded-lg border border-slate-200 px-3 py-2.5 text-center text-xs font-semibold text-slate-700 hover:bg-slate-50" href={`/orders?shop_id=${scopeParam}&status=pickup_ready`}>Menunggu pickup · {operations.readyToShip}</Link>
          </div>
        </Card>
      </section>

      {estimated.unconfirmedOrders || realized.unconfirmedOrders ? <div role="status" className="flex flex-wrap items-center justify-between gap-3 rounded-xl border border-amber-200 bg-amber-50 px-4 py-3 text-xs leading-5 text-amber-950"><span><strong>Angka belum lengkap.</strong> {estimated.unconfirmedOrders} order estimasi dan {realized.unconfirmedOrders} order settlement tertahan karena dana atau HPP Final belum lengkap.</span><Link className="shrink-0 font-bold underline" href={`/finance?shop_id=${encodeURIComponent(scopeParam)}&date_from=${dateFrom}&date_to=${dateTo}&detail=realized#rincian-barang`}>Lihat rincian yang perlu dilengkapi →</Link></div> : null}

      <Card title="Antrean pesanan" description="Semua jumlah di bawah adalah posisi terkini, bukan hanya transaksi dalam periode laporan." className="overflow-hidden">
        <div className="grid gap-px overflow-hidden rounded-xl border border-slate-200 bg-slate-200 sm:grid-cols-2 xl:grid-cols-4">
          <QueueLink label="Belum diatur" value={operations.incoming} hint="Tentukan pickup atau drop-off" href={`/orders?shop_id=${scopeParam}&status=incoming`} tone="amber" />
          <QueueLink label="Menunggu cetak" value={printQueue} hint="Atur / cetak resi" href={`/orders?shop_id=${scopeParam}&status=print_queue`} tone="sky" />
          <QueueLink label="Siap dijemput" value={operations.readyToShip} hint="Sudah siap diserahkan" href={`/orders?shop_id=${scopeParam}&status=pickup_ready`} tone="violet" />
          <QueueLink label="Dalam perjalanan" value={operations.shipped} hint="Paket menuju pembeli" href={`/orders?shop_id=${scopeParam}&status=SHIPPED`} tone="sky" />
        </div>
      </Card>

      <div className="grid gap-5 xl:grid-cols-2">
        <Card title="Pesanan terbaru" description={`Order dibuat pada ${dateFrom}–${dateTo}.`}>
          <div className="divide-y divide-slate-100">
            {report.recentOrders.map((order) => <Link className="grid grid-cols-[1fr_auto] items-center gap-3 py-3 first:pt-0 last:pb-0 hover:text-emerald-700" href={`/orders?shop_id=${encodeURIComponent(order.shopId)}&q=${encodeURIComponent(order.orderSn)}`} key={`${order.shopId}-${order.orderSn}`}><div className="min-w-0"><div className="truncate text-[13px] font-semibold text-slate-900 dark:text-white">{order.orderSn}</div><div className="mt-1 truncate text-[11px] text-slate-500">{order.shopName} · {order.shippingCarrier} · {dateTime(order.createTime)}</div></div><div className="text-right"><div className="text-[13px] font-semibold text-slate-900 dark:text-white">{money(order.amount)}</div><div className={`mt-1 text-[10px] font-semibold ${order.riskLate ? "text-rose-600" : "text-slate-400"}`}>{order.riskLate ? "Berisiko" : order.status || "-"}</div></div></Link>)}
            {report.recentOrders.length === 0 ? <div className="rounded-xl border border-dashed border-slate-200 bg-slate-50 px-4 py-8 text-center"><div className="text-sm font-bold text-slate-700">Belum ada order baru pada periode ini</div><p className="mt-1 text-xs text-slate-500">Untuk aktivitas hari ini pilih 7 atau 30 hari, atau buka antrean operasional di atas.</p><div className="mt-3 flex justify-center gap-2"><Link className="rounded-lg border border-slate-200 px-3 py-2 text-xs font-semibold" href={`/dashboard?shop_id=${encodeURIComponent(scopeParam)}&period=7d`}>7 hari</Link><Link className="rounded-lg border border-slate-200 px-3 py-2 text-xs font-semibold" href={`/dashboard?shop_id=${encodeURIComponent(scopeParam)}&period=30d`}>30 hari</Link></div></div> : null}
          </div>
        </Card>
        <div className="grid gap-5">
          <ProductList title="Produk terlaris · periode" rows={report.products.bestSellers} mode="quantity" emptyMessage={`Belum ada produk terjual ${periodLabel(dateFrom, dateTo)}.`} />
          <ProductList title="Produk dengan HPP belum lengkap" rows={report.products.missingHpp} mode="missing" emptyMessage={report.summary.totalOrders === 0 ? "Belum ada transaksi pada rentang ini." : "HPP semua produk pada transaksi periode ini sudah lengkap."} />
        </div>
      </div>

    </div>
  );
}

function MetricCard({ label, value, hint, accent, href }: { label: string; value: string | number; hint: string; accent: "cyan" | "emerald" | "amber" | "slate"; href: string }) {
  const colors = { cyan: "text-cyan-700", emerald: "text-emerald-700", amber: "text-amber-700", slate: "text-slate-950" };
  return <Link className="summary-item block rounded-xl border border-slate-200 bg-white p-4 transition-colors hover:border-emerald-300 hover:bg-emerald-50/30 dark:border-slate-800 dark:bg-slate-900" href={href}><div className="summary-label">{label}</div><div className={`summary-value ${colors[accent]}`}>{value}</div><div className="mt-1 summary-hint">{hint}</div></Link>;
}

function CompactMetric({ label, value, hint, warning = false }: { label: string; value: string; hint: string; warning?: boolean }) {
  return <div className="flex items-center justify-between gap-4 py-3 first:pt-0 last:pb-0"><div><div className="flex items-center gap-2 text-[12px] font-semibold text-slate-600">{label}{warning ? <span className="h-1.5 w-1.5 rounded-full bg-amber-500" /> : null}</div><div className="mt-1 text-[10px] text-slate-400">{hint}</div></div><div className="text-right text-base font-bold text-slate-950 dark:text-white">{value}</div></div>;
}

function ProfitTrendChart({ rows, dateFrom, dateTo, detailHref }: { rows: Array<{ date: string; estimatedProfit: number; realizedProfit: number; estimatedOrders: number; realizedOrders: number; estimatedConfirmed: number; realizedConfirmed: number; estimatedUnconfirmed: number; realizedUnconfirmed: number }>; dateFrom: string; dateTo: string; detailHref: string }) {
  const rowsByDate = new Map(rows.map((row) => [row.date, row]));
  const to = new Date(`${dateTo}T12:00:00+07:00`);
  const from = new Date(`${dateFrom}T12:00:00+07:00`);
  const visibleStart = new Date(Math.max(from.getTime(), to.getTime() - 29 * 24 * 60 * 60 * 1000));
  const allDates: string[] = [];
  for (const cursor = new Date(visibleStart); cursor <= to; cursor.setDate(cursor.getDate() + 1)) {
    allDates.push(`${cursor.getFullYear()}-${String(cursor.getMonth() + 1).padStart(2, "0")}-${String(cursor.getDate()).padStart(2, "0")}`);
  }
  const data = allDates.slice(-30).map((date) => rowsByDate.get(date) || { date, estimatedProfit: 0, realizedProfit: 0, estimatedOrders: 0, realizedOrders: 0, estimatedConfirmed: 0, realizedConfirmed: 0, estimatedUnconfirmed: 0, realizedUnconfirmed: 0 });
  const confirmedCount = data.reduce((total, row) => total + row.estimatedConfirmed + row.realizedConfirmed, 0);
  const pendingCount = data.reduce((total, row) => total + row.estimatedUnconfirmed + row.realizedUnconfirmed, 0);
  if (confirmedCount === 0 && pendingCount === 0) return <div className="rounded-xl border border-dashed border-slate-200 bg-slate-50 px-4 py-9 text-center dark:border-slate-800 dark:bg-slate-950"><div className="text-sm font-bold text-slate-700 dark:text-slate-200">Belum ada transaksi untuk dibuat grafik</div><p className="mt-1 text-xs text-slate-500">Belum ada order masuk atau settlement pada periode {dateFrom}–{dateTo}. Pilih periode 7 atau 30 hari untuk melihat tren.</p></div>;
  if (confirmedCount === 0) return <div className="rounded-xl border border-amber-200 bg-amber-50 p-4 dark:border-amber-900 dark:bg-amber-950/30"><div className="text-sm font-bold text-amber-900 dark:text-amber-200">Profit belum bisa digambarkan</div><p className="mt-1 text-xs leading-5 text-amber-800 dark:text-amber-300">Ada {pendingCount} order yang datanya belum lengkap. Angka kosong tidak digambar sebagai profit Rp0; lengkapi settlement atau HPP Final terlebih dahulu.</p><Link className="mt-3 inline-flex text-xs font-bold text-amber-900 underline dark:text-amber-200" href={detailHref}>Lihat rincian profit →</Link></div>;
  if (data.length === 1) {
    const row = data[0];
    const points = [
      { label: "Estimasi profit · order dibuat", value: row.estimatedConfirmed ? row.estimatedProfit : null, count: row.estimatedOrders, pending: row.estimatedUnconfirmed, color: "bg-cyan-500" },
      { label: "Profit order · settlement masuk", value: row.realizedConfirmed ? row.realizedProfit : null, count: row.realizedOrders, pending: row.realizedUnconfirmed, color: "bg-emerald-500" },
    ];
    const max = Math.max(1, ...points.map((point) => Math.abs(point.value || 0)));
    return <div className="space-y-3 rounded-xl border border-slate-200 bg-slate-50 p-4 dark:border-slate-800 dark:bg-slate-950">
      <div className="text-xs font-bold text-slate-700 dark:text-slate-200">Perbandingan {periodLabel(dateFrom, dateTo)}</div>
      {points.map((point) => <div key={point.label} className="rounded-lg bg-white p-3 dark:bg-slate-900"><div className="flex flex-wrap items-center justify-between gap-2"><span className="text-xs font-semibold text-slate-600 dark:text-slate-300">{point.label}</span><span className="text-xs font-black tabular-nums text-slate-900 dark:text-white">{point.value === null ? "Belum ada data" : money(point.value)}</span></div>
        {point.value !== null ? <div className="mt-2 h-2 overflow-hidden rounded-full bg-slate-100 dark:bg-slate-800"><div className={`h-full rounded-full ${point.value < 0 ? "bg-rose-500" : point.color}`} style={{ width: `${Math.max(2, Math.abs(point.value) / max * 100)}%` }} /></div> : null}
        <div className="mt-1 text-[10px] text-slate-500">{point.value === null ? "Belum ada transaksi pada jenis ini" : `${point.count} order`} · {point.pending ? `${point.pending} belum lengkap` : "data lengkap"}</div>
      </div>)}
      <p className="text-[10px] leading-4 text-slate-500">Satu hari hanya dibandingkan sebagai dua nilai; tren muncul saat memilih lebih dari satu tanggal. Profit belum lengkap tidak dianggap Rp0.</p>
    </div>;
  }
  const width = 880;
  const height = 280;
  const left = 68;
  const right = 18;
  const top = 18;
  const bottom = 42;
  const plotWidth = width - left - right;
  const plotHeight = height - top - bottom;
  const values = data.flatMap((row) => [row.estimatedConfirmed ? row.estimatedProfit : null, row.realizedConfirmed ? row.realizedProfit : null]).filter((value): value is number => value !== null);
  let min = Math.min(0, ...values);
  let max = Math.max(0, ...values);
  if (min === max) { min -= 1; max += 1; }
  const range = max - min;
  const y = (value: number) => top + ((max - value) / range) * plotHeight;
  const zeroY = y(0);
  const groupWidth = plotWidth / data.length;
  const barWidth = Math.min(13, Math.max(3, groupWidth * 0.28));
  const tickValues = [max, min + range / 2, min];
  const labelEvery = Math.max(1, Math.ceil(data.length / 8));
  return <div>
    <div className="mb-4 flex flex-wrap items-center gap-x-5 gap-y-2 text-[11px] font-semibold text-slate-600 dark:text-slate-300"><span className="inline-flex items-center gap-2"><i className="h-2.5 w-2.5 rounded-sm bg-cyan-500" />Estimasi profit</span><span className="inline-flex items-center gap-2"><i className="h-2.5 w-2.5 rounded-sm bg-emerald-500" />Profit order dari settlement</span><span className="ml-auto text-[10px] font-medium text-slate-400">30 hari terakhir dalam rentang pilihan · sumbu vertikal = rupiah</span></div>
    <div className="overflow-hidden rounded-xl border border-slate-100 bg-gradient-to-b from-slate-50 to-white p-2 dark:border-slate-800 dark:from-slate-950 dark:to-slate-900 sm:p-3">
      <svg aria-label="Grafik batang perbandingan estimasi profit dan profit order per tanggal" className="block h-auto w-full" role="img" viewBox={`0 0 ${width} ${height}`}>
        {tickValues.map((value, index) => { const yy = y(value); return <g key={`${value}-${index}`}><line x1={left} x2={width - right} y1={yy} y2={yy} stroke={value === 0 ? "#94a3b8" : "#e2e8f0"} strokeDasharray={value === 0 ? undefined : "4 5"} strokeWidth={value === 0 ? 1.5 : 1} /><text x={left - 9} y={yy + 4} textAnchor="end" fill="#64748b" fontSize="10">{money(value)}</text></g>; })}
        {data.map((row, index) => {
          const center = left + groupWidth * (index + 0.5);
          const xEst = center - barWidth - 1;
          const xReal = center + 1;
          const estY = row.estimatedConfirmed ? y(row.estimatedProfit) : null;
          const realY = row.realizedConfirmed ? y(row.realizedProfit) : null;
          const date = new Intl.DateTimeFormat("id-ID", { day: "numeric", month: "short" }).format(new Date(`${row.date}T12:00:00+07:00`));
          const showLabel = index % labelEvery === 0 || index === data.length - 1;
          return <g key={row.date}>
            {estY !== null ? <rect x={xEst} y={Math.min(estY, zeroY)} width={barWidth} height={Math.max(1.5, Math.abs(zeroY - estY))} rx="2" fill="#06b6d4"><title>{`${date} · Estimasi profit ${money(row.estimatedProfit)} · ${row.estimatedOrders} order masuk${row.estimatedUnconfirmed ? ` · ${row.estimatedUnconfirmed} belum lengkap` : ""}`}</title></rect> : null}
            {realY !== null ? <rect x={xReal} y={Math.min(realY, zeroY)} width={barWidth} height={Math.max(1.5, Math.abs(zeroY - realY))} rx="2" fill="#10b981"><title>{`${date} · Profit order ${money(row.realizedProfit)} · ${row.realizedOrders} settlement${row.realizedUnconfirmed ? ` · ${row.realizedUnconfirmed} belum lengkap` : ""}`}</title></rect> : null}
            {showLabel ? <text x={center} y={height - 13} textAnchor="middle" fill="#64748b" fontSize="9">{date}</text> : null}
          </g>;
        })}
      </svg>
    </div>
    <p className="mt-3 text-[10px] leading-5 text-slate-500">Tanggal tanpa batang berarti belum ada transaksi lengkap pada hari itu. Arah tanggal dibaca dari kiri (lebih lama) ke kanan (terbaru). {pendingCount ? `${pendingCount} order belum lengkap dan tidak digambar sebagai Rp0.` : "Semua data yang ditampilkan lengkap."}</p>
  </div>;
}

function QueueLink({ label, value, hint, href, tone }: { label: string; value: number; hint: string; href: string; tone: "amber" | "sky" | "violet" | "emerald" | "rose" }) {
  const colors = { amber: "bg-amber-400", sky: "bg-sky-400", violet: "bg-violet-400", emerald: "bg-emerald-400", rose: "bg-rose-400" };
  return <Link className="group flex items-center gap-3 p-4 hover:bg-slate-50 dark:hover:bg-slate-800/60" href={href}><span className={`h-8 w-1 rounded-full ${colors[tone]}`} /><div className="min-w-0 flex-1"><div className="text-[13px] font-bold text-slate-800 group-hover:text-slate-950 dark:text-slate-200">{label}</div><div className="mt-0.5 text-[10px] text-slate-400">{hint}</div></div><span className="text-xl font-black text-slate-950 dark:text-white">{value}</span></Link>;
}

function ProductList({ title, rows, mode, emptyMessage }: { title: string; rows: Array<{ key: string; productName: string; sku: string; quantity: number; omzet: number; missingHpp: number; imageUrl: string | null }>; mode: "quantity" | "missing"; emptyMessage: string }) {
  /* Product images are signed Shopee CDN URLs, so they are rendered directly instead of being proxied by Next Image. */
  // eslint-disable-next-line @next/next/no-img-element
  return <Card title={title}><div className="divide-y divide-slate-100">{rows.slice(0, 6).map((row) => <div className="flex items-center gap-3 py-3 first:pt-0 last:pb-0" key={row.key}>{row.imageUrl ? <img className="h-10 w-10 shrink-0 rounded-[10px] border border-slate-200 object-cover" src={row.imageUrl} alt="" /> : <div className="h-10 w-10 shrink-0 rounded-[10px] bg-slate-100" />}<div className="min-w-0 flex-1"><div className="truncate text-[12px] font-bold text-slate-800 dark:text-slate-100">{row.productName}</div><div className="mt-0.5 truncate text-[10px] text-slate-400">{row.sku || "Tanpa SKU"} · {money(row.omzet)}</div></div><div className={`text-right text-[12px] font-black ${mode === "missing" ? "text-amber-700" : "text-slate-950 dark:text-white"}`}>{mode === "missing" ? `${row.missingHpp} kosong` : `${row.quantity} pcs`}</div></div>)}{rows.length === 0 ? <div className="rounded-xl border border-dashed border-slate-200 bg-slate-50 px-4 py-7 text-center text-xs leading-5 text-slate-500">{emptyMessage}</div> : null}</div></Card>;
}
