// Screen: Reports — five fully-rendered, interactive reports + grayed builder.
// Charts lazy-mount: only the active report (and active sub-view) is rendered,
// so nothing is drawn into a hidden container.

const REPORT_TYPES = [
  { id: 'prescriber', n: '01', title: 'Prescriber Reports', desc: 'Accounts, trends & actions' },
  { id: 'revenue', n: '02', title: 'Revenue & Growth', desc: 'MTD/QTD/YTD · YoY · mix' },
  { id: 'patients', n: '03', title: 'Patient Analytics', desc: 'Aggregate · PHI-safe' },
  { id: 'volume', n: '04', title: 'Volume & Workflow', desc: 'Fills · turnaround · staff' },
  { id: 'controlled', n: '05', title: 'Controlled Substances', desc: 'C-III–C-V · PDMP' },
];

const fmtCount = n => Math.round(n).toLocaleString('en-US');
const fmtM = n => '$' + (n / 1e6).toFixed(2) + 'M';

// ---- Small local viz primitives ----------------------------------------

function Donut({ data, size = 168, thickness = 26, title, sub }) {
  const total = data.reduce((a, d) => a + d.val, 0);
  const r = (size - thickness) / 2;
  const c = 2 * Math.PI * r;
  let off = 0;
  return (
    <svg width={size} height={size} viewBox={`0 0 ${size} ${size}`} aria-hidden="true">
      <g transform={`rotate(-90 ${size / 2} ${size / 2})`}>
        {data.map((d, i) => {
          const len = (d.val / total) * c;
          const seg = (
            <circle key={i} cx={size / 2} cy={size / 2} r={r} fill="none" stroke={d.color}
              strokeWidth={thickness} strokeDasharray={`${len - 1.5} ${c - len + 1.5}`} strokeDashoffset={-off}></circle>
          );
          off += len;
          return seg;
        })}
      </g>
      {title ? (
        <text x={size / 2} y={size / 2 - 4} textAnchor="middle" fontFamily="var(--serif)" fontSize="19" fontWeight="500" fill="var(--ink)">{title}</text>
      ) : null}
      {sub ? (
        <text x={size / 2} y={size / 2 + 13} textAnchor="middle" fontFamily="var(--mono)" fontSize="9.5" fill="var(--ink-3)">{sub}</text>
      ) : null}
    </svg>
  );
}

function DonutBlock({ data, title, sub, fmt }) {
  const total = data.reduce((a, d) => a + d.val, 0);
  const f = fmt || fmtCount;
  return (
    <div className="donut-block">
      <Donut data={data} title={title} sub={sub}></Donut>
      <div className="donut-legend">
        {data.map((d, i) => (
          <div className="dl-row" key={i}>
            <span className="dl-dot" style={{ background: d.color }}></span>
            <span className="dl-name">{d.name}</span>
            <span className="dl-val mono">{f(d.val)}</span>
            <span className="dl-pct mono">{(d.val / total * 100).toFixed(1)}%</span>
          </div>
        ))}
      </div>
    </div>
  );
}

function HBars({ data, fmt }) {
  const max = Math.max(...data.map(d => d.val));
  const f = fmt || fmtCount;
  return (
    <div className="hbars">
      {data.map((d, i) => (
        <div className="hbar" key={i}>
          <div className="hb-label">
            <span>{d.name}</span>
            {d.sub ? <span className="hb-sub">{d.sub}</span> : null}
          </div>
          <div className="hb-track"><i style={{ width: (d.val / max * 100) + '%' }}></i></div>
          <div className="hb-val mono">{f(d.val)}</div>
        </div>
      ))}
    </div>
  );
}

function Kpis({ items }) {
  return (
    <div className="rpt-kpis card">
      {items.map((it, i) => (
        <div className="rpt-kpi" key={i}>
          <div className="kicker">{it.k}</div>
          <div className="v big-num">{it.v}</div>
          {it.sub ? <div className="rk-sub">{it.sub}</div> : null}
        </div>
      ))}
    </div>
  );
}

function PeriodSel({ value, onChange, opts }) {
  return (
    <div className="filt">
      {opts.map(o => (
        <button key={o.key} className={value === o.key ? 'on' : ''} onClick={() => onChange(o.key)}>{o.label}</button>
      ))}
    </div>
  );
}

function ReportHead({ title, sub, period, children }) {
  return (
    <div className="rpt-head">
      <div>
        <h2>{title}</h2>
        {sub ? <div className="rpt-sub">{sub}</div> : null}
      </div>
      <div className="rpt-head-tools">{children}</div>
    </div>
  );
}

function ChangeTag({ pct }) {
  const cls = pct > 1.5 ? 'up' : pct < -1.5 ? 'down' : 'flat';
  const arrow = cls === 'up' ? '▲' : cls === 'down' ? '▼' : '—';
  return <span className={'chg ' + cls}>{arrow} {Math.abs(pct).toFixed(1)}%</span>;
}

// Least-squares fitted line for a dashed trend overlay.
function linfit(data) {
  const n = data.length;
  let sx = 0, sy = 0, sxx = 0, sxy = 0;
  for (let i = 0; i < n; i++) { sx += i; sy += data[i]; sxx += i * i; sxy += i * data[i]; }
  const b = (n * sxy - sx * sy) / (n * sxx - sx * sx);
  const a = (sy - b * sx) / n;
  return data.map((_, i) => +(a + b * i).toFixed(1));
}

// ---- Report 1: Prescriber Reports --------------------------------------

function PrescriberReport({ onPdf }) {
  const { useState } = React;
  const [period, setPeriod] = useState('90d');
  const [selId, setSelId] = useState(null);
  const [sortKey, setSortKey] = useState('rev');
  const months = PRESC_PERIODS.find(p => p.key === period).months;

  const rows = PRESCRIBERS.map(c => {
    const rev = prescRev(c, months);
    const chg = prescChange(c, months);
    return { c, rev, chg };
  });
  const sorted = [...rows].sort((a, b) => sortKey === 'rev' ? b.rev - a.rev : b.chg - a.chg);
  const growing = rows.filter(r => r.chg > 1.5).length;
  const declining = rows.filter(r => r.chg < -1.5).length;
  const totalRev = rows.reduce((a, r) => a + r.rev, 0);

  if (selId) return <PrescriberSingle id={selId} setId={setSelId} period={period} setPeriod={setPeriod} onPdf={onPdf}></PrescriberSingle>;

  const totalMonths = MONTHS_12.map((_, i) => +(PRESCRIBERS.reduce((a, c) => a + c.months[i], 0) / 1000).toFixed(1));
  const series = [
    { name: 'Total', data: totalMonths, color: 'var(--moss)', bold: true },
    { name: '', data: linfit(totalMonths), color: '#8e9385', dash: true },
  ];

  return (
    <div className="rpt-body">
      <ReportHead title="Prescriber Reports" sub="Compounding & specialty accounts — each prescribing clinic is an account.">
        <PeriodSel value={period} onChange={setPeriod} opts={PRESC_PERIODS}></PeriodSel>
        <button className="btn-run" onClick={onPdf}>Generate PDF</button>
      </ReportHead>

      <Kpis items={[
        { k: 'Active prescribers', v: PRESCRIBERS.length },
        { k: 'Total revenue · ' + period, v: fmtK(totalRev) },
        { k: 'Growing', v: growing },
        { k: 'Declining', v: declining },
      ]}></Kpis>

      <div className="card card-pad">
        <SectionHead title="Total prescriber revenue · trailing 12 months · $k"></SectionHead>
        <div style={{ marginTop: 12 }}>
          <TrendChart series={series} labels={MONTHS_12.map((m, i) => i % 2 === 0 ? m : '')}></TrendChart>
        </div>
      </div>

      <div className="card" style={{ overflow: 'hidden' }}>
        <table className="data">
          <thead>
            <tr>
              <th>Prescribing clinic</th>
              <th>Top category</th>
              <th className={'num sortable' + (sortKey === 'rev' ? ' on' : '')} onClick={() => setSortKey('rev')}>Revenue ▾</th>
              <th className={'num sortable' + (sortKey === 'chg' ? ' on' : '')} onClick={() => setSortKey('chg')}>Recent vs prior ▾</th>
            </tr>
          </thead>
          <tbody>
            {sorted.map(({ c, rev, chg }) => (
              <tr key={c.id} className="click" onClick={() => setSelId(c.id)}>
                <td>
                  <div style={{ fontWeight: 600 }}>{c.clinic}</div>
                  <div style={{ fontSize: 11.5, color: 'var(--ink-3)' }}>{c.prescriber} · {c.city}</div>
                </td>
                <td style={{ color: 'var(--ink-2)' }}>{c.topCat}</td>
                <td className="num mono">{fmtK(rev)}</td>
                <td className="num"><ChangeTag pct={chg}></ChangeTag></td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}

function genWeekly(clinic, period) {
  const months = PRESC_PERIODS.find(p => p.key === period).months;
  const monthlyRev = clinic.months[clinic.months.length - 1];
  const sign = clinic.trend === 'up' ? 1 : clinic.trend === 'down' ? -1 : 0;
  const labels = ['May 11', 'May 18', 'May 25', 'Jun 1', 'Jun 8'];
  const baseScripts = clinic.scripts30 / 4.345;
  const baseRev = monthlyRev / 4.345;
  return labels.map((lb, i) => {
    const g = 1 + sign * (i - 2) * 0.03;
    return {
      week: lb,
      scripts: Math.round(baseScripts * g),
      rev: Math.round(baseRev * g / 10) * 10,
      newPts: Math.max(0, clinic.newPerWeek + ((i % 2 === 0) ? 0 : (sign >= 0 ? 1 : -1))),
    };
  });
}

function PrescriberSingle({ id, setId, period, setPeriod, onPdf }) {
  const idx = PRESCRIBERS.findIndex(c => c.id === id);
  const c = PRESCRIBERS[idx];
  const months = PRESC_PERIODS.find(p => p.key === period).months;
  const rev = prescRev(c, months);
  const scripts = Math.round(c.scripts30 * rev / c.months[c.months.length - 1]);
  const avg = rev / scripts;
  const series = [
    { name: c.prescriber.split(' ').slice(-1)[0], data: c.months.map(v => +(v / 1000).toFixed(1)), color: 'var(--moss)', bold: true },
    { name: '', data: linfit(c.months.map(v => +(v / 1000).toFixed(1))), color: '#8e9385', dash: true },
  ];
  const weeks = genWeekly(c, period);
  const prev = () => setId(PRESCRIBERS[(idx - 1 + PRESCRIBERS.length) % PRESCRIBERS.length].id);
  const next = () => setId(PRESCRIBERS[(idx + 1) % PRESCRIBERS.length].id);

  return (
    <div className="rpt-body">
      <ReportHead title="Prescriber Reports" sub="Single account view">
        <PeriodSel value={period} onChange={setPeriod} opts={PRESC_PERIODS}></PeriodSel>
        <button className="btn-run" onClick={onPdf}>Generate PDF</button>
      </ReportHead>

      <div className="presc-layout">
        <div className="card presc-list">
          <div className="pl-head">
            <button className="pl-back" onClick={() => setId(null)}>← All prescribers</button>
          </div>
          {PRESCRIBERS.map(p => (
            <button key={p.id} className={'pl-item' + (p.id === id ? ' on' : '')} onClick={() => setId(p.id)}>
              <span className="pl-name">{p.clinic}</span>
              <span className="pl-cat">{p.topCat}</span>
            </button>
          ))}
        </div>

        <div>
          <div className="card presc-hd">
            <div className="ph-top">
              <div>
                <div className="kicker">Account</div>
                <h3>{c.clinic}</h3>
                <div className="ph-presc">{c.prescriber} · {c.city}</div>
              </div>
              <div className="ph-nav">
                <button onClick={prev} aria-label="Previous">‹</button>
                <button onClick={next} aria-label="Next">›</button>
              </div>
            </div>
            <div className="ph-kpis">
              <div><div className="kicker">Revenue · {period}</div><div className="v big-num">{fmtK(rev)}</div></div>
              <div><div className="kicker">Scripts</div><div className="v big-num">{fmtCount(scripts)}</div></div>
              <div><div className="kicker">Avg / script</div><div className="v big-num">{fmtMoney(avg)}</div></div>
              <div><div className="kicker">Top category</div><div className="v ph-cat">{c.topCat}</div></div>
            </div>
          </div>

          <div className="card card-pad" style={{ marginTop: 14 }}>
            <SectionHead title="Revenue · trailing 12 months · $k"></SectionHead>
            <div style={{ marginTop: 12 }}>
              <TrendChart series={series} labels={MONTHS_12.map((m, i) => i % 2 === 0 ? m : '')}></TrendChart>
            </div>
          </div>

          <div className="analysis-card card" style={{ marginTop: 14 }}>
            <div className="ac-label">Trend analysis</div>
            <p>{c.analysis}</p>
            <div className="ac-rec">
              <span className="ac-rec-tag">Recommended action</span>
              <span>{c.rec}</span>
            </div>
          </div>

          <div className="card" style={{ marginTop: 14, overflow: 'hidden' }}>
            <table className="data">
              <thead>
                <tr><th>Week</th><th className="num">Scripts</th><th className="num">Revenue</th><th className="num">New patients</th></tr>
              </thead>
              <tbody>
                {weeks.map((w, i) => (
                  <tr key={i}>
                    <td className="mono">{w.week}</td>
                    <td className="num">{w.scripts}</td>
                    <td className="num mono">{fmtMoney(w.rev)}</td>
                    <td className="num">{w.newPts}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </div>
  );
}

// ---- Report 2: Revenue & Growth ----------------------------------------

function RevenueReport({ onPdf }) {
  const series = [
    { name: 'This yr', data: REV_THIS_YEAR, color: 'var(--moss)', bold: true },
    { name: 'Last yr', data: REV_LAST_YEAR, color: '#8e9385' },
  ];
  const movers = [...BIGGEST_MOVERS]
    .map(m => ({ ...m, pct: (m.recent - m.prior) / m.prior * 100 }))
    .sort((a, b) => Math.abs(b.recent - b.prior) - Math.abs(a.recent - a.prior));
  return (
    <div className="rpt-body">
      <ReportHead title="Revenue & Growth" sub="Executive view · all locations">
        <button className="btn-run" onClick={onPdf}>Generate PDF</button>
      </ReportHead>

      <Kpis items={[
        { k: 'Revenue · MTD', v: fmtK(REV_KPIS.mtd) },
        { k: 'Revenue · QTD', v: fmtM(REV_KPIS.qtd) },
        { k: 'Revenue · YTD', v: fmtM(REV_KPIS.ytd) },
        { k: 'YoY growth', v: '+' + REV_KPIS.yoy.toFixed(1) + '%' },
      ]}></Kpis>

      <div className="card card-pad">
        <SectionHead title="Monthly revenue · this year vs last year · $k"></SectionHead>
        <div style={{ marginTop: 12 }}>
          <TrendChart series={series} labels={MONTHS_12.map((m, i) => i % 2 === 0 ? m : '')}></TrendChart>
        </div>
      </div>

      <div className="rpt-two">
        <div className="card card-pad">
          <SectionHead title="Sales by category"></SectionHead>
          <DonutBlock data={CATEGORY_MIX} title="$607.5k" sub="last 30 days" fmt={v => '$' + v.toFixed(1) + 'k'}></DonutBlock>
        </div>
        <div className="card" style={{ overflow: 'hidden' }}>
          <div className="card-pad" style={{ paddingBottom: 6 }}>
            <SectionHead title="Biggest movers · 90d vs prior 90d"></SectionHead>
          </div>
          <table className="data">
            <thead>
              <tr><th>Item</th><th className="num">90d revenue</th><th className="num">Change</th></tr>
            </thead>
            <tbody>
              {movers.map((m, i) => (
                <tr key={i}>
                  <td>
                    <div style={{ fontWeight: 600 }}>{m.name}</div>
                    <div style={{ fontSize: 11.5, color: 'var(--ink-3)' }}>{m.cat}</div>
                  </td>
                  <td className="num mono">{fmtK(m.recent)}</td>
                  <td className="num"><ChangeTag pct={m.pct}></ChangeTag></td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}

// ---- Report 3: Patient Analytics ---------------------------------------

function PatientReport({ onPdf }) {
  const a = PATIENT_ANALYTICS;
  const series = [{ name: 'New', data: a.newPerMonth, color: 'var(--moss)', bold: true }];
  return (
    <div className="rpt-body">
      <ReportHead title="Patient Analytics" sub="Aggregate only · no individual records">
        <button className="btn-run" onClick={onPdf}>Generate PDF</button>
      </ReportHead>

      <Kpis items={[
        { k: 'Total patients', v: fmtCount(a.kpis.total) },
        { k: 'New · YTD', v: fmtCount(a.kpis.newYTD) },
        { k: 'Seniors 65+', v: fmtCount(a.kpis.seniors65) },
        { k: 'Allergies flagged', v: fmtCount(a.kpis.allergies) },
        { k: 'Active · 6 mo', v: fmtCount(a.kpis.active6mo) },
      ]}></Kpis>

      <div className="card card-pad">
        <SectionHead title="New patients per month · trailing 12 months"></SectionHead>
        <div style={{ marginTop: 12 }}>
          <TrendChart series={series} labels={MONTHS_12.map((m, i) => i % 2 === 0 ? m : '')} fmt={fmtCount}></TrendChart>
        </div>
      </div>

      <div className="rpt-two">
        <div className="card card-pad">
          <SectionHead title="Patients by age band"></SectionHead>
          <DonutBlock data={a.ageBands} title={fmtCount(a.kpis.total)} sub="patients"></DonutBlock>
        </div>
        <div className="card" style={{ overflow: 'hidden' }}>
          <div className="card-pad" style={{ paddingBottom: 6 }}>
            <SectionHead title="Gender mix"></SectionHead>
          </div>
          <table className="data">
            <thead>
              <tr><th>Gender</th><th className="num">Patients</th><th className="num">Share</th></tr>
            </thead>
            <tbody>
              {a.gender.map((g, i) => (
                <tr key={i}>
                  <td style={{ fontWeight: 600 }}>{g[0]}</td>
                  <td className="num mono">{fmtCount(g[1])}</td>
                  <td className="num mono">{g[2]}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}

// ---- Report 4: Volume & Workflow ---------------------------------------

function VolumeReport({ onPdf }) {
  const { useState } = React;
  const [period, setPeriod] = useState('30d');
  const v = VOLUME;
  const fs = fillsSeries(period);
  const series = [{ name: 'Fills', data: fs.data, color: 'var(--moss)', bold: true }];
  const bars = v.pharmacists.map(p => ({ name: p.name, sub: p.store, val: p.fills }));
  return (
    <div className="rpt-body">
      <ReportHead title="Volume & Workflow" sub="All locations">
        <PeriodSel value={period} onChange={setPeriod} opts={PRESC_PERIODS}></PeriodSel>
        <button className="btn-run" onClick={onPdf}>Generate PDF</button>
      </ReportHead>

      <Kpis items={[
        { k: 'Fills this month', v: fmtCount(v.kpis.fillsMonth) },
        { k: 'Fills · last 7 days', v: fmtCount(v.kpis.fills7d) },
        { k: 'Avg turnaround', v: v.kpis.turnaroundHrs + ' h', sub: 'intake → ready' },
        { k: 'Pharmacists on staff', v: v.kpis.pharmacists },
      ]}></Kpis>

      <div className="card card-pad">
        <SectionHead title={'Fills per ' + (period === '30d' ? 'day' : period === '90d' ? 'week' : 'month') + ' · ' + PRESC_PERIODS.find(p => p.key === period).label + ' · stores closed weekends'}></SectionHead>
        <div style={{ marginTop: 12 }}>
          <TrendChart series={series} labels={fs.labels} fmt={fmtCount}></TrendChart>
        </div>
      </div>

      <div className="card card-pad">
        <SectionHead title="Fills per pharmacist · this month"></SectionHead>
        <div style={{ marginTop: 12 }}>
          <HBars data={bars}></HBars>
        </div>
        <div className="rpt-callout">{v.callout}</div>
      </div>
    </div>
  );
}

// ---- Report 5: Controlled Substance Compliance -------------------------

function ControlledReport({ onPdf }) {
  const k = CONTROLLED;
  const series = [{ name: 'Controlled', data: k.perMonth, color: 'var(--moss)', bold: true }];
  const schedTone = { 'C-III': 'warn', 'C-IV': 'neutral', 'C-V': 'ok' };
  return (
    <div className="rpt-body">
      <ReportHead title="Controlled Substance Compliance" sub="Schedules III–V · no C-II dispensing">
        <button className="btn-run" onClick={onPdf}>Generate PDF</button>
      </ReportHead>

      <Kpis items={[
        { k: 'Controlled fills · YTD', v: fmtCount(k.kpis.fillsYTD) },
        { k: 'Share of all fills', v: k.kpis.sharePct.toFixed(1) + '%', sub: 'of ' + fmtCount(k.kpis.totalFillsYTD) + ' YTD' },
        { k: 'Distinct controlled items', v: k.kpis.distinctItems },
      ]}></Kpis>

      <div className="card card-pad">
        <SectionHead title="Controlled fills per month · trailing 12 months"></SectionHead>
        <div style={{ marginTop: 12 }}>
          <TrendChart series={series} labels={MONTHS_12.map((m, i) => i % 2 === 0 ? m : '')} fmt={fmtCount}></TrendChart>
        </div>
      </div>

      <div className="card" style={{ overflow: 'hidden' }}>
        <div className="card-pad" style={{ paddingBottom: 6 }}>
          <SectionHead title="Top controlled items"></SectionHead>
        </div>
        <table className="data">
          <thead>
            <tr><th>Item</th><th>Schedule</th><th className="num">Fills · YTD</th><th>Last dispensed</th></tr>
          </thead>
          <tbody>
            {k.items.map((it, i) => (
              <tr key={i}>
                <td style={{ fontWeight: 600 }}>{it.name}</td>
                <td><span className={'badge mono ' + (schedTone[it.sched] || 'neutral')}>{it.sched}</span></td>
                <td className="num mono">{fmtCount(it.fills)}</td>
                <td style={{ color: 'var(--ink-2)' }}>{it.lastStore}</td>
              </tr>
            ))}
          </tbody>
        </table>
        <div className="pdmp-foot">{k.pdmp}</div>
      </div>
    </div>
  );
}

// ---- Shell -------------------------------------------------------------

function Reports() {
  const { useState } = React;
  const [active, setActive] = useState('prescriber');
  const [toast, showToast] = useToast();
  const onPdf = () => showToast('Available in full build.');

  const pane = {
    prescriber: <PrescriberReport onPdf={onPdf}></PrescriberReport>,
    revenue: <RevenueReport onPdf={onPdf}></RevenueReport>,
    patients: <PatientReport onPdf={onPdf}></PatientReport>,
    volume: <VolumeReport onPdf={onPdf}></VolumeReport>,
    controlled: <ControlledReport onPdf={onPdf}></ControlledReport>,
  }[active];

  return (
    <div className="content" data-screen-label="Reports">
      <div className="rpt-layout">
        <div className="card rpt-rail">
          {REPORT_TYPES.map(r => (
            <button key={r.id} className={'rr-item' + (active === r.id ? ' on' : '')} onClick={() => setActive(r.id)}>
              <span className="rr-n mono">{r.n}</span>
              <span className="rr-text">
                <span className="rr-title">{r.title}</span>
                <span className="rr-desc">{r.desc}</span>
              </span>
            </button>
          ))}
          <div className="rr-item disabled">
            <span className="rr-n mono">06</span>
            <span className="rr-text">
              <span className="rr-title">Custom builder <span className="rr-phase">Phase 2</span></span>
              <span className="rr-desc">Drag-and-drop report designer</span>
            </span>
          </div>
        </div>

        <div className="rpt-pane">
          {pane}
          <div className="rpt-foot">Aggregate data only · PHI-safe</div>
        </div>
      </div>
      <Toast msg={toast}></Toast>
    </div>
  );
}

Object.assign(window, { Reports });
