/* ============================================================
   ELECTROMED — Reports & Analytics (all data from API)
   ============================================================ */
function Donut({ data, size = 168 }) {
  const total = data.reduce((s, d) => s + d.value, 0);
  if (!total) return <div style={{ width: size, height: size, borderRadius: '50%', background: 'var(--surface-2)' }} />;
  let acc = 0;
  const stops = data.map((d) => {
    const from = (acc / total) * 360; acc += d.value;
    const to   = (acc / total) * 360;
    return `${d.color} ${from}deg ${to}deg`;
  }).join(', ');
  return (
    <div style={{ position: 'relative', width: size, height: size, flexShrink: 0 }}>
      <div style={{ width: size, height: size, borderRadius: '50%', background: `conic-gradient(${stops})` }} />
      <div style={{ position: 'absolute', inset: size * 0.16, borderRadius: '50%', background: '#fff', display: 'grid', placeItems: 'center', textAlign: 'center', boxShadow: 'inset 0 0 0 1px var(--line)' }}>
        <div><div className="tiny muted" style={{ fontWeight: 700 }}>Total</div><div style={{ fontWeight: 800, fontSize: 17 }}>Rs {(total / 1000000).toFixed(1)}M</div></div>
      </div>
    </div>
  );
}

function Reports({ branch, go }) {
  const { PKR } = window.DATA;
  const [view, setView] = useState('Overview');
  const reportRef = useRef(null);
  const bf = branch !== 'All' ? { branch_id: branch } : {};

  const { data: customers }    = useCustomers(bf);
  const { data: dash }         = useDashboard(bf);
  const { data: byModel }      = useSalesByModel(bf);

  const revenueByCategory = dash.revenueByCategory || [];
  const revenueSeries     = dash.revenueSeries     || [];

  const topCust = [...customers].sort((a, b) => (b.device_count || 0) - (a.device_count || 0)).slice(0, 5);

  const totalRevenue  = (revenueByCategory.reduce((s, c) => s + c.value, 0));
  const activeRentals = dash.activeRentals || 0;
  const openJobs      = dash.openJobs      || 0;

  return (
    <div className="view-enter" ref={reportRef}>
      <PageHead eyebrow="08 · Reports & Dashboard" title="Reports & Analytics"
        sub="Revenue analytics plus date-wise, team-wise and doctor-wise sales reports."
        actions={<span className="row no-print" style={{ gap: 10 }}>
          <div className="tabs">
            <button className={cls('tab', view === 'Overview'      && 'active')} onClick={() => setView('Overview')}>Overview</button>
            <button className={cls('tab', view === 'Sales'         && 'active')} onClick={() => setView('Sales')}>Sales Reports</button>
            <button className={cls('tab', view === 'Profitability' && 'active')} onClick={() => setView('Profitability')}>Profitability</button>
            <button className={cls('tab', view === 'Accounting'    && 'active')} onClick={() => setView('Accounting')}>Accounting</button>
          </div>
          <Btn variant="primary" icon={<Icons.download size={16} />} onClick={() => window.printDocument(reportRef.current)}>Export PDF</Btn>
        </span>} />

      {view === 'Accounting' ? <AccountingReports branch={branch} /> : view === 'Sales' ? <SalesReports branch={branch} /> : view === 'Profitability' ? <ProfitabilityReport branch={branch} /> : <>

        <div className="grid" style={{ gridTemplateColumns: 'repeat(4,1fr)', marginBottom: 18 }}>
          <StatCard icon={<Icons.chart  size={18} />} label="Total Revenue"        value={PKR(totalRevenue)}  sub="all time" />
          <StatCard icon={<Icons.rental size={18} />} label="Active Rentals"       value={activeRentals}      sub="fleet on field" />
          <StatCard icon={<Icons.wrench size={18} />} label="Open Job Cards"       value={openJobs}           sub="in workshop" />
          <StatCard icon={<Icons.crm    size={18} />} label="Total Customers"      value={customers.length}   sub="registered" />
        </div>

        <div className="grid" style={{ gridTemplateColumns: '1fr 1fr', alignItems: 'start', marginBottom: 18 }}>
          {/* Revenue by category */}
          <div className="card card-pad">
            <div style={{ fontWeight: 800, fontSize: 17 }}>Revenue by Category</div>
            <div className="tiny muted" style={{ marginTop: 3, marginBottom: 18 }}>Sales · Rentals · Workshop split</div>
            <div className="row" style={{ gap: 26 }}>
              <Donut data={revenueByCategory} />
              <div style={{ display: 'grid', gap: 14, flex: 1 }}>
                {revenueByCategory.map(c => {
                  const pct = totalRevenue > 0 ? Math.round(c.value / totalRevenue * 100) : 0;
                  return (
                    <div key={c.label}>
                      <div className="row" style={{ justifyContent: 'space-between', marginBottom: 5 }}>
                        <span className="row" style={{ gap: 8, fontWeight: 700, fontSize: 13.5 }}>
                          <span style={{ width: 11, height: 11, borderRadius: 3, background: c.color }} />{c.label}
                        </span>
                        <span className="mono" style={{ fontWeight: 700 }}>{pct}%</span>
                      </div>
                      <div className="tiny muted mono">{PKR(c.value)}</div>
                    </div>
                  );
                })}
                {!revenueByCategory.length && <div className="tiny muted">No data yet.</div>}
              </div>
            </div>
          </div>

          {/* Revenue trend */}
          <div className="card card-pad">
            <div style={{ fontWeight: 800, fontSize: 17 }}>Revenue Trend</div>
            <div className="tiny muted" style={{ marginTop: 3, marginBottom: 18 }}>Monthly total · PKR</div>
            {revenueSeries.length > 0
              ? <BarChart data={revenueSeries.map(r => ({ m: r.m, total: r.sales + r.rentals + r.workshop }))}
                  keys={['total']} colors={['var(--lime)']} height={184}
                  fmt={(v) => v >= 1000000 ? (v / 1000000).toFixed(1) + 'M' : Math.round(v / 1000) + 'k'} />
              : <div className="ph-img" style={{ height: 184 }}>No revenue data yet.</div>
            }
          </div>
        </div>

        {/* Sales by model */}
        <div className="card card-pad" style={{ marginBottom: 18 }}>
          <div style={{ fontWeight: 800, fontSize: 17, marginBottom: 4 }}>Sales by Machine Model</div>
          <div className="tiny muted" style={{ marginBottom: 18 }}>Revenue contribution per device</div>
          {byModel.length > 0 ? (
            <div style={{ display: 'grid', gap: 12 }}>
              {byModel.map(m => {
                const max = Math.max(...byModel.map(x => x.value), 1);
                return (
                  <div key={m.label} className="row" style={{ gap: 14 }}>
                    <span style={{ width: 130, fontWeight: 600, fontSize: 13.5, flexShrink: 0 }}>{m.label}</span>
                    <div className="track grow" style={{ height: 14 }}><i style={{ width: (m.value / max * 100) + '%' }} /></div>
                    <span className="mono tiny" style={{ width: 90, textAlign: 'right', fontWeight: 700 }}>{PKR(m.value)}</span>
                  </div>
                );
              })}
            </div>
          ) : <div className="tiny muted">No invoice data yet.</div>}
        </div>

        <div className="grid" style={{ gridTemplateColumns: '1fr 1fr', alignItems: 'start' }}>
          {/* Top customers */}
          <div className="card">
            <div className="card-pad" style={{ paddingBottom: 6 }}><div style={{ fontWeight: 800, fontSize: 17 }}>Top Customers</div></div>
            <table className="tbl">
              <tbody>
                {topCust.map((c, ix) => (
                  <tr key={c.id}>
                    <td style={{ width: 34 }}><span style={{ fontWeight: 800, color: ix < 3 ? 'var(--lime-700)' : 'var(--ink-3)' }}>#{ix + 1}</span></td>
                    <td><div style={{ fontWeight: 700 }}>{c.name}</div><div className="tiny muted">{c.city}</div></td>
                    <td><Badge kind={c.type === 'Hospital' ? 'info' : c.type === 'Sub-Distributor' ? 'warn' : 'idle'}>{c.tag || c.type}</Badge></td>
                    <td className="mono" style={{ fontWeight: 700, textAlign: 'right' }}>{c.device_count || 0} units</td>
                  </tr>
                ))}
                {!topCust.length && <tr><td colSpan="4" className="muted tiny" style={{ padding: 16 }}>No customers yet.</td></tr>}
              </tbody>
            </table>
          </div>

          {/* Staff performance */}
          <StaffPerformance PKR={PKR} />
        </div>
      </>}
    </div>
  );
}

function StaffPerformance({ PKR }) {
  const { data: team } = useSalesTeamReport();
  return (
    <div className="card">
      <div className="card-pad" style={{ paddingBottom: 6 }}><div style={{ fontWeight: 800, fontSize: 17 }}>Staff Performance</div></div>
      <table className="tbl">
        <tbody>
          {team.map(s => (
            <tr key={s.id}>
              <td>
                <div className="row" style={{ gap: 11 }}>
                  <div style={{ width: 36, height: 36, borderRadius: 50, background: 'var(--surface-3)', display: 'grid', placeItems: 'center', fontWeight: 800, fontSize: 12.5, color: 'var(--ink-2)' }}>{s.init}</div>
                  <div><div style={{ fontWeight: 700 }}>{s.name}</div><div className="tiny muted">{s.role}</div></div>
                </div>
              </td>
              <td className="tiny muted">{s.branch}</td>
              <td className="mono" style={{ fontWeight: 700, textAlign: 'right' }}>{s.deals} deals · {PKR(s.booked)}</td>
            </tr>
          ))}
          {!team.length && <tr><td colSpan="3" className="muted tiny" style={{ padding: 16 }}>No sales data yet.</td></tr>}
        </tbody>
      </table>
    </div>
  );
}

/* ── Sales Reports (Date / Team / Doctor wise) ─────────────────── */
function SalesReports({ branch = 'All' }) {
  const { PKR } = window.DATA;
  const [cut, setCut] = useState('Date wise');
  const bf = branch !== 'All' ? { branch_id: branch } : {};
  const { data: invoices } = useInvoices(bf);
  const { data: team }     = useSalesTeamReport();
  const { data: doctors }  = useDoctorReport();

  // Group invoices by date for daily sales
  const dailyMap = {};
  invoices.forEach(iv => {
    const d = (iv.date || '').slice(0, 10);
    if (!d) return;
    if (!dailyMap[d]) dailyMap[d] = { d, sales: 0, count: 0 };
    dailyMap[d].sales += parseFloat(iv.amount || 0);
    dailyMap[d].count += 1;
  });
  const daily = Object.values(dailyMap)
    .sort((a, b) => b.d.localeCompare(a.d))
    .slice(0, 10)
    .map(x => ({ ...x, d: new Date(x.d).toLocaleDateString('en-GB', { day: '2-digit', month: 'short' }) }))
    .reverse();
  const totalDaily = daily.reduce((s, x) => s + x.sales, 0);

  return (
    <div>
      <div style={{ paddingBottom: 18 }}>
        <Tabs tabs={['Date wise', 'Sales team wise', 'Doctor wise']} value={cut} onChange={setCut} />
      </div>

      {cut === 'Date wise' && (
        <div className="grid" style={{ gap: 18 }}>
          <div className="card card-pad">
            <div className="row" style={{ justifyContent: 'space-between', marginBottom: 18 }}>
              <div><div style={{ fontWeight: 800, fontSize: 17 }}>Daily Sales</div><div className="tiny muted" style={{ marginTop: 3 }}>Last 10 days · invoiced value</div></div>
              <div style={{ textAlign: 'right' }}><div className="mono" style={{ fontWeight: 800, fontSize: 18 }}>{PKR(totalDaily)}</div><div className="tiny muted">period total</div></div>
            </div>
            {daily.length > 0
              ? <BarChart data={daily.map(x => ({ label: x.d, v: x.sales }))} keys={['v']} colors={['var(--lime)']} height={180}
                  fmt={(v) => v >= 1000000 ? (v / 1000000).toFixed(1) + 'M' : Math.round(v / 1000) + 'k'} />
              : <div className="tiny muted" style={{ padding: 24 }}>No invoice data yet.</div>
            }
          </div>
          <div className="card">
            <table className="tbl">
              <thead><tr><th>Date</th><th>Invoices</th><th style={{ textAlign: 'right' }}>Sales Value</th><th style={{ textAlign: 'right' }}>Avg / Invoice</th></tr></thead>
              <tbody>
                {daily.filter(x => x.count).map(x => (
                  <tr key={x.d}>
                    <td style={{ fontWeight: 700 }}>{x.d}</td>
                    <td className="mono">{x.count}</td>
                    <td className="mono" style={{ textAlign: 'right', fontWeight: 700 }}>{PKR(x.sales)}</td>
                    <td className="mono muted" style={{ textAlign: 'right' }}>{PKR(Math.round(x.sales / x.count))}</td>
                  </tr>
                ))}
                {!daily.length && <tr><td colSpan="4" className="muted tiny" style={{ padding: 14 }}>No data yet.</td></tr>}
              </tbody>
            </table>
          </div>
        </div>
      )}

      {cut === 'Sales team wise' && (
        <div className="card">
          <div className="card-pad" style={{ paddingBottom: 6 }}>
            <div style={{ fontWeight: 800, fontSize: 17 }}>Sales by Team Member</div>
            <div className="tiny muted" style={{ marginTop: 3 }}>Booked value vs target this quarter</div>
          </div>
          <table className="tbl">
            <thead><tr><th>Salesperson</th><th>Branch</th><th>Deals</th><th>Booked</th><th>Target</th><th style={{ width: 180 }}>Attainment</th></tr></thead>
            <tbody>
              {team.map(s => {
                const pct = s.target > 0 ? Math.round(s.booked / s.target * 100) : 0;
                return (
                  <tr key={s.id}>
                    <td>
                      <div className="row" style={{ gap: 11 }}>
                        <div style={{ width: 36, height: 36, borderRadius: 50, background: 'var(--surface-3)', display: 'grid', placeItems: 'center', fontWeight: 800, fontSize: 12.5, color: 'var(--ink-2)' }}>{s.init}</div>
                        <div><div style={{ fontWeight: 700 }}>{s.name}</div><div className="tiny muted">{s.role}</div></div>
                      </div>
                    </td>
                    <td className="tiny muted">{s.branch}</td>
                    <td className="mono">{s.deals}</td>
                    <td className="mono" style={{ fontWeight: 700 }}>{PKR(s.booked)}</td>
                    <td className="mono muted">{PKR(s.target)}</td>
                    <td>
                      <div className="track" style={{ height: 7 }}><i style={{ width: Math.min(100, pct) + '%', background: pct >= 100 ? 'var(--grad-green)' : 'var(--grad-lime)' }} /></div>
                      <div className="tiny" style={{ marginTop: 4, fontWeight: 700, color: pct >= 100 ? 'var(--ok)' : 'var(--ink-3)' }}>{pct}%</div>
                    </td>
                  </tr>
                );
              })}
              {!team.length && <tr><td colSpan="6" className="muted tiny" style={{ padding: 14 }}>No team data yet.</td></tr>}
            </tbody>
          </table>
        </div>
      )}

      {cut === 'Doctor wise' && (
        <div className="card">
          <div className="card-pad" style={{ paddingBottom: 6 }}>
            <div style={{ fontWeight: 800, fontSize: 17 }}>Sales by Referring Doctor</div>
            <div className="tiny muted" style={{ marginTop: 3 }}>Revenue attributed to referral source</div>
          </div>
          <table className="tbl">
            <thead><tr><th>Doctor</th><th>Speciality</th><th>Hospital / Clinic</th><th>Referrals</th><th style={{ textAlign: 'right' }}>Revenue</th></tr></thead>
            <tbody>
              {doctors.map((dr, ix) => (
                <tr key={dr.id}>
                  <td>
                    <div className="row" style={{ gap: 10 }}>
                      <span style={{ fontWeight: 800, color: ix < 3 ? 'var(--lime-700)' : 'var(--ink-3)', width: 22 }}>#{ix + 1}</span>
                      <div><div style={{ fontWeight: 700 }}>{dr.name}</div><div className="tiny muted">{dr.city}</div></div>
                    </div>
                  </td>
                  <td><Badge kind="info">{dr.spec}</Badge></td>
                  <td className="muted tiny">{dr.hospital}</td>
                  <td className="mono">{dr.referrals}</td>
                  <td className="mono" style={{ textAlign: 'right', fontWeight: 700 }}>{PKR(dr.revenue)}</td>
                </tr>
              ))}
              {!doctors.length && <tr><td colSpan="5" className="muted tiny" style={{ padding: 14 }}>No doctor data yet.</td></tr>}
            </tbody>
          </table>
        </div>
      )}
    </div>
  );
}

/* ── Accounting Reports ──────────────────────────────────────────── */
function AcctStatement({ title, period, children, innerRef }) {
  const { data: companies } = useCompanies();
  const co = companies[0] || { name: 'Electromed Corporation', addr: '', ntn: '', strn: '' };
  return (
    <div ref={innerRef} style={{ border: '1px solid var(--line)', borderRadius: 14, overflow: 'hidden', background: '#fff' }}>
      <div style={{ padding: '16px 22px', borderBottom: '2px solid var(--ink)', display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 16 }}>
        <div className="row" style={{ gap: 11, minWidth: 0 }}>
          <div style={{ width: 36, height: 36, borderRadius: 10, background: 'var(--forest)', display: 'grid', placeItems: 'center', flexShrink: 0 }}>
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="var(--lime)" strokeWidth="2.3" strokeLinecap="round" strokeLinejoin="round"><path d="M2 12h4l2-6 4 13 3-9 2 2h5" /></svg>
          </div>
          <div style={{ minWidth: 0 }}>
            <div style={{ fontWeight: 800, fontSize: 15 }}>{co.name}</div>
            <div className="tiny muted">{co.addr} · NTN {co.ntn}</div>
          </div>
        </div>
        <div style={{ textAlign: 'right', flexShrink: 0 }}>
          <div style={{ fontWeight: 800, fontSize: 15, letterSpacing: '.01em', whiteSpace: 'nowrap' }}>{title}</div>
          <div className="tiny muted" style={{ marginTop: 2 }}>{period}</div>
        </div>
      </div>
      <div style={{ padding: '6px 0' }}>{children}</div>
    </div>
  );
}

function AccountingReports({ branch = 'All' }) {
  const { PKR } = window.DATA;
  const bf = branch !== 'All' ? { branch_id: branch } : {};
  const { data: invoices } = useInvoices(bf);
  const { data: payments } = usePayments(bf);
  const { data: monthly, loading } = useMonthlySales(bf);

  const reports = [
    { id: 'monthly', label: 'Monthly Sales',       icon: Icons.cal   },
    { id: 'yearly',  label: 'Yearly Sales',         icon: Icons.chart },
    { id: 'pnl',     label: 'Profit & Loss',        icon: Icons.sales },
    { id: 'recv',    label: 'Receivables Ageing',   icon: Icons.clock },
    { id: 'gst',     label: 'GST / Tax Summary',    icon: Icons.receipt },
    { id: 'daybook', label: 'Day Book (Cash In)',   icon: Icons.pay   },
  ];
  const [rep, setRep] = useState('monthly');
  const docRef = useRef(null);
  const meta   = reports.find(r => r.id === rep);

  if (loading || !monthly) {
    return <div style={{ padding: 40, textAlign: 'center' }} className="tiny muted">Loading accounting data…</div>;
  }

  const { months, totals, opex, opexTotal, cogs, revenue, grossProfit, netProfit, fyLabel } = monthly;

  return (
    <div className="grid" style={{ gridTemplateColumns: '230px 1fr', gap: 18, alignItems: 'start' }}>
      <div className="card no-print" style={{ padding: 8, position: 'sticky', top: 0 }}>
        <div className="tiny muted" style={{ fontWeight: 700, padding: '8px 10px 6px' }}>ACCOUNTING REPORTS</div>
        {reports.map(r => (
          <button key={r.id} className="nav-item" style={{ fontWeight: rep === r.id ? 700 : 600, background: rep === r.id ? 'var(--surface-2)' : 'transparent', color: rep === r.id ? 'var(--ink)' : 'var(--ink-2)' }} onClick={() => setRep(r.id)}>
            <r.icon className="nav-ic" size={16} style={{ color: rep === r.id ? 'var(--lime-700)' : 'var(--ink-3)' }} />{r.label}
          </button>
        ))}
      </div>

      <div>
        <div className="row no-print" style={{ justifyContent: 'space-between', marginBottom: 12 }}>
          <div><div style={{ fontWeight: 800, fontSize: 17 }}>{meta.label}</div><div className="tiny muted" style={{ marginTop: 2 }}>{fyLabel} · all branches</div></div>
          <div className="row" style={{ gap: 8 }}>
            <Btn icon={<Icons.download size={15} />} onClick={() => window.printDocument(docRef.current)}>Download PDF</Btn>
            <Btn variant="primary" icon={<Icons.print size={15} />} onClick={() => window.printDocument(docRef.current)}>Print</Btn>
          </div>
        </div>

        {rep === 'monthly' && (
          <AcctStatement innerRef={docRef} title="Monthly Sales Report" period={fyLabel}>
            <table className="tbl" style={{ fontSize: 13 }}>
              <thead><tr><th>Month</th><th style={{ textAlign: 'right' }}>Invoices</th><th style={{ textAlign: 'right' }}>Sales</th><th style={{ textAlign: 'right' }}>Rentals</th><th style={{ textAlign: 'right' }}>Workshop</th><th style={{ textAlign: 'right' }}>Total Revenue</th><th style={{ textAlign: 'right' }}>Output GST</th></tr></thead>
              <tbody>
                {months.map(r => (
                  <tr key={r.m}>
                    <td style={{ fontWeight: 700 }}>{r.m}</td>
                    <td className="mono" style={{ textAlign: 'right' }}>{r.inv}</td>
                    <td className="mono" style={{ textAlign: 'right' }}>{PKR(r.sales)}</td>
                    <td className="mono" style={{ textAlign: 'right' }}>{PKR(r.rentals)}</td>
                    <td className="mono" style={{ textAlign: 'right' }}>{PKR(r.workshop)}</td>
                    <td className="mono" style={{ textAlign: 'right', fontWeight: 700 }}>{PKR(r.sales + r.rentals + r.workshop)}</td>
                    <td className="mono muted" style={{ textAlign: 'right' }}>{PKR(r.gst)}</td>
                  </tr>
                ))}
              </tbody>
              <tfoot><tr style={{ borderTop: '2px solid var(--ink)', fontWeight: 800 }}>
                <td>FY Total</td>
                <td className="mono" style={{ textAlign: 'right' }}>{totals.inv}</td>
                <td className="mono" style={{ textAlign: 'right' }}>{PKR(totals.sales)}</td>
                <td className="mono" style={{ textAlign: 'right' }}>{PKR(totals.rentals)}</td>
                <td className="mono" style={{ textAlign: 'right' }}>{PKR(totals.workshop)}</td>
                <td className="mono" style={{ textAlign: 'right' }}>{PKR(revenue)}</td>
                <td className="mono" style={{ textAlign: 'right' }}>{PKR(totals.gst)}</td>
              </tr></tfoot>
            </table>
            <div style={{ padding: '14px 22px' }}>
              <BarChart data={months.map(r => ({ label: r.m.split(' ')[0], v: r.sales + r.rentals + r.workshop }))}
                keys={['v']} colors={['var(--lime)']} height={150}
                fmt={(v) => v >= 1000000 ? (v / 1000000).toFixed(1) + 'M' : Math.round(v / 1000) + 'k'} />
            </div>
          </AcctStatement>
        )}

        {rep === 'yearly' && (
          <AcctStatement innerRef={docRef} title="Yearly Sales Summary" period={fyLabel}>
            <div style={{ padding: '14px 22px' }}>
              <div className="grid" style={{ gridTemplateColumns: 'repeat(4,1fr)', gap: 12, marginBottom: 18 }}>
                {[['Total Revenue', revenue, 'var(--ink)'], ['Sales', totals.sales, 'var(--lime-700)'], ['Rentals', totals.rentals, 'var(--forest)'], ['Workshop', totals.workshop, 'var(--ink-2)']].map(([l, v, c]) => (
                  <div key={l} style={{ border: '1px solid var(--line)', borderRadius: 12, padding: '13px 15px' }}>
                    <div className="tiny muted" style={{ fontWeight: 700 }}>{l}</div>
                    <div className="mono" style={{ fontWeight: 800, fontSize: 17, marginTop: 4, color: c }}>{PKR(v)}</div>
                    <div className="tiny muted" style={{ marginTop: 2 }}>{revenue > 0 ? Math.round(v / revenue * 100) : 0}% of revenue</div>
                  </div>
                ))}
              </div>
              <table className="tbl" style={{ fontSize: 13 }}>
                <thead><tr><th>Quarter</th><th style={{ textAlign: 'right' }}>Sales</th><th style={{ textAlign: 'right' }}>Rentals</th><th style={{ textAlign: 'right' }}>Workshop</th><th style={{ textAlign: 'right' }}>Revenue</th></tr></thead>
                <tbody>
                  {[['Q1 · Jul–Sep', 0, 3], ['Q2 · Oct–Dec', 3, 6], ['Q3 · Jan–Mar', 6, 9], ['Q4 · Apr–Jun', 9, 12]].map(([lbl, a, b]) => {
                    const q   = months.slice(a, b).reduce((s, r) => ({ sales: s.sales + r.sales, rentals: s.rentals + r.rentals, workshop: s.workshop + r.workshop }), { sales: 0, rentals: 0, workshop: 0 });
                    const rev = q.sales + q.rentals + q.workshop;
                    return <tr key={lbl}><td style={{ fontWeight: 700 }}>{lbl}</td><td className="mono" style={{ textAlign: 'right' }}>{PKR(q.sales)}</td><td className="mono" style={{ textAlign: 'right' }}>{PKR(q.rentals)}</td><td className="mono" style={{ textAlign: 'right' }}>{PKR(q.workshop)}</td><td className="mono" style={{ textAlign: 'right', fontWeight: 700 }}>{PKR(rev)}</td></tr>;
                  })}
                </tbody>
                <tfoot><tr style={{ borderTop: '2px solid var(--ink)', fontWeight: 800 }}><td>Year Total</td><td className="mono" style={{ textAlign: 'right' }}>{PKR(totals.sales)}</td><td className="mono" style={{ textAlign: 'right' }}>{PKR(totals.rentals)}</td><td className="mono" style={{ textAlign: 'right' }}>{PKR(totals.workshop)}</td><td className="mono" style={{ textAlign: 'right' }}>{PKR(revenue)}</td></tr></tfoot>
              </table>
            </div>
          </AcctStatement>
        )}

        {rep === 'pnl' && (
          <AcctStatement innerRef={docRef} title="Profit & Loss Statement" period={fyLabel}>
            <div style={{ padding: '8px 22px 16px' }}>
              <PnlSection label="Revenue" rows={[['Equipment Sales', totals.sales], ['Rental Income', totals.rentals], ['Workshop & Service', totals.workshop]]} total={revenue} PKR={PKR} strong />
              <PnlSection label="Cost of Goods Sold" rows={[['Equipment & parts cost (est. 55%)', cogs]]} total={cogs} PKR={PKR} neg />
              <div className="row" style={{ justifyContent: 'space-between', padding: '11px 0', borderTop: '1px solid var(--line)', borderBottom: '1px solid var(--line)', margin: '4px 0' }}>
                <span style={{ fontWeight: 800 }}>Gross Profit</span>
                <span className="mono" style={{ fontWeight: 800 }}>{PKR(grossProfit)} <span className="tiny muted">({revenue > 0 ? Math.round(grossProfit / revenue * 100) : 0}%)</span></span>
              </div>
              <PnlSection label="Operating Expenses" rows={opex.map(o => [o.label, parseFloat(o.amount)])} total={opexTotal} PKR={PKR} neg />
              <div className="row" style={{ justifyContent: 'space-between', padding: '13px 15px', marginTop: 8, borderRadius: 10, background: 'var(--ink)', color: '#fff' }}>
                <span style={{ fontWeight: 800 }}>Net Profit</span>
                <span className="mono" style={{ fontWeight: 800, fontSize: 17 }}>{PKR(netProfit)} <span style={{ color: 'var(--lime)', fontSize: 12 }}>({revenue > 0 ? Math.round(netProfit / revenue * 100) : 0}% margin)</span></span>
              </div>
            </div>
          </AcctStatement>
        )}

        {rep === 'recv' && (() => {
          const today2 = new Date();
          const open = invoices.filter(i => (parseFloat(i.amount || 0) - parseFloat(i.received || 0)) > 0)
            .map(i => ({ ...i, bal: parseFloat(i.amount || 0) - parseFloat(i.received || 0), age: Math.max(0, Math.round((today2 - new Date(i.date)) / 86400000)) }));
          const buckets  = [['Current (0–30)', 0, 30], ['31–60 days', 31, 60], ['61–90 days', 61, 90], ['Over 90 days', 91, 9999]];
          const totalBal = open.reduce((s, i) => s + i.bal, 0);
          return (
            <AcctStatement innerRef={docRef} title="Accounts Receivable — Ageing" period={`As at ${today2.toLocaleDateString('en-GB', { day: 'numeric', month: 'short', year: 'numeric' })}`}>
              <div className="grid no-print" style={{ gridTemplateColumns: 'repeat(4,1fr)', gap: 10, padding: '14px 22px 4px' }}>
                {buckets.map(([lbl, a, b]) => { const v = open.filter(i => i.age >= a && i.age <= b).reduce((s, i) => s + i.bal, 0); return (
                  <div key={lbl} style={{ border: '1px solid var(--line)', borderRadius: 11, padding: '11px 13px' }}><div className="tiny muted" style={{ fontWeight: 700 }}>{lbl}</div><div className="mono" style={{ fontWeight: 800, fontSize: 15, marginTop: 3, color: b > 90 ? 'var(--bad)' : 'var(--ink)' }}>{PKR(v)}</div></div>
                ); })}
              </div>
              <table className="tbl" style={{ fontSize: 13 }}>
                <thead><tr><th>Invoice</th><th>Customer</th><th style={{ textAlign: 'right' }}>Invoiced</th><th style={{ textAlign: 'right' }}>Received</th><th style={{ textAlign: 'right' }}>Balance</th><th style={{ textAlign: 'right' }}>Age</th></tr></thead>
                <tbody>
                  {open.sort((a, b) => b.age - a.age).map(i => (
                    <tr key={i.id}><td className="mono" style={{ fontWeight: 700 }}>{i.invoice_number}</td><td style={{ fontWeight: 600 }}>{i.customer_name}</td><td className="mono" style={{ textAlign: 'right' }}>{PKR(i.amount)}</td><td className="mono muted" style={{ textAlign: 'right' }}>{PKR(i.received || 0)}</td><td className="mono" style={{ textAlign: 'right', fontWeight: 700, color: i.age > 90 ? 'var(--bad)' : 'var(--ink)' }}>{PKR(i.bal)}</td><td className="mono" style={{ textAlign: 'right' }}>{i.age}d</td></tr>
                  ))}
                  {!open.length && <tr><td colSpan="6" className="muted tiny" style={{ padding: 14 }}>No outstanding invoices.</td></tr>}
                </tbody>
                <tfoot><tr style={{ borderTop: '2px solid var(--ink)', fontWeight: 800 }}><td colSpan="4">Total Outstanding</td><td className="mono" style={{ textAlign: 'right' }}>{PKR(totalBal)}</td><td /></tr></tfoot>
              </table>
            </AcctStatement>
          );
        })()}

        {rep === 'gst' && (
          <AcctStatement innerRef={docRef} title="GST / Sales-Tax Summary" period={fyLabel}>
            <table className="tbl" style={{ fontSize: 13 }}>
              <thead><tr><th>Month</th><th style={{ textAlign: 'right' }}>Taxable Sales</th><th style={{ textAlign: 'right' }}>Output GST @ 17%</th></tr></thead>
              <tbody>
                {months.map(r => (
                  <tr key={r.m}><td style={{ fontWeight: 700 }}>{r.m}</td><td className="mono" style={{ textAlign: 'right' }}>{PKR(r.gst > 0 ? r.gst / 0.17 : 0)}</td><td className="mono" style={{ textAlign: 'right', fontWeight: 700 }}>{PKR(r.gst)}</td></tr>
                ))}
              </tbody>
              <tfoot><tr style={{ borderTop: '2px solid var(--ink)', fontWeight: 800 }}><td>Total Output Tax</td><td className="mono" style={{ textAlign: 'right' }}>{PKR(totals.gst > 0 ? totals.gst / 0.17 : 0)}</td><td className="mono" style={{ textAlign: 'right' }}>{PKR(totals.gst)}</td></tr></tfoot>
            </table>
          </AcctStatement>
        )}

        {rep === 'daybook' && (() => {
          let run = 0;
          const rows  = [...payments].sort((a, b) => new Date(a.payment_date) - new Date(b.payment_date));
          const total = rows.reduce((s, p) => s + parseFloat(p.amount || 0), 0);
          return (
            <AcctStatement innerRef={docRef} title="Day Book — Cash & Bank Receipts" period={fyLabel}>
              <table className="tbl" style={{ fontSize: 13 }}>
                <thead><tr><th>Date</th><th>Receipt</th><th>Customer</th><th>Mode</th><th style={{ textAlign: 'right' }}>Amount</th><th style={{ textAlign: 'right' }}>Running</th></tr></thead>
                <tbody>
                  {rows.map(p => { run += parseFloat(p.amount || 0); return (
                    <tr key={p.id}><td className="tiny muted">{p.payment_date}</td><td className="mono" style={{ fontWeight: 700 }}>{p.payment_ref}</td><td style={{ fontWeight: 600 }}>{p.customer_name}</td><td><Badge kind={p.type === 'Rental' ? 'info' : 'idle'}>{p.mode}</Badge></td><td className="mono" style={{ textAlign: 'right', fontWeight: 700, color: 'var(--ok)' }}>{PKR(p.amount)}</td><td className="mono muted" style={{ textAlign: 'right' }}>{PKR(run)}</td></tr>
                  ); })}
                  {!rows.length && <tr><td colSpan="6" className="muted tiny" style={{ padding: 14 }}>No payments yet.</td></tr>}
                </tbody>
                <tfoot><tr style={{ borderTop: '2px solid var(--ink)', fontWeight: 800 }}><td colSpan="4">Total Receipts</td><td className="mono" style={{ textAlign: 'right' }}>{PKR(total)}</td><td /></tr></tfoot>
              </table>
            </AcctStatement>
          );
        })()}
      </div>
    </div>
  );
}

function PnlSection({ label, rows, total, PKR, neg, strong }) {
  return (
    <div style={{ marginBottom: 6 }}>
      <div className="tiny muted" style={{ fontWeight: 800, textTransform: 'uppercase', letterSpacing: '.04em', padding: '10px 0 4px' }}>{label}</div>
      {rows.map(([l, v]) => (
        <div key={l} className="row" style={{ justifyContent: 'space-between', padding: '5px 0 5px 14px' }}>
          <span className="muted" style={{ fontSize: 13 }}>{l}</span>
          <span className="mono" style={{ fontSize: 13 }}>{neg ? '(' : ''}{PKR(v)}{neg ? ')' : ''}</span>
        </div>
      ))}
    </div>
  );
}

/* ── Profitability: revenue − cost of goods sold = gross profit ──── */
function ProfitabilityReport({ branch = 'All' }) {
  const { PKR } = window.DATA;
  const bf = branch !== 'All' ? { branch_id: branch } : {};
  const [data, setData]       = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    setLoading(true);
    api.getProfitability(bf).then(d => { setData(d); setLoading(false); }).catch(() => setLoading(false));
  }, [branch]);

  if (loading) return <div className="card card-pad tiny muted">Loading profitability…</div>;
  if (!data)   return <div className="card card-pad tiny muted">No profitability data yet.</div>;

  const { revenue, cogs, grossProfit, margin, invoice_count, costed_count, by_model } = data;
  const estimated = (invoice_count || 0) - (costed_count || 0);

  return (
    <div>
      <div className="grid" style={{ gridTemplateColumns: 'repeat(4,1fr)', marginBottom: 18 }}>
        <StatCard icon={<Icons.chart size={18} />} label="Revenue (ex-GST)"   value={PKR(revenue)}     sub="net sales" />
        <StatCard icon={<Icons.box   size={18} />} label="Cost of Goods Sold" value={PKR(cogs)}        sub="purchase cost" />
        <StatCard icon={<Icons.pay   size={18} />} label="Gross Profit"       value={PKR(grossProfit)} accent />
        <StatCard icon={<Icons.spark size={18} />} label="Gross Margin"       value={(margin || 0) + '%'} sub="profit ÷ revenue" />
      </div>

      {estimated > 0 && (
        <div className="row no-print" style={{ gap: 10, padding: '12px 16px', background: 'var(--warn-bg)', border: '1px solid var(--warn)', borderRadius: 12, marginBottom: 16 }}>
          <span style={{ fontSize: 18 }}>⚠️</span>
          <span className="tiny" style={{ color: 'var(--ink-2)' }}>
            <b>{estimated}</b> of {invoice_count} sales use an <b>estimated</b> cost (no purchase price recorded). Set the <b>Purchase Price</b> on inventory items so profit is calculated from real cost.
          </span>
        </div>
      )}

      <div className="card" style={{ overflow: 'hidden', marginBottom: 18 }}>
        <div className="card-pad" style={{ paddingBottom: 12 }}>
          <div style={{ fontWeight: 800, fontSize: 17 }}>Profit by Product</div>
          <div className="tiny muted" style={{ marginTop: 3 }}>Revenue, cost and margin per model — most profitable first.</div>
        </div>
        <div style={{ overflowX: 'auto' }}>
          <table className="tbl">
            <thead><tr>
              <th>Product</th><th style={{ textAlign: 'right' }}>Sales</th>
              <th style={{ textAlign: 'right' }}>Revenue</th><th style={{ textAlign: 'right' }}>COGS</th>
              <th style={{ textAlign: 'right' }}>Profit</th><th style={{ textAlign: 'right' }}>Margin</th>
            </tr></thead>
            <tbody>
              {by_model.map(m => (
                <tr key={m.label}>
                  <td style={{ fontWeight: 600 }}>{m.label}</td>
                  <td className="mono" style={{ textAlign: 'right' }}>{m.units}</td>
                  <td className="mono" style={{ textAlign: 'right' }}>{PKR(m.revenue)}</td>
                  <td className="mono muted" style={{ textAlign: 'right' }}>{PKR(m.cogs)}</td>
                  <td className="mono" style={{ textAlign: 'right', fontWeight: 700, color: m.profit >= 0 ? 'var(--ok)' : 'var(--bad)' }}>{PKR(m.profit)}</td>
                  <td style={{ textAlign: 'right' }}><Badge kind={m.margin >= 30 ? 'ok' : m.margin >= 15 ? 'warn' : 'bad'}>{m.margin}%</Badge></td>
                </tr>
              ))}
              {!by_model.length && <tr><td colSpan="6" className="muted tiny" style={{ padding: 14 }}>No sales recorded yet.</td></tr>}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}

window.Reports = Reports;
