// PeriodReport.jsx — Admin Portal page (v25.00): the numbers of one pay
// period on one screen — sales by channel, labor productivity, what the
// crew and the manager earn, and what is left — with one row per period
// in the list. Ryan built the model in a Google Sheet (four tabs at 30k /
// 32k / 40k / 45k gross to see how the manager's pay comes out); this page
// is that sheet, fed:
//
//   Direct sales      — from Square, via sales_daily.by_channel summed over
//                       the period's days, every source that is not a
//                       third-party platform (Kiosk, Square Online, POS…).
//   DoorDash / Uber   — from the platform's own CSV export, uploaded here
//   Eats / GrubHub      per period and read by a per-platform parser
//                       (period_channel_imports keeps the figures AND the
//                       file, so a parser fix can re-read it).
//   Hours             — v25.01: clocked hours from Square (square-hours,
//                       everyone mode), crew only — the manager's own
//                       clock-ins are partial and his pay is a fixed base.
//                       v26.02: total labor hours (clockedHours in code) =
//                       the crew's Square hours + his (manager_hours, at
//                       least the Defaults 70 per two weeks); effective =
//                       total − training.
//                       v26.31: a period has no Manager hours line any more.
//                       Total labor hours are the crew's Square hours,
//                       effective = total − training, and actual
//                       productivity is gross ÷ (effective + the manager's
//                       hours, the Defaults figure manager_fixed_hours, 50).
//                       Training hours are no longer typed: the training
//                       shifts are picked from the clocked shifts
//                       (PrTrainingModal, square-hours v9).
//                       Rates and the typed marketing lines
//                       stay in period_reports.inputs; Google / Meta spend
//                       comes from ads-spend once the accounts are connected.
//   Percentages       — restaurants.period_report_config holds the
//                       defaults; each period keeps its OWN copy in
//                       period_reports.params from the first save on, so a
//                       change to 28% next quarter does not rewrite history.
//
// The formulas are the sheet's, name for name (prCompute below).
// Periods come from getPayPeriod(anchor) like every other pay-period page.
//
// The Simulator (v26.00, PrSimulator) runs one what-if period through the
// same prCompute: gross, net and the hours are typed, the rest is set.

const PR_CHANNELS = [
  { key: 'direct',   label: 'Direct',    source: 'square' },
  { key: 'doordash', label: 'DoorDash',  source: 'csv' },
  { key: 'ubereats', label: 'Uber Eats', source: 'csv' },
  { key: 'grubhub',  label: 'GrubHub',   source: 'csv' },
];
const PR_TPD = PR_CHANNELS.filter(c => c.source === 'csv');
// sales_daily.by_channel keys that are NOT direct. Square spells it
// "Grubhub"; both spellings are excluded to be safe.
const PR_SQUARE_TPD = { 'DoorDash': true, 'Uber Eats': true, 'Grubhub': true, 'GrubHub': true };

// The sheet's constants. Defaults live in restaurants.period_report_config
// (editable from the gear); a period copies them on its first save.
const PR_PARAM_KEYS = ['goal_productivity', 'goal_pace', 'manager_hours', 'manager_fixed_hours', 'manager_bonus_factor', 'manager_commission_rate', 'commission_base_net', 'commission_step', 'commission_cap', 'tax_insurance_rate'];
const PR_PARAM_DEFAULTS = { goal_productivity: 55, goal_pace: 80, manager_hours: 70, manager_fixed_hours: 50, manager_bonus_factor: 35, manager_commission_rate: 0.01, commission_base_net: 30000, commission_step: 0.001, commission_cap: 0.02, tax_insurance_rate: 0.10 };
// The goal productivity rises with sales (v26.11, Ryan: "fixed plus variable
// hours with a floor", milestones for a two-week period). It is the target
// for ACTUAL productivity — gross ÷ (crew + manager) hours — so its hours
// (gross ÷ goal) are the total hours to schedule, the manager's included.
// Between milestones those hours run in a straight line (a fixed part plus
// hours per extra dollar); below the lowest milestone the goal stays at its
// $/hr (the floor); past the highest, one more labor hour for every
// goal_pace dollars of gross (v26.13, Ryan: "instead of 82.50, use 80" — so
// the $40,000/$60 milestone gave way to the $80 pace; $40,000 now reads
// $59.66). Without a pace the last stretch's slope continues.
// A milestone is typed as total labor hours (v26.14, Ryan: "instead of Goal
// per labor hour, let me input the total hours, and it can calculate the
// Productivity"): { gross, hours }, its goal = gross ÷ hours.
// params.goal_milestones is copied per period like the categories;
// goal_productivity (55) is only the fallback when there are none.
const PR_DEFAULT_GOAL_MILESTONES = [
  { gross: 20000, hours: 500 },           // $40/hr
  { gross: 30000, hours: 30000 / 55 },    // 545.45 h, $55/hr
];
// The productivity bonus (v26.10, Ryan: "use the Productivity gap x 35 fixed
// ratio") is (pre-manager productivity − goal) × manager_bonus_factor (35), a
// Defaults number copied per period and click-to-change on a period. It grows
// in a straight line with sales and turns negative below the goal. The 35
// equals 50% × the manager's 70 hours a period, so the 50% share (v26.07) is
// folded in; v26.06–v26.09 multiplied by goal − crew hours instead, which made
// the bonus grow with the SQUARE of sales on a fixed schedule. Old configs and
// periods may still carry manager_bonus_per_hour / manager_bonus_share; unread.
// manager_hours (v26.01; a minimum since v26.02) is the manager's labor per
// two-week period — typed, because his clock-ins are partial. The Defaults
// figure is also the least the Simulator may use. It is part of the
// Simulator's total labor hours. A real period stopped reading it in v26.31.
const PR_PERIOD_DAYS = 14;
// manager_fixed_hours (v26.31) is the manager's hours on a REAL period.
// Ryan: "Remove the Manager hours, since it's not in the equation. (the
// actual productivity just use effective hours + 50hr)", and, asked where
// the 50 should live, "its own Defaults setting": a Defaults number (50 per
// two weeks), copied per period like every other param and click-to-change
// on a period, prorated to the days so far while one runs. It is added to
// effective hours for actual productivity only; pay never read the manager's
// hours (the bonus is pre-manager productivity against the goal). A period
// saved before v26.31 has no copy and follows today's Defaults until it is
// clicked or Reload defaults runs. It is NOT the Manager bonus ratio, which
// happens to be 50 on the live config too. The Simulator is untouched and
// keeps its own typed manager hours (manager_hours above).
// The P&L categories other than labor (v25.03): each holds lines of
// { id, name, mode: 'pct' (% of net sales) | 'amt' ($ per period), value }.
// Defaults are edited in the Defaults drawer and copied into a period on
// its first save; a period then edits its own values. Food & Paper is the
// one category the model already had (28% → Food 25 + Paper 3).
// A $ line is what Ryan pays per year / month / week / day (v25.04, year
// v25.05) and is PRORATED to the period's days: year ÷ 365 × days, month ×
// 12 ÷ 365 × days, week ÷ 7 × days, day × days. A period in progress prorates to the days elapsed so far, so
// Left reads against the sales so far.
const PR_BASES = { year: 'per year', month: 'per month', week: 'per week', day: 'per day' };
const PR_LINE_MODES = [
  { value: 'pct', label: '% of net sales' },
  { value: 'pct|direct', label: '% of direct net sales' },
  { value: 'amt|year', label: '$ per year' },
  { value: 'amt|month', label: '$ per month' },
  { value: 'amt|week', label: '$ per week' },
  { value: 'amt|day', label: '$ per day' },
];
// What a % line is a share of (v26.39, Ryan: "card processing … should only
// be Direct net sales, not including the third party"): `of` 'direct' = the
// direct channel's net sales (Kiosk, Square Online, Point of Sale), 'net' =
// every channel's. The platforms take their own commission and never pass
// through our card processing. A line saved before v26.39 has no `of`; the
// built-in Card processing line (id card_fees, which Ryan's Defaults and
// every saved period still use) reads as direct, so past periods correct
// themselves with no data change. Every other % line stays on all net sales.
const prPctOf = (it) => (it.of === 'direct' || it.of === 'net') ? it.of : (it.id === 'card_fees' ? 'direct' : 'net');
const prModeKey = (it) => it.mode === 'pct' ? (prPctOf(it) === 'direct' ? 'pct|direct' : 'pct') : 'amt|' + (it.basis || 'month');
// A mode key from the select back to a line's fields.
const prModeFields = (key) => {
  const p = String(key).split('|');
  return p[0] === 'pct' ? { mode: 'pct', basis: null, of: p[1] === 'direct' ? 'direct' : 'net' } : { mode: 'amt', basis: p[1] || 'month', of: null };
};
const prLineDef = (it) => it.mode === 'pct'
  ? (prNum(it.value) || 0) + '% of ' + (prPctOf(it) === 'direct' ? 'direct net sales' : 'net sales')
  : prMoney(prNum(it.value) || 0) + ' ' + (PR_BASES[it.basis] || PR_BASES.month);
const prProrate = (it, net, days, directNet) => {
  const v = prNum(it.value) || 0;
  if (it.mode === 'pct') return (prPctOf(it) === 'direct' && directNet != null ? directNet : net) * v / 100;
  const b = it.basis || 'month';
  return b === 'day' ? v * days : (b === 'week' ? v / 7 * days : (b === 'year' ? v / 365 * days : v * 12 / 365 * days));
};
const PR_DEFAULT_CATEGORIES = [
  { key: 'food_paper', name: 'Food & Paper', items: [
    { id: 'food', name: 'Food', mode: 'pct', value: 25 },
    { id: 'paper', name: 'Paper', mode: 'pct', value: 3 } ] },
  { key: 'marketing', name: 'Marketing', items: [
    { id: 'yelp', name: 'Yelp Ads', mode: 'amt', basis: 'month', value: 0 },
    { id: 'spotify', name: 'Spotify Ads', mode: 'amt', basis: 'month', value: 0 },
    { id: 'other_marketing', name: 'Other marketing', mode: 'amt', basis: 'month', value: 0 } ] },
  { key: 'occupancy', name: 'Occupancy', items: [
    { id: 'rent', name: 'Rent', mode: 'amt', basis: 'month', value: 0 },
    { id: 'cam', name: 'CAM / NNN', mode: 'amt', basis: 'month', value: 0 },
    { id: 'property_tax', name: 'Property tax', mode: 'amt', basis: 'month', value: 0 },
    { id: 'property_insurance', name: 'Property insurance', mode: 'amt', basis: 'year', value: 0 } ] },
  { key: 'utilities', name: 'Utilities', items: [
    { id: 'electric', name: 'Electricity', mode: 'amt', basis: 'month', value: 0 },
    { id: 'gas', name: 'Gas', mode: 'amt', basis: 'month', value: 0 },
    { id: 'water', name: 'Water & sewer', mode: 'amt', basis: 'month', value: 0 },
    { id: 'trash', name: 'Trash', mode: 'amt', basis: 'month', value: 0 },
    { id: 'internet', name: 'Internet & phone', mode: 'amt', basis: 'month', value: 0 } ] },
  { key: 'operating', name: 'Operating', items: [
    { id: 'smallwares', name: 'Smallwares & supplies', mode: 'pct', value: 1 },
    { id: 'cleaning', name: 'Cleaning & chemicals', mode: 'pct', value: 0.5 },
    { id: 'repairs', name: 'Repairs & maintenance', mode: 'pct', value: 1 },
    { id: 'pest', name: 'Pest control', mode: 'amt', basis: 'month', value: 0 },
    { id: 'uniforms', name: 'Uniforms & laundry', mode: 'amt', basis: 'month', value: 0 } ] },
  { key: 'tech_fees', name: 'Technology & fees', items: [
    { id: 'card_fees', name: 'Card processing', mode: 'pct', value: 2.7 },
    { id: 'software', name: 'Software & subscriptions', mode: 'amt', basis: 'month', value: 0 },
    { id: 'bank', name: 'Bank fees', mode: 'amt', basis: 'month', value: 0 } ] },
  { key: 'admin', name: 'General & admin', items: [
    { id: 'accounting', name: 'Accounting & bookkeeping', mode: 'amt', basis: 'month', value: 0 },
    { id: 'legal', name: 'Legal', mode: 'amt', basis: 'month', value: 0 },
    { id: 'licenses', name: 'Licenses & permits', mode: 'amt', basis: 'year', value: 0 },
    { id: 'liability', name: 'Liability insurance', mode: 'amt', basis: 'year', value: 0 },
    { id: 'payroll_service', name: 'Payroll service', mode: 'amt', basis: 'month', value: 0 } ] },
  // Interest, taxes, depreciation, amortisation — below the operating line,
  // so the summary shows EBITDA before it (v25.08).
  { key: 'itda', name: 'ITDA', items: [
    { id: 'loan_interest', name: 'Loan interest', mode: 'amt', basis: 'month', value: 0 } ] },
];
const prCloneCats = (cats) => (Array.isArray(cats) ? cats : []).map(cat => ({
  key: String(cat.key || ''), name: String(cat.name || ''),
  items: (Array.isArray(cat.items) ? cat.items : []).map(it => ({
    id: String(it.id || ''), name: String(it.name || ''), mode: it.mode === 'pct' ? 'pct' : 'amt',
    basis: it.mode === 'pct' ? null : (PR_BASES[it.basis] ? it.basis : 'month'), value: prNum(it.value) || 0,
    of: it.mode === 'pct' && (it.of === 'direct' || it.of === 'net') ? it.of : null,
  })),
}));
const prNewId = () => 'x' + Date.now().toString(36) + Math.random().toString(36).slice(2, 6);
// Inputs that also have a default (the sheet's typed-in values).
const PR_INPUT_DEFAULT_KEYS = ['manager_base'];
const PR_INPUT_DEFAULTS = { manager_base: 1200 };
// The Simulator (v26.00): net is usually about 92% of gross (its Apply
// link), the crew is priced at a flat $12.50 an hour — Ryan: "this is for
// simulator only"; a period prices each Square timecard at its own wage.
// The typed numbers are shared by everyone since v26.20 (period_report_sim,
// usePrSimShared); before that each browser kept its own under
// localStorage 'period_report_sim_v2', which is simply no longer read.
const PR_SIM_NET_RATIO = 0.92;
const PR_SIM_CREW_WAGE = 12.5;
// The Simulator's sales (v26.09, Ryan): an estimate per weekday, Sunday first,
// seeded with his numbers; gross for the pay period is two of each day and
// net is PR_SIM_NET_RATIO of it — nothing to type for either.
const PR_SIM_DAYS = [
  { key: 'sun', short: 'Sun', long: 'Sunday',    seed: 2000 },
  { key: 'mon', short: 'Mon', long: 'Monday',    seed: 1700 },
  { key: 'tue', short: 'Tue', long: 'Tuesday',   seed: 1800 },
  { key: 'wed', short: 'Wed', long: 'Wednesday', seed: 2000 },
  { key: 'thu', short: 'Thu', long: 'Thursday',  seed: 2200 },
  { key: 'fri', short: 'Fri', long: 'Friday',    seed: 2600 },
  { key: 'sat', short: 'Sat', long: 'Saturday',  seed: 2400 },
];
const prMoneyShort = (n) => '$' + n.toLocaleString('en-US', { minimumFractionDigits: Number.isInteger(n) ? 0 : 2, maximumFractionDigits: 2 });
// The two marketing lines the APIs fill (inputs.marketing.google / .meta);
// every other marketing line is a category line under Defaults.
const PR_API_ADS = [
  { key: 'google', label: 'Google Ads' },
  { key: 'meta',   label: 'Meta Ads' },
];
// What each column adds up, for the ⓘ on the Sales table.
const PR_HOW = {
  direct: [
    'From Square, every source that isn’t a delivery platform: Kiosk, Square Online, Point of Sale.',
    'Gross = item sales before discounts, by the day each order was due.',
    'Discount = gross − net on those orders (they carry no commission).',
    'Refund = refunds issued during the period on those orders, pre-tax.',
    'Sync recomputes all 14 days from Square.',
  ],
  doordash: [
    'From the Financial Report’s FINANCIAL_DETAILED_TRANSACTIONS file.',
    'Gross = Σ Subtotal.',
    'Commission = Σ Commission (commission tax and payment processing are not counted).',
    'Discount = Σ Customer discounts from marketing (funded by you).',
    'Refund = Σ Error charges.',
    'Marketing fees → 3PD Ads.',
  ],
  ubereats: [
    'From the Payment details report (the short column names on its second header row).',
    'Gross = Σ Sales (excl. tax).',
    'Commission = Σ Marketplace Fee (+ delivery network and order processing fees when present; the fee’s tax is not counted).',
    'Discount = Σ Offers on items + Delivery Offer Redemptions (incl. tax).',
    'Refund = Σ Chargeback Amount.',
    'Offer Redemption Fee → 3PD redemption · Ad Spend → 3PD Ads.',
  ],
  grubhub: [
    'From the Transactions export.',
    'Gross = Σ Subtotal over every row, adjustment rows included (a reversed order nets out of gross, so Refund is always 0 here).',
    'Commission = Σ Commission + Delivery Commission + GH+ Commission + Processing Fee.',
    'Discount = Σ Targeted Promotion.',
  ],
};
// Which file to get from each platform (v26.33, Ryan: "I need a tooltip to
// tell me which report or the report name to get from those platforms"),
// beside each Upload button and in the upload box. DoorDash's file names
// and the Uber Eats one are the ones uploaded so far; DoorDash's zip holds a
// SIMPLIFIED file too, which lacks the "funded by you" discount column.
// `first` = how the right file starts, to tell it apart at a glance.
const PR_CSV_SOURCE = {
  doordash: {
    steps: [
      'DoorDash Merchant Portal → Reports → Create report → Financial Report.',
      'Dates: the first and last day of the pay period.',
      'It downloads as a zip of several CSV files. Upload the one named FINANCIAL_DETAILED_TRANSACTIONS_….csv, not the SIMPLIFIED one.',
    ],
    first: 'Timestamp UTC time, Timestamp UTC date, Timestamp local time',
  },
  ubereats: {
    steps: [
      'Uber Eats Manager → Reports → Request report → Payment details.',
      'Dates: the first and last day of the pay period.',
      'Upload the file as it downloads, named like …-united_states.csv.',
    ],
    first: 'Store name as per Uber Eats manager',
  },
  grubhub: {
    steps: [
      'Grubhub for Restaurants → Financials → Transactions.',
      'Dates: the first and last day of the pay period, then download the CSV.',
    ],
    first: 'Order Channel, ID, Fulfillment Type, Restaurant',
  },
};
const prCsvSourceTip = (c) => {
  const s = PR_CSV_SOURCE[c.key];
  return (
    <>
      <p><b>Which {c.label} file to upload</b></p>
      {s.steps.map((t, i) => <p key={i}>{(i + 1) + '. ' + t}</p>)}
      <p>The right file starts with these columns: {s.first}.</p>
    </>
  );
};
// One icon per section (v25.06); a category without one gets the tag.
const PR_ICONS = {
  sales: 'ri-store-2-line', labor: 'ri-time-line', pay: 'ri-wallet-3-line', laborcost: 'ri-group-line',
  food_paper: 'ri-restaurant-line', marketing: 'ri-megaphone-line', occupancy: 'ri-building-2-line',
  utilities: 'ri-plug-line', operating: 'ri-tools-line', tech_fees: 'ri-bank-card-line', admin: 'ri-briefcase-line',
  left: 'ri-scales-3-line', itda: 'ri-calculator-line', other: 'ri-price-tag-3-line',
};
// pct (v26.21, Ryan: "show the total Labor cost % next to this section
// titles too … and all other sections"): the section's total as a share of
// net sales, beside the title on both the period page and the Simulator.
// Sales (the base) and Labor & productivity (hours) don't pass one.
const PrTitle = ({ icon, children, hint, pct }) => (
  <div className="portal-card-title pr-title">
    <span className="pr-title-ic"><PIcon name={icon || PR_ICONS.other} size={15} /></span>
    <span>{children}</span>
    {hint ? <PrHint text={hint} /> : null}
    {pct != null && isFinite(pct) && (
      <span className={'pr-title-pct' + (pct < -0.0005 ? ' is-neg' : '')} title="Of net sales">{prPct(pct)}</span>
    )}
  </div>
);
// Who is left out of the crew's hours and wages (v25.09): Defaults'
// `exclude_staff` (staff ids) when set, else everyone whose role is Manager
// or Admin — the rule square-hours applies on its own.
const prExcludedIds = (config) => {
  const ids = config && Array.isArray(config.exclude_staff) ? config.exclude_staff.map(String) : null;
  if (ids) return new Set(ids);
  return new Set((window.SAMPLE_STAFF || []).filter(s => /^(manager|admin)$/i.test(String(s.role || ''))).map(s => String(s.id)));
};
const PR_NO_PM = { autoComplete: 'off', 'data-1p-ignore': 'true', 'data-lpignore': 'true', 'data-bwignore': 'true', 'data-form-type': 'other' };
const PR_RAW_MAX = 2 * 1024 * 1024;   // a CSV bigger than this is kept as figures only

// ---- small helpers --------------------------------------------------
const prNum = (v) => {
  if (v == null || v === '') return null;
  const n = Number(String(v).replace(/[$,\s]/g, ''));
  return isFinite(n) ? n : null;
};
const prRound2 = (n) => Math.round(n * 100) / 100;
const prMoney = (n, { zero } = {}) => {
  if (n == null || !isFinite(n)) return '—';
  if (n === 0 && zero) return zero;
  return (n < 0 ? '−' : '') + '$' + Math.abs(n).toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
};
const prPct = (x, digits = 1) => { if (x == null || !isFinite(x)) return '—'; const s = (x * 100).toFixed(digits); return (Number(s) < 0 ? '−' + s.slice(1) : (Number(s) === 0 ? (0).toFixed(digits) : s)) + '%'; };
const prHours = (h) => {
  if (h == null || !isFinite(h)) return '—';
  const r = Math.round(h * 10) / 10;   // −0.04 reads 0.0, not −0.0
  return (r < 0 ? '−' : '') + Math.abs(r).toLocaleString('en-US', { minimumFractionDigits: 1, maximumFractionDigits: 1 });
};
const prNegHours = (h) => h != null && isFinite(h) && Math.round(h * 10) / 10 < 0;
const prInt = (n) => (n == null || !isFinite(n)) ? '—' : Math.round(n).toLocaleString('en-US');
const prDateFromISO = (iso) => { const [y, m, d] = String(iso).split('-').map(Number); return new Date(y, m - 1, d); };
const prShort = (d) => d.toLocaleDateString('en-US', { month: 'short', day: 'numeric' });
const prPeriodLabel = (p) => prShort(p.start) + ' – ' + prShort(p.end) + ', ' + p.end.getFullYear();
const prPeriodKey = (p) => isoDate(p.start);
const prAddDays = (d, n) => { const x = new Date(d); x.setDate(x.getDate() + n); return x; };

// Every period from the earliest date worth showing up to today, oldest
// first. The earliest date is the first day sales_daily knows about or the
// first period anyone saved, whichever is earlier.
const prPeriodsUpToToday = (anchorISO, earliestISO) => {
  const out = [];
  if (!anchorISO || !earliestISO) return out;
  const today = new Date();
  let p = getPayPeriod(anchorISO, prDateFromISO(earliestISO));
  let guard = 0;
  while (p.start <= today && guard < 400) {
    out.push(p);
    p = getPayPeriod(anchorISO, prAddDays(p.end, 1));
    guard += 1;
  }
  return out;
};

// Direct sales for one period from sales_daily rows (cents in, dollars
// out). by_channel carries gross and net per Square source; direct sources
// carry no haircut, so gross − net is exactly the merchant discount.
const prDirectFromRows = (rows) => {
  let gross = 0, net = 0, refund = 0, orders = 0, days = 0, oldest = null;
  rows.forEach(r => {
    days += 1;
    if (r.computed_at && (!oldest || r.computed_at < oldest)) oldest = r.computed_at;
    const bc = (r.by_channel && typeof r.by_channel === 'object') ? r.by_channel : {};
    Object.keys(bc).forEach(k => {
      if (PR_SQUARE_TPD[k]) return;
      const c = bc[k] || {};
      gross += Number(c.gross_cents) || 0;
      net += Number(c.net_cents) || 0;
      refund += Number(c.refund_cents) || 0;
      orders += Number(c.orders) || 0;
    });
  });
  return { gross: gross / 100, discount: Math.max(0, gross - net) / 100, refund: refund / 100, orders, days, computedAt: oldest };
};

// Parameters and inputs in force for a period: the row's own copy first,
// then the defaults from Settings, then the sheet's numbers.
const prParamsFor = (row, config) => {
  const out = Object.assign({}, PR_PARAM_DEFAULTS);
  PR_PARAM_KEYS.forEach(k => { if (config && prNum(config[k]) != null) out[k] = prNum(config[k]); });
  if (row && row.params) PR_PARAM_KEYS.forEach(k => { if (prNum(row.params[k]) != null) out[k] = prNum(row.params[k]); });
  // Categories: the period's own copy, else today's defaults, else the built-in list.
  const rowCats = row && row.params && Array.isArray(row.params.categories) && row.params.categories.length ? row.params.categories : null;
  const cfgCats = config && Array.isArray(config.categories) && config.categories.length ? config.categories : null;
  out.categories = prCloneCats(rowCats || cfgCats || PR_DEFAULT_CATEGORIES);
  const rowMs = row && row.params && Array.isArray(row.params.goal_milestones) && row.params.goal_milestones.length ? row.params.goal_milestones : null;
  const cfgMs = config && Array.isArray(config.goal_milestones) && config.goal_milestones.length ? config.goal_milestones : null;
  out.goal_milestones = prMilestones({ goal_milestones: rowMs || cfgMs || PR_DEFAULT_GOAL_MILESTONES });
  return out;
};
// Valid milestones, lowest gross first, one per gross, each with its hours
// and its goal (gross ÷ hours). Copies saved before v26.14 carry the goal
// instead of the hours; those read as gross ÷ goal hours.
const prMilestones = (p) => {
  const seen = {};
  return (Array.isArray(p && p.goal_milestones) ? p.goal_milestones : [])
    .map(m => {
      const gross = prNum(m && m.gross), typed = prNum(m && m.hours), goal = prNum(m && m.goal);
      const hours = typed > 0 ? typed : (gross > 0 && goal > 0 ? gross / goal : null);
      return { gross, hours, goal: gross > 0 && hours > 0 ? gross / hours : null };
    })
    .filter(m => m.gross > 0 && m.hours > 0)
    .sort((a, b) => a.gross - b.gross)
    .filter(m => (seen[m.gross] ? false : (seen[m.gross] = true)));
};
// The goal at a gross as formulas (v26.13, Ryan: "show the formula instead of
// examples"): the goal hours of the milestone line the gross sits on, then
// gross ÷ those hours, with the numbers put in. G is the two-week gross (a
// running period's two-week pace), the unit the milestones are in.
// Returns { G, lines, source } so each page can lay it out.
const prGoalFormula = (gross, p, days) => {
  const d = days || PR_PERIOD_DAYS;
  const ms = prMilestones(p);
  const G = prRound2(gross * PR_PERIOD_DAYS / d);
  const $s = prMoneyShort, hrs = (h) => prHours(h) + ' h';
  if (!ms.length) return { G, lines: ['Goal productivity = ' + prMoney(p.goal_productivity) + ', the flat goal under Defaults'], source: null };
  const last = ms[ms.length - 1], pace = prNum(p.goal_pace);
  if (G > last.gross && pace > 0) {
    const h = last.hours + (G - last.gross) / pace;
    return {
      G,
      lines: [
        'Goal hours = ' + prHours(last.hours) + ' + (gross − ' + $s(last.gross) + ') ÷ ' + $s(pace) + ' = ' + prHours(last.hours) + ' + (' + $s(G) + ' − ' + $s(last.gross) + ') ÷ ' + $s(pace) + ' = ' + hrs(h),
        'Goal productivity = gross ÷ goal hours = ' + $s(G) + ' ÷ ' + hrs(h) + ' = ' + prMoney(G / h),
      ],
      source: 'The ' + $s(last.gross) + ' milestone under Defaults is ' + hrs(last.hours) + '; past it, one more labor hour for every ' + $s(pace) + ' of gross, also under Defaults.',
    };
  }
  if (G <= ms[0].gross || ms.length === 1) {
    const m = ms[0];
    return {
      G,
      lines: [
        'Goal productivity = ' + $s(m.gross) + ' ÷ ' + hrs(m.hours) + ' = ' + prMoney(m.goal),
        'Goal hours = gross ÷ goal productivity = ' + $s(G) + ' ÷ ' + prMoney(m.goal) + ' = ' + hrs(G / m.goal),
      ],
      source: (G <= m.gross ? 'At or under the ' + $s(m.gross) + ' milestone' : 'With one milestone') + ' under Defaults, the goal stays at its productivity.',
    };
  }
  let b = ms.findIndex(m => m.gross >= G);
  const beyond = b === -1;                              // past the last with no pace: that line continues
  if (beyond) b = ms.length - 1;
  const A = ms[b - 1], B = ms[b];
  const pair = 'Milestones under Defaults: ' + hrs(A.hours) + ' at ' + $s(A.gross) + ' and ' + hrs(B.hours) + ' at ' + $s(B.gross);
  if (Math.abs(B.hours - A.hours) < 1e-9) return { G, lines: ['Goal hours = ' + hrs(A.hours), 'Goal productivity = gross ÷ goal hours = ' + $s(G) + ' ÷ ' + hrs(A.hours) + ' = ' + prMoney(G / A.hours)], source: pair + ', the same hours.' };
  const perHour = prRound2((B.gross - A.gross) / (B.hours - A.hours));   // gross per extra goal hour
  const h = A.hours + (G - A.gross) * (B.hours - A.hours) / (B.gross - A.gross);
  return {
    G,
    lines: [
      'Goal hours = ' + prHours(A.hours) + ' + (gross − ' + $s(A.gross) + ') ÷ ' + $s(perHour) + ' = ' + prHours(A.hours) + ' + (' + $s(G) + ' − ' + $s(A.gross) + ') ÷ ' + $s(perHour) + ' = ' + hrs(h),
      'Goal productivity = gross ÷ goal hours = ' + $s(G) + ' ÷ ' + hrs(h) + ' = ' + prMoney(G / h),
    ],
    source: pair + ', so one more hour for every ' + $s(perHour) + ' of gross' + (beyond ? ', continued past ' + $s(B.gross) + '.' : ' between them.'),
  };
};
// Goal labor hours for a period's gross (v26.11): the milestone curve at the
// period's two-week pace, scaled back to its days while it runs.
const prGoalHours = (gross, p, days) => {
  const d = days || PR_PERIOD_DAYS;
  const ms = prMilestones(p);
  if (!ms.length) return p.goal_productivity > 0 ? gross / p.goal_productivity : null;
  const G = gross * PR_PERIOD_DAYS / d;
  const last = ms[ms.length - 1], pace = prNum(p.goal_pace);
  let h;
  if (G <= ms[0].gross) h = G / ms[0].goal;                       // the floor: never under the lowest milestone's productivity
  else if (G > last.gross && pace > 0) h = last.hours + (G - last.gross) / pace;   // past the last: one hour per $pace
  else if (ms.length === 1) h = G / ms[0].goal;
  else {
    let b = ms.findIndex(m => m.gross >= G);
    if (b === -1) b = ms.length - 1;                              // past the last: keep its pace
    const A = ms[b - 1], B = ms[b];
    h = A.hours + (G - A.gross) * (B.hours - A.hours) / (B.gross - A.gross);
  }
  return h > 0 ? h * d / PR_PERIOD_DAYS : null;
};
// The manager's sales commission moves with net sales (v26.15, Ryan: "make
// 30k net as the base for 1%, every $1000 extra, add 0.1%, every $1000 less,
// minus 0.1%" … "and 2% as the cap"), in whole steps (v26.16, Ryan: "should
// be only 1 [decimal], like meet $1000 difference, then add/minus 0.1%", his
// $27,600 reading 0.7%): one commission_step per $1,000 bracket of net from
// commission_base_net — $30,000–$30,999 is 1.0%, $31,000–$31,999 1.1%,
// $27,000–$27,999 0.7% — never under 0% (Claude's call: under $21,000 earns
// none) or over commission_cap. N is the two-week net (a running period's
// pace), the unit the base is in. No base or no step: the flat rate.
const prCommission = (net, p, days) => {
  const d = days || PR_PERIOD_DAYS;
  const rate0 = prNum(p.manager_commission_rate) || 0;
  const at = prNum(p.commission_base_net), step = prNum(p.commission_step), cap = prNum(p.commission_cap);
  const N = prRound2(net * PR_PERIOD_DAYS / d);
  if (!(at > 0) || !step) return { N, steps: 0, raw: rate0, rate: rate0, sliding: false, capped: false, floored: false };
  const steps = Math.floor((N - at) / 1000 + 1e-9);
  const raw = Math.round((rate0 + step * steps) * 1e6) / 1e6;
  const capped = cap > 0 && raw > cap, floored = !capped && raw < 0;
  return { N, steps, raw, rate: capped ? cap : (floored ? 0 : raw), sliding: true, capped, floored };
};
// A commission rate as Ryan writes it: one decimal, two when it needs them
// (1.0%, 0.1%, 0.05%).
const prRatePct = (x) => (x == null || !isFinite(x)) ? '—' : (x * 100).toFixed(2).replace(/0$/, '') + '%';
const prInputsFor = (row, config) => {
  const out = { act_hours: null, training_hours: 0, crew_wages: null, crew_bonus: null, manager_food_bonus: 0, marketing: {} };
  PR_INPUT_DEFAULT_KEYS.forEach(k => { out[k] = (config && prNum(config[k]) != null) ? prNum(config[k]) : PR_INPUT_DEFAULTS[k]; });
  const inp = (row && row.inputs) || {};
  Object.keys(inp).forEach(k => {
    if (k === 'marketing' || k === 'meta') return;
    const n = prNum(inp[k]);
    if (n != null) out[k] = n;
  });
  PR_API_ADS.forEach(m => { out.marketing[m.key] = prNum((inp.marketing || {})[m.key]); });
  // Where a number came from and when (Square / API / typed), for the badges.
  out.meta = Object.assign({}, inp.meta || {});
  return out;
};

// The manager's productivity bonus spelled out (v26.06, fixed ratio v26.10)
// for the Labor cost note on a period and in the Simulator; the ratio itself
// follows (a click target on a period, plain in the Simulator).
const prBonusNote = (calc, goal) => (calc.preMgrProductivity == null || goal == null)
  ? '(pre-manager productivity − goal) × '
  : '($' + calc.preMgrProductivity.toFixed(2) + ' pre-manager − $' + prRound2(goal) + ' goal) × ';

// ---- the manager's unpaid time off (v26.33) --------------------------
// Ryan: "add unpaid time off period for me to choose the day range, that way
// the formula can update and reflect the correct amount I should be paying
// him" … "base should be calculated based on the percentage of the days
// worked in that 2 week period. and sales bonus should only use those worked
// days, same goes with the productivity bonus calculation", and his 50 hours
// in actual productivity × days worked ÷ 14. Real periods only. The days live
// in inputs.meta.manager_off { days: ['YYYY-MM-DD'…], at, crew_by_day:
// { day: the crew's clocked hours that day, from Square }, hours_at }.
const prMgrOffDays = (inputs, period) => {
  const mo = inputs && inputs.meta && inputs.meta.manager_off;
  const inPeriod = new Set(period.days.map(d => isoDate(d)));
  return (mo && Array.isArray(mo.days) ? mo.days : []).filter(d => inPeriod.has(d)).sort();
};
// The crew's clocked hours per day from a square-hours shift list: closed
// cards of the crew as Defaults has it, the same cards act_hours adds up.
const prCrewByDay = (shifts, config) => {
  const out = {};
  prCrewShifts(shifts, config).forEach(x => { if (!x.open && x.day) out[x.day] = prRound2((out[x.day] || 0) + (prNum(x.hours) || 0)); });
  return out;
};
// Direct sales on one sales_daily row, counted the way prDirectFromRows
// counts a period (gross, less the discount and the refunds).
const prDirectDay = (r) => {
  let g = 0, n = 0, rf = 0;
  const bc = (r.by_channel && typeof r.by_channel === 'object') ? r.by_channel : {};
  Object.keys(bc).forEach(k => {
    if (PR_SQUARE_TPD[k]) return;
    const c = bc[k] || {};
    g += Number(c.gross_cents) || 0; n += Number(c.net_cents) || 0; rf += Number(c.refund_cents) || 0;
  });
  return { gross: g / 100, net: (g - Math.max(0, g - n) - rf) / 100 };
};
// "1 day" / "3 days"; and days as ranges, "Oct 6 – Oct 8, Oct 12".
const prDaysWord = (n) => n + (n === 1 ? ' day' : ' days');
const prDayRanges = (days) => {
  const out = [];
  days.slice().sort().forEach(d => {
    const last = out[out.length - 1];
    if (last && dayDiff(prDateFromISO(d), prDateFromISO(last.to)) === 1) last.to = d;
    else out.push({ from: d, to: d });
  });
  return out.map(r => prShort(prDateFromISO(r.from)) + (r.to !== r.from ? ' – ' + prShort(prDateFromISO(r.to)) : '')).join(', ');
};
// What the manager's pay reads in a period he took days off: his days (the
// period's days so far, less the days off), the sales on them and the crew's
// effective hours on them. A platform with no daily figures, or a period
// whose hours were never read by day, falls back on his share of the days;
// `guessed` names what did, so the page can say so.
const prMgrDays = ({ period, periodDays, off, directByDay, imports, dayFigs, inputs }) => {
  const all = period.days.map(d => isoDate(d));
  const offSet = new Set(off);
  const counted = all.slice(0, periodDays);
  const worked = counted.filter(d => !offSet.has(d));
  const workedSet = new Set(worked);
  const share = counted.length ? worked.length / counted.length : 0;
  const guessed = [];
  let grossW = 0, netW = 0;
  worked.forEach(d => { const x = directByDay && directByDay[d]; if (x) { grossW += x.gross; netW += x.net; } });
  PR_TPD.forEach(c => {
    const im = imports && imports[c.key];
    if (!im) return;
    const f = im.figures || {};
    const byDay = f.by_day || (dayFigs && dayFigs[im.id]) || null;
    if (byDay) { worked.forEach(d => { const x = byDay[d]; if (x) { grossW += x.gross || 0; netW += prDayNet(x); } }); return; }
    const g = prNum(f.gross) || 0;
    grossW += g * share;
    netW += (g - Math.abs(prNum(f.commission) || 0) - Math.abs(prNum(f.discount) || 0) - Math.abs(prNum(f.refund) || 0)) * share;
    guessed.push(c.label);
  });
  let crewW = null;
  if (inputs.act_hours != null) {
    const mo = inputs.meta && inputs.meta.manager_off;
    const byDayH = mo && mo.crew_by_day && typeof mo.crew_by_day === 'object' ? mo.crew_by_day : null;
    const hoursOf = (list) => list.reduce((a, d) => a + (prNum(byDayH[d]) || 0), 0);
    const allH = byDayH ? hoursOf(counted) : 0;
    // The day-by-day split of the period's crew hours (exact when act_hours
    // came from the same Square read; a typed total is split the same way).
    const hShare = allH > 0 ? hoursOf(worked) / allH : share;
    if (!(allH > 0)) guessed.push('crew hours');
    const picks = prTrainPicks(inputs);
    const trainW = picks.length
      ? picks.reduce((a, x) => a + (workedSet.has(x.day) ? (prNum(x.hours) || 0) : 0), 0)
      : (inputs.training_hours || 0) * hShare;
    crewW = prRound2(inputs.act_hours * hShare - trainW);
  }
  const offDays = all.filter(d => offSet.has(d));
  return { offDays, off: offDays.length, worked: worked.length, counted: counted.length, grossW: prRound2(grossW), netW: prRound2(netW), crewW, guessed };
};

// ---- the sheet -------------------------------------------------------
// direct: { gross, discount } · imports: { doordash: figures, … } ·
// inputs / params as above. Commission, discount and refund are held as
// POSITIVE amounts and subtracted; the table shows them negative like the
// sheet does.
const prCompute = ({ direct, imports, inputs, params, periodDays, managerPerTwo, mgrDays }) => {
  const days = periodDays || 14;
  // The manager's unpaid days off (v26.33): prMgrDays' answer, on a real
  // period whose manager took any. The Simulator never passes one.
  const md = mgrDays && mgrDays.off > 0 ? mgrDays : null;
  const mgrShare = md ? (PR_PERIOD_DAYS - md.off) / PR_PERIOD_DAYS : 1;
  const ch = {};
  ch.direct = {
    gross: direct ? direct.gross : 0, commission: 0,
    discount: direct ? direct.discount : 0, refund: direct ? (direct.refund || 0) : 0,
    have: !!direct && direct.days > 0,
  };
  PR_TPD.forEach(c => {
    const f = imports && imports[c.key] ? (imports[c.key].figures || {}) : null;
    ch[c.key] = f ? {
      gross: prNum(f.gross) || 0, commission: Math.abs(prNum(f.commission) || 0),
      discount: Math.abs(prNum(f.discount) || 0), refund: Math.abs(prNum(f.refund) || 0),
      redemption: Math.abs(prNum(f.redemption) || 0), ads: Math.abs(prNum(f.ads) || 0), orders: prNum(f.orders), have: true,
    } : { gross: 0, commission: 0, discount: 0, refund: 0, redemption: 0, ads: 0, orders: null, have: false };
  });
  PR_CHANNELS.forEach(c => { const x = ch[c.key]; x.net = x.gross - x.commission - x.discount - x.refund; });
  const sum = (k) => PR_CHANNELS.reduce((a, c) => a + (ch[c.key][k] || 0), 0);
  const gross = sum('gross'), commission = sum('commission'), discount = sum('discount'), refund = sum('refund');
  const net = gross - commission - discount - refund;

  const p = params, i = inputs;
  const goalHours = prGoalHours(gross, p, days);
  const goalProductivity = goalHours > 0 ? gross / goalHours : null;   // the goal at this gross (v26.11)
  const haveHours = i.act_hours != null;
  // Total labor hours (v26.02, Ryan; "Clocked in" until v26.03 — hence
  // clockedHours — then "Actual" until v26.09) = crew + manager + training.
  // act_hours is the crew's clocked time from Square (trainees included, the
  // manager left out), so actual = act + the manager's hours
  // (params.manager_hours per two weeks, prorated while a period runs) and
  // crew hours = act − training. Effective hours = total − training = crew +
  // manager. Productivity (v26.05, Ryan): pre-manager productivity = gross ÷
  // crew hours (it rises as the manager works hours the crew would have),
  // actual productivity = gross ÷ (crew + manager) hours, and the manager's
  // productivity bonus = (pre-manager productivity − goal) × the Defaults
  // factor (35), negative below the goal. Goal labor hours are for reference.
  // v26.31: a real period passes managerPerTwo (its manager_fixed_hours)
  // instead of reading params.manager_hours, and its page shows act_hours as Total labor
  // hours and crewHours as Effective hours, so its actual productivity reads
  // gross ÷ (effective + the manager's 50). The arithmetic is the same either
  // way; the Simulator passes nothing and keeps params.manager_hours.
  // v26.33: days he took off unpaid don't count, so his hours are the 50
  // × the days he worked ÷ 14.
  const managerHours = (managerPerTwo != null ? managerPerTwo : (prNum(p.manager_hours) || 0)) * (md ? md.worked : days) / PR_PERIOD_DAYS;
  const clockedHours = haveHours ? i.act_hours + managerHours : null;
  const crewHours = haveHours ? i.act_hours - (i.training_hours || 0) : null;
  const effectiveHours = haveHours ? clockedHours - (i.training_hours || 0) : null;
  const preMgrProductivity = (haveHours && crewHours > 0) ? gross / crewHours : null;
  const actProductivity = (haveHours && effectiveHours > 0) ? gross / effectiveHours : null;

  // Crew wages come priced from the same Square timecards as the hours
  // (v25.03); the crew-lead bonus is the Scorecard's figure.
  const crewTotal = i.crew_wages != null ? i.crew_wages : null;
  const haveBonus = i.crew_bonus != null;
  const crewBonus = haveBonus ? i.crew_bonus : 0;
  const bonusFactor = prNum(p.manager_bonus_factor) != null ? prNum(p.manager_bonus_factor) : PR_PARAM_DEFAULTS.manager_bonus_factor;
  // With unpaid days off (v26.33) his pay reads only the days he worked:
  //   base = base × (14 − days off) ÷ 14;
  //   productivity = (gross ÷ the crew's effective hours on his days − the
  //     goal at that gross's two-week pace) × the ratio × (14 − days off) ÷ 14,
  //     the ratio being 50% of a full period's hours (see manager_bonus_factor);
  //   commission = the net sales of his days × the rate their two-week pace
  //     earns, the way a period in progress reads its days so far.
  // Without days off every line below is the arithmetic it always was.
  let managerProdBonus, mgrPre = preMgrProductivity, mgrGoal = goalProductivity;
  if (md) {
    const gh = md.worked > 0 ? prGoalHours(md.grossW, p, md.worked) : null;
    mgrGoal = gh > 0 ? md.grossW / gh : null;
    mgrPre = md.crewW > 0 ? md.grossW / md.crewW : null;
    managerProdBonus = md.worked === 0 ? 0 : ((mgrPre != null && mgrGoal != null) ? (mgrPre - mgrGoal) * bonusFactor * mgrShare : null);
  } else {
    managerProdBonus = (preMgrProductivity != null && goalProductivity != null) ? (preMgrProductivity - goalProductivity) * bonusFactor : null;
  }
  const mgrNet = md ? md.netW : net;
  const mgrCommission = prCommission(mgrNet, p, md ? md.worked : days);   // the manager's sliding rate (v26.15)
  const managerCommission = md && md.worked === 0 ? 0 : mgrNet * mgrCommission.rate;
  const managerFoodBonus = i.manager_food_bonus || 0;
  const managerBase = i.manager_base * mgrShare;
  const managerTotal = managerProdBonus != null ? managerBase + managerProdBonus + managerFoodBonus + managerCommission : null;

  const laborCost = (crewTotal != null && managerTotal != null) ? crewTotal + crewBonus + managerTotal : null;
  const tax = laborCost != null ? laborCost * p.tax_insurance_rate : null;
  const totalLabor = laborCost != null ? laborCost + tax : null;
  const laborPct = (totalLabor != null && net > 0) ? totalLabor / net : null;

  // The P&L categories: each line is % of net sales or a $ amount per
  // month / week / day, prorated to the period's days.
  const emptyCat = (key, name) => ({ key, name, items: [], total: 0, pct: null });
  const cats = (p.categories || []).map(cat => {
    const items = (cat.items || []).map(it => Object.assign({}, it, { amount: prProrate(it, net, days, ch.direct.net) }));
    const total = items.reduce((a, it) => a + it.amount, 0);
    return { key: cat.key, name: cat.name, items, total, pct: net > 0 ? total / net : null };
  });
  const foodPaperCat = cats.find(x => x.key === 'food_paper') || emptyCat('food_paper', 'Food & Paper');
  const marketingCat = cats.find(x => x.key === 'marketing') || emptyCat('marketing', 'Marketing');
  const foodPaper = foodPaperCat.total;
  const otherCats = cats.filter(x => x.key !== 'food_paper' && x.key !== 'marketing');
  const otherTotal = otherCats.reduce((a, x) => a + x.total, 0);
  const redemption = PR_TPD.reduce((a, c) => a + (ch[c.key].redemption || 0), 0);
  const ads = PR_TPD.reduce((a, c) => a + (ch[c.key].ads || 0), 0);
  const apiLines = PR_API_ADS.map(m => ({ key: m.key, label: m.label, value: i.marketing[m.key], have: i.marketing[m.key] != null }));
  const marketingTotal = apiLines.reduce((a, m) => a + (m.value || 0), 0) + redemption + ads + marketingCat.total;
  const marketingPct = net > 0 ? marketingTotal / net : null;
  const remaining = totalLabor != null ? net - totalLabor - foodPaper - marketingTotal - otherTotal : null;
  const itdaCat = cats.find(x => x.key === 'itda') || null;
  const ebitda = (remaining != null && itdaCat) ? remaining + itdaCat.total : null;
  const remainingPct = (remaining != null && net > 0) ? remaining / net : null;

  return {
    ch, gross, commission, discount, refund, net,
    goalHours, goalProductivity, haveHours, managerHours, clockedHours, crewHours, effectiveHours, preMgrProductivity, actProductivity,
    crewTotal, haveBonus, crewBonus, managerProdBonus, mgrCommission, managerCommission, managerFoodBonus, managerTotal,
    managerBase, mgrShare, mgrDays: md, mgrPre, mgrGoal, mgrNet,
    laborCost, tax, totalLabor, laborPct, foodPaper, foodPaperCat, marketingCat, cats, otherCats, otherTotal, days,
    redemption, ads, apiLines, marketingTotal, marketingPct, remaining, remainingPct, itdaCat, ebitda,
  };
};

// ---- CSV -------------------------------------------------------------
// RFC 4180: quoted fields, doubled quotes, CR/LF, a BOM. Returns rows of
// strings; blank lines dropped.
const prParseCsv = (text) => {
  const s = String(text || '').replace(/^﻿/, '');
  const rows = [];
  let row = [], field = '', q = false, i = 0;
  while (i < s.length) {
    const c = s[i];
    if (q) {
      if (c === '"') { if (s[i + 1] === '"') { field += '"'; i += 2; continue; } q = false; i += 1; continue; }
      field += c; i += 1; continue;
    }
    if (c === '"') { q = true; i += 1; continue; }
    if (c === ',') { row.push(field); field = ''; i += 1; continue; }
    if (c === '\r') { i += 1; continue; }
    if (c === '\n') { row.push(field); rows.push(row); row = []; field = ''; i += 1; continue; }
    field += c; i += 1;
  }
  if (field !== '' || row.length) { row.push(field); rows.push(row); }
  return rows.filter(r => r.some(x => String(x).trim() !== ''));
};
const prCsvObjects = (rows) => {
  const hdr = (rows[0] || []).map(h => String(h || '').trim());
  return { headers: hdr, records: rows.slice(1).map(r => { const o = {}; hdr.forEach((h, i) => { o[h] = r[i] == null ? '' : String(r[i]); }); return o; }) };
};
// Money in a platform export: "$1,234.56", "-12.30", "(12.30)", "" → number.
const prCsvMoney = (v) => {
  const s = String(v == null ? '' : v).trim();
  if (!s) return 0;
  const neg = /^\(.*\)$/.test(s) || /^-/.test(s.replace(/[$\s]/g, ''));
  const n = Number(s.replace(/[()$,\s]/g, '').replace(/^-/, ''));
  return isFinite(n) ? (neg ? -n : n) : 0;
};
const prCsvDate = (v) => {
  const s = String(v == null ? '' : v).trim();
  if (!s) return null;
  const m = s.match(/(\d{4})-(\d{2})-(\d{2})/);
  if (m) return m[1] + '-' + m[2] + '-' + m[3];
  const u = s.match(/(\d{1,2})\/(\d{1,2})\/(\d{2,4})/);
  if (u) { const y = u[3].length === 2 ? '20' + u[3] : u[3]; return y + '-' + u[1].padStart(2, '0') + '-' + u[2].padStart(2, '0'); }
  const d = new Date(s);
  return isNaN(d) ? null : isoDate(d);
};

// One reader per platform, written against the exports Ryan sent
// (Sep 6–19, 2026) and checked against the figures he had typed into his
// sheet from the same files. Each takes the parsed rows and returns
// { figures, rows, warnings } or { error }. figures (dollars, positive
// magnitudes): gross, commission, discount, refund, redemption, ads,
// orders, date_from, date_to, plus extras kept for later. Every row of the
// file is counted — a row dated outside the period only raises a warning,
// because a refund is dated by its ORIGINAL order and belongs to the file
// it arrives in, which is how the sheet counted it.
const prCol = (headers, names) => {
  const norm = (s) => String(s || '').trim().toLowerCase().replace(/\s+/g, ' ');
  const hs = headers.map(norm);
  for (const n of names) { const i = hs.indexOf(norm(n)); if (i >= 0) return i; }
  return -1;
};
const prNeed = (headers, spec) => {
  const idx = {}, missing = [];
  Object.keys(spec).forEach(k => { const i = prCol(headers, spec[k]); if (i < 0) missing.push(spec[k][0]); else idx[k] = i; });
  return { idx, missing };
};
const prDateSpan = (dates) => {
  const ds = dates.filter(Boolean).sort();
  return { date_from: ds[0] || null, date_to: ds[ds.length - 1] || null };
};
const prOutside = (dates, ctx) => (ctx && ctx.startISO) ? dates.filter(d => d && (d < ctx.startISO || d > ctx.endISO)).length : 0;
const prSpanWarning = (dates, ctx) => {
  const n = prOutside(dates, ctx);
  if (!n) return null;
  const span = prDateSpan(dates);
  return n + (n === 1 ? ' row is' : ' rows are') + ' dated outside this period (the file runs ' + span.date_from + ' to ' + span.date_to + '). They were counted anyway — export exactly the period so nothing is counted twice.';
};
// The same sums day by day (v26.33), kept with an import as figures.by_day
// so the manager's pay can read only the days he worked: gross and the three
// cuts, signed as the file has them, added up exactly like the totals.
const prDayAdd = (m, day, gross, commission, discount, refund) => {
  if (!day) return;
  const x = m[day] || (m[day] = { gross: 0, commission: 0, discount: 0, refund: 0 });
  x.gross += gross; x.commission += commission; x.discount += discount; x.refund += refund;
};
const prDayRound = (m) => {
  const out = {};
  Object.keys(m).sort().forEach(d => { const x = m[d]; out[d] = { gross: prRound2(x.gross), commission: prRound2(x.commission), discount: prRound2(x.discount), refund: prRound2(x.refund) }; });
  return out;
};
// A day's net: gross less the three cuts, each a cost whatever its sign.
const prDayNet = (x) => (x.gross || 0) - Math.abs(x.commission || 0) - Math.abs(x.discount || 0) - Math.abs(x.refund || 0);

const PR_PARSERS = {
  // DoorDash → Financials → Transactions export. One row per transaction;
  // "Order" rows carry the sale, an "Error Charge" row is a refund.
  // Sheet: gross = Σ Subtotal · commission = Σ Commission (the commission
  // tax and the payment processing fee are NOT in it — kept as extras) ·
  // discount = Σ customer discounts funded by you · refund = Σ Error
  // charges · ads = Σ Marketing fees.
  doordash: {
    parse: (rows, ctx) => {
      const { headers, records } = prCsvObjects(rows);
      const { idx, missing } = prNeed(headers, {
        subtotal: ['Subtotal'], commission: ['Commission'], discount: ['Customer discounts from marketing | (funded by you)'],
        error: ['Error charges'], mkt: ['Marketing fees | (including any applicable taxes)'],
        type: ['Transaction type'], date: ['Timestamp local date', 'Timestamp UTC date'],
      });
      if (missing.length) return { error: 'This doesn’t look like DoorDash’s FINANCIAL_DETAILED_TRANSACTIONS file from the Financial Report — missing column' + (missing.length > 1 ? 's' : '') + ': ' + missing.join(', ') + '.' };
      const opt = { commTax: prCol(headers, ['Commission tax']), proc: prCol(headers, ['Payment processing fee']), adj: prCol(headers, ['Adjustments']), channel: prCol(headers, ['Channel']) };
      let gross = 0, commission = 0, discount = 0, refund = 0, ads = 0, commTax = 0, proc = 0, adjustments = 0, orders = 0;
      const dates = [], channels = {}, byDay = {};
      rows.slice(1).forEach(r => {
        const sub = prCsvMoney(r[idx.subtotal]), com = prCsvMoney(r[idx.commission]), dis = prCsvMoney(r[idx.discount]), err = prCsvMoney(r[idx.error]);
        gross += sub;
        commission += com;
        discount += dis;
        refund += err;
        ads += prCsvMoney(r[idx.mkt]);
        if (opt.commTax >= 0) commTax += prCsvMoney(r[opt.commTax]);
        if (opt.proc >= 0) proc += prCsvMoney(r[opt.proc]);
        if (opt.adj >= 0) adjustments += prCsvMoney(r[opt.adj]);
        if (String(r[idx.type] || '').trim().toLowerCase() === 'order') orders += 1;
        if (opt.channel >= 0) { const ch = String(r[opt.channel] || '').trim(); if (ch) channels[ch] = (channels[ch] || 0) + 1; }
        const day = prCsvDate(r[idx.date]);
        dates.push(day);
        prDayAdd(byDay, day, sub, com, dis, err);
      });
      const warnings = [];
      const w = prSpanWarning(dates, ctx); if (w) warnings.push(w);
      if (adjustments) warnings.push('The file carries ' + prMoney(adjustments) + ' of “Adjustments” — not part of the sheet’s model, so not counted anywhere; kept with the import.');
      return {
        figures: Object.assign({
          gross: prRound2(gross), commission: prRound2(Math.abs(commission)), discount: prRound2(Math.abs(discount)),
          refund: prRound2(Math.abs(refund)), ads: prRound2(Math.abs(ads)), orders,
          extras: { commission_tax: prRound2(Math.abs(commTax)), processing_fee: prRound2(Math.abs(proc)), adjustments: prRound2(adjustments), channels },
          by_day: prDayRound(byDay),
        }, prDateSpan(dates)),
        rows: records.length, warnings,
      };
    },
  },

  // Uber Eats → Payments → order-level CSV. TWO header rows: the first is a
  // long description of each column, the second the short name — the short
  // names are what we read. "Ad Spend" rows have no order id and carry the
  // charge in Other payments.
  // Sheet: gross = Σ Sales (excl. tax) · commission = Σ Marketplace Fee
  // (its tax is NOT in it — kept as an extra; the delivery-network and
  // order-processing fees, zero in the sample, are added when present) ·
  // discount = Σ Offers on items + Delivery Offer Redemptions (incl. tax) ·
  // refund = Σ Chargeback Amount · redemption = Σ Offer Redemption Fee ·
  // ads = Σ Other payments described as Ad Spend / Ad credit + Marketing
  // Adjustment.
  ubereats: {
    parse: (rows, ctx) => {
      let headerRow = 0;
      if (rows.length > 1 && prCol(rows[1], ['Sales (excl. tax)']) >= 0) headerRow = 1;
      else if (prCol(rows[0], ['Sales (excl. tax)']) < 0) return { error: 'This doesn’t look like Uber Eats’ Payment details report — no “Sales (excl. tax)” column in the first two rows.' };
      const headers = rows[headerRow].map(h => String(h || '').trim());
      const { idx, missing } = prNeed(headers, {
        sales: ['Sales (excl. tax)'], fee: ['Marketplace Fee'], offers: ['Offers on items (incl. tax)'],
        chargeback: ['Chargeback Amount'], redemption: ['Offer Redemption Fee'], orderId: ['Order ID'], status: ['Order Status'], date: ['Order Date'],
      });
      if (missing.length) return { error: 'This doesn’t look like Uber Eats’ Payment details report — missing column' + (missing.length > 1 ? 's' : '') + ': ' + missing.join(', ') + '.' };
      const opt = {
        delivOffers: prCol(headers, ['Delivery Offer Redemptions (incl. tax)']), feeTax: prCol(headers, ['Tax on Marketplace Fee']),
        dnf: prCol(headers, ['Delivery Network Fee']), proc: prCol(headers, ['Order Processing Fee']),
        other: prCol(headers, ['Other payments']), otherDesc: prCol(headers, ['Other payments description']), mktAdj: prCol(headers, ['Marketing Adjustment']),
      };
      let gross = 0, commission = 0, discount = 0, refund = 0, redemption = 0, ads = 0, feeTax = 0, otherPayments = 0, orders = 0;
      const dates = [], statuses = {}, byDay = {};
      const data = rows.slice(headerRow + 1);
      data.forEach(r => {
        const sal = prCsvMoney(r[idx.sales]);
        let com = prCsvMoney(r[idx.fee]);
        if (opt.dnf >= 0) com += prCsvMoney(r[opt.dnf]);
        if (opt.proc >= 0) com += prCsvMoney(r[opt.proc]);
        let dis = prCsvMoney(r[idx.offers]);
        if (opt.delivOffers >= 0) dis += prCsvMoney(r[opt.delivOffers]);
        const chb = prCsvMoney(r[idx.chargeback]);
        gross += sal;
        commission += com;
        discount += dis;
        refund += chb;
        redemption += prCsvMoney(r[idx.redemption]);
        if (opt.feeTax >= 0) feeTax += prCsvMoney(r[opt.feeTax]);
        if (opt.mktAdj >= 0) ads += prCsvMoney(r[opt.mktAdj]);
        if (opt.other >= 0) {
          const v = prCsvMoney(r[opt.other]);
          const desc = opt.otherDesc >= 0 ? String(r[opt.otherDesc] || '') : '';
          if (/\bad\b|ad spend|ad credit|advertis/i.test(desc)) ads += v; else otherPayments += v;
        }
        const st = String(r[idx.status] || '').trim();
        if (String(r[idx.orderId] || '').trim() && st.toLowerCase() !== 'refund') orders += 1;
        if (st) statuses[st] = (statuses[st] || 0) + 1;
        const day = prCsvDate(r[idx.date]);
        dates.push(day);
        prDayAdd(byDay, day, sal, com, dis, chb);
      });
      const warnings = [];
      const w = prSpanWarning(dates, ctx); if (w) warnings.push(w);
      if (otherPayments) warnings.push('The file carries ' + prMoney(otherPayments) + ' of “Other payments” that aren’t ad spend — not counted anywhere; kept with the import.');
      return {
        figures: Object.assign({
          gross: prRound2(gross), commission: prRound2(Math.abs(commission)), discount: prRound2(Math.abs(discount)),
          refund: prRound2(Math.abs(refund)), redemption: prRound2(Math.abs(redemption)), ads: prRound2(Math.abs(ads)), orders,
          extras: { marketplace_fee_tax: prRound2(Math.abs(feeTax)), other_payments: prRound2(otherPayments), statuses },
          by_day: prDayRound(byDay),
        }, prDateSpan(dates)),
        rows: data.filter(r => r.some(x => String(x).trim() !== '')).length, warnings,
      };
    },
  },

  // GrubHub → Financials → transaction export. One row per prepaid order;
  // an "Adjustment of O-…" row reverses an order (negative subtotal, the
  // promotion given back).
  // Sheet: gross = Σ Subtotal over EVERY row, adjustments included (so a
  // reversed order nets out of gross rather than showing as a refund — the
  // sheet's way; refund is therefore always 0 here) · commission =
  // Σ Commission + Delivery Commission + GH+ Commission + Processing Fee ·
  // discount = Σ Targeted Promotion.
  grubhub: {
    parse: (rows, ctx) => {
      const { headers, records } = prCsvObjects(rows);
      const { idx, missing } = prNeed(headers, {
        subtotal: ['Subtotal'], commission: ['Commission'], delivComm: ['Delivery Commission'], proc: ['Processing Fee'],
        promo: ['Targeted Promotion'], type: ['Type'], date: ['Date'],
      });
      if (missing.length) return { error: 'This doesn’t look like Grubhub’s Transactions export — missing column' + (missing.length > 1 ? 's' : '') + ': ' + missing.join(', ') + '.' };
      const opt = { ghPlus: prCol(headers, ['GH+ Commission']), rewards: prCol(headers, ['Rewards']), desc: prCol(headers, ['Description']) };
      let gross = 0, commission = 0, discount = 0, orders = 0, adjRows = 0, adjTotal = 0;
      const dates = [], byDay = {};
      rows.slice(1).forEach(r => {
        const sub = prCsvMoney(r[idx.subtotal]);
        let com = prCsvMoney(r[idx.commission]) + prCsvMoney(r[idx.delivComm]) + prCsvMoney(r[idx.proc]);
        if (opt.ghPlus >= 0) com += prCsvMoney(r[opt.ghPlus]);
        const dis = prCsvMoney(r[idx.promo]);
        gross += sub;
        commission += com;
        discount += dis;
        const type = String(r[idx.type] || '').trim();
        if (/^adjustment/i.test(type)) { adjRows += 1; adjTotal += sub; } else if (type) orders += 1;
        const day = prCsvDate(r[idx.date]);
        dates.push(day);
        prDayAdd(byDay, day, sub, com, dis, 0);
      });
      const warnings = [];
      const w = prSpanWarning(dates, ctx); if (w) warnings.push(w);
      if (adjRows) warnings.push(adjRows + (adjRows === 1 ? ' adjustment row (' : ' adjustment rows (') + prMoney(adjTotal) + ') netted into gross sales, the way the sheet counts GrubHub.');
      return {
        figures: Object.assign({
          gross: prRound2(gross), commission: prRound2(Math.abs(commission)), discount: prRound2(Math.abs(discount)),
          refund: 0, redemption: 0, ads: 0, orders,
          extras: { adjustment_rows: adjRows, adjustment_total: prRound2(adjTotal) },
          by_day: prDayRound(byDay),
        }, prDateSpan(dates)),
        rows: records.length, warnings,
      };
    },
  },
};

// ------------------------------------------------------------------
// Root
// ------------------------------------------------------------------
// Access level for this page (v25.09): Settings → Users grants Read only,
// Simulator or Edit per admin (admins.page_access). Owners edit. Simulator
// (v26.00) = Read only plus the Simulator; Edit also gets Defaults and writes.
const prLevel = () => (typeof window.pageLevel === 'function' ? window.pageLevel('period-report') : 'edit');

// ---- Square hours → a period's inputs --------------------------------
// One square-hours `everyone` response turned into what a period stores
// (v25.01; pulled out in v26.31 so Sync again and the training picker write
// the same thing). Crew = everyone not left out under Defaults.
const prHoursFromSquare = (d, config) => {
  const excluded = prExcludedIds(config);
  const people = (d.people || []).map(x => ({ staff_id: x.staff_id || null, name: x.name || ('Unlinked ' + String(x.team_member_id || '').slice(-6)), role: x.role || 'Not in Crew', hours: x.hours, days: x.days, crew: x.staff_id ? !excluded.has(String(x.staff_id)) : true, cost: prRound2((x.cost_cents || 0) / 100), unpriced: x.unpriced_hours || 0 }));
  const crew = people.filter(x => x.crew), out = people.filter(x => !x.crew);
  return {
    people, out, total: d.total_hours,
    crewHours: prRound2(crew.reduce((a, x) => a + x.hours, 0)),
    crewCost: prRound2(crew.reduce((a, x) => a + x.cost, 0)),
    unpriced: prRound2(crew.reduce((a, x) => a + (x.unpriced || 0), 0)),
    outHours: prRound2(out.reduce((a, x) => a + x.hours, 0)),
  };
};
const prHoursInputs = (h, at) => ({
  act_hours: h.crewHours, crew_wages: h.crewCost,
  meta: { hours: { source: 'square', synced_at: at || new Date().toISOString(), total: h.total, manager: h.outHours, excluded: h.out.map(x => x.name), crew_cost: h.crewCost, unpriced: h.unpriced, people: h.people } },
});

// ---- training shifts (v26.31) ----------------------------------------
// Ryan: "For training hours, open a full screen popup and show the clocked
// in shifts for the whole week (I can switch between the 1st and 2nd week),
// and let me click the shifts that are training shifts". The picks are kept
// in inputs.meta.training { source: 'shifts', at, shifts: [{ id, staff_id,
// name, day, start_at, end_at, hours }] }, id being the Square timecard's,
// and inputs.training_hours is their sum. A figure that was typed (every
// period before this, or the picker's fallback when the shifts can't be
// listed) has source 'typed', or no meta.training at all.
const PR_STORE_TZ = 'America/Chicago';   // the days square-hours buckets by
const prCrewShifts = (shifts, config) => {
  const excluded = prExcludedIds(config);
  return (shifts || []).filter(x => x && x.id && (x.staff_id ? !excluded.has(String(x.staff_id)) : true));
};
const prTrainShift = (x) => ({ id: x.id, staff_id: x.staff_id || null, name: x.name || null, day: x.day, start_at: x.start_at, end_at: x.end_at, hours: x.hours });
const prTrainInputs = (list, at) => ({
  training_hours: prRound2(list.reduce((a, x) => a + (prNum(x.hours) || 0), 0)),
  meta: { training: { source: 'shifts', at: at || new Date().toISOString(), shifts: list } },
});
const prTrainPicks = (inputs) => {
  const t = inputs && inputs.meta && inputs.meta.training;
  return t && t.source === 'shifts' && Array.isArray(t.shifts) ? t.shifts : [];
};
// Stored picks against a fresh Square read: a pick whose timecard is still
// there takes the card's current times and hours; one whose card is gone
// (deleted in Square, reopened, or its owner now left out of the crew) is
// dropped, because its hours are no longer in the total either.
const prTrainReconcile = (picks, crewShifts) => {
  const byId = new Map(crewShifts.map(x => [x.id, x]));
  const kept = [];
  let dropped = 0, changed = 0;
  (picks || []).forEach(pk => {
    const x = byId.get(pk.id);
    if (!x || x.open) { dropped += 1; return; }
    if (x.hours !== pk.hours || x.start_at !== pk.start_at || x.end_at !== pk.end_at || x.day !== pk.day) changed += 1;
    kept.push(prTrainShift(x));
  });
  return { kept, dropped, changed };
};
// A clock time the way Square's schedule writes it: "8:02 am", ":00" dropped.
const prClock = (iso) => {
  const d = new Date(iso);
  if (isNaN(d)) return '';
  return d.toLocaleTimeString('en-US', { timeZone: PR_STORE_TZ, hour: 'numeric', minute: '2-digit' }).replace(/\s/g, ' ').replace(':00', '').toLowerCase();
};
// "5:07 – 9:44 pm", "11:30 am – 5 pm": the first am/pm goes when both match.
const prClockRange = (a, b) => {
  const x = prClock(a), y = b ? prClock(b) : '';
  if (!y) return x;
  return (x.slice(-2) === y.slice(-2) ? x.slice(0, -3) : x) + ' – ' + y;
};

const PeriodReport = ({ payAnchor }) => {
  const level = prLevel();
  const canEdit = level === 'edit';
  const canSimulate = level === 'edit' || level === 'simulate';
  const [sales, setSales] = useState(null);        // sales_daily rows
  const [reports, setReports] = useState({});      // period_start → row
  const [imports, setImports] = useState({});      // period_start|channel → row
  const [config, setConfig] = useState(null);      // restaurants.period_report_config
  const [loadErr, setLoadErr] = useState('');
  const [openKey, setOpenKey] = useState(null);   // period_start of the open period
  const [defaultsOpen, setDefaultsOpen] = useState(false);
  const [simOpen, setSimOpen] = useState(false);   // the Simulator (v26.00)
  const [toast, setToast] = useState('');
  const chainRef = useRef({});

  useEffect(() => {
    let cancelled = false;
    const load = async () => {
      try {
        const [s, r, im, c] = await Promise.all([
          window.supa.from('sales_daily').select('the_date, gross_cents, net_cents, discount_cents, refund_cents, order_count, by_channel, computed_at').eq('restaurant_id', window.RESTAURANT_ID).order('the_date', { ascending: true }),
          window.supa.from('period_reports').select('*').eq('restaurant_id', window.RESTAURANT_ID),
          window.supa.from('period_channel_imports').select('id, period_start, channel, figures, file_name, file_rows, uploaded_by, uploaded_at').eq('restaurant_id', window.RESTAURANT_ID),
          window.supa.from('restaurants').select('period_report_config').eq('id', window.RESTAURANT_ID).maybeSingle(),
        ]);
        if (cancelled) return;
        const err = s.error || r.error || im.error || c.error;
        if (err) { setLoadErr(err.message || String(err)); }
        setSales(s.data || []);
        const rm = {}; (r.data || []).forEach(x => { rm[x.period_start] = x; });
        setReports(rm);
        const imm = {}; (im.data || []).forEach(x => { imm[x.period_start + '|' + x.channel] = x; });
        setImports(imm);
        setConfig((c.data && c.data.period_report_config) || {});
      } catch (e) {
        if (!cancelled) setLoadErr(e.message || String(e));
      }
    };
    load();
    return () => { cancelled = true; };
  }, []);

  const anchor = payAnchor || null;
  const periods = useMemo(() => {
    if (!anchor || !sales) return [];
    const dates = [];
    if (sales.length) dates.push(sales[0].the_date);
    Object.keys(reports).forEach(k => dates.push(k));
    Object.keys(imports).forEach(k => dates.push(k.split('|')[0]));
    if (!dates.length) dates.push(isoDate(new Date()));
    dates.sort();
    // Periods before Defaults' "first period" are not shown (the data stays).
    const first = config && /^\d{4}-\d{2}-\d{2}$/.test(String(config.first_period || '')) ? String(config.first_period) : null;
    const from = first && first > dates[0] ? first : dates[0];
    return prPeriodsUpToToday(anchor, from).filter(p => !first || isoDate(p.end) >= first).reverse();   // newest first
  }, [anchor, sales, reports, imports]);

  // sales_daily rows bucketed by period start.
  const directByPeriod = useMemo(() => {
    const m = {};
    if (!anchor || !sales) return m;
    const buckets = {};
    sales.forEach(r => {
      const k = prPeriodKey(getPayPeriod(anchor, prDateFromISO(r.the_date)));
      (buckets[k] = buckets[k] || []).push(r);
    });
    Object.keys(buckets).forEach(k => { m[k] = prDirectFromRows(buckets[k]); });
    return m;
  }, [anchor, sales]);
  // The same rows day by day (v26.33), for a manager's unpaid days off.
  const directDaysByPeriod = useMemo(() => {
    const m = {};
    if (!anchor || !sales) return m;
    sales.forEach(r => {
      const k = prPeriodKey(getPayPeriod(anchor, prDateFromISO(r.the_date)));
      (m[k] = m[k] || {})[r.the_date] = prDirectDay(r);
    });
    return m;
  }, [anchor, sales]);

  // Platform figures by day (v26.33). Imports saved since v26.33 keep them
  // (figures.by_day); an older one is read back from its stored CSV, only
  // for a period whose manager took days off. id → by_day, or null when the
  // file wasn't kept (bigger than PR_RAW_MAX) or can't be read.
  const [dayFigs, setDayFigs] = useState({});
  const dayFigsAsked = useRef({});   // import id → asked once (an import replaced later has a new id)
  useEffect(() => {
    const want = [];
    Object.keys(reports).forEach(k => {
      const mo = reports[k] && reports[k].inputs && reports[k].inputs.meta && reports[k].inputs.meta.manager_off;
      if (!mo || !Array.isArray(mo.days) || !mo.days.length) return;
      PR_TPD.forEach(c => {
        const im = imports[k + '|' + c.key];
        if (im && !(im.figures && im.figures.by_day) && !dayFigsAsked.current[im.id]) want.push(im);
      });
    });
    if (!want.length) return;
    want.forEach(im => { dayFigsAsked.current[im.id] = true; });
    (async () => {
      const next = {};
      want.forEach(im => { next[im.id] = null; });
      try {
        const { data } = await window.supa.from('period_channel_imports').select('id, channel, raw_csv').in('id', want.map(im => im.id));
        (data || []).forEach(row => {
          if (!row.raw_csv || !PR_PARSERS[row.channel]) return;
          try {
            const out = PR_PARSERS[row.channel].parse(prParseCsv(row.raw_csv), {});
            if (out && out.figures && out.figures.by_day) next[row.id] = out.figures.by_day;
          } catch (e) { /* stays null: his share of the days stands in */ }
        });
      } catch (e) { /* the same */ }
      setDayFigs(prev => Object.assign({}, prev, next));
    })();
  }, [reports, imports]);

  const importsFor = (key) => {
    const out = {};
    PR_TPD.forEach(c => { const row = imports[key + '|' + c.key]; if (row) out[c.key] = row; });
    return out;
  };
  const rowsWithCalc = useMemo(() => periods.map(p => {
    const key = prPeriodKey(p);
    const row = reports[key] || null;
    const inputs = prInputsFor(row, config);
    const params = prParamsFor(row, config);
    const direct = directByPeriod[key] || null;
    const im = importsFor(key);
    const today = new Date();
    const total = p.days.length;
    const running = p.end >= new Date(today.getFullYear(), today.getMonth(), today.getDate());
    const periodDays = running ? Math.max(1, Math.min(total, dayDiff(today, p.start) + 1)) : total;
    const off = prMgrOffDays(inputs, p);
    const mgrDays = off.length ? prMgrDays({ period: p, periodDays, off, directByDay: directDaysByPeriod[key] || {}, imports: im, dayFigs, inputs }) : null;
    return { period: p, key, row, inputs, params, direct, imports: im, periodDays, calc: prCompute({ direct, imports: im, inputs, params, periodDays, managerPerTwo: prNum(params.manager_fixed_hours) != null ? prNum(params.manager_fixed_hours) : PR_PARAM_DEFAULTS.manager_fixed_hours, mgrDays }) };
  }), [periods, reports, imports, config, directByPeriod, directDaysByPeriod, dayFigs]);

  // ---- writes -----------------------------------------------------
  const persistReport = (next) => {
    const key = next.period_start;
    const payload = {
      restaurant_id: window.RESTAURANT_ID, period_start: next.period_start, period_end: next.period_end,
      inputs: next.inputs, params: next.params, note: next.note || '', updated_at: new Date().toISOString(),
    };
    const run = async () => {
      const { data, error } = await window.supa.from('period_reports').upsert(payload, { onConflict: 'restaurant_id,period_start' }).select().single();
      if (error) { setToast('Couldn’t save: ' + error.message); return; }
      setReports(prev => prev[key] ? Object.assign({}, prev, { [key]: Object.assign({}, prev[key], { id: data.id }) }) : prev);
    };
    chainRef.current[key] = (chainRef.current[key] || Promise.resolve()).then(run, run);
  };
  // patch: { inputs?: {…}, params?: {…}, note? } — marketing merges one level deeper.
  const saveReport = (p, patch) => {
    const key = prPeriodKey(p);
    setReports(prev => {
      const cur = prev[key];
      // First save copies the defaults in force, so later default edits leave this period alone.
      const base = cur ? cur : {
        period_start: key, period_end: isoDate(p.end), note: '',
        inputs: (() => { const d = {}; PR_INPUT_DEFAULT_KEYS.forEach(k => { d[k] = prInputsFor(null, config)[k]; }); return d; })(),
        params: prParamsFor(null, config),
      };
      const inputs = Object.assign({}, base.inputs || {}, patch.inputs || {});
      if (patch.inputs && patch.inputs.marketing) inputs.marketing = Object.assign({}, (base.inputs || {}).marketing || {}, patch.inputs.marketing);
      if (patch.inputs && patch.inputs.meta) inputs.meta = Object.assign({}, (base.inputs || {}).meta || {}, patch.inputs.meta);
      const next = Object.assign({}, base, { inputs, params: Object.assign({}, base.params || {}, patch.params || {}) });
      if (patch.note != null) next.note = patch.note;
      persistReport(next);
      return Object.assign({}, prev, { [key]: next });
    });
  };

  const saveImport = async (p, channel, parsed, file) => {
    const key = prPeriodKey(p);
    const payload = {
      restaurant_id: window.RESTAURANT_ID, period_start: key, channel,
      figures: parsed.figures, file_name: file.name || '', file_rows: parsed.rows || 0,
      raw_csv: (file.text && file.text.length <= PR_RAW_MAX) ? file.text : null,
      uploaded_by: window.currentAdminEmail || null, uploaded_at: new Date().toISOString(),
    };
    const { data, error } = await window.supa.from('period_channel_imports').upsert(payload, { onConflict: 'restaurant_id,period_start,channel' })
      .select('id, period_start, channel, figures, file_name, file_rows, uploaded_by, uploaded_at').single();
    if (error) { setToast('Couldn’t save the import: ' + error.message); return false; }
    setImports(prev => Object.assign({}, prev, { [key + '|' + channel]: data }));
    return true;
  };
  const deleteImport = async (p, channel) => {
    const key = prPeriodKey(p);
    const row = imports[key + '|' + channel];
    if (!row) return;
    if (!window.confirm('Remove the ' + (PR_TPD.find(c => c.key === channel) || {}).label + ' import for this period? The figures go back to blank until a CSV is uploaded again.')) return;
    const { error } = await window.supa.from('period_channel_imports').delete().eq('id', row.id);
    if (error) { setToast('Couldn’t remove the import: ' + error.message); return; }
    setImports(prev => { const n = Object.assign({}, prev); delete n[key + '|' + channel]; return n; });
  };
  // ---- Square syncs (v25.01) ----------------------------------------
  const [syncing, setSyncing] = useState({});   // 'sales|<key>' / 'hours|<key>' / 'ads|<key>' → true
  const setBusy = (k, on) => setSyncing(prev => { const n = Object.assign({}, prev); if (on) n[k] = true; else delete n[k]; return n; });

  // Recompute every day of the period from Square (sales-rollup range mode),
  // then reload those rows so gross / discount / refund follow.
  const syncSales = async (p) => {
    const key = prPeriodKey(p), s = isoDate(p.start), e = isoDate(p.end);
    setBusy('sales|' + key, true);
    try {
      const res = await window.supa.functions.invoke('sales-rollup', { body: { start_date: s, end_date: e } });
      if (res.error || !res.data || res.data.ok === false) throw new Error((res.data && res.data.error) || (res.error && res.error.message) || 'sync failed');
      const { data, error } = await window.supa.from('sales_daily').select('the_date, gross_cents, net_cents, discount_cents, refund_cents, order_count, by_channel, computed_at')
        .eq('restaurant_id', window.RESTAURANT_ID).gte('the_date', s).lte('the_date', e).order('the_date', { ascending: true });
      if (error) throw error;
      setSales(prev => (prev || []).filter(r => r.the_date < s || r.the_date > e).concat(data || []).sort((a, b) => a.the_date < b.the_date ? -1 : 1));
      const refunds = (res.data.days || []).reduce((a, d) => a + (d.refunds || 0), 0);
      setToast('Square synced — ' + (res.data.days || []).length + ' days recomputed' + (refunds ? ', ' + prMoney(refunds) + ' refunded' : ', no refunds') + '.');
    } catch (err) {
      setToast('Couldn’t sync from Square: ' + (err.message || String(err)));
    } finally {
      setBusy('sales|' + key, false);
    }
  };

  // Clocked hours for everyone in the period (square-hours, everyone mode);
  // the crew's total becomes act_hours, their share of total labor hours.
  const syncHours = async (p) => {
    const key = prPeriodKey(p), s = isoDate(p.start), e = isoDate(p.end);
    setBusy('hours|' + key, true);
    try {
      // Picked training shifts are checked against the same read (v26.31),
      // and a manager's days off take the crew's hours by day from it
      // (v26.33), so the shift list is only asked for when either needs it.
      const curInputs = (reports[key] || {}).inputs;
      const picks = prTrainPicks(curInputs);
      const offDays = prMgrOffDays(curInputs, p);
      const res = await window.supa.functions.invoke('square-hours', { body: Object.assign({ start_date: s, end_date: e, everyone: true }, (picks.length || offDays.length) ? { shifts: true } : {}) });
      if (res.error || !res.data || res.data.error) throw new Error((res.data && res.data.error) || (res.error && res.error.message) || 'sync failed');
      const d = res.data;
      // Crew = everyone not excluded under Defaults (falls back to the role rule).
      const h = prHoursFromSquare(d, config);
      const inputs = prHoursInputs(h);
      let trainNote = '';
      if (picks.length && Array.isArray(d.shifts)) {
        const rec = prTrainReconcile(picks, prCrewShifts(d.shifts, config));
        if (rec.dropped || rec.changed) {
          const t = prTrainInputs(rec.kept);
          inputs.training_hours = t.training_hours;
          inputs.meta.training = t.meta.training;
          trainNote = ' · training now ' + prHours(t.training_hours) + ' h' + (rec.dropped ? ' (' + rec.dropped + (rec.dropped === 1 ? ' picked shift is' : ' picked shifts are') + ' no longer in Square)' : '');
        }
      }
      if (offDays.length && Array.isArray(d.shifts)) {
        const curOff = (curInputs && curInputs.meta && curInputs.meta.manager_off) || {};
        inputs.meta.manager_off = Object.assign({}, curOff, { crew_by_day: prCrewByDay(d.shifts, config), hours_at: new Date().toISOString() });
      }
      saveReport(p, { inputs });
      setToast('Square synced — ' + prHours(h.crewHours) + ' crew hours, ' + prMoney(h.crewCost) + ' in wages' + (h.out.length ? ' (' + h.out.map(x => x.name.split(' ')[0]).join(', ') + ' left out)' : '') + (h.unpriced ? ' · ' + prHours(h.unpriced) + ' h had no rate' : '') + trainNote + '.');
    } catch (err) {
      setToast('Couldn’t fetch hours from Square: ' + (err.message || String(err)));
    } finally {
      setBusy('hours|' + key, false);
    }
  };

  // The manager's unpaid days off (v26.33). The days save at once; then the
  // period's shifts are read from Square for the crew's hours on each day,
  // which his productivity bonus needs. A second save that lands while the
  // first read is out wins: only the latest read is kept.
  const offReqRef = useRef({});
  const saveManagerOff = async (p, days) => {
    const key = prPeriodKey(p);
    const at = new Date().toISOString();
    offReqRef.current[key] = at;
    const curOff = (((reports[key] || {}).inputs || {}).meta || {}).manager_off || {};
    if (!days.length) {
      saveReport(p, { inputs: { meta: { manager_off: null } } });
      setToast('No unpaid time off — the manager’s pay counts all 14 days again.');
      return;
    }
    saveReport(p, { inputs: { meta: { manager_off: { days, at, crew_by_day: curOff.crew_by_day || null, hours_at: curOff.hours_at || null } } } });
    try {
      const res = await window.supa.functions.invoke('square-hours', { body: { start_date: isoDate(p.start), end_date: isoDate(p.end), everyone: true, shifts: true } });
      if (res.error || !res.data || res.data.error || !Array.isArray(res.data.shifts)) throw new Error((res.data && res.data.error) || (res.error && res.error.message) || 'no shift list from Square');
      if (offReqRef.current[key] !== at) return;
      saveReport(p, { inputs: { meta: { manager_off: { days, at, crew_by_day: prCrewByDay(res.data.shifts, config), hours_at: new Date().toISOString() } } } });
      setToast(prDaysWord(days.length) + ' off saved — his pay now reads the ' + prDaysWord(PR_PERIOD_DAYS - days.length) + ' he worked.');
    } catch (err) {
      if (offReqRef.current[key] !== at) return;
      setToast('Days off saved, but each day’s crew hours couldn’t be read from Square (' + (err.message || String(err)) + '). His productivity bonus splits the hours by his share of the days until Sync again on Labor & productivity.');
    }
  };

  // The crew-lead bonus, scored exactly as the Crew Lead Scorecard scores it
  // (window.scLoadPeriod, shared with that page) — fetched on demand because
  // review-rating points are entered at the end of the period.
  const syncBonus = async (p) => {
    const key = prPeriodKey(p);
    setBusy('bonus|' + key, true);
    try {
      if (typeof window.scLoadPeriod !== 'function') throw new Error('the Crew Lead Scorecard code isn’t loaded');
      const r = await window.scLoadPeriod(p);
      const leads = (r.leads || []).map(l => ({ name: l.name, hours: prRound2(l.hours || 0), final_pct: Math.round((l.final_pct || 0) * 10) / 10, rate: l.rate, bonus: prRound2(l.bonus || 0) }));
      const total = prRound2(r.total_bonus || 0);
      saveReport(p, { inputs: { crew_bonus: total, meta: { bonus: { source: 'scorecard', synced_at: new Date().toISOString(), leads } } } });
      setToast('Scorecard fetched — ' + prMoney(total) + ' of bonus across ' + leads.length + (leads.length === 1 ? ' lead' : ' leads') + '.');
    } catch (err) {
      setToast('Couldn’t fetch the bonus: ' + (err.message || String(err)));
    } finally {
      setBusy('bonus|' + key, false);
    }
  };

  // Google / Meta spend for the period (ads-spend). A platform that isn't
  // connected comes back configured:false with the secrets it still needs.
  const syncAds = async (p) => {
    const key = prPeriodKey(p), s = isoDate(p.start), e = isoDate(p.end);
    setBusy('ads|' + key, true);
    try {
      const res = await window.supa.functions.invoke('ads-spend', { body: { start_date: s, end_date: e } });
      if (res.error || !res.data || res.data.ok === false) throw new Error((res.data && res.data.error) || (res.error && res.error.message) || 'fetch failed');
      const d = res.data, marketing = {}, meta = {};
      const notes = [];
      ['google', 'meta'].forEach(k => {
        const r = d[k] || {};
        if (r.configured && r.ok) { marketing[k] = prRound2(r.spend || 0); meta[k] = { source: 'api', synced_at: new Date().toISOString(), days: r.days || null }; notes.push((k === 'google' ? 'Google' : 'Meta') + ' ' + prMoney(r.spend || 0)); }
        else if (r.configured) notes.push((k === 'google' ? 'Google' : 'Meta') + ' failed: ' + (r.error || 'unknown error'));
        else notes.push((k === 'google' ? 'Google' : 'Meta') + ' not connected');
      });
      if (Object.keys(marketing).length) saveReport(p, { inputs: { marketing, meta: { ads: meta } } });
      setToast('Ad spend — ' + notes.join(' · ') + '.');
    } catch (err) {
      setToast('Couldn’t fetch ad spend: ' + (err.message || String(err)));
    } finally {
      setBusy('ads|' + key, false);
    }
  };

  const saveConfig = async (next) => {
    setConfig(next);
    const { error } = await window.supa.from('restaurants').update({ period_report_config: next }).eq('id', window.RESTAURANT_ID);
    if (error) setToast('Couldn’t save the defaults: ' + error.message);
    else setToast('Defaults saved — they apply to periods that haven’t been saved yet.');
  };

  const open = openKey ? rowsWithCalc.find(r => r.key === openKey) : null;
  const openIdx = open ? rowsWithCalc.indexOf(open) : -1;

  return (
    <div className="portal-page pr-page">
      <style>{`
.pr-page { max-width: 1160px; }
.pr-stat-row { display: grid; grid-template-columns: repeat(5, minmax(0, 1fr)); gap: 12px; margin-bottom: 16px; }
.pr-sec { margin-bottom: 16px; }
.pr-sec .portal-card-header { display: flex; align-items: baseline; justify-content: space-between; gap: 12px; }
.pr-sec-sub { font-size: 12px; color: var(--fg-3); font-weight: 400; }
.pr-lines { width: 100%; border-collapse: collapse; font-size: 13.5px; }
.pr-lines td { padding: 9px 14px; border-bottom: 1px solid var(--border-2); vertical-align: middle; }
.pr-lines tr:last-child td { border-bottom: none; }
.pr-lines td.pr-l { color: var(--fg-1); width: 40%; padding-left: 54px; }
.pr-lines td.pr-v { text-align: right; font-variant-numeric: tabular-nums; white-space: nowrap; width: 160px; }
.pr-lines td.pr-n { color: var(--fg-3); font-size: 12px; }
.pr-lines tr.pr-total td { font-weight: 600; border-top: 1px solid var(--border-1); background: #FAFAFC; }
.pr-lines tr.pr-sub td.pr-l { padding-left: 72px; color: var(--fg-2); }
.pr-lines td.pr-neg, .pr-neg { color: #B42318; }
.pr-lines td.pr-muted { color: var(--fg-3); }
.pr-in { width: 128px; text-align: right; font-variant-numeric: tabular-nums; padding: 5px 9px; height: 30px; }
.pr-in.is-hours { width: 96px; }
.pr-unit { display: inline-block; width: 34px; text-align: left; color: var(--fg-3); font-size: 12px; margin-left: 6px; }
.pr-sales { width: 100%; border-collapse: collapse; font-size: 13.5px; }
.pr-sales th { text-align: right; font-weight: 500; font-size: 11px; letter-spacing: 0.07em; text-transform: uppercase; color: var(--fg-3); padding: 10px 14px; border-bottom: 1px solid var(--border-2); background: #FAFAFC; white-space: nowrap; }
.pr-sales th:first-child { text-align: left; }
.pr-sales th { vertical-align: bottom; }
.pr-sales td:first-child, .pr-sales th:first-child { padding-left: 54px; }
.pr-title { display: inline-flex; align-items: center; gap: 10px; }
.pr-title-ic { width: 26px; height: 26px; border-radius: 8px; background: var(--bg-sunken); color: var(--fg-2); display: inline-flex; align-items: center; justify-content: center; flex-shrink: 0; }
.pr-colhead { display: grid; grid-template-rows: 18px 16px 16px 30px; row-gap: 2px; justify-items: end; align-items: center; }
.pr-colname { display: inline-flex; align-items: center; }
.pr-colhead .pr-file { font-size: 11px; color: var(--fg-3); font-weight: 400; text-transform: none; letter-spacing: 0; max-width: 170px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; line-height: 16px; }
.pr-colacts { display: inline-flex; align-items: center; gap: 4px; height: 30px; }
.pr-sales td { padding: 9px 14px; border-bottom: 1px solid var(--border-2); text-align: right; font-variant-numeric: tabular-nums; white-space: nowrap; }
.pr-sales td:first-child { text-align: left; }
.pr-sales tr:last-child td { border-bottom: none; }
.pr-sales tr.pr-total td { font-weight: 600; border-top: 1px solid var(--border-1); background: #FAFAFC; }
.pr-sales td.pr-tot { font-weight: 600; }
.pr-src { display: inline-flex; align-items: center; gap: 4px; font-size: 10.5px; letter-spacing: 0.04em; text-transform: uppercase; color: var(--fg-3); font-weight: 500; margin-left: 6px; }
.pr-chip { display: inline-flex; align-items: center; gap: 4px; padding: 2px 7px; border-radius: 999px; font-size: 11px; font-weight: 500; border: 1px solid var(--border-1); color: var(--fg-2); background: var(--bg-surface); white-space: nowrap; }
.pr-chip.is-on { background: #181818; color: #fff; border-color: #181818; }
.pr-chip.is-warn { background: #FFF6E5; color: #8A5A00; border-color: #F5D9A6; }
.pr-chip.is-live { background: #E8F1FF; color: #1B4F9C; border-color: #C6DBF7; }
.pr-list tbody tr { cursor: pointer; }
.pr-list td.pr-num { text-align: right; font-variant-numeric: tabular-nums; white-space: nowrap; }
.pr-list th.pr-num { text-align: right; }
.pr-list .pr-period { font-weight: 500; white-space: nowrap; }
.pr-list .pr-chips { display: flex; gap: 4px; flex-wrap: wrap; }
.pr-empty { padding: 30px; text-align: center; color: var(--fg-3); font-size: 12.5px; }
.pr-help { font-size: 12px; color: var(--fg-3); line-height: 1.5; margin-top: 12px; }
.pr-preview { border: 1px solid var(--border-2); border-radius: 8px; overflow: hidden; }
.pr-preview table { width: 100%; border-collapse: collapse; font-size: 13px; }
.pr-preview td { padding: 7px 12px; border-bottom: 1px solid var(--border-2); }
.pr-preview tr:last-child td { border-bottom: none; }
.pr-preview td.pr-v { text-align: right; font-variant-numeric: tabular-nums; }
.pr-warn { background: #FFF6E5; color: #8A5A00; border: 1px solid #F5D9A6; border-radius: 8px; padding: 9px 12px; font-size: 12.5px; line-height: 1.5; }
.pr-err { background: #FEF1F0; color: #B42318; border: 1px solid #F5C6C2; border-radius: 8px; padding: 9px 12px; font-size: 12.5px; line-height: 1.5; }
.pr-params { display: grid; grid-template-columns: repeat(auto-fill, minmax(190px, 1fr)); gap: 14px; }
.pr-tip { position: relative; display: inline-flex; align-items: center; margin-left: 5px; color: var(--fg-3); cursor: help; vertical-align: middle; }
.pr-tip:hover { color: var(--fg-1); }
.pr-tip-box { display: none; position: absolute; top: calc(100% + 6px); right: 0; z-index: 30; width: 300px; background: var(--bg-surface); border: 1px solid var(--border-1); border-radius: 10px; box-shadow: 0 10px 30px rgba(24,24,27,0.14); padding: 10px 12px; text-align: left; text-transform: none; letter-spacing: 0; font-size: 12px; font-weight: 400; color: var(--fg-2); line-height: 1.5; white-space: normal; }
.pr-tip:hover .pr-tip-box, .pr-tip:focus-within .pr-tip-box { display: block; }
.pr-tip-box .pr-tip-title { font-weight: 600; color: var(--fg-1); margin-bottom: 4px; }
.pr-tip-box ul { margin: 0; padding-left: 16px; }
.pr-tip-box li { margin: 2px 0; }
.pr-badge { display: inline-flex; align-items: center; gap: 4px; padding: 1px 7px; border-radius: 999px; font-size: 10.5px; font-weight: 500; letter-spacing: 0.03em; text-transform: uppercase; border: 1px solid var(--border-1); color: var(--fg-3); background: var(--bg-surface); white-space: nowrap; vertical-align: middle; }
.pr-badge.is-square { background: #E8F1FF; color: #1B4F9C; border-color: #C6DBF7; }
.pr-badge.is-api { background: #EAF7EE; color: #1E6B3A; border-color: #BFE5CB; }
.pr-vrow { display: inline-flex; align-items: center; gap: 8px; justify-content: flex-end; }
.pr-people { margin: 0; padding: 0; list-style: none; font-size: 12px; color: var(--fg-2); columns: 2; column-gap: 24px; }
.pr-people li { display: flex; justify-content: space-between; gap: 10px; padding: 2px 0; break-inside: avoid; }
.pr-people li.is-out { color: var(--fg-3); }
.pr-people .pr-ph { font-variant-numeric: tabular-nums; }
.portal-stat-value.pr-neg { color: #B42318; }
.pr-drawer-back { position: fixed; inset: 0; background: rgba(0,0,0,0.30); z-index: 1000; animation: fade-in 160ms; }
.pr-drawer { position: absolute; top: 0; right: 0; bottom: 0; width: 600px; max-width: 100%; background: var(--bg-surface); box-shadow: -20px 0 60px rgba(0,0,0,0.18); display: flex; flex-direction: column; animation: pr-slide 220ms cubic-bezier(0.25,0.46,0.45,0.94); }
@keyframes pr-slide { from { transform: translateX(40px); opacity: 0; } to { transform: none; opacity: 1; } }
.pr-drawer-head { display: flex; align-items: flex-start; justify-content: space-between; gap: 16px; padding: 18px 22px 14px; border-bottom: 1px solid var(--border-2); }
.pr-drawer-body { flex: 1; overflow: auto; padding: 8px 22px 22px; }
.pr-drawer-foot { display: flex; justify-content: flex-end; gap: 8px; padding: 12px 22px; border-top: 1px solid var(--border-2); background: #FAFAFC; }
.pr-dsec { padding: 16px 0 6px; border-bottom: 1px solid var(--border-2); }
.pr-dsec:last-child { border-bottom: none; }
.pr-dsec-title { font-size: 11.5px; font-weight: 600; letter-spacing: 0.06em; text-transform: uppercase; color: var(--fg-3); margin-bottom: 10px; }
.pr-drows { display: flex; flex-direction: column; gap: 6px; }
.pr-drow { display: grid; grid-template-columns: minmax(0, 1fr) 96px 132px 26px; gap: 8px; align-items: center; }
.pr-sel { height: 32px; padding: 4px 8px; font-size: 12.5px; }
.pr-click { background: none; border: none; padding: 2px 4px; margin: -2px -4px; border-radius: 6px; font: inherit; color: var(--fg-1); cursor: pointer; font-variant-numeric: tabular-nums; text-decoration: underline dotted var(--fg-3); text-underline-offset: 3px; }
.pr-click:hover { background: var(--bg-sunken); text-decoration-color: var(--fg-1); }
.pr-editor { display: inline-flex; align-items: center; gap: 6px; }
.pr-editor .pr-in { width: 110px; }
.pr-editor .pr-sel { width: 140px; }
.pr-lines tr.pr-grp td { padding: 10px 14px 4px; font-size: 10.5px; font-weight: 600; letter-spacing: 0.06em; text-transform: uppercase; color: var(--fg-3); background: #FAFAFC; border-bottom: 1px solid var(--border-2); }
.pr-drow .portal-input { height: 32px; padding: 5px 9px; }
.pr-drow .pr-in { width: 100%; min-width: 0; }
.pr-drow .portal-segment button { padding: 4px 10px; }
.pr-dunit { font-size: 11px; color: var(--fg-3); white-space: nowrap; }
.pr-dx { width: 26px; height: 26px; border: none; background: transparent; border-radius: 6px; color: var(--fg-3); cursor: pointer; display: inline-flex; align-items: center; justify-content: center; }
.pr-dx:hover { background: var(--bg-sunken); color: #B42318; }
.pr-dadd { align-self: flex-start; border: 1px dashed var(--border-1); background: transparent; border-radius: 8px; padding: 5px 10px; font-size: 12px; color: var(--fg-2); cursor: pointer; display: inline-flex; align-items: center; gap: 4px; margin-top: 2px; }
.pr-dadd:hover { background: var(--bg-sunken); color: var(--fg-1); }
.pr-staffgrid { display: grid; grid-template-columns: 1fr 1fr; gap: 4px; }
.pr-staff { display: flex; align-items: center; gap: 8px; padding: 5px 8px; border-radius: 7px; font-size: 12.5px; cursor: pointer; user-select: none; }
.pr-staff.is-on { background: var(--bg-sunken); }
.pr-staff input { margin: 0; }
.pr-staffrole { margin-left: auto; font-size: 11px; color: var(--fg-3); }
.pr-stat-row.is-4 { grid-template-columns: repeat(4, minmax(0, 1fr)); }
.pr-simin { display: inline-flex; align-items: center; gap: 6px; }
.pr-simin .pr-in { width: 132px; }
.pr-simfix { color: var(--fg-3); font-size: 13px; }
.pr-apply { background: none; border: none; padding: 0; margin-left: 5px; font: inherit; font-size: 12px; font-weight: 600; color: var(--fg-1); cursor: pointer; text-decoration: underline; text-underline-offset: 2px; }
.pr-apply:hover { color: var(--fg-2); }
.pr-apply:disabled { color: var(--fg-3); font-weight: 500; cursor: default; text-decoration: none; }
.pr-simwarn { color: #B42318; }
.pr-simref { font-size: 12px; color: var(--fg-3); line-height: 1.5; }
.pr-lines th { text-align: right; font-weight: 500; font-size: 10.5px; letter-spacing: 0.07em; text-transform: uppercase; color: var(--fg-3); padding: 8px 14px; border-bottom: 1px solid var(--border-2); background: #FAFAFC; white-space: nowrap; }
.pr-lines th:first-child, .pr-lines th:last-child { text-align: left; }
.pr-lines.pr-two td.pr-l { width: 28%; }
.pr-lines.pr-two td.pr-v { width: 140px; }
.pr-hint { display: inline-flex; align-items: center; margin-left: 6px; color: var(--fg-3); cursor: help; vertical-align: middle; border-radius: 999px; }
.pr-hint:hover, .pr-hint:focus-visible { color: var(--fg-1); outline: none; }
.pr-title .pr-hint { margin-left: -4px; }
.pr-title-pct { font-size: 12px; font-weight: 600; font-variant-numeric: tabular-nums; color: var(--fg-2); background: var(--bg-sunken); border-radius: 999px; padding: 2px 9px; letter-spacing: 0; }
.pr-title-pct.is-neg { color: var(--danger); background: var(--danger-bg); }
.pr-hint-box { position: fixed; z-index: 3000; background: var(--bg-surface); border: 1px solid var(--border-1); border-radius: 10px; box-shadow: 0 10px 30px rgba(24,24,27,0.14); padding: 9px 12px; font-size: 12px; font-weight: 400; color: var(--fg-2); line-height: 1.5; text-transform: none; letter-spacing: 0; white-space: normal; text-align: left; pointer-events: none; }
.pr-hint-box p { margin: 0 0 6px; }
.pr-hint-box p:last-child { margin-bottom: 0; }
.pr-lines.pr-tipped td.pr-l, .pr-lines.pr-two.pr-tipped td.pr-l { width: auto; }
.pr-lines.pr-tipped th:last-child { text-align: right; }
.pr-days { display: grid; grid-template-columns: repeat(7, minmax(0, 1fr)); gap: 8px; padding: 14px 18px; border-bottom: 1px solid var(--border-2); }
.pr-day { display: flex; flex-direction: column; align-items: center; gap: 4px; padding: 10px 6px; border: 1px solid var(--border-1); border-radius: 10px; background: var(--bg-surface); cursor: pointer; font: inherit; color: var(--fg-1); transition: background 120ms; }
.pr-day:hover { background: var(--bg-sunken); }
.pr-day-name { font-size: 11px; font-weight: 600; letter-spacing: 0.06em; text-transform: uppercase; color: var(--fg-3); }
.pr-day-amt { display: inline-flex; align-items: center; gap: 5px; font-size: 14px; font-weight: 600; font-variant-numeric: tabular-nums; }
.pr-day-amt i { color: var(--fg-3); }
.pr-mrow { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr) 84px 26px; gap: 8px; align-items: center; }
.pr-mprod { text-align: right; font-size: 13px; font-variant-numeric: tabular-nums; color: var(--fg-2); white-space: nowrap; }
.pr-mhead .pr-mprod { font-size: 11px; color: var(--fg-3); }
.pr-mhead { font-size: 11px; font-weight: 600; letter-spacing: 0.06em; text-transform: uppercase; color: var(--fg-3); }
.pr-mrow .pr-simin { width: 100%; }
.pr-mrow .pr-simin .pr-in { width: 100%; min-width: 0; height: 32px; }
.pr-off-grid { display: grid; grid-template-columns: repeat(7, minmax(0, 1fr)); gap: 6px; }
.pr-off-wd { font-size: 11px; font-weight: 600; letter-spacing: 0.06em; text-transform: uppercase; color: var(--fg-3); text-align: center; padding-bottom: 2px; }
.pr-off-day { display: flex; flex-direction: column; align-items: flex-start; gap: 2px; padding: 8px 9px; border-radius: 8px; border: 1px solid var(--border-1); background: var(--bg-surface); color: var(--fg-1); font: inherit; text-align: left; cursor: pointer; transition: background 120ms, border-color 120ms; }
.pr-off-day:hover { border-color: var(--fg-3); }
.pr-off-day:focus-visible { outline: 2px solid var(--fg-1); outline-offset: 1px; }
.pr-off-day.is-on { background: #FEF3C7; border-color: #E5B94E; color: #8A5A00; }
.pr-off-day.is-on:hover { border-color: #C99A2E; }
.pr-off-day.is-today .pr-off-date::after { content: ' · today'; font-weight: 400; color: var(--fg-3); }
.pr-off-date { font-size: 12.5px; font-weight: 600; white-space: nowrap; }
.pr-off-tag { font-size: 11px; color: var(--fg-3); }
.pr-off-day.is-on .pr-off-tag { color: #8A5A00; }
.pr-src-steps { margin: 6px 0 0; padding-left: 18px; }
.pr-src-steps li { margin: 3px 0; }
.pr-tr-back { position: fixed; inset: 0; background: rgba(0,0,0,0.30); z-index: 1000; animation: fade-in 160ms; }
.pr-tr { position: absolute; inset: 20px; background: var(--bg-surface); border-radius: 14px; box-shadow: 0 20px 60px rgba(0,0,0,0.22); display: flex; flex-direction: column; overflow: hidden; animation: pop-in 200ms cubic-bezier(0.25,0.46,0.45,0.94); }
.pr-tr-head { display: flex; align-items: center; gap: 18px; padding: 14px 20px; border-bottom: 1px solid var(--border-2); flex-shrink: 0; }
.pr-tr-title { font-size: 15px; font-weight: 600; letter-spacing: -0.01em; }
.pr-tr-sub2 { font-size: 12px; color: var(--fg-3); margin-top: 2px; }
.pr-tr-sum { font-size: 13px; color: var(--fg-2); white-space: nowrap; font-variant-numeric: tabular-nums; }
.pr-tr-sum b { color: var(--fg-1); font-weight: 600; }
.pr-tr-notes { display: flex; flex-direction: column; gap: 8px; padding: 12px 20px 0; flex-shrink: 0; }
.pr-tr-body { flex: 1; min-height: 0; overflow: auto; }
.pr-tr-state { padding: 64px 20px; text-align: center; color: var(--fg-3); font-size: 13px; }
.pr-tr-grid { width: 100%; min-width: 1220px; border-collapse: separate; border-spacing: 0; table-layout: fixed; font-size: 12.5px; }
.pr-tr-grid th { position: sticky; top: 0; z-index: 2; background: #FAFAFC; text-align: left; font-weight: 600; font-size: 12px; color: var(--fg-1); padding: 10px 8px; border-bottom: 1px solid var(--border-2); border-left: 1px solid var(--border-2); white-space: nowrap; }
.pr-tr-grid td { padding: 6px; border-bottom: 1px solid var(--border-2); border-left: 1px solid var(--border-2); vertical-align: top; height: 58px; }
.pr-tr-grid .pr-tr-who { width: 196px; position: sticky; left: 0; z-index: 1; background: var(--bg-surface); border-left: none; padding: 10px 12px 10px 20px; vertical-align: middle; }
.pr-tr-grid th.pr-tr-who { z-index: 3; background: #FAFAFC; }
.pr-tr-name { font-size: 13px; font-weight: 500; color: var(--fg-1); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.pr-tr-sub { font-size: 11.5px; color: var(--fg-3); margin-top: 2px; font-variant-numeric: tabular-nums; white-space: nowrap; }
.pr-tr-sub .is-train { color: #8A5A00; }
.pr-tr-shift { display: block; width: 100%; text-align: left; font: inherit; padding: 6px 8px; border-radius: 8px; border: 1px solid #C6DBF7; background: #E8F1FF; color: #1B4F9C; cursor: pointer; transition: background 120ms, border-color 120ms; }
.pr-tr-shift + .pr-tr-shift { margin-top: 4px; }
.pr-tr-shift:hover { border-color: #8FB8EE; }
.pr-tr-shift:focus-visible { outline: 2px solid var(--fg-1); outline-offset: 1px; }
.pr-tr-shift.is-on { background: #FEF3C7; border-color: #E5B94E; color: #8A5A00; }
.pr-tr-shift.is-on:hover { border-color: #C99A2E; }
.pr-tr-shift.is-open { background: transparent; border-style: dashed; border-color: var(--border-1); color: var(--fg-3); cursor: default; }
.pr-tr-time { font-size: 12px; font-weight: 600; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.pr-tr-meta { display: flex; align-items: center; gap: 3px; font-size: 11.5px; margin-top: 1px; font-variant-numeric: tabular-nums; white-space: nowrap; }
.pr-tr-foot { display: flex; align-items: center; gap: 18px; padding: 10px 20px; border-top: 1px solid var(--border-2); background: #FAFAFC; flex-shrink: 0; font-size: 12px; color: var(--fg-3); }
.pr-tr-key { display: inline-flex; align-items: center; gap: 6px; }
.pr-tr-swatch { width: 12px; height: 12px; border-radius: 4px; border: 1px solid #C6DBF7; background: #E8F1FF; }
.pr-tr-swatch.is-on { border-color: #E5B94E; background: #FEF3C7; }
      `}</style>

      {loadErr && <div className="pr-err" style={{ marginBottom: 14 }}>Couldn’t load: {loadErr}</div>}

      {!anchor || !sales ? (
        <div className="pr-empty">Loading periods…</div>
      ) : simOpen && canSimulate ? (
        <PrSimulator rows={rowsWithCalc} config={config || {}} onBack={() => setSimOpen(false)} />
      ) : open ? (
        <PrDetail
          row={open}
          hasPrev={openIdx < rowsWithCalc.length - 1}
          hasNext={openIdx > 0}
          onPrev={() => setOpenKey(rowsWithCalc[openIdx + 1].key)}
          onNext={() => setOpenKey(rowsWithCalc[openIdx - 1].key)}
          onBack={() => setOpenKey(null)}
          onSave={(patch) => saveReport(open.period, patch)}
          onImport={(channel, parsed, file) => saveImport(open.period, channel, parsed, file)}
          onDeleteImport={(channel) => deleteImport(open.period, channel)}
          onManagerOff={(days) => saveManagerOff(open.period, days)}
          onDefaults={() => setDefaultsOpen(true)}
          canEdit={canEdit}
          level={level}
          isCurrent={openIdx === 0}
          syncing={syncing}
          onSyncSales={() => syncSales(open.period)}
          onSyncHours={() => syncHours(open.period)}
          onSyncBonus={() => syncBonus(open.period)}
          onSyncPay={async () => { await syncHours(open.period); await syncBonus(open.period); }}
          onSyncAds={() => syncAds(open.period)}
          defaultParams={prParamsFor(null, config)}
          config={config || {}}
        />
      ) : (
        <PrList rows={rowsWithCalc} onOpen={(key) => setOpenKey(key)} onDefaults={() => setDefaultsOpen(true)} onSimulator={() => { setOpenKey(null); setSimOpen(true); }} canEdit={canEdit} canSimulate={canSimulate} level={level} />
      )}

      {defaultsOpen && config && canEdit && (
        <PrDefaultsDrawer config={config} onSave={(next) => { saveConfig(next); setDefaultsOpen(false); }} onClose={() => setDefaultsOpen(false)} />
      )}
      <PToast message={toast} open={!!toast} onClose={() => setToast('')} />
    </div>
  );
};

// ------------------------------------------------------------------
// List — one row per pay period, newest first
// ------------------------------------------------------------------
const PrStatusChips = ({ r, compact }) => {
  const sq = r.direct ? r.direct.days : 0;
  const total = r.period.days.length;
  const today = new Date();
  const running = r.period.end >= new Date(today.getFullYear(), today.getMonth(), today.getDate());
  const elapsed = running ? Math.min(total, dayDiff(today, r.period.start) + 1) : total;
  return (
    <div className="pr-chips">
      <span className={'pr-chip ' + (sq >= elapsed && sq > 0 ? 'is-on' : (sq > 0 ? 'is-warn' : ''))} title={'Square: ' + sq + ' of ' + elapsed + ' days'}>
        Square {compact ? '' : sq + '/' + elapsed}
      </span>
      {PR_TPD.map(c => (
        <span key={c.key} className={'pr-chip ' + (r.imports[c.key] ? 'is-on' : '')} title={r.imports[c.key] ? c.label + ' CSV uploaded' : c.label + ' CSV not uploaded'}>
          {compact ? c.label.split(' ')[0] : c.label}
        </span>
      ))}
      <span className={'pr-chip ' + (r.calc.haveHours ? 'is-on' : '')} title={r.calc.haveHours ? 'Hours entered' : 'Hours not entered'}>Hours</span>
    </div>
  );
};

const PrLevelChip = ({ level }) => level === 'edit' ? null : (
  <span className="pr-chip is-warn" title={level === 'simulate' ? 'Read-only access to the periods, plus the Simulator' : 'Read-only access'}>
    Read only
  </span>
);

const PrList = ({ rows, onOpen, onDefaults, onSimulator, canEdit, canSimulate, level }) => (
  <>
    <div className="portal-page-header">
      <div>
        <h1 className="portal-page-title">Period Report</h1>
        <div className="portal-page-subtitle">
          Every pay period’s sales, labor productivity and pay on one line — open a period for the full breakdown. Direct sales, refunds and the crew’s hours come from Square; DoorDash, Uber Eats and GrubHub from their CSV exports; Google and Meta spend from their APIs; training shifts are picked from the clocked shifts, and the rest of marketing is typed in.
        </div>
      </div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
        <PrLevelChip level={level} />
        {canSimulate && <PBtn size="md" icon="ri-flask-line" title="Try out a period’s numbers before it happens" onClick={onSimulator}>Simulator</PBtn>}
        {canEdit && <PBtn size="md" icon="ri-settings-3-line" onClick={onDefaults}>Defaults</PBtn>}
      </div>
    </div>

    <div className="portal-card">
      <table className="portal-table pr-list">
        <thead>
          <tr>
            <th>Period</th>
            <th className="pr-num">Gross sales</th>
            <th className="pr-num">Net sales</th>
            <th className="pr-num">Labor %</th>
            <th className="pr-num">Productivity</th>
            <th className="pr-num">Manager pay</th>
            <th className="pr-num">Left</th>
            <th>Data</th>
            <th style={{ width: 40 }}></th>
          </tr>
        </thead>
        <tbody>
          {rows.length === 0 && (
            <tr><td colSpan={9} className="pr-empty">No periods yet — Square sales start flowing into sales_daily and the periods appear here.</td></tr>
          )}
          {rows.map((r, i) => (
            <tr key={r.key} onClick={() => onOpen(r.key)}>
              <td>
                <div className="pr-period">{prPeriodLabel(r.period)}</div>
                <div style={{ fontSize: 11.5, color: 'var(--fg-3)', marginTop: 2 }}>
                  {i === 0 ? 'In progress' : 'Period ' + r.period.index}
                </div>
              </td>
              <td className="pr-num">{prMoney(r.calc.gross)}</td>
              <td className="pr-num">{prMoney(r.calc.net)}</td>
              <td className={'pr-num' + (r.calc.laborPct == null ? ' pr-muted' : '')}>{prPct(r.calc.laborPct)}</td>
              <td className={'pr-num' + (r.calc.actProductivity == null ? ' pr-muted' : '')}>{r.calc.actProductivity == null ? '—' : '$' + r.calc.actProductivity.toFixed(1) + '/hr'}</td>
              <td className={'pr-num' + (r.calc.managerTotal == null ? ' pr-muted' : '')}>{prMoney(r.calc.managerTotal)}</td>
              <td className={'pr-num' + (r.calc.remaining == null ? ' pr-muted' : (r.calc.remaining < 0 ? ' pr-neg' : ''))}>{prMoney(r.calc.remaining)}</td>
              <td><PrStatusChips r={r} compact /></td>
              <td style={{ textAlign: 'right', color: 'var(--fg-3)' }}><PIcon name="ri-arrow-right-s-line" size={16} /></td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
    <div className="pr-help">
      A period is two weeks from the pay-period anchor in Settings. Labor % and pay show once the period’s hours are typed in; Net sales counts every channel that has data, so a period without its CSVs reads low until they’re uploaded.
    </div>
  </>
);

// ------------------------------------------------------------------
// Number input — draft while focused, commits on blur / Enter
// ------------------------------------------------------------------
const PrInput = ({ value, onCommit, unit, hours, pct, placeholder, title }) => {
  const [draft, setDraft] = useState(null);
  const shown = draft != null ? draft : (value == null ? '' : (pct ? String(prRound2(value * 100)) : String(value)));
  const commit = () => {
    if (draft == null) return;
    const n = prNum(draft);
    setDraft(null);
    const next = n == null ? null : (pct ? n / 100 : n);
    // Tabbing through a box is not an edit: a fetched number keeps its
    // badge unless the value actually changes.
    const cur = value == null ? null : Number(value);
    if (next === cur || (next != null && cur != null && Math.abs(next - cur) < 1e-9)) return;
    onCommit(next);
  };
  return (
    <span style={{ display: 'inline-flex', alignItems: 'center' }}>
      <input className={'portal-input pr-in' + (hours ? ' is-hours' : '')} {...PR_NO_PM} inputMode="decimal" title={title}
        value={shown} placeholder={placeholder || ''}
        onFocus={() => setDraft(shown)}
        onChange={e => setDraft(e.target.value)}
        onBlur={commit}
        onKeyDown={e => { if (e.key === 'Enter') { e.preventDefault(); e.target.blur(); } if (e.key === 'Escape') { setDraft(null); e.target.blur(); } }} />
      {unit != null && <span className="pr-unit">{unit}</span>}
    </span>
  );
};

// ⓘ with a hover / focus popover listing how a column is read.
const PrTip = ({ title, lines }) => (
  <span className="pr-tip" tabIndex={0} aria-label={'How ' + title + ' is calculated'}>
    <PIcon name="ri-information-line" size={13} />
    <span className="pr-tip-box" role="tooltip">
      <div className="pr-tip-title">How {title} is read</div>
      <ul>{lines.map((l, i) => <li key={i}>{l}</li>)}</ul>
    </span>
  </span>
);
// ⓘ with a hover / focus popover for one explanation (v26.09, the
// Simulator's notes). The box is portalled to <body> with fixed positioning:
// .portal-card clips its overflow, so a popover inside a card would be cut
// off at the card's edge. It opens below the ⓘ, or above it near the bottom
// of the window, and closes on scroll.
const PrHint = ({ text, label, wide, size }) => {
  const [pos, setPos] = useState(null);
  const ref = useRef(null);
  useEffect(() => {
    if (!pos) return undefined;
    const hide = () => setPos(null);
    window.addEventListener('scroll', hide, true);
    window.addEventListener('resize', hide);
    return () => { window.removeEventListener('scroll', hide, true); window.removeEventListener('resize', hide); };
  }, [pos]);
  if (text == null || text === '' || text === false) return null;
  const show = () => {
    const r = ref.current && ref.current.getBoundingClientRect();
    if (!r) return;
    const w = Math.min(wide ? 440 : 300, window.innerWidth - 24);
    const left = Math.max(12, Math.min(r.left - 10, window.innerWidth - w - 12));
    setPos(r.bottom < window.innerHeight * 0.66
      ? { left, top: r.bottom + 6, width: w }
      : { left, bottom: window.innerHeight - r.top + 6, width: w });
  };
  return (
    <span ref={ref} className="pr-hint" tabIndex={0} aria-label={label || (typeof text === 'string' ? text : 'How this is worked out')}
      onMouseEnter={show} onMouseLeave={() => setPos(null)} onFocus={show} onBlur={() => setPos(null)}>
      <PIcon name="ri-information-line" size={size || 13} />
      {pos && ReactDOM.createPortal(<div className="pr-hint-box" role="tooltip" style={pos}>{text}</div>, document.body)}
    </span>
  );
};
const prWhen = (iso) => { const d = new Date(iso); return isNaN(d) ? '' : d.toLocaleString('en-US', { month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit' }); };

// ------------------------------------------------------------------
// Detail — one period, section by section
// ------------------------------------------------------------------
const PrDetail = ({ row, hasPrev, hasNext, onPrev, onNext, onBack, onSave, onImport, onDeleteImport, onManagerOff, onDefaults, isCurrent, syncing, onSyncSales, onSyncHours, onSyncBonus, onSyncPay, onSyncAds, defaultParams, config, canEdit, level }) => {
  const { period, calc, inputs, params, direct, imports } = row;
  const [importFor, setImportFor] = useState(null);   // channel key
  const [peopleOpen, setPeopleOpen] = useState(false);
  const [trainingOpen, setTrainingOpen] = useState(false);   // the training-shift picker (v26.31)
  const [offOpen, setOffOpen] = useState(false);   // the manager's unpaid days off (v26.33)
  const [leadsOpen, setLeadsOpen] = useState(false);
  const busyBonus = !!(syncing && syncing['bonus|' + prPeriodKey(period)]);
  const bonusMeta = (inputs.meta && inputs.meta.bonus) || null;
  const reloadDefaults = () => {
    if (!window.confirm('Replace this period’s parameters and expense lines with today’s Defaults? Typed values on this period’s lines are overwritten.')) return;
    onSave({ params: defaultParams, inputs: { meta: { manager: null } } });
  };
  const key = prPeriodKey(period);
  const busySales = !!(syncing && syncing['sales|' + key]);
  const busyHours = !!(syncing && syncing['hours|' + key]);
  const busyAds = !!(syncing && syncing['ads|' + key]);
  const hoursMeta = (inputs.meta && inputs.meta.hours) || null;
  const adsMeta = (inputs.meta && inputs.meta.ads) || {};
  const total = period.days.length;
  const sqDays = direct ? direct.days : 0;
  const status = isCurrent
    ? 'In progress — ' + sqDays + ' of ' + total + ' days so far'
    : (sqDays >= total ? 'All ' + total + ' days from Square' : (sqDays > 0 ? sqDays + ' of ' + total + ' days from Square' : 'No Square data for this period'));
  const setInput = (k, v) => onSave({ inputs: { [k]: v } });
  // Click-to-edit (v25.04): one editor open at a time, keyed by what it edits.
  const [editing, setEditing] = useState(null);   // 'param|goal_productivity' · 'input|manager_base' · 'line|occupancy|rent'
  const closeEdit = () => setEditing(null);
  const setLine = (catKey, itemId, patch) => onSave({ params: { categories: (params.categories || []).map(cat => cat.key !== catKey ? cat
    : Object.assign({}, cat, { items: cat.items.map(it => it.id !== itemId ? it : Object.assign({}, it, patch)) })) } });
  // A category line's value cell: the prorated amount, click to edit the
  // line (number + % of net / $ per month / week / day) for this period.
  const lineCell = (catKey, it) => {
    const k = 'line|' + catKey + '|' + it.id;
    if (editing === k) return <PrLineEditor value={it.value} modeKey={prModeKey(it)} allowMode onSave={(next) => { setLine(catKey, it.id, next); closeEdit(); }} onCancel={closeEdit} />;
    if (!canEdit) return <span title={prLineDef(it)}>{prMoney(it.amount)}</span>;
    return <button type="button" className="pr-click" title={'Click to change — ' + prLineDef(it)} onClick={() => setEditing(k)}>{prMoney(it.amount)}</button>;
  };
  // A parameter or a typed input as a click target (v25.05): the value with
  // its unit, click to key in the number. `param` keys live in
  // params (this period's copy of the defaults), `input` keys in inputs.
  const PR_FIELDS = {
    manager_bonus_factor:    { kind: 'param', pct: false, unit: null,   short: (v) => String(prRound2(v)) },
    manager_fixed_hours:     { kind: 'param', pct: false, unit: 'hr',   short: (v) => prHours(v) + ' hr' },
    manager_commission_rate: { kind: 'param', pct: true,  unit: '%',    short: (v) => prRatePct(v) },
    commission_base_net:     { kind: 'param', pct: false, unit: null,   short: (v) => prMoneyShort(v) },
    commission_step:         { kind: 'param', pct: true,  unit: '%',    short: (v) => prRatePct(v) },
    commission_cap:          { kind: 'param', pct: true,  unit: '%',    short: (v) => prRatePct(v) },
    tax_insurance_rate:      { kind: 'param', pct: true,  unit: '%',    short: (v) => prPct(v, 1) },
    manager_base:            { kind: 'input', pct: false, unit: null,   short: (v) => prMoney(v) },
    manager_food_bonus:      { kind: 'input', pct: false, unit: null,   short: (v) => prMoney(v) },
  };
  const fieldCell = (key, title) => {
    const f = PR_FIELDS[key];
    const k = f.kind + '|' + key;
    const cur = f.kind === 'param' ? params[key] : inputs[key];
    if (editing === k) return <PrLineEditor value={f.pct ? prRound2((cur || 0) * 100) : cur} unit={f.unit} onSave={(next) => {
      const v = f.pct ? next.value / 100 : next.value;
      if (f.kind === 'param') onSave({ params: { [key]: key === 'manager_fixed_hours' ? Math.abs(v) : v } });
      else setInput(key, v);
      closeEdit();
    }} onCancel={closeEdit} />;
    const shown = cur == null ? 0 : cur;
    if (!canEdit) return <span>{f.short(shown)}</span>;
    return <button type="button" className="pr-click" title={title || 'Click to change for this period'} onClick={() => setEditing(k)}>{f.short(shown)}</button>;
  };
  // Total labor hours: the crew's clocked hours from Square, nothing added
  // (v26.31; from v26.02 the manager's typed hours were part of it). Typing a
  // number makes it this period's own figure.
  const clockedCell = () => {
    const k = 'input|clocked';
    const T = inputs.act_hours;
    if (editing === k) return <PrLineEditor value={T == null ? null : prRound2(T)} unit="hr" onSave={(next) => {
      // Typing over a Square figure makes it typed: the badge and the people list go.
      onSave({ inputs: { act_hours: prRound2(Math.abs(next.value)), meta: { hours: { source: 'typed', synced_at: null, people: null } } } });
      closeEdit();
    }} onCancel={closeEdit} />;
    const shown = T == null ? '—' : prHours(T) + ' hr';
    if (!canEdit) return <span>{shown}</span>;
    return <button type="button" className="pr-click" title="The crew’s clocked hours — click to type your own for this period" onClick={() => setEditing(k)}>{shown}</button>;
  };
  // Training hours (v26.31): the sum of the shifts picked in the full-screen
  // picker. The inline box is only the picker's fallback ("Type the hours
  // instead"), and a typed figure forgets any picked shifts.
  const trainPicks = prTrainPicks(inputs);
  const trainTyped = !trainPicks.length && (inputs.training_hours || 0) > 0;
  const trainingCell = () => {
    const k = 'input|training_hours';
    if (editing === k) return <PrLineEditor value={inputs.training_hours} unit="hr" onSave={(next) => {
      onSave({ inputs: { training_hours: Math.abs(next.value), meta: { training: { source: 'typed', at: new Date().toISOString(), shifts: null } } } });
      closeEdit();
    }} onCancel={closeEdit} />;
    const shown = prHours(inputs.training_hours || 0) + ' hr';
    if (!canEdit) return <span>{shown}</span>;
    return <button type="button" className="pr-click" title="Training hours — click to pick the training shifts" onClick={() => setTrainingOpen(true)}>{shown}</button>;
  };
  // The manager's hours in the Actual productivity note (v26.31): this
  // period's own figure, a click away from being changed. While a period
  // runs, what counts is its share for the days so far.
  const mgrCell = fieldCell('manager_fixed_hours', 'The manager’s hours in actual productivity, per two weeks — click to change for this period');
  // The manager's unpaid days off (v26.33): `md` only when he took any.
  const md = calc.mgrDays;
  const offList = prMgrOffDays(inputs, period);
  const workedOf14 = PR_PERIOD_DAYS - (md ? md.off : 0);
  const mgrNote = md
    ? <>{prHours(calc.managerHours)} hr for the manager, {mgrCell} per two weeks × the {prDaysWord(md.worked)} he worked{calc.days < PR_PERIOD_DAYS ? ' so far' : ''} ÷ 14</>
    : calc.days < PR_PERIOD_DAYS
    ? <>{prHours(calc.managerHours)} hr for the manager, {mgrCell} per two weeks at {calc.days}{calc.days === 1 ? ' day' : ' days'} so far</>
    : <>{mgrCell} for the manager</>;
  const offCell = canEdit
    ? <button type="button" className="pr-click" title="Click to mark the days the manager was off without pay" onClick={() => setOffOpen(true)}>{offList.length ? prDaysWord(offList.length) : 'None'}</button>
    : <span>{offList.length ? prDaysWord(offList.length) : 'None'}</span>;
  const bonusRatio = fieldCell('manager_bonus_factor', 'The manager’s bonus ratio — × (pre-manager productivity − goal), click to change for this period');
  // Sales commission note: what it reads (the period's net, or his days'),
  // then the sliding scale's numbers, each a click away.
  const commTail = calc.mgrCommission.sliding
    ? <> · every ±$1,000 of net from {fieldCell('commission_base_net', 'The base net sales for a two-week period — click to change for this period')} = ±{fieldCell('commission_step', 'The step for each $1,000 of net — click to change for this period')}, starting at {fieldCell('manager_commission_rate', 'The rate at the base net sales — click to change for this period')}, up to {fieldCell('commission_cap', 'The highest rate — click to change for this period')}</>
    : null;
  const commNote = md
    ? (md.worked === 0 ? 'he worked none of the period’s days so far'
      : calc.mgrCommission.sliding
        ? <>{prMoney(calc.mgrNet)} net on his {prDaysWord(md.worked)} × {prRatePct(calc.mgrCommission.rate)}{calc.mgrCommission.capped ? ', the cap' : ''} (their two-week pace, {prMoney(calc.mgrCommission.N)}, sets the rate){commTail}</>
        : <>{prMoney(calc.mgrNet)} net on his {prDaysWord(md.worked)} × {fieldCell('manager_commission_rate', 'Manager commission — % of net sales, click to change for this period')}</>)
    : calc.mgrCommission.sliding
      ? <>{prMoney(calc.net)} × {prRatePct(calc.mgrCommission.rate)}{calc.mgrCommission.capped ? ', the cap' : ''}{calc.days < PR_PERIOD_DAYS ? ' (its two-week pace, ' + prMoney(calc.mgrCommission.N) + ', sets the rate)' : ''}{commTail}</>
      : <>{fieldCell('manager_commission_rate', 'Manager commission — % of net sales, click to change for this period')} of net sales</>;
  const prodNote = md
    ? (md.worked === 0 ? 'he worked none of the period’s days so far'
      : <>{'(' + (calc.mgrPre != null ? '$' + calc.mgrPre.toFixed(2) + ' pre-manager on his days' : 'pre-manager productivity on his days') + ' − ' + (calc.mgrGoal != null ? '$' + prRound2(calc.mgrGoal) + ' goal' : 'goal') + ') × '}{bonusRatio}{' × ' + workedOf14 + '/14 · ' + (md.crewW == null ? 'sync the period’s hours first' : 'his days: ' + prMoney(md.grossW) + ' gross ÷ ' + prHours(md.crewW) + ' effective crew hours')}</>)
    : <>{prBonusNote(calc, calc.goalProductivity)}{bonusRatio}</>;
  const neg = (n) => n ? prMoney(-n) : prMoney(0);
  const negCls = (n) => (n ? ' pr-neg' : '');
  const ordersTotal = (direct ? direct.orders : 0) + PR_TPD.reduce((a, ch) => a + (calc.ch[ch.key].orders || 0), 0);

  return (
    <>
      <div className="portal-page-header" style={{ alignItems: 'flex-start' }}>
        <div style={{ minWidth: 0 }}>
          <button className="portal-back" onClick={onBack} style={{ background: 'none', border: 'none', padding: 0, cursor: 'pointer', color: 'var(--fg-3)', fontSize: 12.5, display: 'inline-flex', alignItems: 'center', gap: 4, marginBottom: 6 }}>
            <PIcon name="ri-arrow-left-line" size={14} /> All periods
          </button>
          <h1 className="portal-page-title">{prPeriodLabel(period)}</h1>
          <div className="portal-page-subtitle">Pay period {period.index} · {status}</div>
        </div>
        <div style={{ display: 'flex', gap: 8, flexShrink: 0, alignItems: 'center' }}>
          <PBtn size="md" icon="ri-arrow-left-s-line" ariaLabel="Previous period" title="Previous period" disabled={!hasPrev} onClick={onPrev} />
          <PBtn size="md" icon="ri-arrow-right-s-line" ariaLabel="Next period" title="Next period" disabled={!hasNext} onClick={onNext} />
          <PrLevelChip level={level} />
          {canEdit && <PBtn size="md" icon="ri-restart-line" title="Replace this period’s parameters and expense lines with today’s Defaults" onClick={reloadDefaults}>Reload defaults</PBtn>}
          {canEdit && <PBtn size="md" icon="ri-settings-3-line" onClick={onDefaults}>Defaults</PBtn>}
        </div>
      </div>

      <div className="pr-stat-row">
        <div className="portal-stat">
          <div className="portal-stat-label">Gross sales</div>
          <div className="portal-stat-value">{prMoney(calc.gross)}</div>
          <div className="portal-stat-sub">{PR_TPD.filter(c => calc.ch[c.key].have).length} of 3 platforms uploaded</div>
        </div>
        <div className="portal-stat">
          <div className="portal-stat-label">Net sales</div>
          <div className="portal-stat-value">{prMoney(calc.net)}</div>
          <div className="portal-stat-sub">after commission, discounts, refunds</div>
        </div>
        <div className="portal-stat">
          <div className="portal-stat-label">Total labor</div>
          <div className="portal-stat-value">{prPct(calc.laborPct)}</div>
          <div className="portal-stat-sub">{calc.totalLabor != null ? prMoney(calc.totalLabor) + ' incl. tax & insurance' : 'fetch the period’s hours'}</div>
        </div>
        <div className="portal-stat">
          <div className="portal-stat-label">Productivity</div>
          <div className="portal-stat-value">{calc.actProductivity == null ? '—' : '$' + calc.actProductivity.toFixed(1)}</div>
          <div className="portal-stat-sub">{'goal ' + (calc.goalProductivity != null ? '$' + calc.goalProductivity.toFixed(1) : '—') + (calc.preMgrProductivity != null ? ' · pre-manager $' + calc.preMgrProductivity.toFixed(1) : ' · gross per labor hour')}</div>
        </div>
        <div className="portal-stat">
          <div className="portal-stat-label">Left</div>
          <div className={'portal-stat-value' + (calc.remaining != null && calc.remaining < 0 ? ' pr-neg' : '')}>{prMoney(calc.remaining)}</div>
          <div className="portal-stat-sub">{calc.remainingPct != null ? prPct(calc.remainingPct) + ' of net after every expense' : 'fetch hours and wages'}</div>
        </div>
      </div>

      {/* ---- Sales ---- */}
      <div className="portal-card pr-sec">
        <div className="portal-card-header">
          <PrTitle icon={PR_ICONS.sales}>Sales</PrTitle>
          <div className="pr-sec-sub">Direct from Square · platforms from their CSV exports</div>
        </div>
        <table className="pr-sales">
          <thead>
            <tr>
              <th></th>
              <th>Total</th>
              {PR_CHANNELS.map(c => {
                const im = c.source === 'csv' ? imports[c.key] : null;
                return (
                  <th key={c.key}>
                    <div className="pr-colhead">
                      <span className="pr-colname">{c.label}<PrTip title={c.label} lines={PR_HOW[c.key]} /></span>
                      {c.source === 'square' ? (
                        <>
                          <span className="pr-file">{sqDays ? 'Square · ' + sqDays + (sqDays === 1 ? ' day' : ' days') : 'Square · no data'}</span>
                          <span className="pr-file" title="The oldest of the period’s daily computations">{direct && direct.computedAt ? 'as of ' + prWhen(direct.computedAt) : ''}</span>
                          <span className="pr-colacts">{canEdit && <PBtn size="sm" icon="ri-refresh-line" disabled={busySales} onClick={onSyncSales}>{busySales ? 'Syncing…' : 'Sync'}</PBtn>}</span>
                        </>
                      ) : (
                        <>
                          <span className="pr-file" title={im ? im.file_name + ' · ' + (im.file_rows || 0) + ' rows' : ''}>{im ? (im.file_name || 'uploaded') : 'no file yet'}</span>
                          <span className="pr-file">{im && im.uploaded_at ? 'uploaded ' + prWhen(im.uploaded_at) : ''}</span>
                          <span className="pr-colacts">
                            {canEdit && <PBtn size="sm" icon={im ? 'ri-refresh-line' : 'ri-upload-2-line'} onClick={() => setImportFor(c.key)}>{im ? 'Replace' : 'Upload CSV'}</PBtn>}
                            {canEdit && im && <PBtn size="sm" variant="ghost" icon="ri-delete-bin-line" ariaLabel="Remove import" title="Remove this import" onClick={() => onDeleteImport(c.key)} />}
                            {canEdit && PR_CSV_SOURCE[c.key] && <PrHint wide label={'Which ' + c.label + ' file to upload'} text={prCsvSourceTip(c)} />}
                          </span>
                        </>
                      )}
                    </div>
                  </th>
                );
              })}
            </tr>
          </thead>
          <tbody>
            <tr>
              <td>Gross sales</td>
              <td className="pr-tot">{prMoney(calc.gross)}</td>
              {PR_CHANNELS.map(c => <td key={c.key} className={calc.ch[c.key].have ? '' : 'pr-muted'}>{calc.ch[c.key].have ? prMoney(calc.ch[c.key].gross) : '—'}</td>)}
            </tr>
            <tr>
              <td>Commission (3PD)</td>
              <td className={'pr-tot' + negCls(calc.commission)}>{neg(calc.commission)}</td>
              {PR_CHANNELS.map(c => <td key={c.key} className={c.source === 'square' ? 'pr-muted' : (calc.ch[c.key].have ? negCls(calc.ch[c.key].commission) : 'pr-muted')}>{c.source === 'square' ? '—' : (calc.ch[c.key].have ? neg(calc.ch[c.key].commission) : '—')}</td>)}
            </tr>
            <tr>
              <td>Discount (merchant)</td>
              <td className={'pr-tot' + negCls(calc.discount)}>{neg(calc.discount)}</td>
              {PR_CHANNELS.map(c => <td key={c.key} className={calc.ch[c.key].have ? negCls(calc.ch[c.key].discount) : 'pr-muted'}>{calc.ch[c.key].have ? neg(calc.ch[c.key].discount) : '—'}</td>)}
            </tr>
            <tr>
              <td>Refund</td>
              <td className={'pr-tot' + negCls(calc.refund)}>{neg(calc.refund)}</td>
              {PR_CHANNELS.map(c => (
                <td key={c.key} className={calc.ch[c.key].have ? negCls(calc.ch[c.key].refund) : 'pr-muted'}>{calc.ch[c.key].have ? neg(calc.ch[c.key].refund) : '—'}</td>
              ))}
            </tr>
            <tr className="pr-total">
              <td>Net sales</td>
              <td>{prMoney(calc.net)}</td>
              {PR_CHANNELS.map(c => <td key={c.key} className={calc.ch[c.key].have ? '' : 'pr-muted'}>{calc.ch[c.key].have ? prMoney(calc.ch[c.key].net) : '—'}</td>)}
            </tr>
            <tr>
              <td className="pr-muted">Orders</td>
              <td className="pr-muted">{prInt((direct ? direct.orders : 0) + PR_TPD.reduce((a, c) => a + (calc.ch[c.key].orders || 0), 0))}</td>
              <td className="pr-muted">{direct ? prInt(direct.orders) + (ordersTotal > 0 ? ' · ' + prPct(direct.orders / ordersTotal) : '') : '—'}</td>
              {PR_TPD.map(c => <td key={c.key} className="pr-muted">{calc.ch[c.key].orders == null ? '—' : prInt(calc.ch[c.key].orders)}</td>)}
            </tr>
          </tbody>
        </table>
      </div>

      {/* ---- Labor & productivity ---- */}
      <div className="portal-card pr-sec">
        <div className="portal-card-header">
          <PrTitle icon={PR_ICONS.labor}>Labor &amp; productivity</PrTitle>
          <div className="pr-sec-sub" style={{ display: 'inline-flex', alignItems: 'center', gap: 10 }}>
            <span>gross sales per labor hour · the crew’s clocked hours from Square · click a number to change it for this period</span>
            {canEdit && <PBtn size="sm" icon="ri-refresh-line" disabled={busyHours} onClick={onSyncHours}>{busyHours ? 'Syncing…' : 'Sync again'}</PBtn>}
          </div>
        </div>
        <table className="pr-lines">
          <tbody>
            <tr><td className="pr-l">Goal productivity</td><td className="pr-v">{calc.goalProductivity == null ? '—' : '$' + calc.goalProductivity.toFixed(2) + '/hr'}</td><td className="pr-n">{(() => { const f = prGoalFormula(calc.gross, params, calc.days); return (calc.days < PR_PERIOD_DAYS ? 'At the two-week pace of ' + prMoney(f.G) + ': ' : 'The goal for actual productivity at this gross: ') + f.lines.join('. ') + '.' + (f.source ? ' ' + f.source : ''); })()}</td></tr>
            <tr><td className="pr-l">Goal labor hours</td><td className="pr-v">{prHours(calc.goalHours)} hr</td><td className="pr-n">gross ÷ goal productivity, {prMoney(calc.gross)} ÷ {(calc.goalProductivity != null ? '$' + calc.goalProductivity.toFixed(2) : '—')}</td></tr>
            <tr>
              <td className="pr-l">Total labor hours</td>
              <td className="pr-v">
                <span className="pr-vrow">
                  {hoursMeta && hoursMeta.source === 'square' && inputs.act_hours != null && <span className="pr-badge is-square" title={'Synced ' + prWhen(hoursMeta.synced_at)}>Square</span>}
                  {clockedCell()}
                </span>
              </td>
              <td className="pr-n">
                <span style={{ display: 'inline-flex', alignItems: 'center', gap: 8, flexWrap: 'wrap' }}>
                  <span>{inputs.act_hours == null ? 'not synced yet — the crew’s clocked hours from Square' : (hoursMeta && hoursMeta.source === 'typed' ? 'typed for this period' : 'the crew’s clocked hours from Square') + (hoursMeta && hoursMeta.source === 'square' && hoursMeta.manager ? ' · ' + (hoursMeta.excluded && hoursMeta.excluded.length ? hoursMeta.excluded.map(n => String(n).split(' ')[0]).join(', ') + '’s own ' : 'the manager’s own ') + prHours(hoursMeta.manager) + ' h left out' : '')}</span>
                  {hoursMeta && hoursMeta.people && hoursMeta.people.length > 0 && (
                    <button type="button" onClick={() => setPeopleOpen(o => !o)} style={{ background: 'none', border: 'none', padding: 0, cursor: 'pointer', color: 'var(--fg-2)', fontSize: 12, textDecoration: 'underline' }}>{peopleOpen ? 'Hide people' : 'By person'}</button>
                  )}
                </span>
              </td>
            </tr>
            {peopleOpen && hoursMeta && hoursMeta.people && (
              <tr><td colSpan={3} style={{ padding: '6px 14px 12px 72px', background: '#FAFAFC' }}>
                <ul className="pr-people">
                  {hoursMeta.people.map((x, i) => (
                    <li key={i} className={x.crew === false ? 'is-out' : ''}>
                      <span>{x.name}<span style={{ color: 'var(--fg-3)' }}> · {x.role}{x.crew === false ? ' · not counted' : ''}</span></span>
                      <span className="pr-ph">{prHours(x.hours)} h</span>
                    </li>
                  ))}
                </ul>
              </td></tr>
            )}
            <tr className="pr-sub"><td className="pr-l">Training hours</td><td className="pr-v">{trainingCell()}</td><td className="pr-n">paid, but not counted as productive{trainPicks.length ? ' · ' + trainPicks.length + (trainPicks.length === 1 ? ' shift picked' : ' shifts picked') : (trainTyped ? ' · typed' : (canEdit ? ' · click the number to pick the training shifts' : ''))}</td></tr>
            <tr><td className="pr-l">Effective hours</td><td className={'pr-v' + (prNegHours(calc.crewHours) ? ' pr-neg' : '')}>{calc.crewHours == null ? '—' : prHours(calc.crewHours) + ' hr'}</td><td className="pr-n">total − training</td></tr>
            <tr><td className="pr-l">Actual productivity</td><td className={'pr-v' + (calc.actProductivity != null && calc.goalProductivity != null && calc.actProductivity < calc.goalProductivity ? ' pr-neg' : '')}>{calc.actProductivity == null ? '—' : '$' + calc.actProductivity.toFixed(2) + '/hr'}</td><td className="pr-n">gross ÷ (effective hours + {mgrNote}) · the goal at this gross is {(calc.goalProductivity != null ? '$' + calc.goalProductivity.toFixed(2) : '—')}</td></tr>
            <tr className="pr-total"><td className="pr-l">Pre-manager productivity</td><td className={'pr-v' + (calc.preMgrProductivity != null && calc.goalProductivity != null && calc.preMgrProductivity < calc.goalProductivity ? ' pr-neg' : '')}>{calc.preMgrProductivity == null ? '—' : '$' + calc.preMgrProductivity.toFixed(2) + '/hr'}</td><td className="pr-n">gross ÷ effective hours · above the {(calc.goalProductivity != null ? '$' + calc.goalProductivity.toFixed(2) : '—')} goal it earns the manager’s productivity bonus</td></tr>
          </tbody>
        </table>
      </div>

      {/* ---- Labor cost: crew wages, crew bonus, manager (base · productivity · food and paper · sales commission), tax ---- */}
      <div className="portal-card pr-sec">
        <div className="portal-card-header">
          <PrTitle icon={PR_ICONS.laborcost} pct={calc.laborPct}>Labor cost</PrTitle>
          <div className="pr-sec-sub" style={{ display: 'inline-flex', alignItems: 'center', gap: 10 }}>
            <span>wages from Square’s timecards · bonus from the Crew Lead Scorecard · click a number to change it for this period</span>
            {canEdit && <PBtn size="sm" icon="ri-refresh-line" disabled={busyHours || busyBonus} onClick={onSyncPay}>{busyHours || busyBonus ? 'Syncing…' : 'Sync again'}</PBtn>}
          </div>
        </div>
        <table className="pr-lines">
          <tbody>
            <tr>
              <td className="pr-l">Crew wages</td>
              <td className="pr-v">
                <span className="pr-vrow">
                  {hoursMeta && hoursMeta.source === 'square' && calc.crewTotal != null && <span className="pr-badge is-square" title={'Synced ' + prWhen(hoursMeta.synced_at)}>Square</span>}
                  <span className={calc.crewTotal == null ? 'pr-muted' : ''}>{prMoney(calc.crewTotal)}</span>
                </span>
              </td>
              <td className="pr-n">{calc.crewTotal == null ? 'not synced yet — the crew’s timecards priced at each card’s wage' : 'each timecard × its wage, training hours included' + (hoursMeta && hoursMeta.unpriced ? ' · ' + prHours(hoursMeta.unpriced) + ' h had no rate in Square' : '')}</td>
            </tr>
            <tr>
              <td className="pr-l">Crew bonus</td>
              <td className="pr-v">
                <span className="pr-vrow">
                  {bonusMeta && bonusMeta.source === 'scorecard' && calc.haveBonus && <span className="pr-badge is-api" title={'Fetched ' + prWhen(bonusMeta.synced_at)}>Scorecard</span>}
                  <span className={calc.haveBonus ? '' : 'pr-muted'}>{calc.haveBonus ? prMoney(calc.crewBonus) : '—'}</span>
                </span>
              </td>
              <td className="pr-n">
                <span style={{ display: 'inline-flex', alignItems: 'center', gap: 8, flexWrap: 'wrap' }}>
                  <span>{calc.haveBonus ? 'the Scorecard’s bonus for this period — sync again after the end-of-period ratings' : 'not synced yet — the Crew Lead Scorecard’s bonus for this period'}</span>
                  {bonusMeta && bonusMeta.leads && bonusMeta.leads.length > 0 && (
                    <button type="button" onClick={() => setLeadsOpen(o => !o)} style={{ background: 'none', border: 'none', padding: 0, cursor: 'pointer', color: 'var(--fg-2)', fontSize: 12, textDecoration: 'underline' }}>{leadsOpen ? 'Hide leads' : 'By lead'}</button>
                  )}
                </span>
              </td>
            </tr>
            {leadsOpen && bonusMeta && bonusMeta.leads && (
              <tr><td colSpan={3} style={{ padding: '6px 14px 12px 72px', background: '#FAFAFC' }}>
                <ul className="pr-people">
                  {bonusMeta.leads.map((x, i) => (
                    <li key={i}>
                      <span>{x.name}<span style={{ color: 'var(--fg-3)' }}> · {prHours(x.hours)} h × ${x.rate != null ? x.rate : '?'} × {x.final_pct}%</span></span>
                      <span className="pr-ph">{prMoney(x.bonus)}</span>
                    </li>
                  ))}
                </ul>
              </td></tr>
            )}
            <tr><td className="pr-l">Manager</td><td className="pr-v">{prMoney(calc.managerTotal)}</td><td className="pr-n">base + productivity + food and paper + sales commission{md ? ', on the ' + prDaysWord(workedOf14) + ' he worked' : ''}</td></tr>
            <tr className="pr-sub"><td className="pr-l">Unpaid time off</td><td className="pr-v">{offCell}</td><td className="pr-n">{md
              ? prDayRanges(md.offDays) + ' · his pay counts the ' + workedOf14 + ' of 14 days he worked' + (md.guessed.length ? ' · split by his share of the days for ' + md.guessed.join(' and ') + ' (no day-by-day figures)' : '')
              : (canEdit ? 'click None to mark the days he was off without pay' : 'none')}</td></tr>
            <tr className="pr-sub"><td className="pr-l">Base</td><td className="pr-v">{md ? prMoney(calc.managerBase) : fieldCell('manager_base')}</td><td className="pr-n">{md ? <>{fieldCell('manager_base')} per period × {workedOf14}/14 days</> : 'per period'}</td></tr>
            <tr className="pr-sub"><td className="pr-l">Productivity</td><td className={'pr-v' + (calc.managerProdBonus != null && calc.managerProdBonus < 0 ? ' pr-neg' : '')}>{prMoney(calc.managerProdBonus)}</td><td className="pr-n">{prodNote}</td></tr>
            <tr className="pr-sub"><td className="pr-l">Food and paper</td><td className="pr-v">{fieldCell('manager_food_bonus')}</td><td className="pr-n">not defined yet</td></tr>
            <tr className="pr-sub"><td className="pr-l">Sales commission</td><td className="pr-v">{prMoney(calc.managerCommission)}</td><td className="pr-n">{commNote}</td></tr>
            <tr><td className="pr-l">Labor cost</td><td className="pr-v">{prMoney(calc.laborCost)}</td><td className="pr-n">crew wages + crew bonus + manager</td></tr>
            <tr><td className="pr-l">Tax &amp; insurance</td><td className="pr-v">{prMoney(calc.tax)}</td><td className="pr-n">{fieldCell('tax_insurance_rate', 'Tax & insurance — % of labor cost, click to change for this period')} of labor cost</td></tr>
            <tr className="pr-total"><td className="pr-l">Total labor</td><td className="pr-v">{prMoney(calc.totalLabor)}</td><td className="pr-n">{calc.laborPct != null ? prPct(calc.laborPct) + ' of net sales' : 'sync the period’s hours and wages'}</td></tr>
          </tbody>
        </table>
      </div>

      {/* ---- Food & Paper ---- */}
      <PrCategoryCard cat={calc.foodPaperCat} net={calc.net} subtitle="% of net sales for now — later from purchases · click a number to change it for this period" cell={lineCell} />

      {/* ---- Marketing ---- */}
      <div className="portal-card pr-sec">
        <div className="portal-card-header">
          <PrTitle icon={PR_ICONS.marketing} pct={calc.marketingPct}>Marketing</PrTitle>
          <div className="pr-sec-sub" style={{ display: 'inline-flex', alignItems: 'center', gap: 10 }}>
            <span>Google &amp; Meta from their APIs · 3PD lines from the platform CSVs · the rest from Defaults, click to change</span>
            {canEdit && <PBtn size="sm" icon="ri-refresh-line" disabled={busyAds} onClick={onSyncAds}>{busyAds ? 'Fetching…' : 'Fetch Google & Meta'}</PBtn>}
          </div>
        </div>
        <table className="pr-lines">
          <tbody>
            {calc.apiLines.map(m => {
              const am = adsMeta[m.key];
              return (
                <tr key={m.key}>
                  <td className="pr-l">{m.label}</td>
                  <td className="pr-v">
                    <span className="pr-vrow">
                      {m.have && am && am.source === 'api' && <span className="pr-badge is-api" title={'Fetched ' + prWhen(am.synced_at)}>API</span>}
                      <span className={m.have ? '' : 'pr-muted'}>{m.have ? prMoney(m.value) : '—'}</span>
                    </span>
                  </td>
                  <td className="pr-n">{m.have ? 'spend on the period’s days, from the API' : 'not fetched yet — Fetch Google & Meta'}</td>
                </tr>
              );
            })}
            <tr><td className="pr-l">3PD Ads</td><td className="pr-v">{prMoney(calc.ads)}</td><td className="pr-n">ad spend and marketing fees charged by the platforms, from their CSVs</td></tr>
            <tr><td className="pr-l">3PD redemption</td><td className="pr-v">{prMoney(calc.redemption)}</td><td className="pr-n">offer redemption fees on the platforms, from their CSVs</td></tr>
            {calc.marketingCat.items.map(it => (
              <tr key={it.id}><td className="pr-l">{it.name}</td><td className="pr-v">{lineCell('marketing', it)}</td><td className="pr-n">{prLineDef(it)}{it.mode !== 'pct' ? ', prorated to ' + calc.days + (calc.days === 1 ? ' day' : ' days') : ''}</td></tr>
            ))}
            <tr className="pr-total"><td className="pr-l">Total marketing</td><td className="pr-v">{prMoney(calc.marketingTotal)}</td><td className="pr-n">{prPct(calc.marketingPct)} of net sales</td></tr>
          </tbody>
        </table>
      </div>

      {/* ---- the other P&L categories ---- */}
      {calc.otherCats.map(cat => (
        <PrCategoryCard key={cat.key} cat={cat} net={calc.net} subtitle={'% lines follow net sales · $ lines are prorated to ' + calc.days + ' days · click a number to change it for this period'} cell={lineCell} />
      ))}

      {/* ---- Bottom line ---- */}
      <PrBottomLine calc={calc} pending="fetch the period’s hours and wages" />

      <div className="pr-help">
        Every typed number saves as you leave the box. Direct sales are the Square sources that aren’t a delivery platform (Kiosk, Square Online, Point of Sale), summed over the period’s days from the same rollup Sales vs. Labor uses; their discount is gross minus net, their refunds are the ones Square issued during the period, pre-tax. Sync recomputes the period from Square. The platforms’ own exports carry the commission, merchant-funded discounts and refunds Square can’t see, so each period takes one CSV per platform. Total labor hours are the crew’s closed timecards for the period; the same timecards are the crew wages, each priced at the wage Square stamped on it. Whoever is ticked under Defaults (the manager) is left out of them because his clock-ins are partial. Training hours are the shifts picked as training, because Square can’t tell them apart: click the number to see the period’s clocked shifts a week at a time, and click the ones that were training. Effective hours are total − training. Actual productivity is gross ÷ (effective hours + the manager’s hours, the Manager hours figure under Defaults, counted by the day while a period runs), and the goal is a target for it that rises with sales: milestones under Defaults give the total labor hours to schedule at a two-week gross (the goal is gross ÷ those hours), with the goal hours in a straight line between them, never under the lowest milestone’s productivity, and one more hour per the Defaults dollar amount past the highest. Pre-manager productivity is gross ÷ effective hours alone: every hour the manager works himself is one the crew doesn’t, so it rises as he works more, and his productivity bonus is (pre-manager productivity − the goal) × the Manager bonus ratio under Defaults ({prRound2(prNum(defaultParams && defaultParams.manager_bonus_factor) != null ? prNum(defaultParams.manager_bonus_factor) : PR_PARAM_DEFAULTS.manager_bonus_factor)}): positive above the goal, a penalty below it. Goal labor hours are there for reference. The manager’s sales commission moves with net sales in steps: the rate at the base net under Defaults, one step up or down for each $1,000 of net above or below it (read at the two-week pace while a period runs), never under 0% or over the cap. The crew bonus is the Crew Lead Scorecard’s number for the period; Sync again on Pay refreshes wages and bonus together. Unpaid time off, under the manager’s pay, takes the days he was off out of it: his base is × the days he worked ÷ 14, his sales commission is the net sales of his days at the rate their two-week pace earns, his productivity bonus compares gross ÷ the crew’s effective hours on his days with the goal at that pace and is × the days he worked ÷ 14, and his hours in actual productivity are the Manager hours figure × the days he worked ÷ 14. Expense lines under Food &amp; Paper, Marketing and the other categories are % of net sales (Card processing is % of direct net sales: DoorDash, Uber Eats and GrubHub orders never go through our card processing) or $ per month / week / day prorated to the period’s days (a period in progress prorates to the days so far); the lines themselves live under Defaults, and a click on any value — a line, an hour figure, a rate — changes it for this period only; Reload defaults puts today’s Defaults back on the period.
      </div>

      {trainingOpen && canEdit && (
        <PrTrainingModal
          period={period}
          config={config}
          inputs={inputs}
          onSave={onSave}
          onClose={() => setTrainingOpen(false)}
          onType={() => { setTrainingOpen(false); setEditing('input|training_hours'); }}
        />
      )}
      {importFor && (
        <PrImportModal
          channel={PR_TPD.find(c => c.key === importFor)}
          period={period}
          existing={imports[importFor] || null}
          onSave={async (parsed, file) => { const ok = await onImport(importFor, parsed, file); if (ok) setImportFor(null); }}
          onClose={() => setImportFor(null)}
        />
      )}
      {offOpen && canEdit && (
        <PrMgrOffModal
          period={period}
          value={offList}
          onSave={(days) => { setOffOpen(false); onManagerOff(days); }}
          onClose={() => setOffOpen(false)}
        />
      )}
    </>
  );
};

// ------------------------------------------------------------------
// Import modal — pick the platform's CSV, see what was read, save
// ------------------------------------------------------------------
const PrImportModal = ({ channel, period, existing, onSave, onClose }) => {
  const [file, setFile] = useState(null);       // { name, text }
  const [parsed, setParsed] = useState(null);   // { figures, rows, warnings } | { error, headers }
  const [busy, setBusy] = useState(false);
  const fileRef = useRef(null);
  const startISO = isoDate(period.start), endISO = isoDate(period.end);
  const src = PR_CSV_SOURCE[channel.key] || null;   // which file to get (v26.33)

  const onPick = async (e) => {
    const f = e.target.files && e.target.files[0];
    e.target.value = '';
    if (!f) return;
    const text = await f.text();
    setFile({ name: f.name, text });
    try {
      const rows = prParseCsv(text);
      const parser = PR_PARSERS[channel.key];
      const out = parser.parse(rows, { startISO, endISO });
      if (out.error) setParsed({ error: out.error, headers: rows[0] || [] });
      else {
        setParsed({ figures: out.figures || {}, rows: out.rows || Math.max(0, rows.length - 1), warnings: (out.warnings || []).slice() });
      }
    } catch (err) {
      setParsed({ error: 'Couldn’t read the file: ' + (err.message || String(err)), headers: [] });
    }
  };
  const save = async () => {
    if (!parsed || parsed.error || busy) return;
    setBusy(true);
    try { await onSave(parsed, file); } finally { setBusy(false); }
  };
  const f = parsed && !parsed.error ? parsed.figures : null;

  return (
    <PModal open onClose={onClose} title={(existing ? 'Replace the ' : 'Upload the ') + channel.label + ' export'} width={560} footer={
      <>
        <PBtn variant="ghost" onClick={onClose}>Cancel</PBtn>
        <PBtn variant="primary" disabled={!f || busy} onClick={save}>{busy ? 'Saving…' : (existing ? 'Replace' : 'Save')}</PBtn>
      </>
    }>
      <div style={{ padding: 18, display: 'flex', flexDirection: 'column', gap: 14 }}>
        <div style={{ fontSize: 12.5, color: 'var(--fg-2)', lineHeight: 1.5 }}>
          {src ? (
            <>
              Get the {channel.label} file for <strong>{prPeriodLabel(period)}</strong>:
              <ol className="pr-src-steps">{src.steps.map((t, i) => <li key={i}>{t}</li>)}</ol>
              <div style={{ marginTop: 6 }}>Then pick it here. The numbers it reads show below before anything is saved{existing ? '; saving replaces ' + (existing.file_name || 'the current import') : ''}.</div>
            </>
          ) : (
            <>Export the period <strong>{prPeriodLabel(period)}</strong> from {channel.label}’s dashboard as a CSV and pick it here. The numbers it reads show below before anything is saved{existing ? '; saving replaces ' + (existing.file_name || 'the current import') : ''}.</>
          )}
        </div>
        <input ref={fileRef} type="file" accept=".csv,text/csv" style={{ display: 'none' }} onChange={onPick} />
        <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
          <PBtn size="md" icon="ri-upload-2-line" onClick={() => fileRef.current && fileRef.current.click()}>Choose CSV</PBtn>
          <span style={{ fontSize: 12.5, color: file ? 'var(--fg-1)' : 'var(--fg-3)' }}>{file ? file.name : 'No file chosen'}</span>
        </div>
        {parsed && parsed.error && (
          <div className="pr-err">
            {parsed.error}
            {parsed.headers && parsed.headers.length > 0 && (
              <div style={{ marginTop: 6, fontSize: 11.5, color: 'var(--fg-2)' }}>Columns in this file: {parsed.headers.join(' · ')}</div>
            )}
          </div>
        )}
        {f && (
          <>
            <div className="pr-preview">
              <table>
                <tbody>
                  <tr><td>Gross sales</td><td className="pr-v">{prMoney(f.gross)}</td></tr>
                  <tr><td>Commission</td><td className="pr-v pr-neg">{prMoney(-(Math.abs(f.commission) || 0))}</td></tr>
                  <tr><td>Discount (merchant)</td><td className="pr-v pr-neg">{prMoney(-(Math.abs(f.discount) || 0))}</td></tr>
                  <tr><td>Refund</td><td className="pr-v pr-neg">{prMoney(-(Math.abs(f.refund) || 0))}</td></tr>
                  <tr><td><strong>Net</strong></td><td className="pr-v"><strong>{prMoney((f.gross || 0) - Math.abs(f.commission || 0) - Math.abs(f.discount || 0) - Math.abs(f.refund || 0))}</strong></td></tr>
                  {(f.ads || 0) > 0 && <tr><td>Ads &amp; marketing fees → Marketing</td><td className="pr-v">{prMoney(Math.abs(f.ads))}</td></tr>}
                  {(f.redemption || 0) > 0 && <tr><td>Offer redemption fees → Marketing</td><td className="pr-v">{prMoney(Math.abs(f.redemption))}</td></tr>}
                  <tr><td style={{ color: 'var(--fg-3)' }}>Orders · dates</td><td className="pr-v" style={{ color: 'var(--fg-3)' }}>{f.orders != null ? prInt(f.orders) : '—'}{f.date_from ? ' · ' + f.date_from + ' → ' + f.date_to : ''}</td></tr>
                </tbody>
              </table>
            </div>
            {parsed.warnings.map((w, i) => <div key={i} className="pr-warn">{w}</div>)}
          </>
        )}
      </div>
    </PModal>
  );
};

// ------------------------------------------------------------------
// Unpaid time off (v26.33) — the manager's days off in one period
// ------------------------------------------------------------------
// The period's 14 days as its two weeks; a click marks a day off or back
// on, and a shift-click marks every day from the last one clicked, so a
// range is two clicks. Nothing is written until Save.
const PrMgrOffModal = ({ period, value, onSave, onClose }) => {
  const all = period.days.map(d => isoDate(d));
  const [sel, setSel] = useState(() => new Set(value || []));
  const [last, setLast] = useState(null);
  const todayISO = isoDate(new Date());
  const click = (iso, e) => {
    const next = new Set(sel);
    const on = !next.has(iso);
    if (e.shiftKey && last && last !== iso) {
      const a = all.indexOf(last), b = all.indexOf(iso);
      for (let k = Math.min(a, b); k <= Math.max(a, b); k++) { if (on) next.add(all[k]); else next.delete(all[k]); }
    } else if (on) next.add(iso);
    else next.delete(iso);
    setSel(next);
    setLast(iso);
  };
  const list = all.filter(d => sel.has(d));
  const unchanged = list.join() === (value || []).slice().sort().join();
  return (
    <PModal open onClose={onClose} title="Unpaid time off" width={600} footer={
      <>
        {list.length > 0 && <PBtn variant="ghost" onClick={() => setSel(new Set())}>Clear</PBtn>}
        <span style={{ flex: 1 }} />
        <PBtn variant="ghost" onClick={onClose}>Cancel</PBtn>
        <PBtn variant="primary" disabled={unchanged} onClick={() => onSave(list)}>Save</PBtn>
      </>
    }>
      <div style={{ padding: 18, display: 'flex', flexDirection: 'column', gap: 14 }}>
        <div style={{ fontSize: 12.5, color: 'var(--fg-2)', lineHeight: 1.5 }}>
          Click each day the manager was off without pay in <strong>{prPeriodLabel(period)}</strong>. To mark a range, click its first day, then shift-click its last. His base, productivity bonus, sales commission and hours then count only the days he worked.
        </div>
        <div className="pr-off-grid">
          {all.slice(0, 7).map(iso => <div key={'wd' + iso} className="pr-off-wd">{prDateFromISO(iso).toLocaleDateString('en-US', { weekday: 'short' })}</div>)}
          {all.map(iso => {
            const on = sel.has(iso);
            return (
              <button key={iso} type="button" className={'pr-off-day' + (on ? ' is-on' : '') + (iso === todayISO ? ' is-today' : '')} aria-pressed={on} onClick={(e) => click(iso, e)}
                title={on ? 'Off without pay. Click to count it as worked.' : 'Click to mark this day off without pay.'}>
                <span className="pr-off-date">{prShort(prDateFromISO(iso))}</span>
                <span className="pr-off-tag">{on ? 'Off' : 'Worked'}</span>
              </button>
            );
          })}
        </div>
        <div style={{ fontSize: 12.5, color: 'var(--fg-2)', lineHeight: 1.5 }}>
          {list.length
            ? <><strong>{prDaysWord(list.length)} off</strong>: {prDayRanges(list)}. He worked {PR_PERIOD_DAYS - list.length} of {PR_PERIOD_DAYS} days.</>
            : 'No days off: his pay counts all 14 days.'}
        </div>
      </div>
    </PModal>
  );
};

// ------------------------------------------------------------------
// Training shifts (v26.31) — a full-screen picker over one period
// ------------------------------------------------------------------
// Ryan: "open a full screen popup and show the clocked in shifts for the
// whole week (I can switch between the 1st and 2nd week), and let me click
// the shifts that are training shifts", with Square's schedule grid as the
// picture: a row per team member, a column per day, a block per shift.
// The shifts are read fresh from Square on open (square-hours, everyone +
// shifts) and nothing is written until a shift is clicked. A click saves at
// once, like every other number on the page: the picks, their total as
// training_hours and, unless the period's total was typed, the crew hours and
// wages of that same read, so the total always holds every shift on screen.
// People left out of the crew under Defaults have no row: their hours are
// not in the total, so there is nothing of theirs to take out.
const PrTrainingModal = ({ period, config, inputs, onSave, onClose, onType }) => {
  const startISO = isoDate(period.start), endISO = isoDate(period.end);
  const [st, setSt] = useState({ loading: true, err: '', data: null, at: null });
  const [tries, setTries] = useState(0);
  // The week on screen: the second one only while today falls in it.
  const [week, setWeek] = useState(() => (isoDate(new Date()) >= isoDate(period.days[7]) && isoDate(new Date()) <= endISO) ? 1 : 0);

  useEffect(() => {
    let cancelled = false;
    setSt({ loading: true, err: '', data: null, at: null });
    (async () => {
      try {
        const res = await window.supa.functions.invoke('square-hours', { body: { start_date: startISO, end_date: endISO, everyone: true, shifts: true } });
        if (res.error || !res.data || res.data.error) throw new Error((res.data && res.data.error) || (res.error && res.error.message) || 'no answer from Square');
        // An older square-hours answers without the list (function and portal out of step).
        if (!Array.isArray(res.data.shifts)) throw new Error('the shift list isn’t available yet');
        if (!cancelled) setSt({ loading: false, err: '', data: res.data, at: new Date().toISOString() });
      } catch (err) {
        if (!cancelled) setSt({ loading: false, err: err.message || String(err), data: null, at: null });
      }
    })();
    return () => { cancelled = true; };
  }, [startISO, endISO, tries]);

  useEffect(() => {
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    document.addEventListener('keydown', onKey);
    return () => document.removeEventListener('keydown', onKey);
  }, [onClose]);

  const stored = prTrainPicks(inputs);
  const hoursMeta = (inputs.meta && inputs.meta.hours) || null;
  const typedTotal = !!hoursMeta && hoursMeta.source === 'typed';
  const typedTraining = !stored.length && (inputs.training_hours || 0) > 0;

  const shifts = st.data ? prCrewShifts(st.data.shifts, config) : [];
  const fresh = st.data ? prHoursFromSquare(st.data, config) : null;
  // What is picked, as Square has those cards now; `rec.dropped` are gone.
  const rec = st.data ? prTrainReconcile(stored, shifts) : { kept: stored, dropped: 0, changed: 0 };
  const picked = rec.kept;
  const pickedIds = new Set(picked.map(x => x.id));
  const pickedHours = prRound2(picked.reduce((a, x) => a + (prNum(x.hours) || 0), 0));

  const save = (list) => {
    const t = prTrainInputs(list.slice().sort((a, b) => Date.parse(a.start_at) - Date.parse(b.start_at)));
    const patch = { training_hours: t.training_hours, meta: { training: t.meta.training } };
    if (!typedTotal && fresh) {
      const hp = prHoursInputs(fresh, st.at);
      patch.act_hours = hp.act_hours; patch.crew_wages = hp.crew_wages; patch.meta.hours = hp.meta.hours;
    }
    onSave({ inputs: patch });
  };
  const toggle = (x) => {
    if (x.open) return;
    save(pickedIds.has(x.id) ? picked.filter(k => k.id !== x.id) : picked.concat([prTrainShift(x)]));
  };

  // Rows: everyone in the crew with a shift in the period, by name, so the
  // list holds still when the week changes.
  const people = [];
  const seen = {};
  shifts.forEach(x => {
    if (seen[x.team_member_id]) return;
    seen[x.team_member_id] = true;
    people.push({ tm: x.team_member_id, name: x.name || ('Unlinked ' + String(x.team_member_id || '').slice(-6)) });
  });
  people.sort((a, b) => a.name.localeCompare(b.name));
  const days = period.days.slice(week * 7, week * 7 + 7);
  const dayISOs = days.map(d => isoDate(d));
  const cell = {};
  shifts.forEach(x => { if (dayISOs.indexOf(x.day) >= 0) (cell[x.team_member_id + '|' + x.day] = cell[x.team_member_id + '|' + x.day] || []).push(x); });
  const weekLabel = (i) => 'Week ' + (i + 1) + ' · ' + prShort(period.days[i * 7]) + ' – ' + prShort(period.days[i * 7 + 6]);
  const squareMoved = !!fresh && !typedTotal && inputs.act_hours != null && Math.abs(fresh.crewHours - inputs.act_hours) >= 0.01;

  return (
    <div className="pr-tr-back" onMouseDown={e => { if (e.target === e.currentTarget) onClose(); }}>
      <div className="pr-tr" role="dialog" aria-modal="true" aria-label="Training shifts">
        <div className="pr-tr-head">
          <div style={{ minWidth: 0, flex: 1 }}>
            <div className="pr-tr-title">Training shifts</div>
            <div className="pr-tr-sub2">{prPeriodLabel(period)} · Click the shifts that were training. They stay paid and come out of effective hours.</div>
          </div>
          <PSegment options={[{ value: 0, label: weekLabel(0) }, { value: 1, label: weekLabel(1) }]} value={week} onChange={setWeek} />
          {/* a typed figure with nothing picked must not read as 0 */}
          <div className="pr-tr-sum">{typedTraining
            ? <><b>{prHours(inputs.training_hours)} hr</b> training, typed</>
            : <><b>{picked.length}</b> {picked.length === 1 ? 'shift' : 'shifts'} · <b>{prHours(pickedHours)} hr</b> training</>}</div>
          <PBtn variant="primary" onClick={onClose}>Done</PBtn>
        </div>

        {st.data && (typedTraining || rec.dropped > 0 || squareMoved || typedTotal) && (
          <div className="pr-tr-notes">
            {typedTraining && <div className="pr-warn">{prHours(inputs.training_hours)} hr of training were typed for this period. Clicking a shift replaces that number with the hours of the shifts you pick.</div>}
            {rec.dropped > 0 && <div className="pr-warn">{rec.dropped === 1 ? 'One picked shift is' : rec.dropped + ' picked shifts are'} no longer in Square. {rec.dropped === 1 ? 'It comes' : 'They come'} off with your next click here, or with Sync again.</div>}
            {squareMoved && <div className="pr-warn">Square now shows {prHours(fresh.crewHours)} clocked crew hours; this period holds {prHours(inputs.act_hours)} from its last sync. Clicking a shift brings the period up to date.</div>}
            {typedTotal && <div className="pr-warn">Total labor hours were typed for this period, so picking shifts changes the training hours only.</div>}
          </div>
        )}

        <div className="pr-tr-body">
          {st.loading ? (
            <div className="pr-tr-state">Reading the clocked shifts from Square…</div>
          ) : st.err ? (
            <div className="pr-tr-state">
              <div className="pr-err" style={{ textAlign: 'left', maxWidth: 520, margin: '0 auto' }}>Couldn’t list the shifts: {st.err}.</div>
              <div style={{ marginTop: 14, display: 'flex', justifyContent: 'center', gap: 8 }}>
                <PBtn onClick={() => setTries(n => n + 1)}>Try again</PBtn>
                <PBtn variant="ghost" onClick={onType}>Type the hours instead</PBtn>
              </div>
            </div>
          ) : people.length === 0 ? (
            <div className="pr-tr-state">No clocked shifts in this period yet.</div>
          ) : (
            <table className="pr-tr-grid">
              <thead>
                <tr>
                  <th className="pr-tr-who">Team member</th>
                  {days.map((d, i) => <th key={dayISOs[i]}>{d.toLocaleDateString('en-US', { weekday: 'short' })} {d.getMonth() + 1}/{d.getDate()}</th>)}
                </tr>
              </thead>
              <tbody>
                {people.map(pp => {
                  const mine = dayISOs.reduce((a, iso) => a.concat(cell[pp.tm + '|' + iso] || []), []);
                  const wkHours = mine.reduce((a, x) => a + (x.hours || 0), 0);
                  const wkTrain = mine.reduce((a, x) => a + (pickedIds.has(x.id) ? (x.hours || 0) : 0), 0);
                  return (
                    <tr key={pp.tm}>
                      <td className="pr-tr-who">
                        <div className="pr-tr-name" title={pp.name}>{pp.name}</div>
                        <div className="pr-tr-sub">{prHours(wkHours)} h{wkTrain > 0 && <span className="is-train"> · {prHours(wkTrain)} h training</span>}</div>
                      </td>
                      {dayISOs.map(iso => (
                        <td key={iso}>
                          {(cell[pp.tm + '|' + iso] || []).map(x => x.open ? (
                            <div key={x.id} className="pr-tr-shift is-open" title="Still clocked in. It can be picked once the shift is closed in Square.">
                              <div className="pr-tr-time">{prClock(x.start_at)} – now</div>
                              <div className="pr-tr-meta">still clocked in</div>
                            </div>
                          ) : (
                            <button key={x.id} type="button" className={'pr-tr-shift' + (pickedIds.has(x.id) ? ' is-on' : '')} aria-pressed={pickedIds.has(x.id)} onClick={() => toggle(x)}
                              title={pickedIds.has(x.id) ? 'Training. Click to count it as a regular shift again.' : 'Click to mark this shift as training.'}>
                              <div className="pr-tr-time">{prClockRange(x.start_at, x.end_at)}</div>
                              <div className="pr-tr-meta">{pickedIds.has(x.id) && <PIcon name="ri-check-line" size={12} />}{prHours(x.hours)} h{pickedIds.has(x.id) ? ' · Training' : ''}</div>
                            </button>
                          ))}
                        </td>
                      ))}
                    </tr>
                  );
                })}
              </tbody>
            </table>
          )}
        </div>

        <div className="pr-tr-foot">
          <span className="pr-tr-key"><span className="pr-tr-swatch" /> Clocked shift</span>
          <span className="pr-tr-key"><span className="pr-tr-swatch is-on" /> Training</span>
          <span style={{ flex: 1 }} />
          {picked.length > 0 && <button type="button" className="pr-apply" style={{ marginLeft: 0 }} onClick={() => { if (window.confirm('Unpick all ' + picked.length + (picked.length === 1 ? ' training shift' : ' training shifts') + ' for this period? Training hours go back to 0.')) save([]); }}>Clear all</button>}
        </div>
      </div>
    </div>
  );
};

// ------------------------------------------------------------------
// Inline editor (v25.04): a number, and for expense lines the way it
// counts (% of net / $ per month / week / day). Enter saves, Escape cancels.
// ------------------------------------------------------------------
const PrLineEditor = ({ value, modeKey, allowMode, unit, min, onSave, onCancel }) => {
  const [v, setV] = useState(value == null ? '' : String(value));
  const [m, setM] = useState(modeKey || 'amt|month');
  const [err, setErr] = useState('');
  const ref = useRef(null);
  useEffect(() => { if (ref.current) { ref.current.focus(); ref.current.select(); } }, []);
  const save = () => {
    const n = prNum(v);
    if (n == null) { onCancel(); return; }
    // A floor (v26.02, the manager's hours): below it the editor stays open.
    if (min != null && n < min) { setErr('at least ' + prRound2(min)); return; }
    onSave(allowMode ? Object.assign({ value: n }, prModeFields(m)) : { value: n });
  };
  return (
    <span className="pr-editor" onClick={e => e.stopPropagation()}>
      <input ref={ref} className="portal-input pr-in" {...PR_NO_PM} inputMode="decimal" value={v}
        onChange={e => { setV(e.target.value); setErr(''); }}
        onKeyDown={e => { if (e.key === 'Enter') { e.preventDefault(); save(); } if (e.key === 'Escape') { e.preventDefault(); onCancel(); } }} />
      {allowMode
        ? <select className="portal-input pr-sel" value={m} onChange={e => setM(e.target.value)}>{PR_LINE_MODES.map(o => <option key={o.value} value={o.value}>{o.label}</option>)}</select>
        : (unit ? <span className="pr-unit">{unit}</span> : null)}
      <PBtn size="sm" variant="primary" onClick={save}>Save</PBtn>
      <PBtn size="sm" variant="ghost" onClick={onCancel}>Cancel</PBtn>
      {err && <span className="pr-simwarn" style={{ fontSize: 12 }}>{err}</span>}
    </span>
  );
};

// ------------------------------------------------------------------
// One expense category on the period: its lines as plain numbers, each a
// click away from being changed for this period
// ------------------------------------------------------------------
const PrCategoryCard = ({ cat, net, subtitle, cell, tips }) => (
  // tips (v26.09, the Simulator): the subtitle and every note move into an ⓘ.
  <div className="portal-card pr-sec">
    <div className="portal-card-header">
      <PrTitle icon={PR_ICONS[cat.key] || PR_ICONS.other} hint={tips ? subtitle : null} pct={net > 0 ? cat.pct : null}>{cat.name}</PrTitle>
      {!tips && <div className="pr-sec-sub">{subtitle}</div>}
    </div>
    <table className={'pr-lines' + (tips ? ' pr-tipped' : '')}>
      <tbody>
        {cat.items.map(it => {
          const note = prLineDef(it) + ((it.mode !== 'pct' || prPctOf(it) === 'direct') && net > 0 && it.amount ? ' — ' + prPct(it.amount / net) + ' of net sales' : '');
          return (
            <tr key={it.id}>
              <td className="pr-l">{it.name}{tips && <PrHint text={note + '.'} />}</td>
              <td className="pr-v">{cell(cat.key, it)}</td>
              {!tips && <td className="pr-n">{note}</td>}
            </tr>
          );
        })}
        {cat.items.length === 0 && <tr><td colSpan={tips ? 2 : 3} className="pr-n" style={{ padding: '12px 14px' }}>No lines yet — add them under Defaults.</td></tr>}
        <tr className="pr-total"><td className="pr-l">Total {cat.name}{tips && <PrHint text={prPct(cat.pct) + ' of net sales.'} />}</td><td className="pr-v">{prMoney(cat.total)}</td>{!tips && <td className="pr-n">{prPct(cat.pct)} of net sales</td>}</tr>
      </tbody>
    </table>
  </div>
);

// ------------------------------------------------------------------
// Left after everything — the bottom line, shared by a period and the
// Simulator (v26.00)
// ------------------------------------------------------------------
const prNeg = (n) => n ? prMoney(-n) : prMoney(0);
const prNegCls = (n) => (n ? ' pr-neg' : '');
const PrBottomLine = ({ calc, pending, tips }) => {
  // tips (v26.09, the Simulator): the notes move into an ⓘ beside each label.
  const note = (content) => tips ? null : <td className="pr-n">{content}</td>;
  const hint = (content) => (tips && content) ? <PrHint text={content} /> : null;
  const share = (x) => prPct(x) + ' of net sales.';
  return (
    <div className="portal-card pr-sec">
      <div className="portal-card-header">
        <PrTitle icon={PR_ICONS.left} pct={calc.remainingPct} hint={tips ? 'Net sales − labor − food & paper − marketing − the other categories.' : null}>Left after everything</PrTitle>
        {!tips && <div className="pr-sec-sub">net sales − labor − food &amp; paper − marketing − the other categories</div>}
      </div>
      <table className={'pr-lines' + (tips ? ' pr-tipped' : '')}>
        <tbody>
          <tr><td className="pr-l">Net sales</td><td className="pr-v">{prMoney(calc.net)}</td>{note('')}</tr>
          <tr className="pr-sub"><td className="pr-l">Total labor{hint(share(calc.laborPct))}</td><td className={'pr-v' + prNegCls(calc.totalLabor)}>{calc.totalLabor != null ? prNeg(calc.totalLabor) : '—'}</td>{note(prPct(calc.laborPct))}</tr>
          <tr className="pr-sub"><td className="pr-l">Food &amp; Paper{hint(share(calc.foodPaperCat.pct))}</td><td className={'pr-v' + prNegCls(calc.foodPaper)}>{prNeg(calc.foodPaper)}</td>{note(prPct(calc.foodPaperCat.pct))}</tr>
          <tr className="pr-sub"><td className="pr-l">Marketing{hint(share(calc.marketingPct))}</td><td className={'pr-v' + prNegCls(calc.marketingTotal)}>{prNeg(calc.marketingTotal)}</td>{note(prPct(calc.marketingPct))}</tr>
          {calc.otherCats.map(cat => (
            <React.Fragment key={cat.key}>
              {cat.key === 'itda' && (
                <tr><td className="pr-l">Before ITDA (EBITDA){hint(calc.ebitda != null && calc.net > 0 ? share(calc.ebitda / calc.net) : '')}</td><td className={'pr-v' + (calc.ebitda != null && calc.ebitda < 0 ? ' pr-neg' : '')}>{prMoney(calc.ebitda)}</td>{note(calc.ebitda != null && calc.net > 0 ? prPct(calc.ebitda / calc.net) + ' of net sales' : '')}</tr>
              )}
              <tr className="pr-sub"><td className="pr-l">{cat.name}{hint(share(cat.pct))}</td><td className={'pr-v' + prNegCls(cat.total)}>{prNeg(cat.total)}</td>{note(prPct(cat.pct))}</tr>
            </React.Fragment>
          ))}
          <tr className="pr-total"><td className="pr-l">Left{hint(calc.remainingPct != null ? share(calc.remainingPct) : pending)}</td><td className={'pr-v' + (calc.remaining != null && calc.remaining < 0 ? ' pr-neg' : '')}>{prMoney(calc.remaining)}</td>{note(calc.remainingPct != null ? prPct(calc.remainingPct) + ' of net sales' : pending)}</tr>
        </tbody>
      </table>
    </div>
  );
};

// ------------------------------------------------------------------
// Simulator (v26.00) — one what-if pay period, "for Omar to play around the
// numbers and see what next period would look like". Ryan's spec: gross and
// net sales typed (net is usually 92% of gross; Apply fills it), the hours
// typed through a popup for ONE week and doubled for the pay period (v26.02:
// total labor hours, manager hours at least half the Defaults figure,
// training hours; crew hours are the rest), every default-driven
// number set and shown plain, crew wages at a flat $12.50 an hour, and
// Google / Meta "adopted from last period". The 3PD ad and redemption fees
// and the crew bonus come from last period the same way. Nothing is written
// to a period; the typed numbers stay in this browser (usePersistent).
// ------------------------------------------------------------------

// What the Simulator borrows from "last period": for each figure, the newest
// FINISHED period it was fetched for after that period ended. A mid-period
// fetch is only part of the period, and a period that has just ended isn't
// closed out yet, so the one before it stands in until it is.
const prSimCarry = (rows) => {
  const now = new Date();
  const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
  const done = (rows || []).filter(r => r.period.end < today);   // newest first
  const after = (r, iso) => !!iso && new Date(iso) >= prAddDays(r.period.end, 1);
  const closed = (r, m) => !m || m.source === 'typed' || after(r, m.synced_at);
  const meta = (r) => r.inputs.meta || {};
  const label = (r) => prShort(r.period.start) + ' – ' + prShort(r.period.end);
  const adsRow = done.find(r => PR_API_ADS.some(a => r.inputs.marketing[a.key] != null && closed(r, (meta(r).ads || {})[a.key])));
  const tpdRow = done.find(r => PR_TPD.some(c => r.imports[c.key] && after(r, r.imports[c.key].uploaded_at)));
  const bonusRow = done.find(r => r.inputs.crew_bonus != null && closed(r, meta(r).bonus));
  const hoursRow = done.find(r => r.inputs.act_hours > 0 && closed(r, meta(r).hours));
  // Sales for the day popup: the finished period whose platform CSVs are in
  // (so gross covers every channel), else the newest finished one.
  const salesRow = tpdRow || done.find(r => r.calc.gross > 0) || null;
  const by = {};
  if (tpdRow) PR_TPD.forEach(c => { const x = tpdRow.calc.ch[c.key]; by[c.key] = { ads: x.ads || 0, redemption: x.redemption || 0 }; });
  return {
    ads: adsRow ? { label: label(adsRow), google: adsRow.inputs.marketing.google, meta: adsRow.inputs.marketing.meta } : null,
    tpd: tpdRow ? { label: label(tpdRow), by } : null,
    bonus: bonusRow ? { label: label(bonusRow), value: bonusRow.inputs.crew_bonus } : null,
    sales: salesRow && salesRow.calc.gross > 0 ? { label: label(salesRow), perDay: salesRow.calc.gross / salesRow.period.days.length } : null,
    hours: hoursRow ? { label: label(hoursRow), act: hoursRow.inputs.act_hours, training: hoursRow.inputs.training_hours || 0, manager: hoursRow.calc.managerHours || 0 } : null,
  };
};

// One full period at the typed numbers, through the period page's own
// formulas. The carried 3PD fees go in as each platform's figures with no
// sales of their own — gross and net are typed as totals.
const prSimCompute = ({ gross, net, clocked, manager, training, carry, params, managerBase, days }) => {
  // Two-week hours here. act_hours is the crew's share of the actual labor
  // hours (trainees included), the way a period's Square figure is.
  const act = clocked != null ? clocked - manager : null;
  const imports = {};
  if (carry.tpd) PR_TPD.forEach(c => { const x = carry.tpd.by[c.key]; if (x && (x.ads || x.redemption)) imports[c.key] = { figures: { ads: x.ads, redemption: x.redemption } }; });
  return prCompute({
    direct: { gross, discount: gross - net, refund: 0, days },
    imports,
    inputs: {
      act_hours: act, training_hours: training || 0,
      crew_wages: act != null ? Math.max(0, act) * PR_SIM_CREW_WAGE : null,
      crew_bonus: carry.bonus ? carry.bonus.value : null,
      manager_base: managerBase, manager_food_bonus: 0,
      marketing: { google: carry.ads ? carry.ads.google : null, meta: carry.ads ? carry.ads.meta : null },
    },
    params: Object.assign({}, params, { manager_hours: manager }), periodDays: days,
  });
};

// The hours are typed through a popup (Ryan: "make it a button, it will
// open a popup to input the number"). Empty clears the figure.
const PrSimHoursModal = ({ title, hint, reference, value, min, minLabel, prefix, unit, onSave, onClose }) => {
  const [v, setV] = useState(value == null ? '' : String(value));
  const ref = useRef(null);
  useEffect(() => { if (ref.current) { ref.current.focus(); ref.current.select(); } }, []);
  const n = prNum(v);
  const empty = String(v).trim() === '';
  const floor = min || 0;
  const ok = empty || (n != null && n >= floor);
  const save = () => { if (ok) onSave(empty ? null : prRound2(n)); };
  return (
    <PModal open onClose={onClose} width={440} title={title} footer={
      <>
        <PBtn variant="ghost" onClick={onClose}>Cancel</PBtn>
        <PBtn variant="primary" disabled={!ok} onClick={save}>Save</PBtn>
      </>
    }>
      <div style={{ padding: 18, display: 'flex', flexDirection: 'column', gap: 10 }}>
        <div style={{ fontSize: 13, color: 'var(--fg-2)', lineHeight: 1.5 }}>{hint}</div>
        <span className="pr-simin">
          {prefix && <span className="pr-simfix">{prefix}</span>}
          <input ref={ref} className="portal-input pr-in" {...PR_NO_PM} inputMode="decimal" aria-label={title} placeholder="0" value={v}
            onChange={e => setV(e.target.value)}
            onKeyDown={e => { if (e.key === 'Enter') { e.preventDefault(); save(); } if (e.key === 'Escape') { e.preventDefault(); onClose(); } }} />
          {unit !== '' && <span className="pr-unit">{unit || 'hr'}</span>}
        </span>
        {!ok && <div className="pr-simwarn" style={{ fontSize: 12 }}>{n != null && n < floor && minLabel ? minLabel : (prefix ? 'Type an amount, or leave it empty.' : 'Type a number of hours, or leave it empty.')}</div>}
        {reference && <div className="pr-simref">{reference}</div>}
      </div>
    </PModal>
  );
};

// The Simulator's numbers are shared (v26.20, Ryan: "if I go in and Omar go
// in on our own computer, the numbers are tied to our browser storage or
// caching, instead of seeing one same numbers"). One row per input in
// period_report_sim — day:sun … day:sat, clocked, manager, training — read
// on open and kept in step by realtime, so a change shows on every open
// Simulator. A save writes only the input it changed, so two people can't
// overwrite each other's other numbers. Clear writes '' to every input
// rather than deleting: a filtered realtime channel delivers UPDATEs but
// not DELETEs. RLS lets the Simulate and Edit levels write.
const PR_SIM_INPUTS = ['day:sun', 'day:mon', 'day:tue', 'day:wed', 'day:thu', 'day:fri', 'day:sat', 'clocked', 'manager', 'training'];
const usePrSimShared = () => {
  const [byKey, setByKey] = useState({});
  const [loaded, setLoaded] = useState(false);
  const [error, setError] = useState(null);
  useEffect(() => {
    if (!window.supa) { setLoaded(true); return; }
    let alive = true;
    window.supa.from('period_report_sim').select('key, value, updated_by, updated_at').eq('restaurant_id', window.RESTAURANT_ID)
      .then(({ data, error: err }) => {
        if (!alive) return;
        if (err) setError(err.message || 'Couldn’t load the shared numbers.');
        const m = {};
        (data || []).forEach(r => { m[r.key] = r; });
        setByKey(m);
        setLoaded(true);
      });
    const ch = window.supa.channel('period-report-sim:' + window.RESTAURANT_ID)
      .on('postgres_changes', { event: '*', schema: 'public', table: 'period_report_sim', filter: 'restaurant_id=eq.' + window.RESTAURANT_ID }, (p) => {
        const r = p.new && p.new.key ? p.new : null;
        if (r) setByKey(prev => Object.assign({}, prev, { [r.key]: r }));
      })
      .subscribe();
    return () => { alive = false; window.supa.removeChannel(ch); };
  }, []);
  // entries: [[key, value], …] — optimistic here, then one upsert.
  const write = async (entries) => {
    const now = new Date().toISOString();
    const out = entries.map(([key, value]) => ({
      restaurant_id: window.RESTAURANT_ID, key, value: value == null ? '' : String(value),
      updated_by: window.currentAdminEmail || null, updated_at: now,
    }));
    setByKey(prev => { const n = Object.assign({}, prev); out.forEach(r => { n[r.key] = r; }); return n; });
    if (!window.supa) return;
    const { error: err } = await window.supa.from('period_report_sim').upsert(out, { onConflict: 'restaurant_id,key' });
    setError(err ? (err.message || 'Couldn’t save — try again.') : null);
  };
  // The newest change, for the "last change by …" line.
  const last = Object.values(byKey).reduce((a, r) => (!a || String(r.updated_at || '') > String(a.updated_at || '') ? r : a), null);
  return { byKey, loaded, error, write, last };
};
// Who made a change, as a first name ("you" for yourself); the address
// only when no crew record matches it.
const prSimWho = (email) => {
  const e = String(email || '').trim().toLowerCase();
  if (!e) return '';
  if (e === String(window.currentAdminEmail || '').trim().toLowerCase()) return 'you';
  const hit = (window.SAMPLE_STAFF || []).find(x => String(x.email || '').trim().toLowerCase() === e);
  return hit ? String(hit.name || '').split(/\s+/)[0] : e.split('@')[0];
};

const PrSimulator = ({ rows, config, onBack }) => {
  const shared = usePrSimShared();
  const s = { days: {}, clocked: '', manager: '', training: '' };
  Object.keys(shared.byKey).forEach(k => {
    const v = shared.byKey[k] && shared.byKey[k].value != null ? String(shared.byKey[k].value) : '';
    if (k.indexOf('day:') === 0) s.days[k.slice(4)] = v;
    else if (k in s) s[k] = v;
  });
  const set = (k, v) => shared.write([[k, v]]);
  const setDay = (key, v) => shared.write([['day:' + key, v]]);
  const clearAll = () => {
    if (!window.confirm('Clear the Simulator’s numbers? They’re shared, so this clears them for everyone.')) return;
    shared.write(PR_SIM_INPUTS.map(k => [k, '']));
  };
  const [hoursFor, setHoursFor] = useState(null);   // 'clocked' | 'manager' | 'training' — the open popup
  const [dayFor, setDayFor] = useState(null);       // index into PR_SIM_DAYS — the open popup
  // One week of sales, day by day (v26.09): a typed estimate or Ryan's seed.
  const dayVals = PR_SIM_DAYS.map(d => { const n = prNum(s.days[d.key]); return n != null ? Math.max(0, n) : d.seed; });
  const weekGross = dayVals.reduce((a, n) => a + n, 0);
  const gross = prRound2(weekGross * 2);
  const net = prRound2(gross * PR_SIM_NET_RATIO);
  const params = useMemo(() => prParamsFor(null, config), [config]);
  // The typed hours are ONE week; the pay period is twice that. The manager's
  // week can't go below half the Defaults figure (35 of 70).
  const minWeek = (prNum(params.manager_hours) != null ? prNum(params.manager_hours) : PR_PARAM_DEFAULTS.manager_hours) / 2;
  // Until hours are typed, the schedule follows the goal (v26.11, Ryan:
  // "always make the schedule based on the productivity goal"): goal hours
  // for the week's sales plus training, so actual productivity lands on it.
  const typedClocked = prNum(s.clocked) != null ? Math.abs(prNum(s.clocked)) : null;
  const manager1 = Math.max(minWeek, prNum(s.manager) != null ? prNum(s.manager) : minWeek);
  const training1 = prNum(s.training) != null ? Math.abs(prNum(s.training)) : 0;
  const managerBase = prInputsFor(null, config).manager_base;
  const carry = useMemo(() => prSimCarry(rows), [rows]);
  const days = rows && rows.length ? rows[0].period.days.length : 14;
  const goalHours2 = gross > 0 ? prGoalHours(gross, params, days) : null;
  const clocked1 = typedClocked != null ? typedClocked : (goalHours2 != null ? prRound2(goalHours2 / 2 + training1) : null);
  const ready = gross > 0;
  const calc = ready ? prSimCompute({ gross, net, clocked: clocked1 == null ? null : clocked1 * 2, manager: manager1 * 2, training: training1 * 2, carry, params, managerBase, days }) : null;
  const ratioLabel = Math.round(PR_SIM_NET_RATIO * 100) + '%';
  const touched = PR_SIM_DAYS.some(d => prNum(s.days[d.key]) != null) || ['clocked', 'manager', 'training'].some(k => String(s[k] || '') !== '');
  // Set numbers read plain — no dotted underline, nothing to click.
  const plain = (catKey, it) => <span>{prMoney(it.amount)}</span>;
  const hoursBtn = (k, v, empty) => (
    <PBtn size="sm" icon="ri-pencil-line" title="Click to type one week’s hours" onClick={() => setHoursFor(k)}>{v != null ? prHours(v) + ' hr' : empty}</PBtn>
  );
  const hr = (h) => h == null ? '—' : prHours(h) + ' hr';
  const wk = (h) => h == null ? '—' : prHours(h / 2) + ' hr';
  const negH = (h) => (prNegHours(h) ? ' pr-neg' : '');
  // Productivity is a rate, the same for one week and two.
  const preTxt = calc && calc.preMgrProductivity != null ? '$' + calc.preMgrProductivity.toFixed(2) + '/hr' : '—';
  const preNeg = calc && calc.preMgrProductivity != null && calc.goalProductivity != null && calc.preMgrProductivity < calc.goalProductivity ? ' pr-neg' : '';
  const actNeg = calc && calc.actProductivity != null && calc.goalProductivity != null && calc.actProductivity < calc.goalProductivity - 0.005 ? ' pr-neg' : '';
  const goalTxt = calc && calc.goalProductivity != null ? '$' + calc.goalProductivity.toFixed(2) : '—';
  const goalRate = calc && calc.goalProductivity != null ? '$' + calc.goalProductivity.toFixed(2) + '/hr' : '—';

  // Every explanation sits in an ⓘ (v26.09, Ryan: "hide all the gray
  // explanation text to a tooltip in simulator"); only numbers stay on view.
  const H = (text) => <PrHint text={text} />;
  const actTxt = calc && calc.actProductivity != null ? '$' + calc.actProductivity.toFixed(2) + '/hr' : '—';
  const pageHint = (
    <>
      <p>A full {days}-day pay period at the numbers you expect. Set each day’s sales and the week’s hours; gross is two of each day, net is {ratioLabel} of gross, and everything else is set. Nothing here is saved to a period. The numbers you type are shared: everyone who opens the Simulator sees the same ones, and a change shows up on every open Simulator. Clear resets them for everyone.</p>
      <p>Google and Meta spend, the 3PD ad and redemption fees and the crew bonus are last period’s: for each, the newest finished period it was fetched for after that period ended. Everything else is today’s Defaults, with $ lines prorated to {days} days.</p>
    </>
  );

  // The shared numbers arrive in one quick read; showing the seeds first and
  // then jumping to someone's typed numbers would read as a glitch.
  if (!shared.loaded) {
    return <div className="portal-card" style={{ padding: 40, textAlign: 'center', color: 'var(--fg-3)', fontSize: 13 }}>Loading the shared Simulator numbers…</div>;
  }

  return (
    <>
      <div className="portal-page-header" style={{ alignItems: 'flex-start' }}>
        <div style={{ minWidth: 0 }}>
          <button className="portal-back" onClick={onBack} style={{ background: 'none', border: 'none', padding: 0, cursor: 'pointer', color: 'var(--fg-3)', fontSize: 12.5, display: 'inline-flex', alignItems: 'center', gap: 4, marginBottom: 6 }}>
            <PIcon name="ri-arrow-left-line" size={14} /> All periods
          </button>
          <h1 className="portal-page-title" style={{ display: 'flex', alignItems: 'center' }}>Simulator<PrHint text={pageHint} wide size={16} label="How the Simulator works" /></h1>
        </div>
        <div style={{ display: 'flex', gap: 10, flexShrink: 0, alignItems: 'center' }}>
          {shared.error
            ? <span style={{ fontSize: 12, color: 'var(--danger)' }}>{shared.error}</span>
            : shared.last && shared.last.updated_at && (
              <span style={{ fontSize: 12, color: 'var(--fg-3)' }} title="The Simulator’s numbers are shared — everyone sees the same ones">
                Shared · last change{shared.last.updated_by ? ' by ' + prSimWho(shared.last.updated_by) : ''}, {prWhen(shared.last.updated_at)}
              </span>
            )}
          <PBtn size="md" variant="ghost" icon="ri-eraser-line" disabled={!touched} title="Clear the numbers — for everyone, since they’re shared" onClick={clearAll}>Clear</PBtn>
        </div>
      </div>

      <div className="pr-stat-row is-4">
        <div className="portal-stat">
          <div className="portal-stat-label">Total labor</div>
          <div className="portal-stat-value">{calc && calc.laborPct != null ? prPct(calc.laborPct) : '—'}</div>
          <div className="portal-stat-sub">{calc && calc.totalLabor != null ? prMoney(calc.totalLabor) + ' incl. tax & insurance' : 'of net sales, once the hours are in'}</div>
        </div>
        <div className="portal-stat">
          <div className="portal-stat-label">Productivity</div>
          <div className="portal-stat-value">{calc && calc.actProductivity != null ? '$' + calc.actProductivity.toFixed(1) : '—'}</div>
          <div className="portal-stat-sub">{'goal ' + (calc && calc.goalProductivity != null ? '$' + calc.goalProductivity.toFixed(1) : '—') + (calc && calc.preMgrProductivity != null ? ' · pre-manager $' + calc.preMgrProductivity.toFixed(1) : ' · gross per labor hour')}</div>
        </div>
        <div className="portal-stat">
          <div className="portal-stat-label">Manager pay</div>
          <div className={'portal-stat-value' + (calc && calc.managerTotal != null && calc.managerTotal < 0 ? ' pr-neg' : '')}>{calc && calc.managerTotal != null ? prMoney(calc.managerTotal) : '—'}</div>
          <div className="portal-stat-sub">base + productivity + commission</div>
        </div>
        <div className="portal-stat">
          <div className="portal-stat-label">Left</div>
          <div className={'portal-stat-value' + (calc && calc.remaining != null && calc.remaining < 0 ? ' pr-neg' : '')}>{calc && calc.remaining != null ? prMoney(calc.remaining) : '—'}</div>
          <div className="portal-stat-sub">{calc && calc.remainingPct != null ? prPct(calc.remainingPct) + ' of net after every expense' : 'after every expense'}</div>
        </div>
      </div>

      {/* ---- Sales: one week, day by day (v26.09); the period is two of them ---- */}
      <div className="portal-card pr-sec">
        <div className="portal-card-header">
          <PrTitle icon={PR_ICONS.sales} hint="Gross sales you expect on each day of the week, every channel together. Click a day to change it.">Sales</PrTitle>
        </div>
        <div className="pr-days">
          {PR_SIM_DAYS.map((d, idx) => (
            <button key={d.key} type="button" className="pr-day" title={'Click to change ' + d.long + '’s estimate'} onClick={() => setDayFor(idx)}>
              <span className="pr-day-name">{d.short}</span>
              <span className="pr-day-amt"><PIcon name="ri-pencil-line" size={12} />{prMoneyShort(dayVals[idx])}</span>
            </button>
          ))}
        </div>
        <table className="pr-lines pr-two pr-tipped">
          <thead><tr><th></th><th>1 week</th><th>2 weeks</th></tr></thead>
          <tbody>
            <tr><td className="pr-l">Gross sales{H('The seven days above; the pay period is two of each.')}</td><td className="pr-v">{prMoney(weekGross)}</td><td className="pr-v">{prMoney(gross)}</td></tr>
            <tr><td className="pr-l">Net sales{H(ratioLabel + ' of gross sales: gross after the platforms’ commission, discounts and refunds.')}</td><td className="pr-v">{prMoney(net / 2)}</td><td className="pr-v">{prMoney(net)}</td></tr>
          </tbody>
        </table>
      </div>

      {!ready ? (
        <div className="portal-card pr-sec">
          <div className="pr-empty">Every day is at $0 — click a day above to set its sales. Labor, expenses and what’s left fill in from there.</div>
        </div>
      ) : (
        <>
          {/* ---- Labor & productivity: one week (typed) and the two-week period ---- */}
          <div className="portal-card pr-sec">
            <div className="portal-card-header">
              <PrTitle icon={PR_ICONS.labor} hint="Gross sales per labor hour. Type one week’s hours; the pay period is twice that.">Labor &amp; productivity</PrTitle>
            </div>
            <table className="pr-lines pr-two pr-tipped">
              <thead><tr><th></th><th>1 week</th><th>2 weeks</th></tr></thead>
              <tbody>
                <tr><td className="pr-l">Goal productivity<PrHint label="How the goal productivity is worked out" text={(() => { const f = prGoalFormula(calc.gross, params, days); return (<><p>{'The goal for productivity with ' + prMoneyShort(prRound2(calc.gross / 2)) + ' of weekly gross sales, ' + prMoneyShort(f.G) + ' for the two weeks.'}</p>{f.lines.map((l, k) => <p key={k}>{l + '.'}</p>)}{f.source && <p>{f.source}</p>}</>); })()} /></td><td className="pr-v">{goalRate}</td><td className="pr-v">{goalRate}</td></tr>
                <tr><td className="pr-l">Goal labor hours{H('Gross ÷ goal productivity: ' + prMoney(calc.gross) + ' ÷ ' + goalTxt + ' for the two weeks, half of it for one.')}</td><td className="pr-v">{wk(calc.goalHours)}</td><td className="pr-v">{hr(calc.goalHours)}</td></tr>
                <tr><td className="pr-l">Total labor hours{H(typedClocked != null ? 'Everyone’s hours, the manager’s and training included.' : 'Everyone’s hours, the manager’s and training included. Until you type your own, the schedule follows the goal: goal hours plus training.')}</td><td className="pr-v">{hoursBtn('clocked', clocked1, 'Enter hours')}</td><td className="pr-v">{hr(calc.clockedHours)}</td></tr>
                <tr className="pr-sub"><td className="pr-l">Crew hours{H('Total − manager − training.')}</td><td className={'pr-v' + negH(calc.crewHours == null ? null : calc.crewHours / 2)}>{wk(calc.crewHours)}</td><td className={'pr-v' + negH(calc.crewHours)}>{hr(calc.crewHours)}</td></tr>
                <tr className="pr-sub"><td className="pr-l">Manager hours{H('At least ' + prHours(minWeek) + ' a week, from Defaults.')}</td><td className="pr-v">{hoursBtn('manager', manager1)}</td><td className="pr-v">{hr(calc.managerHours)}</td></tr>
                <tr className="pr-sub"><td className="pr-l">Training hours{H('Paid, but not counted as productive.')}</td><td className="pr-v">{hoursBtn('training', training1)}</td><td className="pr-v">{hr(training1 * 2)}</td></tr>
                <tr><td className="pr-l">Effective hours{H('Total − training, so crew + manager.')}</td><td className="pr-v">{wk(calc.effectiveHours)}</td><td className="pr-v">{hr(calc.effectiveHours)}</td></tr>
                <tr><td className="pr-l">Actual productivity{H('Gross ÷ (crew + manager) hours. The goal at this gross is ' + goalTxt + '.')}</td><td className={'pr-v' + actNeg}>{actTxt}</td><td className={'pr-v' + actNeg}>{actTxt}</td></tr>
                <tr className="pr-total"><td className="pr-l">Pre-manager productivity{H('Gross ÷ crew hours. Above the ' + goalTxt + ' goal it earns the manager’s productivity bonus; below it, a penalty.')}</td><td className={'pr-v' + preNeg}>{preTxt}</td><td className={'pr-v' + preNeg}>{preTxt}</td></tr>
              </tbody>
            </table>
          </div>

          {/* ---- Labor cost ---- */}
          <div className="portal-card pr-sec">
            <div className="portal-card-header">
              <PrTitle icon={PR_ICONS.laborcost} pct={calc.laborPct} hint={'Crew at ' + prMoney(PR_SIM_CREW_WAGE) + ' an hour · crew bonus as last period · the manager’s pay from Defaults.'}>Labor cost</PrTitle>
            </div>
            <table className="pr-lines pr-tipped">
              <tbody>
                <tr><td className="pr-l">Crew wages{H(clocked1 == null ? 'Enter the total labor hours.' : 'Crew and training hours, ' + prHours(Math.max(0, calc.clockedHours - calc.managerHours)) + ' hr × ' + prMoney(PR_SIM_CREW_WAGE) + ' per hour.')}</td><td className={'pr-v' + (calc.crewTotal == null ? ' pr-muted' : '')}>{prMoney(calc.crewTotal)}</td></tr>
                <tr><td className="pr-l">Crew bonus{H(carry.bonus ? 'As ' + carry.bonus.label + ', from the Crew Lead Scorecard.' : 'No finished period has a Scorecard bonus yet.')}</td><td className={'pr-v' + (carry.bonus ? '' : ' pr-muted')}>{carry.bonus ? prMoney(carry.bonus.value) : '—'}</td></tr>
                <tr><td className="pr-l">Manager{H('Base + productivity + food and paper + sales commission.')}</td><td className="pr-v">{prMoney(calc.managerTotal)}</td></tr>
                <tr className="pr-sub"><td className="pr-l">Base{H('Per period, from Defaults.')}</td><td className="pr-v">{prMoney(managerBase)}</td></tr>
                <tr className="pr-sub"><td className="pr-l">Productivity{H(calc.preMgrProductivity == null ? 'Enter the total labor hours.' : prBonusNote(calc, calc.goalProductivity) + prRound2(params.manager_bonus_factor) + '.')}</td><td className={'pr-v' + (calc.managerProdBonus != null && calc.managerProdBonus < 0 ? ' pr-neg' : '')}>{prMoney(calc.managerProdBonus)}</td></tr>
                <tr className="pr-sub"><td className="pr-l">Food and paper{H('Not defined yet.')}</td><td className="pr-v">{prMoney(0)}</td></tr>
                <tr className="pr-sub"><td className="pr-l">Sales commission{H(!calc.mgrCommission.sliding ? prRatePct(calc.mgrCommission.rate) + ' of net sales.' : (
                  <>
                    <p>{prMoney(calc.net) + ' × ' + prRatePct(calc.mgrCommission.rate) + ' = ' + prMoney(calc.managerCommission) + '.'}</p>
                    <p>{'Every ±$1,000 of net from ' + prMoneyShort(params.commission_base_net) + ' = ±' + prRatePct(params.commission_step) + ', starting at ' + prRatePct(params.manager_commission_rate) + ' and up to ' + prRatePct(params.commission_cap) + '.'}</p>
                  </>
                ))}</td><td className="pr-v">{prMoney(calc.managerCommission)}</td></tr>
                <tr><td className="pr-l">Labor cost{H('Crew wages + crew bonus + manager.')}</td><td className="pr-v">{prMoney(calc.laborCost)}</td></tr>
                <tr><td className="pr-l">Tax &amp; insurance{H(prPct(params.tax_insurance_rate, 1) + ' of labor cost.')}</td><td className="pr-v">{prMoney(calc.tax)}</td></tr>
                <tr className="pr-total"><td className="pr-l">Total labor{H(calc.laborPct != null ? prPct(calc.laborPct) + ' of net sales.' : 'Enter the total labor hours.')}</td><td className="pr-v">{prMoney(calc.totalLabor)}</td></tr>
              </tbody>
            </table>
          </div>

          {/* ---- Food & Paper ---- */}
          <PrCategoryCard cat={calc.foodPaperCat} net={calc.net} subtitle="% of net sales, from Defaults." cell={plain} tips />

          {/* ---- Marketing ---- */}
          <div className="portal-card pr-sec">
            <div className="portal-card-header">
              <PrTitle icon={PR_ICONS.marketing} pct={calc.marketingPct} hint="Ad spend and 3PD fees as last period · the rest from Defaults.">Marketing</PrTitle>
            </div>
            <table className="pr-lines pr-tipped">
              <tbody>
                {calc.apiLines.map(m => (
                  <tr key={m.key}><td className="pr-l">{m.label}{H(m.have ? 'As ' + carry.ads.label + ', from the API.' : (carry.ads ? 'Not fetched for ' + carry.ads.label + '.' : 'No finished period has it yet.'))}</td><td className={'pr-v' + (m.have ? '' : ' pr-muted')}>{m.have ? prMoney(m.value) : '—'}</td></tr>
                ))}
                <tr><td className="pr-l">3PD Ads{H(carry.tpd ? 'As ' + carry.tpd.label + ', from the platform CSVs.' : 'No finished period has the platform CSVs yet.')}</td><td className="pr-v">{prMoney(calc.ads)}</td></tr>
                <tr><td className="pr-l">3PD redemption{H(carry.tpd ? 'As ' + carry.tpd.label + ', from the platform CSVs.' : 'No finished period has the platform CSVs yet.')}</td><td className="pr-v">{prMoney(calc.redemption)}</td></tr>
                {calc.marketingCat.items.map(it => (
                  <tr key={it.id}><td className="pr-l">{it.name}{H(prLineDef(it) + (it.mode !== 'pct' ? ', prorated to ' + days + ' days' : '') + '.')}</td><td className="pr-v">{plain('marketing', it)}</td></tr>
                ))}
                <tr className="pr-total"><td className="pr-l">Total marketing{H(prPct(calc.marketingPct) + ' of net sales.')}</td><td className="pr-v">{prMoney(calc.marketingTotal)}</td></tr>
              </tbody>
            </table>
          </div>

          {/* ---- the other P&L categories ---- */}
          {calc.otherCats.map(cat => (
            <PrCategoryCard key={cat.key} cat={cat} net={calc.net} subtitle={'From Defaults · % lines follow net sales · $ lines are prorated to ' + days + ' days.'} cell={plain} tips />
          ))}

          <PrBottomLine calc={calc} pending="Enter the total labor hours." tips />
        </>
      )}

      {dayFor != null && (
        <PrSimHoursModal
          key={'day' + dayFor}
          title={PR_SIM_DAYS[dayFor].long + ' sales'}
          hint={'Gross sales you expect on a ' + PR_SIM_DAYS[dayFor].long + ', every channel together. The pay period has two of them. Leave it empty for ' + prMoneyShort(PR_SIM_DAYS[dayFor].seed) + '.'}
          prefix="$" unit=""
          reference={carry.sales ? 'For reference, ' + carry.sales.label + ' averaged ' + prMoney(carry.sales.perDay) + ' a day.' : null}
          value={dayVals[dayFor]}
          onSave={(v) => { setDay(PR_SIM_DAYS[dayFor].key, v == null ? '' : String(v)); setDayFor(null); }}
          onClose={() => setDayFor(null)}
        />
      )}
      {hoursFor && (
        <PrSimHoursModal
          key={hoursFor}
          title={(hoursFor === 'clocked' ? 'Total labor hours' : (hoursFor === 'manager' ? 'Manager hours' : 'Training hours')) + ' · 1 week'}
          hint={hoursFor === 'clocked'
            ? 'Everyone’s hours for one week — the crew, the manager and training included. The pay period counts twice this. Leave it empty to schedule to the goal.'
            : (hoursFor === 'manager'
              ? 'The manager’s hours for one week, at least ' + prHours(minWeek) + '. Leave it empty for ' + prHours(minWeek) + '.'
              : 'The hours new hires will spend training in one week. They are part of the total labor hours: paid, but not counted as productive.')}
          min={hoursFor === 'manager' ? minWeek : 0}
          minLabel={hoursFor === 'manager' ? 'The manager’s hours can’t go below ' + prHours(minWeek) + ' a week.' : null}
          reference={carry.hours ? (hoursFor === 'clocked'
            ? 'For reference, ' + carry.hours.label + ' averaged ' + prHours((carry.hours.act + carry.hours.manager) / 2) + ' h a week, the manager’s ' + prHours(carry.hours.manager / 2) + ' h included.'
            : (hoursFor === 'manager'
              ? 'For reference, ' + carry.hours.label + ' counted ' + prHours(carry.hours.manager / 2) + ' h a week.'
              : 'For reference, ' + carry.hours.label + ' averaged ' + prHours(carry.hours.training / 2) + ' h of training a week.')) : null}
          value={hoursFor === 'clocked' ? clocked1 : (hoursFor === 'manager' ? manager1 : training1)}
          onSave={(v) => { set(hoursFor, v == null ? '' : String(v)); setHoursFor(null); }}
          onClose={() => setHoursFor(null)}
        />
      )}
    </>
  );
};

// ------------------------------------------------------------------
// Defaults — a drawer: the constants a new period starts from, and the
// expense lines of every category (name · value · % of net or $ per month / week / day)
// ------------------------------------------------------------------
const PrDefaultsDrawer = ({ config, onSave, onClose }) => {
  const [d, setD] = useState(() => {
    const out = {};
    PR_PARAM_KEYS.forEach(k => { out[k] = prNum(config[k]) != null ? prNum(config[k]) : PR_PARAM_DEFAULTS[k]; });
    PR_INPUT_DEFAULT_KEYS.forEach(k => { out[k] = prNum(config[k]) != null ? prNum(config[k]) : PR_INPUT_DEFAULTS[k]; });
    return out;
  });
  const [excluded, setExcluded] = useState(() => prExcludedIds(config));
  const toggleExcluded = (id) => setExcluded(prev => { const n = new Set(prev); if (n.has(id)) n.delete(id); else n.add(id); return n; });
  const staffChoices = (window.SAMPLE_STAFF || []).filter(s => s.active !== false).slice().sort((a, b) => String(a.name || '').localeCompare(String(b.name || '')));
  const [milestones, setMilestones] = useState(() => prMilestones({ goal_milestones: Array.isArray(config.goal_milestones) && config.goal_milestones.length ? config.goal_milestones : PR_DEFAULT_GOAL_MILESTONES })
    .map(m => ({ id: prNewId(), gross: String(m.gross), hours: String(prRound2(m.hours)) })));
  const patchMilestone = (id, patch) => setMilestones(prev => prev.map(m => m.id !== id ? m : Object.assign({}, m, patch)));
  const [firstPeriod, setFirstPeriod] = useState(() => /^\d{4}-\d{2}-\d{2}$/.test(String(config.first_period || '')) ? String(config.first_period) : '');
  const [cats, setCats] = useState(() => prCloneCats(Array.isArray(config.categories) && config.categories.length ? config.categories : PR_DEFAULT_CATEGORIES)
    .map(cat => Object.assign({}, cat, { items: cat.items.map(it => Object.assign({}, it, { value: String(it.value) })) })));
  const set = (k, v) => { if (v != null) setD(prev => Object.assign({}, prev, { [k]: v })); };
  const patchItem = (ck, id, patch) => setCats(prev => prev.map(cat => cat.key !== ck ? cat : Object.assign({}, cat, { items: cat.items.map(it => it.id !== id ? it : Object.assign({}, it, patch)) })));
  const addItem = (ck) => setCats(prev => prev.map(cat => cat.key !== ck ? cat : Object.assign({}, cat, { items: cat.items.concat([{ id: prNewId(), name: '', mode: 'amt', basis: 'month', value: '' }]) })));
  const setMode = (ck, id, key) => patchItem(ck, id, prModeFields(key));
  const removeItem = (ck, id) => setCats(prev => prev.map(cat => cat.key !== ck ? cat : Object.assign({}, cat, { items: cat.items.filter(it => it.id !== id) })));
  const save = () => onSave(Object.assign({}, config, d, {
    first_period: /^\d{4}-\d{2}-\d{2}$/.test(firstPeriod) ? firstPeriod : null,
    goal_milestones: prMilestones({ goal_milestones: milestones }).map(m => ({ gross: m.gross, hours: m.hours })),
    exclude_staff: Array.from(excluded),
    categories: cats.map(cat => ({
      key: cat.key, name: cat.name,
      items: cat.items.filter(it => String(it.name || '').trim()).map(it => Object.assign(
        { id: it.id, name: String(it.name).trim(), mode: it.mode === 'pct' ? 'pct' : 'amt', basis: it.mode === 'pct' ? null : (PR_BASES[it.basis] ? it.basis : 'month'), value: prNum(it.value) || 0 },
        it.mode === 'pct' && (it.of === 'direct' || it.of === 'net') ? { of: it.of } : {})),
    })),
  }));
  useEffect(() => {
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, []);
  return (
    <div className="pr-drawer-back" onClick={onClose}>
      <div className="pr-drawer" role="dialog" aria-label="Defaults for new periods" onClick={e => e.stopPropagation()}>
        <div className="pr-drawer-head">
          <div>
            <div style={{ fontSize: 15, fontWeight: 600, letterSpacing: '-0.01em' }}>Defaults for new periods</div>
            <div style={{ fontSize: 12, color: 'var(--fg-3)', marginTop: 2 }}>A period copies these on its first save and keeps its own copy after that; Reload defaults on a period pulls them in again.</div>
          </div>
          <button type="button" onClick={onClose} aria-label="Close" style={{ width: 30, height: 30, borderRadius: 999, border: 'none', background: 'var(--bg-sunken)', cursor: 'pointer', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}><PIcon name="ri-close-line" size={16} /></button>
        </div>
        <div className="pr-drawer-body">
          <div className="pr-dsec">
            <div className="pr-dsec-title">Parameters</div>
            <div className="pr-params">
              <PField label="Manager hours" hint="added to effective hours for actual productivity, per two weeks"><PrInput hours value={d.manager_fixed_hours} unit="hr" onCommit={v => set('manager_fixed_hours', v == null ? v : Math.abs(v))} /></PField>
              <PField label="Manager hours, Simulator" hint="its minimum per two weeks"><PrInput hours value={d.manager_hours} unit="hr" onCommit={v => set('manager_hours', v == null ? v : Math.abs(v))} /></PField>
              <PField label="Manager bonus ratio" hint="× (pre-manager productivity − goal)"><PrInput value={d.manager_bonus_factor} onCommit={v => set('manager_bonus_factor', v)} /></PField>
              <PField label="Tax & insurance" hint="% of labor cost"><PrInput pct value={d.tax_insurance_rate} unit="%" onCommit={v => set('tax_insurance_rate', v)} /></PField>
              <PField label="Manager base" hint="$ per period"><PrInput value={d.manager_base} onCommit={v => set('manager_base', v)} /></PField>
              <PField label="First period" hint="periods before this stay out of the list">
                <input type="date" className="portal-input" {...PR_NO_PM} value={firstPeriod} onChange={e => setFirstPeriod(e.target.value)} style={{ height: 30, padding: '4px 8px' }} />
              </PField>
            </div>
          </div>
          <div className="pr-dsec">
            <div className="pr-dsec-title">Manager’s sales commission</div>
            <div style={{ fontSize: 12, color: 'var(--fg-3)', marginBottom: 8 }}>The rate moves in steps with net sales, one step for each $1,000 of net: the rate at the base for $30,000–$30,999, one step up for $31,000–$31,999, one step down for $29,000–$29,999, and so on, never under 0% or over the cap. A period in progress is read at its two-week pace.</div>
            <div className="pr-params">
              <PField label="Rate at the base" hint="% of net sales"><PrInput pct value={d.manager_commission_rate} unit="%" onCommit={v => set('manager_commission_rate', v)} /></PField>
              <PField label="Base net sales" hint="$ for a two-week period"><PrInput value={d.commission_base_net} onCommit={v => set('commission_base_net', v == null ? v : Math.abs(v))} /></PField>
              <PField label="Step per $1,000" hint="% up above the base, down below"><PrInput pct value={d.commission_step} unit="%" onCommit={v => set('commission_step', v == null ? v : Math.abs(v))} /></PField>
              <PField label="Cap" hint="the highest rate"><PrInput pct value={d.commission_cap} unit="%" onCommit={v => set('commission_cap', v == null ? v : Math.abs(v))} /></PField>
            </div>
          </div>
          <div className="pr-dsec">
            <div className="pr-dsec-title">Goal productivity</div>
            <div style={{ fontSize: 12, color: 'var(--fg-3)', marginBottom: 8 }}>Milestones for a two-week period: at this gross, schedule this many total labor hours, the manager’s included; the goal productivity is gross ÷ those hours. Between milestones the hours run in a straight line, under the lowest milestone the goal stays at its productivity, and past the highest one the hours grow by one for every dollar amount set below.</div>
            <div className="pr-drows">
              <div className="pr-mrow pr-mhead"><span>Two-week gross</span><span>Total labor hours</span><span className="pr-mprod">Productivity</span><span /></div>
              {milestones.map(m => {
                const g = prNum(m.gross), h = prNum(m.hours);
                const prod = g > 0 && h > 0 ? g / h : null;
                return (
                  <div className="pr-mrow" key={m.id}>
                    <span className="pr-simin"><span className="pr-simfix">$</span><input className="portal-input pr-in" {...PR_NO_PM} inputMode="decimal" aria-label="Two-week gross" value={m.gross} placeholder="30000" onChange={e => patchMilestone(m.id, { gross: e.target.value })} /></span>
                    <span className="pr-simin"><input className="portal-input pr-in" {...PR_NO_PM} inputMode="decimal" aria-label="Total labor hours" value={m.hours} placeholder="545" onChange={e => patchMilestone(m.id, { hours: e.target.value })} /><span className="pr-dunit">hr</span></span>
                    <span className="pr-mprod" title="Gross ÷ total labor hours">{prod != null ? prMoney(prod) + '/hr' : '—'}</span>
                    <button type="button" className="pr-dx" aria-label="Remove milestone" title="Remove this milestone" onClick={() => setMilestones(prev => prev.filter(x => x.id !== m.id))}><PIcon name="ri-close-line" size={14} /></button>
                  </div>
                );
              })}
              <button type="button" className="pr-dadd" onClick={() => setMilestones(prev => prev.concat([{ id: prNewId(), gross: '', hours: '' }]))}><PIcon name="ri-add-line" size={14} /> Add a milestone</button>
            </div>
            <div style={{ marginTop: 12 }}>
              <PField label="Past the last milestone" hint="$ of gross for each extra labor hour"><PrInput value={d.goal_pace} onCommit={v => set('goal_pace', v == null ? v : Math.abs(v))} /></PField>
            </div>
          </div>
          <div className="pr-dsec">
            <div className="pr-dsec-title">Left out of crew hours &amp; wages</div>
            <div style={{ fontSize: 12, color: 'var(--fg-3)', marginBottom: 8 }}>Their timecards don’t count toward the crew’s hours or wages — the manager, whose hours are the Manager hours above and whose pay is the base. Applies from the next Sync again.</div>
            <div className="pr-staffgrid">
              {staffChoices.map(s => (
                <label key={s.id} className={'pr-staff' + (excluded.has(String(s.id)) ? ' is-on' : '')}>
                  <input type="checkbox" checked={excluded.has(String(s.id))} onChange={() => toggleExcluded(String(s.id))} />
                  <span>{s.name}</span><span className="pr-staffrole">{s.role || ''}</span>
                </label>
              ))}
            </div>
          </div>
          {cats.map(cat => (
            <div className="pr-dsec" key={cat.key}>
              <div className="pr-dsec-title">{cat.name}</div>
              <div className="pr-drows">
                {cat.items.map(it => (
                  <div className="pr-drow" key={it.id}>
                    <input className="portal-input" {...PR_NO_PM} value={it.name} placeholder="Expense" onChange={e => patchItem(cat.key, it.id, { name: e.target.value })} />
                    <input className="portal-input pr-in" {...PR_NO_PM} inputMode="decimal" value={it.value} placeholder="0" onChange={e => patchItem(cat.key, it.id, { value: e.target.value })} />
                    <select className="portal-input pr-sel" value={prModeKey(it)} onChange={e => setMode(cat.key, it.id, e.target.value)}>
                      {PR_LINE_MODES.map(o => <option key={o.value} value={o.value}>{o.label}</option>)}
                    </select>
                    <button type="button" className="pr-dx" aria-label="Remove line" title="Remove this line" onClick={() => removeItem(cat.key, it.id)}><PIcon name="ri-close-line" size={14} /></button>
                  </div>
                ))}
                <button type="button" className="pr-dadd" onClick={() => addItem(cat.key)}><PIcon name="ri-add-line" size={14} /> Add a line</button>
              </div>
            </div>
          ))}
        </div>
        <div className="pr-drawer-foot">
          <PBtn variant="ghost" onClick={onClose}>Cancel</PBtn>
          <PBtn variant="primary" onClick={save}>Save defaults</PBtn>
        </div>
      </div>
    </div>
  );
};

Object.assign(window, { PeriodReport });
