/* ============================================================
   ELECTROMED — Enhanced Dashboard
   ============================================================ */
function Dashboard({ go, branch }) {
  const { PKR } = window.DATA;
  const bf = branch !== 'All' ? { branch_id: branch } : {};

  const { data: dash, loading, refetch } = useDashboard(bf);
  const { data: branchList }             = useBranches();

  const user      = api.user || {};
  const firstName = (user.name || 'there').split(' ')[0];
  const today     = new Date();
  const greeting  = today.getHours() < 12 ? 'Good morning' : today.getHours() < 17 ? 'Good afternoon' : 'Good evening';
  const branchLabel = branch === 'All' ? 'all branches'
    : (branchList.find(b => String(b.id) === String(branch))?.name || branch);

  if (loading) return (
    <div className="view-enter" style={{ display: 'grid', placeItems: 'center', minHeight: 320 }}>
      <div style={{ textAlign: 'center' }}>
        <div className="track" style={{ width: 200, margin: '0 auto 12px' }}><i style={{ width: '60%' }} /></div>
        <div className="tiny muted">Loading dashboard…</div>
      </div>
    </div>
  );

  /* ── Derived values ──────────────────────────────────────── */
  const monthlyTarget  = dash.monthlyTarget || 4200000;
  const monthCollected = dash.monthCollected || 0;
  const targetPct      = Math.min(100, Math.round(monthCollected / monthlyTarget * 100));
  const revenueSeries  = dash.revenueSeries  || [];
  const alerts         = dash.alerts         || [];
  const recentActivity = dash.recentActivity || [];
  const unpaidInvoices = dash.unpaidInvoices || [];
  const expiringSoon   = dash.expiringSoon   || [];
  const branchPerf     = dash.branchPerformance || [];

  const payModeIcon = (mode) => {
    if (!mode) return '—';
    if (mode === 'Cash') return '💵 Cash';
    if (mode === 'Cheque') return '🏦 Cheque';
    if (mode === 'Online') return '📱 Online';
    return '🏛 ' + mode;
  };

  return (
    <div className="view-enter">

      {/* ── Header ─────────────────────────────────────────── */}
      <div className="page-head">
        <div>
          <div className="eyebrow" style={{ marginBottom: 6 }}>
            {today.toLocaleDateString('en-GB', { weekday: 'long', day: 'numeric', month: 'long', year: 'numeric' })}
          </div>
          <h1 className="page-title" style={{ fontSize: 32 }}>{greeting}, {firstName} 👋</h1>
          <div className="page-sub">Electromed · {branchLabel} — complete business snapshot</div>
        </div>
        <div className="row" style={{ gap: 10 }}>
          <Btn variant="ghost" icon={<Icons.download size={16} />}>Export</Btn>
          <Btn variant="ghost" icon={<Icons.pay size={16} />} onClick={() => go('payments')}>Record Payment</Btn>
          <Btn variant="primary" icon={<Icons.plus size={16} stroke={2.6} />} onClick={() => go('sales')}>New Invoice</Btn>
        </div>
      </div>

      {/* ── Row 1: 6 KPI cards ─────────────────────────────── */}
      <div className="grid" style={{ gridTemplateColumns: 'repeat(6,1fr)', gap: 12, marginBottom: 16 }}>
        <KpiCard icon={<Icons.pay size={18} />} label="Today Collected" value={PKR(dash.todayCollected || 0)} accent="lime" />
        <KpiCard icon={<Icons.chart size={18} />} label="This Month" value={PKR(monthCollected)} accent="lime" />
        <KpiCard icon={<Icons.pay size={18} />} label="Outstanding Dues" value={PKR(dash.outstanding || 0)} accent="bad" />
        <KpiCard icon={<Icons.rental size={18} />} label="Active Rentals" value={dash.activeRentals || 0} sub={`${dash.overdueRentals || 0} overdue`} accent={dash.overdueRentals > 0 ? 'bad' : 'ok'} />
        <KpiCard icon={<Icons.shield size={18} />} label="Deposits Held" value={PKR(dash.depositsCollected || 0)} sub="refundable" accent="info" />
        <KpiCard icon={<Icons.wrench size={18} />} label="Open Job Cards" value={dash.openJobs || 0} sub={`${dash.lowStockCount || 0} low stock`} accent={dash.lowStockCount > 0 ? 'warn' : 'ok'} />
      </div>

      {/* ── Row 2: Hero card + Revenue chart ───────────────── */}
      <div className="grid" style={{ gridTemplateColumns: '1fr 1.6fr', gap: 14, marginBottom: 14 }}>

        {/* Hero: monthly collection + target */}
        <div className="card card-pad" style={{ background: 'var(--grad-green)', color: '#fff', border: 'none' }}>
          <div className="row" style={{ justifyContent: 'space-between', marginBottom: 4 }}>
            <span style={{ color: 'rgba(255,255,255,.75)', fontWeight: 600, fontSize: 13 }}>Total Collected · This Month</span>
            <span className="badge" style={{ background: 'rgba(169,236,110,.2)', color: 'var(--lime)', fontSize: 11 }}>
              {targetPct}% of target
            </span>
          </div>
          <div style={{ fontSize: 38, fontWeight: 800, letterSpacing: '-.03em', margin: '8px 0 2px' }}>{PKR(monthCollected)}</div>
          <div className="tiny" style={{ color: 'rgba(255,255,255,.6)', marginBottom: 14 }}>Sales · Rentals · Workshop combined</div>

          {/* Target progress */}
          <div style={{ background: 'rgba(255,255,255,.12)', borderRadius: 8, height: 8, marginBottom: 6, overflow: 'hidden' }}>
            <div style={{ height: '100%', width: targetPct + '%', background: 'var(--lime)', borderRadius: 8, transition: 'width .6s ease' }} />
          </div>
          <div className="row" style={{ justifyContent: 'space-between', marginBottom: 18 }}>
            <span className="tiny" style={{ color: 'rgba(255,255,255,.6)' }}>Target: {PKR(monthlyTarget)}</span>
            <span className="tiny" style={{ color: 'rgba(255,255,255,.6)' }}>{PKR(Math.max(0, monthlyTarget - monthCollected))} remaining</span>
          </div>

          {/* Mini breakdown */}
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3,1fr)', gap: 10, paddingTop: 16, borderTop: '1px solid rgba(255,255,255,.14)' }}>
            {[
              ['Today', PKR(dash.todayCollected || 0)],
              ['Rental / mo', PKR(dash.monthlyRentalInc || 0)],
              ['Outstanding', PKR(dash.outstanding || 0)],
            ].map(([k, v]) => (
              <div key={k}>
                <div className="tiny" style={{ color: 'rgba(255,255,255,.55)' }}>{k}</div>
                <div style={{ fontWeight: 700, fontSize: 14, marginTop: 2 }}>{v}</div>
              </div>
            ))}
          </div>

          <div className="row" style={{ gap: 8, marginTop: 18 }}>
            <button className="btn btn-primary" style={{ flex: 1, fontSize: 13 }} onClick={() => go('payments')}>
              <Icons.pay size={14} />Record Payment
            </button>
            <button className="btn" style={{ flex: 1, background: 'rgba(255,255,255,.12)', color: '#fff', fontSize: 13 }} onClick={() => go('reports')}>
              <Icons.chart size={14} />Reports
            </button>
          </div>
        </div>

        {/* Revenue by stream chart */}
        <div className="card card-pad">
          <div className="row" style={{ justifyContent: 'space-between', marginBottom: 4 }}>
            <div>
              <div style={{ fontWeight: 800, fontSize: 16 }}>Revenue by Stream</div>
              <div className="tiny muted" style={{ marginTop: 2 }}>Last 6 months · PKR</div>
            </div>
            <div className="row" style={{ gap: 14 }}>
              {[['Sales', 'var(--lime)'], ['Rentals', 'var(--forest)'], ['Workshop', 'var(--ink-3)']].map(([l, c]) => (
                <span key={l} className="row tiny" style={{ gap: 5, fontWeight: 700 }}>
                  <span style={{ width: 10, height: 10, borderRadius: 3, background: c, flexShrink: 0 }} />{l}
                </span>
              ))}
            </div>
          </div>
          <div style={{ marginTop: 16 }}>
            {revenueSeries.length > 0
              ? <BarChart data={revenueSeries} keys={['sales', 'rentals', 'workshop']}
                  colors={['var(--lime)', 'var(--forest)', 'var(--ink-3)']}
                  fmt={(v) => v >= 1000000 ? (v/1000000).toFixed(1)+'M' : v >= 1000 ? Math.round(v/1000)+'k' : String(v)} />
              : <div className="tiny muted" style={{ padding: '48px 0', textAlign: 'center' }}>No revenue data yet.</div>
            }
          </div>
        </div>
      </div>

      {/* ── Row 3: Rental Finance + Deposits + Workshop ────── */}
      <div className="grid" style={{ gridTemplateColumns: '1fr 1fr 1fr', gap: 14, marginBottom: 14 }}>

        {/* Rental income tracker */}
        <div className="card card-pad">
          <div className="row" style={{ justifyContent: 'space-between', marginBottom: 16 }}>
            <div style={{ fontWeight: 800, fontSize: 15 }}>Rental Income</div>
            <span className="badge" style={{ background: 'var(--lime-soft)', color: 'var(--lime-700)' }}>Active: {dash.activeRentals || 0}</span>
          </div>
          <div style={{ display: 'grid', gap: 10 }}>
            {[
              { label: 'Monthly recurring',    value: dash.monthlyRentalInc || 0,  color: 'var(--ink)',    bold: true },
              { label: 'Collected (all time)', value: dash.rpPaid || 0,             color: 'var(--ok)',    bold: false },
              { label: 'Expected (billed)',    value: dash.rpDue  || 0,             color: 'var(--ink-2)', bold: false },
              { label: 'Pending / outstanding',value: dash.rpOutstanding || 0,      color: dash.rpOutstanding > 0 ? 'var(--bad)' : 'var(--ok)', bold: false },
            ].map(({ label, value, color, bold }) => (
              <div key={label} className="row" style={{ justifyContent: 'space-between', padding: '8px 12px', background: 'var(--surface-2)', borderRadius: 10 }}>
                <span className="tiny" style={{ fontWeight: 600, color: 'var(--ink-2)' }}>{label}</span>
                <span className="mono" style={{ fontWeight: bold ? 800 : 700, fontSize: bold ? 15 : 13, color }}>{PKR(value)}</span>
              </div>
            ))}
          </div>
          {(dash.overdueRentals || 0) > 0 && (
            <div className="row" style={{ gap: 8, marginTop: 12, padding: '8px 12px', background: 'var(--bad-bg)', borderRadius: 10, cursor: 'pointer' }} onClick={() => go('rentals')}>
              <Icons.clock size={14} style={{ color: 'var(--bad)', flexShrink: 0 }} />
              <span className="tiny" style={{ color: 'var(--bad)', fontWeight: 700 }}>{dash.overdueRentals} overdue rental{dash.overdueRentals > 1 ? 's' : ''} — collect now</span>
            </div>
          )}
        </div>

        {/* Deposits tracker */}
        <div className="card card-pad">
          <div style={{ fontWeight: 800, fontSize: 15, marginBottom: 16 }}>Security Deposits</div>
          <div style={{ display: 'grid', gap: 10 }}>
            {[
              { label: 'Collected (held)',   value: dash.depositsCollected || 0,  color: 'var(--ok)',    icon: '✓' },
              { label: 'Pending collection', value: dash.depositsPending   || 0,  color: 'var(--warn)',  icon: '!' },
              { label: 'Refundable (closed)',value: dash.depositsRefundable || 0, color: 'var(--info)',  icon: '↩' },
            ].map(({ label, value, color, icon }) => (
              <div key={label} className="row" style={{ justifyContent: 'space-between', padding: '8px 12px', background: 'var(--surface-2)', borderRadius: 10 }}>
                <span className="row tiny" style={{ gap: 7, fontWeight: 600, color: 'var(--ink-2)' }}>
                  <span style={{ color, fontWeight: 800 }}>{icon}</span>{label}
                </span>
                <span className="mono" style={{ fontWeight: 700, color }}>{PKR(value)}</span>
              </div>
            ))}
          </div>
          <div style={{ marginTop: 16, paddingTop: 14, borderTop: '1px solid var(--line)' }}>
            <div className="row" style={{ justifyContent: 'space-between' }}>
              <span className="tiny muted">Total liability</span>
              <span className="mono" style={{ fontWeight: 800, fontSize: 15 }}>{PKR((dash.depositsCollected||0) + (dash.depositsPending||0))}</span>
            </div>
          </div>
        </div>

        {/* Workshop summary */}
        <div className="card card-pad">
          <div className="row" style={{ justifyContent: 'space-between', marginBottom: 16 }}>
            <div style={{ fontWeight: 800, fontSize: 15 }}>Workshop</div>
            <Btn variant="ghost" sm onClick={() => go('workshop')}>View all <Icons.chevR size={12} /></Btn>
          </div>
          <div className="grid" style={{ gridTemplateColumns: '1fr 1fr', gap: 10, marginBottom: 14 }}>
            {[
              { label: 'Open',        val: (dash.jobsByStatus||{}).Open       || 0, color: 'var(--bad-bg)',  tc: 'var(--bad)'  },
              { label: 'In Progress', val: (dash.jobsByStatus||{}).InProgress || 0, color: 'var(--warn-bg)', tc: 'var(--warn)' },
              { label: 'Pending Parts',val:(dash.jobsByStatus||{}).Pending    || 0, color: 'var(--info-bg)', tc: 'var(--info)' },
              { label: 'Billed',      val: (dash.jobsByStatus||{}).Billed     || 0, color: 'var(--lime-soft)',tc:'var(--lime-700)' },
            ].map(({ label, val, color, tc }) => (
              <div key={label} style={{ background: color, borderRadius: 10, padding: '10px 13px' }}>
                <div style={{ fontSize: 22, fontWeight: 800, color: tc }}>{val}</div>
                <div className="tiny" style={{ color: tc, fontWeight: 600, marginTop: 2 }}>{label}</div>
              </div>
            ))}
          </div>
          {(dash.workshopRevenue || 0) > 0 && (
            <div className="row" style={{ justifyContent: 'space-between', padding: '8px 12px', background: 'var(--surface-2)', borderRadius: 10 }}>
              <span className="tiny muted">Estimated workshop revenue</span>
              <span className="mono" style={{ fontWeight: 700 }}>{PKR(dash.workshopRevenue || 0)}</span>
            </div>
          )}
        </div>
      </div>

      {/* ── Row 4: Alerts + Recent Activity ─────────────────── */}
      <div className="grid" style={{ gridTemplateColumns: '1fr 1.8fr', gap: 14, marginBottom: 14 }}>

        {/* Operational Alerts */}
        <div className="card card-pad">
          <div style={{ fontWeight: 800, fontSize: 15, marginBottom: 14 }}>
            Operational Alerts
            {alerts.length > 0 && <span className="badge" style={{ marginLeft: 8, background: 'var(--bad-bg)', color: 'var(--bad)' }}>{alerts.length}</span>}
          </div>
          {alerts.length === 0 ? (
            <div style={{ textAlign: 'center', padding: '24px 0' }}>
              <div style={{ fontSize: 26, marginBottom: 8 }}>✅</div>
              <div className="tiny muted" style={{ fontWeight: 600 }}>All clear — no active alerts</div>
            </div>
          ) : (
            <div style={{ display: 'grid', gap: 9 }}>
              {alerts.map((a, i) => (
                <div key={i} className="row" style={{ gap: 10, padding: '10px 12px', borderRadius: 10, cursor: 'pointer',
                  background: a.type === 'danger' ? 'var(--bad-bg)' : a.type === 'warn' ? 'var(--warn-bg)' : 'var(--info-bg)'
                }} onClick={() => go(a.link)}>
                  <span style={{ fontSize: 16, flexShrink: 0 }}>
                    {a.type === 'danger' ? '🔴' : a.type === 'warn' ? '🟡' : '🔵'}
                  </span>
                  <span className="tiny" style={{
                    fontWeight: 600,
                    color: a.type === 'danger' ? 'var(--bad)' : a.type === 'warn' ? 'var(--warn)' : 'var(--info)'
                  }}>{a.msg}</span>
                  <Icons.chevR size={13} style={{ marginLeft: 'auto', flexShrink: 0, opacity: 0.5 }} />
                </div>
              ))}
            </div>
          )}

          {/* Low stock items */}
          {(dash.lowStockItems || []).length > 0 && (
            <div style={{ marginTop: 14, paddingTop: 12, borderTop: '1px solid var(--line)' }}>
              <div className="tiny muted" style={{ fontWeight: 700, marginBottom: 8 }}>LOW STOCK ITEMS</div>
              {(dash.lowStockItems || []).map(item => (
                <div key={item.id} className="row" style={{ justifyContent: 'space-between', marginBottom: 6 }}>
                  <span className="tiny" style={{ fontWeight: 600 }}>{item.name}</span>
                  <span className="tiny mono" style={{ color: 'var(--bad)', fontWeight: 700 }}>
                    {item.stock} / {item.low_threshold}
                  </span>
                </div>
              ))}
            </div>
          )}
        </div>

        {/* Recent Activity */}
        <div className="card">
          <div className="row card-pad" style={{ justifyContent: 'space-between', paddingBottom: 6 }}>
            <div style={{ fontWeight: 800, fontSize: 15 }}>Recent Transactions</div>
            <Btn variant="ghost" sm onClick={() => go('payments')}>View all <Icons.chevR size={12} /></Btn>
          </div>
          <div style={{ overflowX: 'auto' }}>
            <table className="tbl" style={{ fontSize: 12.5 }}>
              <thead>
                <tr>
                  <th>Customer</th>
                  <th>Type</th>
                  <th>Mode</th>
                  <th style={{ textAlign: 'right' }}>Amount</th>
                  <th>Date</th>
                </tr>
              </thead>
              <tbody>
                {recentActivity.length === 0 && (
                  <tr><td colSpan={5} className="tiny muted" style={{ textAlign: 'center', padding: 18 }}>No transactions yet.</td></tr>
                )}
                {recentActivity.map((t, i) => (
                  <tr key={t.id || i}>
                    <td style={{ fontWeight: 600 }}>
                      {t.customer_name || '—'}
                      {t.period_label && <div className="tiny muted">{t.period_label}</div>}
                    </td>
                    <td>
                      <Badge kind={t.type === 'Rental' ? 'info' : t.type === 'Workshop' ? 'warn' : 'ok'}>
                        {t.type || 'Sale'}
                      </Badge>
                    </td>
                    <td className="tiny muted">{t.mode || '—'}</td>
                    <td className="mono" style={{ textAlign: 'right', fontWeight: 700, color: 'var(--ok)' }}>
                      {PKR(parseFloat(t.amount || 0))}
                    </td>
                    <td className="tiny mono muted">{(t.payment_date || '').slice(0, 10) || '—'}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      </div>

      {/* ── Row 5: Unpaid Invoices + Expiring Contracts + Branch Perf ─ */}
      <div className="grid" style={{ gridTemplateColumns: '1.4fr 1fr 1fr', gap: 14 }}>

        {/* Unpaid / partial invoices */}
        <div className="card">
          <div className="row card-pad" style={{ justifyContent: 'space-between', paddingBottom: 6 }}>
            <div>
              <div style={{ fontWeight: 800, fontSize: 15 }}>Unpaid Invoices</div>
              <div className="tiny muted" style={{ marginTop: 2 }}>Outstanding: {PKR(dash.outstanding || 0)}</div>
            </div>
            <Btn variant="ghost" sm onClick={() => go('sales')}>View all <Icons.chevR size={12} /></Btn>
          </div>
          <div style={{ overflowX: 'auto' }}>
            <table className="tbl" style={{ fontSize: 12.5 }}>
              <thead><tr><th>#</th><th>Customer</th><th style={{ textAlign: 'right' }}>Amount</th><th style={{ textAlign: 'right' }}>Received</th><th>Status</th></tr></thead>
              <tbody>
                {unpaidInvoices.length === 0 && (
                  <tr><td colSpan={5} className="tiny muted" style={{ textAlign: 'center', padding: 16 }}>All invoices paid 🎉</td></tr>
                )}
                {unpaidInvoices.slice(0, 6).map((iv) => (
                  <tr key={iv.id} style={{ cursor: 'pointer' }} onClick={() => go('sales')}>
                    <td className="mono tiny muted">{iv.invoice_number}</td>
                    <td style={{ fontWeight: 600 }}>{iv.customer_name}</td>
                    <td className="mono" style={{ textAlign: 'right' }}>{PKR(iv.amount)}</td>
                    <td className="mono" style={{ textAlign: 'right', color: 'var(--ok)' }}>{PKR(iv.received || 0)}</td>
                    <td><Badge kind={window.statusKind ? window.statusKind(iv.status) : 'warn'}>{iv.status}</Badge></td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>

        {/* Expiring contracts */}
        <div className="card card-pad">
          <div style={{ fontWeight: 800, fontSize: 15, marginBottom: 14 }}>
            Expiring Soon
            <span className="tiny muted" style={{ fontWeight: 400, marginLeft: 8 }}>within 14 days</span>
          </div>
          {expiringSoon.length === 0 ? (
            <div className="tiny muted" style={{ padding: '20px 0', textAlign: 'center' }}>No contracts expiring soon.</div>
          ) : (
            <div style={{ display: 'grid', gap: 9 }}>
              {expiringSoon.map(r => {
                const daysLeft = Math.ceil((new Date(r.due_date) - new Date()) / 86400000);
                return (
                  <div key={r.id} style={{ padding: '10px 12px', borderRadius: 10, border: '1px solid var(--line)', cursor: 'pointer' }} onClick={() => go('rentals')}>
                    <div className="row" style={{ justifyContent: 'space-between', marginBottom: 3 }}>
                      <span style={{ fontWeight: 700, fontSize: 13 }}>{r.customer_name || r.device}</span>
                      <Badge kind={daysLeft <= 3 ? 'bad' : daysLeft <= 7 ? 'warn' : 'idle'}>
                        {daysLeft <= 0 ? 'Today' : daysLeft + 'd'}
                      </Badge>
                    </div>
                    <div className="tiny muted">{r.rental_number} · {r.device} · {r.plan}</div>
                  </div>
                );
              })}
            </div>
          )}
        </div>

        {/* Branch performance */}
        <div className="card card-pad">
          <div style={{ fontWeight: 800, fontSize: 15, marginBottom: 16 }}>Branch Performance</div>
          {branchPerf.length === 0 ? (
            <div className="tiny muted" style={{ padding: '20px 0', textAlign: 'center' }}>No payments this month yet.</div>
          ) : (() => {
            const max = Math.max(...branchPerf.map(b => b.total), 1);
            return branchPerf.map(b => (
              <div key={b.id} style={{ marginBottom: 14 }}>
                <div className="row" style={{ justifyContent: 'space-between', marginBottom: 6 }}>
                  <span style={{ fontWeight: 600, fontSize: 13 }}>{b.name}</span>
                  <span className="mono tiny">{PKR(b.total)}</span>
                </div>
                <div className="track" style={{ height: 8 }}>
                  <i style={{ width: Math.round(b.total / max * 100) + '%' }} />
                </div>
              </div>
            ));
          })()}
        </div>
      </div>

    </div>
  );
}

/* ── KPI Card helper ──────────────────────────────────────────── */
function KpiCard({ icon, label, value, sub, accent }) {
  const bg    = accent === 'bad'  ? 'var(--bad-bg)'   :
                accent === 'warn' ? 'var(--warn-bg)'  :
                accent === 'info' ? 'var(--info-bg)'  :
                accent === 'ok'   ? 'var(--lime-soft)' : 'var(--surface-2)';
  const ic    = accent === 'bad'  ? 'var(--bad)'   :
                accent === 'warn' ? 'var(--warn)'  :
                accent === 'info' ? 'var(--info)'  :
                accent === 'ok'   ? 'var(--ok)'    :
                accent === 'lime' ? 'var(--lime-700)' : 'var(--ink-2)';
  return (
    <div className="card card-pad" style={{ background: bg }}>
      <div className="row" style={{ justifyContent: 'space-between', marginBottom: 10 }}>
        <span style={{ color: ic }}>{icon}</span>
        {sub && <span className="tiny" style={{ color: ic, fontWeight: 600, fontSize: 11 }}>{sub}</span>}
      </div>
      <div style={{ fontWeight: 800, fontSize: 18, fontVariantNumeric: 'tabular-nums' }}>{value}</div>
      <div className="tiny muted" style={{ marginTop: 3, fontWeight: 600 }}>{label}</div>
    </div>
  );
}

window.Dashboard = Dashboard;
