// Schaffner OS — fictional but credible data layer
// All data dummy. Skagit Valley, WA flavor throughout.

const STORES = [
  {
    id: 'sw', name: 'Sedro-Woolley', tag: 'SW', sub: 'Flagship · Compounding Lab',
    revMTD: 248300, revDelta: 4.2, scriptsToday: 162, inQueue: 23, waitMin: 11,
    compShare: 0.31, spark: [168, 171, 166, 175, 182, 178, 188, 192, 186, 197, 204, 211],
  },
  {
    id: 'ana', name: 'Anacortes', tag: 'ANA', sub: 'Commercial Ave',
    revMTD: 186900, revDelta: 1.8, scriptsToday: 141, inQueue: 17, waitMin: 9,
    compShare: 0.07, spark: [142, 139, 145, 141, 148, 144, 151, 149, 153, 150, 156, 158],
  },
  {
    id: 'bur', name: 'Burlington', tag: 'BUR', sub: 'Fairhaven Ave',
    revMTD: 172400, revDelta: -0.9, scriptsToday: 128, inQueue: 31, waitMin: 19,
    compShare: 0.05, spark: [139, 144, 141, 147, 143, 149, 146, 142, 145, 141, 144, 140],
  },
];

const TREND_LABELS = ['Mar', '', '', '', 'Apr', '', '', '', 'May', '', '', 'Jun'];

const MARGIN_STORY = {
  compounding: { share: 0.18, margin: 0.584, gp: 63400 },
  retail: { share: 0.82, margin: 0.172, gp: 86100 },
  headline: 'Compounding is 18% of revenue — and 42% of gross profit.',
};

const ALERTS = [
  { sev: 'bad', store: 'BUR', text: 'C-II perpetual count due Friday — last cycle 87 days ago', time: '7:02a' },
  { sev: 'warn', store: 'ALL', text: '18 refills come due in the next 48 hours — 2 awaiting prescriber renewal', time: '6:58a', link: 'refills' },
  { sev: 'warn', store: 'ANA', text: 'Fridge #2 logged 45.8°F at 5:12a — excursion review needed before first fill', time: '5:14a' },
  { sev: 'warn', store: 'SW', text: 'Premera remittance variance $312.40 on 14 claims, week of Jun 1', time: 'Yesterday' },
  { sev: 'ok', store: 'SW', text: 'Semaglutide API lot SW-2606-118 passed potency verification', time: 'Yesterday' },
];

const PAYER_MIX = [
  { name: 'Regence BlueShield', share: 0.27, gpPerRx: 11.4 },
  { name: 'Premera Blue Cross', share: 0.22, gpPerRx: 9.8 },
  { name: 'Medicare Part D', share: 0.24, gpPerRx: 6.1 },
  { name: 'Apple Health (Medicaid)', share: 0.13, gpPerRx: 5.2 },
  { name: 'Cash / HSA', share: 0.14, gpPerRx: 28.7 },
];

// ---- Compounding -------------------------------------------------------

const FORMULAS = [
  {
    id: 'f1', name: 'Estradiol 0.5 mg / Progesterone 100 mg per gm', form: 'Topical cream · Topi-CLICK 35 mL',
    category: 'Hormone therapy', bud: '180 days', lot: 'SW-2606-104', costPerUnit: 14.2, price: 78.0,
    mtdFills: 64, prescriber: 'Dr. P. Raghavan — Fidalgo Bay Women’s Health',
    ingredients: [
      { name: 'Estradiol USP, micronized', qty: '17.5 mg', cost: 2.86 },
      { name: 'Progesterone USP, micronized', qty: '3.5 g', cost: 6.12 },
      { name: 'Versabase® cream', qty: 'qs 35 g', cost: 4.05 },
      { name: 'Topi-CLICK 35 dispenser', qty: '1 ea', cost: 1.17 },
    ],
  },
  {
    id: 'f2', name: 'Semaglutide 2.5 mg/mL Injection', form: 'Sterile vial · 3 mL · with B12 1 mg/mL',
    category: 'GLP-1 / metabolic', bud: '28 days', lot: 'SW-2606-118', costPerUnit: 38.6, price: 189.0,
    mtdFills: 89, prescriber: 'ARNP D. Kirsch — Cascade Ridge Wellness',
    ingredients: [
      { name: 'Semaglutide acetate API', qty: '7.5 mg', cost: 29.4 },
      { name: 'Cyanocobalamin (B12)', qty: '3 mg', cost: 1.92 },
      { name: 'Bacteriostatic water, sterile', qty: 'qs 3 mL', cost: 0.84 },
      { name: 'Sterile vial + filtration, ISO 5', qty: '1 ea', cost: 6.44 },
    ],
  },
  {
    id: 'f3', name: 'Ketamine 10% in PLO Gel', form: 'Transdermal gel · 60 g pump',
    category: 'Pain management', bud: '90 days', lot: 'SW-2605-097', costPerUnit: 22.7, price: 96.0,
    mtdFills: 31, prescriber: 'Dr. M. Okafor — Cascade Pain & Spine, Burlington',
    ingredients: [
      { name: 'Ketamine HCl USP (C-III)', qty: '6 g', cost: 14.55 },
      { name: 'PLO gel base, lecithin-isopropyl', qty: 'qs 60 g', cost: 5.6 },
      { name: 'Pump dispenser 60 g', qty: '1 ea', cost: 2.55 },
    ],
  },
  {
    id: 'f4', name: 'Naltrexone 4.5 mg (LDN) Capsules', form: 'Capsules · #90 · avicel filler',
    category: 'Autoimmune / off-label', bud: '365 days', lot: 'SW-2606-101', costPerUnit: 9.8, price: 64.0,
    mtdFills: 57, prescriber: 'Dr. K. Mossberg — Salish Family Medicine, Sedro-Woolley',
    ingredients: [
      { name: 'Naltrexone HCl USP', qty: '405 mg', cost: 4.86 },
      { name: 'Microcrystalline cellulose NF', qty: 'qs', cost: 1.34 },
      { name: 'Gelatin capsules, size 3', qty: '90 ea', cost: 3.6 },
    ],
  },
  {
    id: 'f5', name: 'Methimazole 5 mg/0.1 mL Transdermal', form: 'Veterinary · feline · ear pinna gel, 3 mL syringe',
    category: 'Veterinary', bud: '60 days', lot: 'SW-2606-110', costPerUnit: 7.4, price: 52.0,
    mtdFills: 26, prescriber: 'Dr. T. Reilly, DVM — Chuckanut Valley Veterinary',
    ingredients: [
      { name: 'Methimazole USP', qty: '150 mg', cost: 1.05 },
      { name: 'Lipoderm® base', qty: 'qs 3 mL', cost: 4.1 },
      { name: 'Topi-dose syringes 1 mL ×3', qty: '3 ea', cost: 2.25 },
    ],
  },
  {
    id: 'f6', name: 'Testosterone 100 mg/mL Cream', form: 'Topical cream · 30 mL pump',
    category: 'Hormone therapy', bud: '180 days', lot: 'SW-2606-095', costPerUnit: 11.9, price: 71.0,
    mtdFills: 42, prescriber: 'Dr. K. Mossberg — Salish Family Medicine, Sedro-Woolley',
    ingredients: [
      { name: 'Testosterone USP, micronized (C-III)', qty: '3 g', cost: 6.3 },
      { name: 'Atrevis® hydrogel base', qty: 'qs 30 mL', cost: 4.2 },
      { name: 'Metered pump 30 mL', qty: '1 ea', cost: 1.4 },
    ],
  },
  {
    id: 'f7', name: 'Gabapentin 100 mg/mL Oral Suspension', form: 'Veterinary · canine · chicken flavor, 60 mL',
    category: 'Veterinary', bud: '90 days', lot: 'SW-2605-088', costPerUnit: 8.1, price: 44.0,
    mtdFills: 19, prescriber: 'Dr. T. Reilly, DVM — Chuckanut Valley Veterinary',
    ingredients: [
      { name: 'Gabapentin USP', qty: '6 g', cost: 2.7 },
      { name: 'SuspendIt® vehicle, sugar-free', qty: 'qs 60 mL', cost: 3.3 },
      { name: 'Chicken flavor concentrate', qty: '1.2 mL', cost: 0.9 },
      { name: 'Amber bottle + adapter', qty: '1 ea', cost: 1.2 },
    ],
  },
  {
    id: 'f8', name: 'Hydrocortisone 2.5% / Pramoxine 1% Ointment', form: 'Topical · 30 g jar',
    category: 'Dermatology', bud: '90 days', lot: 'SW-2606-115', costPerUnit: 6.2, price: 38.0,
    mtdFills: 22, prescriber: 'Dr. E. Vargas — Skagit Dermatology Assoc.',
    ingredients: [
      { name: 'Hydrocortisone USP', qty: '750 mg', cost: 1.95 },
      { name: 'Pramoxine HCl', qty: '300 mg', cost: 1.4 },
      { name: 'Emollient ointment base', qty: 'qs 30 g', cost: 2.1 },
      { name: 'Jar 30 g, amber', qty: '1 ea', cost: 0.75 },
    ],
  },
];

// ---- Fill queue --------------------------------------------------------

const QUEUE_STAGES = ['Intake', 'Data Entry', 'Verification', 'Filling', 'Ready for Pickup'];

const QUEUE_RX = [
  { rx: '7104482', stage: 0, patient: 'M. Tran', drug: 'Atorvastatin 40 mg #90', store: 'SW', payer: 'Regence', wait: 4, note: 'E-script from Salish Family Medicine', flag: null },
  { rx: '7104483', stage: 0, patient: 'D. Okada', drug: 'Semaglutide 2.5 mg/mL inj (compound)', store: 'SW', payer: 'Cash', wait: 6, note: 'New patient consult requested', flag: 'compound' },
  { rx: '7104477', stage: 0, patient: 'R. Castillo', drug: 'Lisinopril 20 mg #30', store: 'BUR', payer: 'Apple Health', wait: 12, note: 'Transfer in from Rite Aid, Mount Vernon', flag: null },
  { rx: '7104471', stage: 1, patient: 'S. Whitfield', drug: 'Eliquis 5 mg #60', store: 'ANA', payer: 'Medicare D', wait: 9, note: 'Prior auth on file through Dec', flag: 'neg-margin' },
  { rx: '7104474', stage: 1, patient: 'J. Petersen', drug: 'Metformin ER 1000 mg #60', store: 'BUR', payer: 'Premera', wait: 14, note: 'Sync with Jun 24 refill batch', flag: null },
  { rx: '7104465', stage: 2, patient: 'L. Nygaard', drug: 'Estradiol/Prog cream (compound)', store: 'SW', payer: 'Cash', wait: 8, note: 'RPh verify — new strength, Dr. Raghavan', flag: 'compound' },
  { rx: '7104468', stage: 2, patient: 'A. Bowen', drug: 'Amoxicillin 500 mg #21', store: 'ANA', payer: 'Regence', wait: 5, note: 'Pediatric weight check complete', flag: null },
  { rx: '7104469', stage: 2, patient: 'C. Dunbar', drug: 'Oxycodone 5 mg #30 (C-II)', store: 'BUR', payer: 'Medicare D', wait: 21, note: 'Hard copy required — in transit from prescriber', flag: 'cii' },
  { rx: '7104452', stage: 3, patient: 'H. Salvesen', drug: 'Ketamine 10% PLO gel (compound)', store: 'SW', payer: 'Cash', wait: 17, note: 'Lab bench 2 · lot SW-2605-097', flag: 'compound' },
  { rx: '7104458', stage: 3, patient: 'P. Mehta', drug: 'Levothyroxine 75 mcg #90', store: 'ANA', payer: 'Premera', wait: 7, note: '', flag: null },
  { rx: '7104440', stage: 4, patient: 'G. Albright', drug: 'LDN 4.5 mg caps #90 (compound)', store: 'SW', payer: 'Cash', wait: 0, note: 'Will pick up after 4p — texted', flag: 'compound' },
  { rx: '7104444', stage: 4, patient: 'T. Vasquez', drug: 'Rosuvastatin 10 mg #90', store: 'BUR', payer: 'Regence', wait: 0, note: 'Delivery route 2, Thursday', flag: null },
  { rx: '7104446', stage: 4, patient: 'K. O’Leary', drug: 'Methimazole transdermal (vet)', store: 'SW', payer: 'Cash', wait: 0, note: 'Owner notified — for “Biscuit”', flag: 'compound' },
];

// ---- Inventory ---------------------------------------------------------

const INVENTORY = [
  { ndc: '00093-7424-98', drug: 'Atorvastatin 40 mg tab', pkg: '500 ct', store: 'SW', onHand: 1240, par: 800, daysSupply: 23, status: 'ok', vendor: 'McKesson' },
  { ndc: '68180-0512-09', drug: 'Lisinopril 20 mg tab', pkg: '1000 ct', store: 'BUR', onHand: 310, par: 600, daysSupply: 6, status: 'low', vendor: 'McKesson' },
  { ndc: '00002-1434-80', drug: 'Eliquis 5 mg tab', pkg: '60 ct', store: 'ANA', onHand: 4, par: 12, daysSupply: 3, status: 'reorder', vendor: 'McKesson' },
  { ndc: '00378-1805-10', drug: 'Metformin ER 1000 mg tab', pkg: '500 ct', store: 'BUR', onHand: 890, par: 700, daysSupply: 19, status: 'ok', vendor: 'McKesson' },
  { ndc: 'API-SEMA-0025', drug: 'Semaglutide acetate API', pkg: '25 mg vial', store: 'SW', onHand: 3, par: 6, daysSupply: 8, status: 'low', vendor: 'Letco Medical' },
  { ndc: 'API-PROG-0100', drug: 'Progesterone USP micronized', pkg: '100 g', store: 'SW', onHand: 2, par: 4, daysSupply: 11, status: 'low', vendor: 'PCCA' },
  { ndc: '00074-3799-13', drug: 'Levothyroxine 75 mcg tab', pkg: '100 ct', store: 'ANA', onHand: 460, par: 300, daysSupply: 27, status: 'ok', vendor: 'McKesson' },
  { ndc: '59762-1740-01', drug: 'Oxycodone 5 mg tab (C-II)', pkg: '100 ct', store: 'BUR', onHand: 180, par: 200, daysSupply: 9, status: 'watch', vendor: 'McKesson' },
  { ndc: 'API-KETA-0010', drug: 'Ketamine HCl USP (C-III)', pkg: '10 g', store: 'SW', onHand: 1, par: 3, daysSupply: 5, status: 'reorder', vendor: 'Letco Medical' },
  { ndc: '00781-5077-10', drug: 'Amoxicillin 500 mg cap', pkg: '500 ct', store: 'ANA', onHand: 720, par: 500, daysSupply: 31, status: 'ok', vendor: 'McKesson' },
  { ndc: 'BASE-VERSA-01', drug: 'Versabase® cream', pkg: '1 kg', store: 'SW', onHand: 6, par: 4, daysSupply: 34, status: 'ok', vendor: 'PCCA' },
  { ndc: '13668-0095-90', drug: 'Rosuvastatin 10 mg tab', pkg: '90 ct', store: 'BUR', onHand: 95, par: 180, daysSupply: 7, status: 'low', vendor: 'McKesson' },
  { ndc: '00093-0058-01', drug: 'Tramadol 50 mg tab (C-IV)', pkg: '500 ct', store: 'BUR', onHand: 420, par: 400, daysSupply: 21, status: 'ok', vendor: 'McKesson' },
  { ndc: '00121-0656-16', drug: 'Guaifenesin/Codeine AC syrup (C-V)', pkg: '473 mL', store: 'ANA', onHand: 9, par: 8, daysSupply: 26, status: 'ok', vendor: 'McKesson' },
];

// ---- Insights ----------------------------------------------------------

const INSIGHTS = [
  {
    id: 'i1', tone: 'money', tag: 'Opportunity · est. $48,200/yr',
    title: 'Anacortes is referring compounding out of the family.',
    body: 'In the last 90 days, 31 hormone-therapy patients at Anacortes had prescriptions that match formulas your Sedro-Woolley lab already makes — and 24 of them were routed to an out-of-county compounder. A weekly lab courier run would keep that revenue inside the company.',
    facts: [['Matching scripts, 90d', '31'], ['Routed elsewhere', '24'], ['Avg gross/fill', '$61.40']],
    action: 'Draft courier schedule',
  },
  {
    id: 'i5', tone: 'bad', tag: 'Claims · $1,870 in rework',
    title: 'Premera bounced 12 HRT compound claims this week.',
    body: 'Premera began requiring prior authorization on compounded hormone therapy June 1. Twelve claims rejected with code 75 this week; six remain unresolved, four of them HRT creams. CoverMyMeds turns these PAs around in about two days — every day they sit is a patient who might not come back.',
    facts: [['Rejected, 7d', '12'], ['Unresolved', '6'], ['Avg claim', '$118']],
    action: 'View claims',
  },
  {
    id: 'i2', tone: 'bad', tag: 'Leak · −$1,690 MTD',
    title: 'Eliquis is being dispensed below cost on two Part D plans.',
    body: 'Across 41 Medicare Part D fills this month, average reimbursement on Eliquis 5 mg landed $4.12 under acquisition. SilverScript and one Humana plan account for 86% of the loss. Worth a wholesaler rebid before the July contract window closes.',
    facts: [['Fills MTD', '41'], ['Avg under cost', '−$4.12'], ['Worst plan', 'SilverScript']],
    action: 'Open payer detail',
  },
  {
    id: 'i3', tone: 'money', tag: 'Margin · +6.3 pts',
    title: 'Semaglutide margin widened — demand didn’t blink.',
    body: 'Your API cost per vial dropped 18% on the June Letco order while fills grew 38% quarter over quarter. At current pace this single formula clears $14,800 gross profit this month — your best-performing SKU across all three stores, retail included.',
    facts: [['Fills, QoQ', '+38%'], ['API cost', '−18%'], ['GP this month', '$14.8k']],
    action: 'View formula',
  },
  {
    id: 'i4', tone: 'warn', tag: 'Operations',
    title: 'Burlington’s Wednesday queue is a staffing problem, not a volume problem.',
    body: 'Wednesday script volume at Burlington is only 6% above weekday average, but verification wait runs 2.4× longer. The pattern matches Dr. Okafor’s clinic day — a single tech shifted from Sedro-Woolley on Wednesdays would flatten it.',
    facts: [['Wed volume', '+6%'], ['Wed verify wait', '2.4×'], ['Fix', '1 tech, 1 day']],
    action: 'See queue history',
  },
];

const ASK_CHIPS = [
  'Which payer shorts us the most?',
  'Top compounds by margin',
  'Where is refill leakage worst?',
  'Compare the three stores this month',
];

const ASK_ANSWERS = {
  'Which payer shorts us the most?':
    'Medicare Part D, by a wide margin. Average gross profit per fill is $6.10 versus $11.40 on Regence — and on 7 specific NDCs (led by Eliquis 5 mg) you are net-negative. Part D is 24% of your volume but only 13% of your gross profit. Cash and HSA fills, mostly compounding, return $28.70 per fill.',
  'Top compounds by margin':
    'By gross margin: Naltrexone 4.5 mg LDN caps (84.7%), Methimazole transdermal (85.8%), Estradiol/Progesterone cream (81.8%), Semaglutide injection (79.6%). By total dollars, semaglutide leads at $14.8k this month on 89 fills — volume beats percentage.',
  'Where is refill leakage worst?':
    'Burlington. 90-day refill completion runs 81% there versus 89% at Sedro-Woolley. The gap concentrates in maintenance statins and metformin — about 140 fills a quarter quietly not returning. An enrollment push into med-sync on the Burlington queue would recover most of it.',
  'Compare the three stores this month':
    'Sedro-Woolley: $248.3k, +4.2%, carried by the lab (31% of revenue is compounding). Anacortes: $186.9k, +1.8%, steady retail but near-zero compounding share — that’s the growth lever. Burlington: $172.4k, −0.9%, the only store trending down; queue wait of 19 min is the canary, see the Wednesday staffing finding.',
};

// ====== Reports data layer ==============================================
// Trailing-12-month label set (oldest → newest), ending current month (Jun).
const MONTHS_12 = ['Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'];

// --- Report 1: Prescriber Reports (compounding & specialty accounts) -----
// months[] are monthly compounding revenue in $ (oldest → newest). The last
// month sums across all clinics to $109,400 = 18% of $607.5k combined revenue
// (the MARGIN_STORY compounding share), so prescriber totals reconcile.
const PRESC_PERIODS = [
  { key: '30d', label: '30d', months: 1 },
  { key: '90d', label: '90d', months: 3 },
  { key: '6mo', label: '6 mo', months: 6 },
  { key: '12mo', label: '12 mo', months: 12 },
];

const PRESCRIBERS = [
  {
    id: 'ridge', clinic: 'Cascade Ridge Wellness', prescriber: 'ARNP D. Kirsch', city: 'Mount Vernon',
    topCat: 'GLP-1 / metabolic', trend: 'up', scripts30: 172, newPerWeek: 7,
    months: [18200, 19100, 20400, 21800, 22600, 24100, 25300, 26800, 28200, 29600, 30700, 31800],
    analysis: 'Cascade Ridge is the lab’s fastest-growing account. Semaglutide volume is up 38% quarter over quarter while the June Letco order cut API cost 18% — margin widened as demand climbed. This single clinic now drives more compounded revenue than any other prescriber.',
    rec: 'Lock a standing weekly API reservation with Letco so a stockout never throttles the busiest account.',
  },
  {
    id: 'fidalgo', clinic: 'Fidalgo Bay Women’s Health', prescriber: 'Dr. P. Raghavan', city: 'Anacortes',
    topCat: 'Hormone therapy', trend: 'down', scripts30: 248, newPerWeek: 3,
    months: [28200, 28600, 28100, 28800, 28300, 27900, 27600, 26400, 25100, 24200, 23300, 22400],
    analysis: 'Fidalgo Bay revenue is down 12% over the period, driven almost entirely by HRT cream volume. Premera began requiring prior authorization on compounded hormone therapy June 1, and that friction is the likely cause — claims are bouncing with reject code 75.',
    rec: 'Resolve the 6 open Premera PAs through CoverMyMeds, then schedule a check-in visit with Dr. Raghavan.',
  },
  {
    id: 'salish', clinic: 'Salish Family Medicine', prescriber: 'Dr. K. Mossberg', city: 'Sedro-Woolley',
    topCat: 'Hormone therapy', trend: 'flat', scripts30: 286, newPerWeek: 4,
    months: [19200, 19500, 19100, 19800, 19400, 19700, 19300, 19900, 19500, 19800, 19400, 19600],
    analysis: 'Salish Family Medicine is steady — LDN and testosterone volume holds flat month over month with no churn signals. A dependable, diversified account rather than a growth or risk story.',
    rec: 'Maintain the quarterly formulary touch-base; no intervention needed.',
  },
  {
    id: 'pain', clinic: 'Cascade Pain & Spine', prescriber: 'Dr. M. Okafor', city: 'Burlington',
    topCat: 'Pain management', trend: 'flat', scripts30: 142, newPerWeek: 3,
    months: [13900, 14100, 13800, 14300, 14000, 14200, 13900, 14400, 14100, 14300, 14000, 14200],
    analysis: 'Cascade Pain & Spine runs flat and predictable, anchored by ketamine PLO gel. Volume tracks Dr. Okafor’s Wednesday clinic day — the same day Burlington’s verification queue backs up.',
    rec: 'Hold current cadence; coordinate Wednesday fills with the Burlington staffing fix.',
  },
  {
    id: 'vet', clinic: 'Chuckanut Valley Veterinary', prescriber: 'Dr. T. Reilly, DVM', city: 'Bow',
    topCat: 'Veterinary', trend: 'up', scripts30: 248, newPerWeek: 6,
    months: [7800, 8200, 8600, 9100, 9500, 10100, 10600, 11200, 11600, 12100, 12500, 12800],
    analysis: 'Chuckanut Valley is the quiet breakout — feline methimazole transdermal has compounded steadily for six months as more clinics route hyperthyroid cats here rather than fight oral dosing. Gabapentin suspension adds a stable second line.',
    rec: 'Pitch the transdermal program to two more Skagit-area veterinary clinics while the reference base is strong.',
  },
  {
    id: 'derm', clinic: 'Skagit Dermatology Assoc.', prescriber: 'Dr. E. Vargas', city: 'Mount Vernon',
    topCat: 'Dermatology', trend: 'flat', scripts30: 214, newPerWeek: 3,
    months: [8700, 8500, 8800, 8400, 8600, 8500, 8700, 8400, 8600, 8500, 8700, 8600],
    analysis: 'Skagit Dermatology Associates is flat and small — a single hydrocortisone/pramoxine ointment line with consistent but modest reorder volume. Stable, low-effort account.',
    rec: 'Bundle into the quarterly review; explore a second derm formula to deepen the account.',
  },
];

// Sum of last N months for a clinic.
function prescRev(clinic, nMonths) {
  return clinic.months.slice(-nMonths).reduce((a, v) => a + v, 0);
}
// Recent-half vs prior-half per-month average change (%), over the period window.
function prescChange(clinic, nMonths) {
  if (nMonths <= 1) {
    const a = clinic.months[clinic.months.length - 1], b = clinic.months[clinic.months.length - 2];
    return ((a - b) / b) * 100;
  }
  const w = clinic.months.slice(-nMonths);
  const mid = Math.floor(w.length / 2);
  const prior = w.slice(0, mid), recent = w.slice(mid);
  const avg = arr => arr.reduce((x, y) => x + y, 0) / arr.length;
  return ((avg(recent) - avg(prior)) / avg(prior)) * 100;
}

// --- Report 2: Revenue & Growth (executive) -----------------------------
// Trailing 12 months, $k. Last value (Jun) = 607.5 = combined MTD revenue.
const REV_THIS_YEAR = [556, 547, 569, 558, 581, 604, 571, 566, 585, 590, 598, 607.5];
const REV_LAST_YEAR = [498, 489, 506, 497, 515, 542, 503, 499, 514, 519, 527, 534];
const REV_KPIS = {
  mtd: 607500,                                   // = STORES combined (Command Center)
  qtd: (590 + 598 + 607.5) * 1000,               // Apr+May+Jun
  ytd: (571 + 566 + 585 + 590 + 598 + 607.5) * 1000, // Jan–Jun
  yoy: ((607.5 - 534) / 534) * 100,              // Jun this year vs last
};
// Company revenue by category, $k of 607.5 total. Compounding categories sum
// to 109.3k (18%); GLP-1 ties to Cascade Ridge, Pain ties to Cascade P&S.
const CATEGORY_MIX = [
  { name: 'Retail', val: 498.2, color: '#8e9385' },
  { name: 'HRT', val: 38.0, color: '#2f6b4a' },
  { name: 'GLP-1', val: 31.8, color: '#a8652f' },
  { name: 'Veterinary', val: 15.0, color: '#5b6b8c' },
  { name: 'Pain', val: 14.2, color: '#97690f' },
  { name: 'Dermatology', val: 10.3, color: '#4a7a5c' },
];
// Biggest movers: 90d vs prior 90d (revenue, $). Ties: semaglutide riser (i3),
// HRT cream decliner (Premera PA / i5 / Fidalgo), feline transdermal riser.
const BIGGEST_MOVERS = [
  { name: 'Semaglutide 2.5 mg/mL injection', cat: 'GLP-1', recent: 50500, prior: 36600 },
  { name: 'Estradiol/Progesterone HRT cream', cat: 'Hormone therapy', recent: 13400, prior: 15580 },
  { name: 'Methimazole transdermal (feline)', cat: 'Veterinary', recent: 4060, prior: 3050 },
  { name: 'Naltrexone 4.5 mg LDN caps', cat: 'Autoimmune', recent: 10950, prior: 10140 },
  { name: 'Ketamine 10% PLO gel', cat: 'Pain', recent: 8930, prior: 8670 },
];

// --- Report 3: Patient Analytics (aggregate only · PHI-safe) -------------
const PATIENT_ANALYTICS = {
  kpis: { total: 18420, newYTD: 1240, seniors65: 5180, allergies: 3960, active6mo: 11800 },
  // New patients per month, trailing 12. Jan–Jun (last 6) sums to 1,240 = newYTD.
  newPerMonth: [176, 189, 183, 197, 205, 194, 198, 205, 210, 206, 213, 208],
  ageBands: [
    { name: '0–17', val: 1474, color: '#8e9385' },
    { name: '18–34', val: 3316, color: '#a8652f' },
    { name: '35–49', val: 4052, color: '#97690f' },
    { name: '50–64', val: 4398, color: '#5b6b8c' },
    { name: '65+', val: 5180, color: '#2f6b4a' },
  ],
  gender: [['Female', 10684, '58.0%'], ['Male', 7552, '41.0%'], ['Undisclosed', 184, '1.0%']],
};

// --- Report 4: Volume & Workflow ----------------------------------------
const FILLS_MONTHLY = [9120, 8980, 9210, 9050, 9380, 9620, 9180, 9240, 9410, 9460, 9520, 9480];
const VOLUME = {
  kpis: { fillsMonth: 9480, fills7d: 2150, turnaroundHrs: 3.4, pharmacists: 4 },
  // Pharmacists only — C. Schaffner + J. Okada (both PharmD in patient notes)
  // plus two distinct PharmD names. Techs (M. Reyes, K. Tanaka, R. Delgado)
  // are NOT listed. Monthly fills sum to 9,480 = fillsMonth.
  pharmacists: [
    { name: 'J. Okada, PharmD', store: 'Anacortes', fills: 2640 },
    { name: 'L. Brandt, PharmD', store: 'Burlington', fills: 2460 },
    { name: 'N. Ferreira, PharmD', store: 'Sedro-Woolley', fills: 2200 },
    { name: 'C. Schaffner, PharmD', store: 'Sedro-Woolley', fills: 2180 },
  ],
  callout: 'Burlington’s Wednesday verification wait runs 2.4× the weekday average — a staffing pattern, not a volume spike.',
};
// Fills time-series by period. 30d = daily with weekends closed (stores shut
// Sat/Sun); longer periods aggregate to weekly/monthly from FILLS_MONTHLY.
function fillsSeries(periodKey) {
  if (periodKey === '30d') {
    const data = [], labels = [];
    for (let i = 0; i < 30; i++) {
      const d = 29 - i;                 // days back from today (Thu)
      const dow = (((4 - d) % 7) + 7) % 7; // 0=Sun … 6=Sat; today Thu=4
      const closed = dow === 0 || dow === 6;
      data.push(closed ? 0 : 400 + ((i * 37 + 13) % 70));
      labels.push(i % 7 === 1 ? 'wk' + (Math.floor(i / 7) + 1) : '');
    }
    return { data, labels };
  }
  if (periodKey === '90d') {
    const data = [], labels = [];
    for (let i = 0; i < 13; i++) {
      data.push(2040 + Math.round(i * 11) + ((i * 23) % 40));
      labels.push(i % 3 === 0 ? 'w' + (i + 1) : '');
    }
    return { data, labels };
  }
  if (periodKey === '6mo') {
    return { data: FILLS_MONTHLY.slice(-6), labels: MONTHS_12.slice(-6) };
  }
  return { data: FILLS_MONTHLY, labels: MONTHS_12.map((m, i) => (i % 2 === 0 ? m : '')) };
}

// --- Report 5: Controlled Substance Compliance --------------------------
// C-III/C-IV/C-V only — no C-II dispensing. Controlled YTD = 2,814 ≈ 5.0% of
// ~56,290 total fills YTD (within the realistic 4–7% band).
const CONTROLLED = {
  kpis: { fillsYTD: 2814, sharePct: 5.0, distinctItems: 4, totalFillsYTD: 56290 },
  perMonth: [442, 455, 448, 461, 450, 468, 459, 471, 463, 476, 470, 475],
  items: [
    { name: 'Tramadol 50 mg tab', sched: 'C-IV', fills: 1640, lastStore: 'Burlington' },
    { name: 'Guaifenesin/Codeine AC syrup', sched: 'C-V', fills: 520, lastStore: 'Anacortes' },
    { name: 'Testosterone 100 mg/mL cream', sched: 'C-III', fills: 370, lastStore: 'Sedro-Woolley' },
    { name: 'Ketamine 10% PLO gel', sched: 'C-III', fills: 284, lastStore: 'Sedro-Woolley' },
  ],
  pdmp: 'PDMP reporting current · Last submission today 6:02a',
};

// ---- Periods (Command Center date selector) ----------------------------

const PERIOD_OPTS = [7, 14, 30, 60, 90];
const REV_RATES = {
  sw:  { rate: 8270, delta: { 7: 5.1, 14: 4.6, 30: 4.2, 60: 3.1, 90: 2.4 } },
  ana: { rate: 6230, delta: { 7: 2.2, 14: 1.9, 30: 1.8, 60: 0.9, 90: 1.1 } },
  bur: { rate: 5750, delta: { 7: -1.8, 14: -1.2, 30: -0.9, 60: -0.4, 90: 0.3 } },
};
function revFor(id, days) { return Math.round((REV_RATES[id].rate * days) / 100) * 100; }
function deltaFor(id, days) { return REV_RATES[id].delta[days]; }

Object.assign(window, {
  STORES, TREND_LABELS, MARGIN_STORY, ALERTS, PAYER_MIX,
  FORMULAS, QUEUE_STAGES, QUEUE_RX, INVENTORY,
  INSIGHTS, ASK_CHIPS, ASK_ANSWERS,
  PERIOD_OPTS, revFor, deltaFor,
  MONTHS_12, PRESC_PERIODS, PRESCRIBERS, prescRev, prescChange,
  REV_THIS_YEAR, REV_LAST_YEAR, REV_KPIS, CATEGORY_MIX, BIGGEST_MOVERS,
  PATIENT_ANALYTICS, FILLS_MONTHLY, VOLUME, fillsSeries, CONTROLLED,
});
