// Dashboard screen + KPI cards + activity feed

function KpiCard({ label, value, format, delta, icon, tint }) {
  return (
    <Card className="p-5" style={{ background: tint || "var(--surface)" }}>
      <div className="flex items-start justify-between mb-3 gap-3">
        <span className="type-kpi-label whitespace-nowrap">{label}</span>
        <div className="w-7 h-7 rounded-md grid place-items-center flex-shrink-0" style={{ background: "var(--surface)", border: "1px solid var(--hairline)" }}>
          <Icon name={icon} size={14} className="text-[var(--ink-3)]"/>
        </div>
      </div>
      <div className="font-semibold tabular-nums" style={{ color: "var(--ink)", fontFamily: "var(--font-display)", fontSize: 28, letterSpacing: "-0.01em" }}>
        <CountUp value={value} format={format || (n => n.toLocaleString("en-IN"))} />
      </div>
      {delta && (
        <div className="mt-2 flex items-center gap-1.5 text-[12px] whitespace-nowrap">
          <span className={cn("inline-flex items-center gap-1 font-medium whitespace-nowrap", delta.dir === "up" ? "text-[var(--positive-text)]" : "text-[var(--critical-text)]")}>
            <Icon name={delta.dir === "up" ? "trending-up" : "trending-down"} size={12}/>
            {delta.value}
          </span>
          <span className="text-[var(--ink-3)] whitespace-nowrap">{delta.label}</span>
        </div>
      )}
    </Card>
  );
}

function DashboardPage({ kpis, highlightApprovalId }) {
  return (
    <main className="px-8 py-6 space-y-6">
      <BiPageHeader title="Dashboard" subtitle="Your warehouse at a glance · FY 25-26"/>
      {/* KPI grid */}
      <div className="grid grid-cols-4 gap-4">
        <KpiCard
          label="Stock Value"
          value={kpis.stockValue}
          format={(n) => fmtINRCompact(n)}
          icon="wallet"
          delta={{ dir: "up", value: "+2.4%", label: "WoW" }}
          tint="oklch(0.54 0.21 268 / 0.04)"
        />
        <KpiCard
          label="Pending Approvals"
          value={kpis.pendingApprovals}
          icon="clock"
          delta={{ dir: "down", value: "−1", label: "today" }}
          tint="oklch(0.72 0.13 75 / 0.05)"
        />
        <KpiCard
          label="Low Stock Items"
          value={kpis.lowStockItems}
          icon="alert-triangle"
          delta={{ dir: "down", value: "−1", label: "post-GRN" }}
          tint="oklch(0.60 0.20 25 / 0.04)"
        />
        <KpiCard
          label="Today’s Movements"
          value={kpis.todayInward + kpis.todayOutward}
          icon="activity"
          delta={{ dir: "up", value: `${kpis.todayInward} in · ${kpis.todayOutward} out`, label: "" }}
          tint="oklch(0.58 0.13 152 / 0.04)"
        />
      </div>

      <div className="grid grid-cols-3 gap-4">
        {/* Pending approvals */}
        <Card className="col-span-2" dataId="approvals-card">
          <div className="flex items-center justify-between px-5 py-4 border-b border-[var(--hairline)] gap-3">
            <div className="min-w-0">
              <h3 className="text-[15px] font-semibold text-[var(--ink)] whitespace-nowrap">Pending Approvals</h3>
              <div className="text-[12px] text-[var(--ink-3)] mt-0.5 whitespace-nowrap">Vouchers awaiting your review</div>
            </div>
            <Pill kind="caution" className="flex-shrink-0 whitespace-nowrap">{PENDING_APPROVALS.length} waiting</Pill>
          </div>
          <table className="w-full">
            <thead>
              <tr className="border-b border-[var(--hairline)]">
                <th className="type-table-head text-left px-5 py-2.5">Voucher</th>
                <th className="type-table-head text-left px-3 py-2.5">Party</th>
                <th className="type-table-head text-left px-3 py-2.5">Loc</th>
                <th className="type-table-head text-right px-3 py-2.5">Lines</th>
                <th className="type-table-head text-right px-3 py-2.5">Value</th>
                <th className="type-table-head text-left px-3 py-2.5">Submitted by</th>
                <th className="type-table-head text-right px-5 py-2.5"></th>
              </tr>
            </thead>
            <tbody>
              {PENDING_APPROVALS.map((p) => (
                <tr key={p.id}
                  data-id={`approval-${p.id}`}
                  className={cn(
                    "border-b border-[var(--hairline)] last:border-0 hover:bg-[var(--sunken)] transition-colors",
                    highlightApprovalId === p.id && "bg-[var(--accent-1-wash)]"
                  )}>
                  <td className="px-5 py-3">
                    <div className="flex items-center gap-2.5">
                      <span className="w-7 h-7 rounded-md grid place-items-center" style={{
                        background: p.type === "Receipt" ? "var(--positive-tint)" : p.type === "Dispatch" ? "var(--info-tint)" : "var(--sunken)",
                        color: p.type === "Receipt" ? "var(--positive-text)" : p.type === "Dispatch" ? "var(--info-text)" : "var(--ink-3)",
                      }}>
                        <Icon name={p.type === "Receipt" ? "arrow-down-to-line" : p.type === "Dispatch" ? "arrow-up-from-line" : "scale"} size={13}/>
                      </span>
                      <div className="min-w-0">
                        <div className="text-[13px] font-semibold text-[var(--ink)] tabular-nums whitespace-nowrap">{p.id}</div>
                        <div className="text-[11px] text-[var(--ink-3)] whitespace-nowrap">{p.at}</div>
                      </div>
                    </div>
                  </td>
                  <td className="px-3 py-3 text-[13px] text-[var(--ink-2)]">{p.party}</td>
                  <td className="px-3 py-3"><span className="type-kbd">{p.loc}</span></td>
                  <td className="px-3 py-3 text-right text-[13px] tabular-nums">{p.lines}</td>
                  <td className="px-3 py-3 text-right text-[13px] font-semibold tabular-nums">{fmtINR(p.value)}</td>
                  <td className="px-3 py-3 text-[13px] text-[var(--ink-2)]">{p.by}</td>
                  <td className="px-5 py-3 text-right">
                    <Button variant="ghost" size="sm">Review <Icon name="arrow-right" size={12}/></Button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </Card>

        {/* Activity feed */}
        <Card>
          <div className="px-5 py-4 border-b border-[var(--hairline)]">
            <h3 className="text-[15px] font-semibold text-[var(--ink)] whitespace-nowrap">Activity</h3>
            <div className="text-[12px] text-[var(--ink-3)] mt-0.5 whitespace-nowrap">Recent events</div>
          </div>
          <div className="p-2">
            {ACTIVITY.map((a, i) => (
              <div key={i} className="flex items-start gap-3 px-3 py-2.5 rounded-md hover:bg-[var(--sunken)] transition-colors">
                <div className="w-7 h-7 rounded-full grid place-items-center mt-0.5 flex-shrink-0" style={{
                  background: a.kind === "approve" ? "var(--positive-tint)" :
                              a.kind === "create"  ? "var(--accent-1-tint)" :
                              a.kind === "low"     ? "var(--caution-tint)" : "var(--info-tint)",
                  color:      a.kind === "approve" ? "var(--positive-text)" :
                              a.kind === "create"  ? "var(--accent-1-text)" :
                              a.kind === "low"     ? "var(--caution-text)" : "var(--info-text)",
                }}>
                  <Icon name={a.kind === "approve" ? "check" : a.kind === "create" ? "plus" : a.kind === "low" ? "alert-triangle" : "arrow-up-from-line"} size={13}/>
                </div>
                <div className="flex-1 min-w-0">
                  <div className="text-[13px] text-[var(--ink-2)]"><span className="font-semibold text-[var(--ink)]">{a.who}</span> {a.what}</div>
                  <div className="text-[11px] text-[var(--ink-4)] mt-0.5">{a.when}</div>
                </div>
              </div>
            ))}
          </div>
        </Card>
      </div>

      {/* Bottom strip: 7-day movement + low-stock alerts — fills the dashboard, gives the recording something to land on */}
      <div className="grid grid-cols-3 gap-4">
        <Card className="col-span-2 p-5">
          <div className="flex items-start justify-between mb-4 gap-3">
            <div className="min-w-0">
              <h3 className="text-[14.5px] font-semibold text-[var(--ink)] whitespace-nowrap">Stock Movement</h3>
              <div className="text-[12px] text-[var(--ink-3)] mt-0.5 whitespace-nowrap">Last 7 days</div>
            </div>
            <div className="flex items-center gap-3 text-[11.5px] flex-shrink-0 whitespace-nowrap">
              <span className="flex items-center gap-1.5"><span className="w-2.5 h-2.5 rounded-sm" style={{ background: "var(--positive)" }}/>Inward</span>
              <span className="flex items-center gap-1.5"><span className="w-2.5 h-2.5 rounded-sm" style={{ background: "var(--info)" }}/>Outward</span>
            </div>
          </div>
          <Sparkline7Day/>
        </Card>

        <Card className="overflow-hidden">
          <div className="px-5 py-4 border-b border-[var(--hairline)]">
            <h3 className="text-[14.5px] font-semibold text-[var(--ink)] whitespace-nowrap">Low Stock</h3>
            <div className="text-[12px] text-[var(--ink-3)] mt-0.5 whitespace-nowrap">Below reorder level</div>
          </div>
          <div className="p-2">
            {LOW_STOCK_ITEMS.map((it, i) => (
              <div key={i} className="flex items-center gap-3 px-3 py-2 rounded-md hover:bg-[var(--sunken)] transition-colors">
                <div className="w-7 h-7 rounded-md grid place-items-center flex-shrink-0" style={{ background: "var(--caution-tint)", color: "var(--caution-text)" }}>
                  <Icon name="alert-triangle" size={13}/>
                </div>
                <div className="flex-1 min-w-0">
                  <div className="text-[13px] font-semibold text-[var(--ink)] truncate">{it.name}</div>
                  <div className="text-[11px] text-[var(--ink-3)] mono">{it.sku}</div>
                </div>
                <div className="text-right flex-shrink-0 whitespace-nowrap">
                  <div className="text-[13px] font-semibold tabular-nums text-[var(--critical-text)] whitespace-nowrap">{it.qty} <span className="text-[var(--ink-4)] font-normal">/ {it.reorder}</span></div>
                  <div className="text-[10px] text-[var(--ink-3)] whitespace-nowrap">below reorder</div>
                </div>
              </div>
            ))}
          </div>
        </Card>
      </div>
    </main>
  );
}

// Tiny SVG bar chart — 7 days, two series (inward/outward)
function Sparkline7Day() {
  const data = [
    { d: "Mon", inw: 240, out: 180 },
    { d: "Tue", inw: 320, out: 260 },
    { d: "Wed", inw: 180, out: 320 },
    { d: "Thu", inw: 280, out: 240 },
    { d: "Fri", inw: 420, out: 360 },
    { d: "Sat", inw: 380, out: 280 },
    { d: "Sun", inw: 660, out: 240 },  // big inward bump = today's receipt scene
  ];
  const max = Math.max(...data.flatMap(d => [d.inw, d.out]));
  const W = 700, H = 130, pad = 8;
  const barW = (W - pad * 2) / data.length / 2.6;
  const gap = (W - pad * 2) / data.length;
  return (
    <div className="w-full">
      <svg viewBox={`0 0 ${W} ${H + 28}`} preserveAspectRatio="none" style={{ width: "100%", height: 158 }}>
        {/* baseline */}
        <line x1={pad} y1={H} x2={W - pad} y2={H} stroke="var(--hairline)" strokeWidth="1"/>
        {data.map((d, i) => {
          const x = pad + i * gap + gap / 2;
          const inwH = (d.inw / max) * (H - 12);
          const outH = (d.out / max) * (H - 12);
          return (
            <g key={i}>
              <rect x={x - barW - 2} y={H - inwH} width={barW} height={inwH} rx={2} fill="var(--positive)" opacity={i === 6 ? 1 : 0.85}/>
              <rect x={x + 2}        y={H - outH} width={barW} height={outH} rx={2} fill="var(--info)" opacity={0.75}/>
              {i === 6 && (
                <>
                  <text x={x - barW / 2 - 1} y={H - inwH - 6} textAnchor="middle" fontSize="11" fontWeight="600" fill="var(--positive-text)" style={{ fontFamily: "var(--font-sans)" }}>+660</text>
                  <rect x={x - barW - 4} y={H - inwH - 2} width={barW + 4} height={inwH + 2} rx={3} fill="none" stroke="var(--positive)" strokeWidth="1.2" strokeDasharray="3 3" opacity="0.55"/>
                </>
              )}
              <text x={x} y={H + 18} textAnchor="middle" fontSize="11" fill={i === 6 ? "var(--ink)" : "var(--ink-3)"} fontWeight={i === 6 ? "600" : "400"} style={{ fontFamily: "var(--font-sans)" }}>{d.d}</text>
            </g>
          );
        })}
      </svg>
    </div>
  );
}

Object.assign(window, { DashboardPage, KpiCard });
