// Associate Doctor Pay tool — UI.
// Depends on tools-shared.jsx (loaded first) + associate-engine.jsx (loaded second).
// Mount: ReactDOM.createRoot('#associate-pay-root').render(<AssociatePayTool />)
const { useState: aUseState, useMemo: aUseMemo } = React;

const aMoney = (n) => (n < 0 ? '−' : '') + '$' + Math.round(Math.abs(n)).toLocaleString();
const DRAW_COLOR = '#b3541e';

const cleanNum = (raw) => String(raw).replace(/[^0-9.]/g, '');
const commafy = (v) => {
  if (v === '' || v == null) return '';
  const s = String(v);
  const m = s.match(/^(\d*)(\.\d*)?$/);
  if (!m) return s;
  const intPart = m[1] === '' ? '' : Number(m[1]).toLocaleString();
  return intPart + (m[2] || '');
};

const microLabel = {
  fontFamily: 'var(--pdt-mono)', fontSize: 10, letterSpacing: '0.08em',
  textTransform: 'uppercase', color: 'var(--pdt-mute)',
};

// ---- Compact cell input (used in the input tables) ----
function CellInput({ value, onChange, prefix, suffix, align = 'right', ariaLabel }) {
  return (
    <div style={{
      display: 'flex', alignItems: 'stretch',
      border: '1px solid var(--pdt-line)', background: '#fff',
    }}>
      {prefix && (
        <span style={{
          padding: '10px 10px', borderRight: '1px solid var(--pdt-line-soft)',
          fontFamily: 'var(--pdt-mono)', fontSize: 13, color: 'var(--pdt-mute)',
          background: 'var(--pdt-paper-deep)', display: 'flex', alignItems: 'center',
        }}>{prefix}</span>
      )}
      <input
        type="text" inputMode="decimal" aria-label={ariaLabel}
        value={value}
        onChange={(e) => onChange(cleanNum(e.target.value))}
        style={{
          flex: 1, minWidth: 0, width: '100%',
          padding: '10px 12px', border: 'none', background: 'transparent',
          fontFamily: 'var(--pdt-sans)', fontSize: 16, fontWeight: 500,
          color: 'var(--pdt-ink)', outline: 'none', textAlign: align,
        }}
      />
      {suffix && (
        <span style={{
          padding: '10px 10px', borderLeft: '1px solid var(--pdt-line-soft)',
          fontFamily: 'var(--pdt-mono)', fontSize: 13, color: 'var(--pdt-mute)',
          background: 'var(--pdt-paper-deep)', display: 'flex', alignItems: 'center',
        }}>{suffix}</span>
      )}
    </div>
  );
}

// ---- Pay-plan (tiers) card ----
function PayPlanCard({ tiers, setTiers }) {
  const setTier = (i, key, raw) => {
    setTiers((prev) => prev.map((t, idx) => idx === i ? { ...t, [key]: cleanNum(raw) } : t));
  };
  return (
    <div style={{
      background: 'var(--pdt-paper)', border: '1px solid var(--pdt-line)',
      padding: 'clamp(22px, 3vw, 32px)',
    }}>
      <div className="t-eyebrow" style={{ marginBottom: 6, color: 'var(--pdt-mute)' }}>
        The pay plan
      </div>
      <p style={{
        fontFamily: 'var(--pdt-serif)', fontSize: 15, lineHeight: 1.5,
        color: 'var(--pdt-ink-soft)', margin: '0 0 24px', maxWidth: 460,
      }}>
        Four production tiers. Each sets the percentage the associate earns on
        net production once it reaches that level. Tier 1 applies from the first dollar.
      </p>

      <div style={{ marginBottom: 30 }}>
        <div className="assoc-grid-head assoc-tier-head" style={{ marginBottom: 10 }}>
          <div style={microLabel}>Tier</div>
          <div style={microLabel}>From</div>
          <div style={microLabel}>To</div>
          <div style={{ ...microLabel, textAlign: 'right' }}>Rate</div>
        </div>
        {tiers.map((t, i) => {
          const next = tiers[i + 1];
          return (
            <div className="assoc-tier-row" key={i}>
              <div className="assoc-tier-num" style={{
                fontFamily: 'var(--pdt-mono)', fontSize: 13, color: 'var(--pdt-forest)',
                fontWeight: 500, whiteSpace: 'nowrap',
              }}>Tier 0{i + 1}</div>
              <div className="assoc-field">
                <div className="assoc-inline-label">From</div>
                {i === 0 ? (
                  <div style={{
                    padding: '10px 12px', border: '1px dashed var(--pdt-line)',
                    background: 'var(--pdt-paper-deep)', fontFamily: 'var(--pdt-sans)',
                    fontSize: 16, fontWeight: 500, color: 'var(--pdt-mute)', whiteSpace: 'nowrap',
                  }}>$0 <span style={{ fontFamily: 'var(--pdt-mono)', fontSize: 11 }}>floor</span></div>
                ) : (
                  <CellInput
                    prefix="$" align="left"
                    ariaLabel={`Tier ${i + 1} starts at`}
                    value={commafy(t.threshold)}
                    onChange={(v) => setTier(i, 'threshold', v)}
                  />
                )}
              </div>
              <div className="assoc-field">
                <div className="assoc-inline-label">To</div>
                <div style={{
                  padding: '10px 12px', border: '1px solid var(--pdt-line-soft)',
                  background: 'var(--pdt-paper-deep)', fontFamily: 'var(--pdt-sans)',
                  fontSize: 16, fontWeight: 500, whiteSpace: 'nowrap',
                  color: next ? 'var(--pdt-ink-soft)' : 'var(--pdt-mute)',
                }}>
                  {next
                    ? '$' + commafy(next.threshold)
                    : <span style={{ fontFamily: 'var(--pdt-mono)', fontSize: 12 }}>no cap</span>}
                </div>
              </div>
              <div className="assoc-field">
                <div className="assoc-inline-label">Rate</div>
                <CellInput
                  suffix="%"
                  ariaLabel={`Tier ${i + 1} rate`}
                  value={t.pct}
                  onChange={(v) => setTier(i, 'pct', v)}
                />
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

// ---- Production inputs card ----
// Period start + existing draw live at the top of this card (above the month grid).
function ProductionCard({ months, setMonths, ends, startMonth, setStartMonth, existingDraw, setExistingDraw }) {
  const setMonth = (i, key, raw) => {
    setMonths((prev) => prev.map((m, idx) => idx === i ? { ...m, [key]: cleanNum(raw) } : m));
  };
  return (
    <div style={{
      background: 'var(--pdt-paper)', border: '1px solid var(--pdt-line)',
      padding: 'clamp(22px, 3vw, 32px)',
    }}>
      <div className="t-eyebrow" style={{ marginBottom: 6, color: 'var(--pdt-mute)' }}>
        Three months of production
      </div>
      <p style={{
        fontFamily: 'var(--pdt-serif)', fontSize: 15, lineHeight: 1.5,
        color: 'var(--pdt-ink-soft)', margin: '0 0 24px', maxWidth: 460,
      }}>
        Enter each month as billed. Lab fees come off production before the tier
        is applied. The daily minimum is the guaranteed monthly total.
      </p>

      {/* Starting values: period + existing draw */}
      <div style={{
        marginBottom: 26, paddingBottom: 26, borderBottom: '1px solid var(--pdt-line-soft)',
        display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(200px, 1fr))',
        gap: 20, alignItems: 'start',
      }}>
        <div>
          <div style={microLabel}>Period — first month end</div>
          <input
            type="month" value={startMonth}
            onChange={(e) => setStartMonth(e.target.value)}
            style={{
              marginTop: 8, width: '100%', boxSizing: 'border-box',
              padding: '10px 12px', border: '1px solid var(--pdt-line)', background: '#fff',
              fontFamily: 'var(--pdt-sans)', fontSize: 16, fontWeight: 500,
              color: 'var(--pdt-ink)', outline: 'none',
            }}
          />
          <div style={{ marginTop: 8, fontFamily: 'var(--pdt-mono)', fontSize: 11, color: 'var(--pdt-mute)' }}>
            {ends.map((d) => fmtMonthEnd(d)).join('  →  ')}
          </div>
        </div>
        <div>
          <div style={microLabel}>Existing draw</div>
          <div style={{ marginTop: 8 }}>
            <CellInput
              prefix="$" align="left"
              ariaLabel="Existing draw carried in"
              value={commafy(existingDraw)}
              onChange={setExistingDraw}
            />
          </div>
          <div style={{ marginTop: 8, fontFamily: 'var(--pdt-mono)', fontSize: 11, color: 'var(--pdt-mute)' }}>
            carried in from before month 1 · no negative sign needed
          </div>
        </div>
      </div>

      <div>
        <div className="assoc-grid-head assoc-prod-head" style={{ marginBottom: 12 }}>
          <div style={microLabel}>Month</div>
          <div style={microLabel}>Actual production</div>
          <div style={microLabel}>Daily minimum</div>
          <div style={microLabel}>Lab fees</div>
        </div>
        {months.map((m, i) => (
          <div className="assoc-prod-row" key={i}>
            <div className="assoc-prod-monthlabel" style={{ minWidth: 0 }}>
              <div style={{ fontFamily: 'var(--pdt-mono)', fontSize: 12, color: 'var(--pdt-forest)', fontWeight: 500 }}>
                Month {i + 1}
              </div>
              <div style={{ fontFamily: 'var(--pdt-mono)', fontSize: 11, color: 'var(--pdt-mute)' }}>
                ends {fmtMonthEnd(ends[i])}
              </div>
            </div>
            <div className="assoc-field">
              <div className="assoc-inline-label">Actual production</div>
              <CellInput prefix="$" value={commafy(m.actual)} onChange={(v) => setMonth(i, 'actual', v)} ariaLabel={`Month ${i + 1} production`} />
            </div>
            <div className="assoc-field">
              <div className="assoc-inline-label">Daily minimum</div>
              <CellInput prefix="$" value={commafy(m.min)} onChange={(v) => setMonth(i, 'min', v)} ariaLabel={`Month ${i + 1} daily minimum`} />
            </div>
            <div className="assoc-field">
              <div className="assoc-inline-label">Lab fees</div>
              <CellInput prefix="$" value={commafy(m.lab)} onChange={(v) => setMonth(i, 'lab', v)} ariaLabel={`Month ${i + 1} lab fees`} />
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

// ---- Summary headline ----
function SummaryPanel({ result }) {
  const { totalBonusPaid, endingDraw, totalDrawTaken, totalDailyMin, totalPaid } = result;
  const owes = endingDraw > 0.5;
  const eqTerm = (val, label) => (
    <span style={{ whiteSpace: 'nowrap' }}>
      <span style={{ fontWeight: 600 }}>{aMoney(val)}</span>{' '}
      <span style={{ fontFamily: 'var(--pdt-mono)', fontSize: 12, opacity: 0.75, letterSpacing: '0.02em' }}>{label}</span>
    </span>
  );
  const op = (s) => (
    <span style={{ fontFamily: 'var(--pdt-serif)', opacity: 0.55, margin: '0 4px' }}>{s}</span>
  );
  return (
    <div style={{
      background: 'var(--pdt-mint)', border: '1px solid var(--pdt-sage)',
      padding: 'clamp(28px, 4vw, 44px)',
    }}>
      <div className="t-eyebrow" style={{ color: 'var(--pdt-forest-deep)', marginBottom: 18 }}>
        Over the three months
      </div>
      <div style={{
        display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(220px, 1fr))',
        gap: 'clamp(24px, 4vw, 48px)', alignItems: 'end',
      }}>
        <div>
          <div style={{ ...microLabel, color: 'var(--pdt-forest-deep)', opacity: 0.75, marginBottom: 10 }}>
            Total paid to associate
          </div>
          <div style={{
            fontFamily: 'var(--pdt-sans)', fontSize: 'clamp(42px, 6.5vw, 72px)', fontWeight: 500,
            letterSpacing: '-0.025em', lineHeight: 1, color: 'var(--pdt-forest-deep)',
          }}>{aMoney(totalPaid)}</div>
        </div>
        <div>
          <div style={{ ...microLabel, color: owes ? DRAW_COLOR : 'var(--pdt-mute)', opacity: 0.9, marginBottom: 10 }}>
            {owes ? 'Draw still owed at period end' : 'Draw outstanding at period end'}
          </div>
          <div style={{
            fontFamily: 'var(--pdt-sans)', fontSize: 'clamp(34px, 5vw, 52px)', fontWeight: 500,
            letterSpacing: '-0.02em', lineHeight: 1,
            color: owes ? DRAW_COLOR : 'var(--pdt-forest-deep)', opacity: owes ? 1 : 0.55,
          }}>{aMoney(endingDraw)}</div>
        </div>
      </div>

      <div style={{
        marginTop: 26, paddingTop: 22, borderTop: '1px solid var(--pdt-sage)',
        fontFamily: 'var(--pdt-sans)', fontSize: 'clamp(16px, 2vw, 19px)',
        color: 'var(--pdt-forest-deep)', display: 'flex', flexWrap: 'wrap', alignItems: 'baseline',
        rowGap: 6,
      }}>
        {eqTerm(totalDailyMin, 'in daily minimum')}
        {op('+')}
        {eqTerm(totalBonusPaid, 'bonus')}
        {op('=')}
        {eqTerm(totalPaid, 'total paid')}
      </div>

      <div style={{
        marginTop: 20, fontFamily: 'var(--pdt-serif)', fontStyle: 'italic', fontSize: 15, lineHeight: 1.55,
        color: 'var(--pdt-forest-deep)', opacity: 0.9,
      }}>
        {owes
          ? `The associate drew ${aMoney(totalDrawTaken)} against the daily minimum and finished the period owing ${aMoney(endingDraw)} to the practice, carried into the next period.`
          : totalDrawTaken > 0.5
            ? `The associate drew ${aMoney(totalDrawTaken)} against the daily minimum early on, then earned it all back. Everything above the draw was paid out as bonus.`
            : `Every month cleared its daily minimum. No draw was taken; the full surplus was paid as bonus.`}
      </div>
    </div>
  );
}

// ---- Schedule table + mobile card view ----
function ScheduleTable({ result, ends }) {
  const cols = [
    'Month end', 'Net production', 'Tier', 'Comp', 'Daily min',
    'Bonus earned', 'Bonus paid', 'Draw balance',
  ];
  const th = {
    ...microLabel, textAlign: 'right', padding: '0 0 12px', whiteSpace: 'nowrap',
    borderBottom: '1px solid var(--pdt-line)',
  };
  const td = {
    padding: '16px 0', textAlign: 'right', whiteSpace: 'nowrap',
    fontFamily: 'var(--pdt-sans)', fontSize: 16, color: 'var(--pdt-ink)',
    borderBottom: '1px solid var(--pdt-line-soft)',
  };
  return (
    <>
      {/* Desktop: full table */}
      <div className="assoc-sched-scroll" style={{ overflowX: 'auto' }}>
        <table style={{ width: '100%', borderCollapse: 'collapse', minWidth: 720 }}>
          <thead>
            <tr>
              {cols.map((c, i) => (
                <th key={c} style={{ ...th, textAlign: i === 0 ? 'left' : 'right' }}>{c}</th>
              ))}
            </tr>
          </thead>
          <tbody>
            {result.rows.map((r, i) => {
              const draw = r.endDraw > 0.5;
              return (
                <tr key={i}>
                  <td style={{ ...td, textAlign: 'left' }}>
                    <div style={{ fontWeight: 500 }}>{fmtMonthEnd(ends[i])}</div>
                    <div style={{ fontFamily: 'var(--pdt-mono)', fontSize: 11, color: 'var(--pdt-mute)' }}>
                      Month {i + 1}
                    </div>
                  </td>
                  <td style={td}>
                    {aMoney(r.net)}
                    <div style={{ fontFamily: 'var(--pdt-mono)', fontSize: 11, color: 'var(--pdt-mute)' }}>
                      after {aMoney(r.lab)} lab
                    </div>
                  </td>
                  <td style={td}>
                    <span style={{ fontFamily: 'var(--pdt-mono)', fontSize: 13 }}>{(r.pct * 100).toFixed(0)}%</span>
                    <div style={{ fontFamily: 'var(--pdt-mono)', fontSize: 11, color: 'var(--pdt-mute)' }}>
                      tier 0{r.tierIndex + 1}
                    </div>
                  </td>
                  <td style={td}>{aMoney(r.comp)}</td>
                  <td style={{ ...td, color: 'var(--pdt-mute)' }}>{aMoney(r.min)}</td>
                  <td style={{ ...td, color: r.earned < 0 ? DRAW_COLOR : 'var(--pdt-ink)', fontWeight: 500 }}>
                    {r.earned < 0 ? `(${aMoney(-r.earned)})` : aMoney(r.earned)}
                  </td>
                  <td style={{ ...td, fontWeight: 600, color: r.bonusPaid > 0.5 ? 'var(--pdt-forest)' : 'var(--pdt-mute)' }}>
                    {aMoney(r.bonusPaid)}
                  </td>
                  <td style={{ ...td, color: draw ? DRAW_COLOR : 'var(--pdt-mute)', fontWeight: draw ? 600 : 400 }}>
                    {draw ? `(${aMoney(r.endDraw)})` : '$0'}
                  </td>
                </tr>
              );
            })}
            <tr>
              <td style={{ ...td, textAlign: 'left', fontWeight: 600, borderBottom: 'none', paddingTop: 20 }}>
                3-month total
              </td>
              <td style={{ ...td, borderBottom: 'none', fontWeight: 600, paddingTop: 20 }}>
                {aMoney(result.totalNet)}
              </td>
              <td style={{ ...td, borderBottom: 'none', paddingTop: 20 }}></td>
              <td style={{ ...td, borderBottom: 'none', fontWeight: 600, paddingTop: 20 }}>
                {aMoney(result.totalComp)}
              </td>
              <td style={{ ...td, borderBottom: 'none', color: 'var(--pdt-mute)', fontWeight: 600, paddingTop: 20 }}>
                {aMoney(result.totalDailyMin)}
              </td>
              <td style={{ ...td, borderBottom: 'none', fontWeight: 600, paddingTop: 20,
                color: result.totalEarned < 0 ? DRAW_COLOR : 'var(--pdt-ink)' }}>
                {result.totalEarned < 0 ? `(${aMoney(-result.totalEarned)})` : aMoney(result.totalEarned)}
              </td>
              <td style={{ ...td, borderBottom: 'none', fontWeight: 700, color: 'var(--pdt-forest)', fontSize: 18, paddingTop: 20 }}>
                {aMoney(result.totalBonusPaid)}
              </td>
              <td style={{ ...td, borderBottom: 'none', fontWeight: 700, fontSize: 18, paddingTop: 20,
                color: result.endingDraw > 0.5 ? DRAW_COLOR : 'var(--pdt-mute)' }}>
                {result.endingDraw > 0.5 ? `(${aMoney(result.endingDraw)})` : '$0'}
              </td>
            </tr>
          </tbody>
        </table>
      </div>

      {/* Mobile: stacked cards (hidden on desktop via CSS) */}
      <div className="assoc-sched-cards">
        {result.rows.map((r, i) => {
          const draw = r.endDraw > 0.5;
          const line = (lbl, val, valStyle) => (
            <div className="assoc-sched-line">
              <span className="lbl">{lbl}</span>
              <span style={valStyle}>{val}</span>
            </div>
          );
          return (
            <div className="assoc-sched-card" key={i}>
              <div className="assoc-sched-card-head">
                <span style={{ fontFamily: 'var(--pdt-sans)', fontSize: 17, fontWeight: 600, color: 'var(--pdt-ink)' }}>
                  {fmtMonthEnd(ends[i])}
                </span>
                <span style={{ fontFamily: 'var(--pdt-mono)', fontSize: 12, color: 'var(--pdt-mute)' }}>
                  Month {i + 1}
                </span>
              </div>
              {line('Net production', <span>{aMoney(r.net)} <span style={{ fontFamily: 'var(--pdt-mono)', fontSize: 11, color: 'var(--pdt-mute)' }}>after {aMoney(r.lab)} lab</span></span>)}
              {line('Tier', <span style={{ fontFamily: 'var(--pdt-mono)', fontSize: 13 }}>{(r.pct * 100).toFixed(0)}% · tier 0{r.tierIndex + 1}</span>)}
              {line('Comp', aMoney(r.comp))}
              {line('Daily min', aMoney(r.min), { color: 'var(--pdt-mute)' })}
              {line('Bonus earned', r.earned < 0 ? `(${aMoney(-r.earned)})` : aMoney(r.earned), { fontWeight: 500, color: r.earned < 0 ? DRAW_COLOR : 'var(--pdt-ink)' })}
              {line('Bonus paid', aMoney(r.bonusPaid), { fontWeight: 600, color: r.bonusPaid > 0.5 ? 'var(--pdt-forest)' : 'var(--pdt-mute)' })}
              {line('Draw balance', draw ? `(${aMoney(r.endDraw)})` : '$0', { fontWeight: draw ? 600 : 400, color: draw ? DRAW_COLOR : 'var(--pdt-mute)' })}
            </div>
          );
        })}
        {/* Totals card */}
        <div className="assoc-sched-card is-total">
          <div className="assoc-sched-card-head" style={{ borderBottomColor: 'var(--pdt-sage)' }}>
            <span style={{ fontFamily: 'var(--pdt-sans)', fontSize: 17, fontWeight: 700, color: 'var(--pdt-forest-deep)' }}>
              3-month total
            </span>
          </div>
          <div className="assoc-sched-line" style={{ borderBottomColor: 'var(--pdt-sage)' }}>
            <span className="lbl">Net production</span>
            <span style={{ fontWeight: 600 }}>{aMoney(result.totalNet)}</span>
          </div>
          <div className="assoc-sched-line" style={{ borderBottomColor: 'var(--pdt-sage)' }}>
            <span className="lbl">Comp</span>
            <span style={{ fontWeight: 600 }}>{aMoney(result.totalComp)}</span>
          </div>
          <div className="assoc-sched-line" style={{ borderBottomColor: 'var(--pdt-sage)' }}>
            <span className="lbl">Daily min</span>
            <span style={{ fontWeight: 600, color: 'var(--pdt-mute)' }}>{aMoney(result.totalDailyMin)}</span>
          </div>
          <div className="assoc-sched-line" style={{ borderBottomColor: 'var(--pdt-sage)' }}>
            <span className="lbl">Bonus earned</span>
            <span style={{ fontWeight: 600, color: result.totalEarned < 0 ? DRAW_COLOR : 'var(--pdt-ink)' }}>
              {result.totalEarned < 0 ? `(${aMoney(-result.totalEarned)})` : aMoney(result.totalEarned)}
            </span>
          </div>
          <div className="assoc-sched-line" style={{ borderBottomColor: 'var(--pdt-sage)' }}>
            <span className="lbl">Bonus paid</span>
            <span style={{ fontWeight: 700, fontSize: 17, color: 'var(--pdt-forest)' }}>{aMoney(result.totalBonusPaid)}</span>
          </div>
          <div className="assoc-sched-line">
            <span className="lbl">Draw balance</span>
            <span style={{ fontWeight: 700, fontSize: 17, color: result.endingDraw > 0.5 ? DRAW_COLOR : 'var(--pdt-mute)' }}>
              {result.endingDraw > 0.5 ? `(${aMoney(result.endingDraw)})` : '$0'}
            </span>
          </div>
        </div>
      </div>
    </>
  );
}

// ---- Main tool ----
function AssociatePayTool() {
  const [tiers, setTiers] = aUseState([
    { threshold: 0,       pct: '30' },
    { threshold: '60000', pct: '31' },
    { threshold: '70000', pct: '32' },
    { threshold: '80000', pct: '33' },
  ]);
  const [startMonth, setStartMonth] = aUseState('2026-05');
  const [existingDraw, setExistingDraw] = aUseState('');
  const [months, setMonths] = aUseState([
    { actual: '68000', min: '22000', lab: '3000' },
    { actual: '78000', min: '21000', lab: '3000' },
    { actual: '88000', min: '22000', lab: '3000' },
  ]);

  const ends = aUseMemo(() => {
    const [y, m] = startMonth.split('-').map(Number);
    return periodMonthEnds(y, (m || 1) - 1);
  }, [startMonth]);

  const result = aUseMemo(() => {
    const tierObjs = tiers.map((t) => ({
      threshold: Number(t.threshold) || 0,
      pct: (Number(t.pct) || 0) / 100,
    }));
    const monthObjs = months.map((m) => ({
      actual: Number(m.actual) || 0,
      min: Number(m.min) || 0,
      lab: Number(m.lab) || 0,
    }));
    return computeAssociatePay(tierObjs, monthObjs, Number(existingDraw) || 0);
  }, [tiers, months, existingDraw]);

  return (
    <>
      <ToolPageHeader
        eyebrow="Tool 03"
        title="Associate Doctor Draw & Bonus Calculator"
        scope="Three months of production, run against a tiered pay plan. See exactly what was earned, what was drawn against the daily minimum, and what gets paid out as bonus."
      />

      <section style={{
        padding: 'clamp(28px, 4vw, 48px) clamp(16px, 4vw, 32px) clamp(16px, 3vw, 28px)',
        maxWidth: 1280, margin: '0 auto',
      }}>
        <div className="assoc-input-grid" style={{
          display: 'grid', gridTemplateColumns: 'minmax(0, 1fr) minmax(0, 1.05fr)',
          gap: 'clamp(20px, 3vw, 32px)', alignItems: 'start',
        }}>
          <PayPlanCard tiers={tiers} setTiers={setTiers} />
          <ProductionCard
            months={months} setMonths={setMonths} ends={ends}
            startMonth={startMonth} setStartMonth={setStartMonth}
            existingDraw={existingDraw} setExistingDraw={(v) => setExistingDraw(cleanNum(v))}
          />
        </div>
      </section>

      <section style={{
        padding: 'clamp(16px, 3vw, 28px) clamp(16px, 4vw, 32px) clamp(32px, 5vw, 56px)',
        maxWidth: 1280, margin: '0 auto',
      }}>
        <SummaryPanel result={result} />
        <div style={{ marginTop: 'clamp(20px, 3vw, 32px)' }}>
          <div className="t-eyebrow" style={{ marginBottom: 20, color: 'var(--pdt-mute)' }}>
            Month by month
          </div>
          <ScheduleTable result={result} ends={ends} />
        </div>
      </section>

      <ToolReference
        glossary={[
          { term: 'Net production', definition: 'Actual billed production minus lab fees. This is the figure the tier percentage is applied to — labs come off the top before the associate is paid.' },
          { term: 'Tier rate', definition: 'A flat percentage set by which production band the month lands in. It applies to the whole net figure, not just the amount above the band.' },
          { term: 'Daily minimum', definition: 'The monthly total the associate is paid regardless of production. Falling short of it creates a draw.' },
          { term: 'Draw', definition: 'A loan against the daily minimum. When a month earns less than its minimum, the practice still pays the minimum; the shortfall is carried and recouped from later bonus months.' },
          { term: 'Bonus', definition: 'What is actually paid out on top of the daily minimum — only after any outstanding draw has been repaid in full.' },
        ]}
        whyCare={(
          <>
            The draw is the part of the pay plan that quietly compounds. A strong month pays it
            down; a light month adds to it, and the balance rides along in the background where
            it is easy to lose track. For the associate, this is the difference between a check
            and what was actually earned. For the owner, it is a running receivable that belongs
            on the books. Both sides are better off seeing the same schedule — so the number
            speaks for itself, and the conversation is about the work, not the math.
          </>
        )}
      />

      <ToolFooter
        doesntMeasure="This runs a single associate on the plan as entered. It doesn't handle mid-period tier changes or special-case overrides, and it assumes the daily minimum you enter is the true monthly figure. It does carry a draw forward from month to month, and lets you enter one carried in from before the period starts."
        ctaTitle="Want more detail?"
        ctaText="Need more than three months of history, more customized pay plans, or a place to keep this for every associate? That's the portal we're building for associate doctors and owners alike — tell us what would make it worth it."
        ctaLinkText="Tell us what you need →"
        ctaHref="/Contact"
      />
    </>
  );
}

ReactDOM.createRoot(document.getElementById('associate-pay-root')).render(
  React.createElement(AssociatePayTool)
);
