// PlaybookPdfTemplate
// Renders a multi-page, print-formatted version of the user's completed playbook,
// reading from the live playbook state. Intended to be captured by html2canvas + jsPDF.
//
// Constraints (html2canvas-safe):
//   - Inline styles only. No external CSS dependencies, no CSS variables.
//   - No position: fixed, no transforms on captured content.
//   - No iframes, no url() background images. Linear gradients are OK (synchronous).
//   - Fonts (Outfit, Inter) are loaded by the host page via Google Fonts.
//
// The whole component renders into a wrapper <div id="playbook-pdf-content">
// positioned off-screen via absolute + negative left. html2canvas captures the
// element directly by id, so off-screen positioning does not affect capture.

(function () {
  // ---------- Tokens (literal values, NOT CSS vars) ----------
  const C = {
    ink: '#161B3D',
    inkSoft: '#2C325C',
    inkMuted: '#4A4F61',
    line: '#DCE6F0',
    lineSoft: '#ECF2F8',
    paper: '#FFFFFF',
    paperDeep: '#F3F7FC',
    blue: '#0878D8',
    blueDeep: '#0A4E94',
    blueSoft: '#E4F1FB',
    blueMid: '#55A6E5',
    greenOk: '#2F6B3E',
    amber: '#B76E00',
    amberSoft: '#FEF6E7',
  };

  const FF_SERIF = "'Outfit', system-ui, sans-serif";
  const FF_SANS  = "'Inter', -apple-system, BlinkMacSystemFont, sans-serif";
  const FF_MONO  = "'Outfit', system-ui, sans-serif"; // tabular numerics

  // US Letter at 96dpi
  const PAGE_W = 816;
  const PAGE_H = 1056;

  // ---------- Helpers ----------
  function fmtDate(d) {
    try {
      return new Date(d).toLocaleDateString('en-US', { year: 'numeric', month: 'long', day: 'numeric' });
    } catch (e) { return ''; }
  }

  // Classify a task (mirror of phase2-audit.jsx classifyTask)
  function classify(t) {
    if (!t) return 'delegate';
    if (t.impact === 'high' && t.expertise === 'high') return 'keep';
    if (t.expertise === 'specialist') return 'find';
    if (t.impact === 'high' && t.expertise === 'medium') return 'find';
    return 'delegate';
  }

  function levelDots(value, opts = {}) {
    // value: 'low'|'medium'|'high'|'specialist'
    const map = { low: 1, medium: 2, high: 3, specialist: 3 };
    const n = map[value] || 1;
    const label = { low: 'Low', medium: 'Med', high: 'High', specialist: 'Spec' }[value] || value;
    const onColor = opts.blue ? C.blue : C.ink;
    return (
      <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, fontSize: 11, color: C.inkSoft, fontWeight: 500 }}>
        <span style={{ display: 'inline-flex', gap: 3 }}>
          {[0, 1, 2].map(i => (
            <span key={i} style={{
              width: 6, height: 6, borderRadius: 3,
              background: i < n ? onColor : C.line,
            }} />
          ))}
        </span>
        {label}
      </span>
    );
  }

  function verdictPill(zone) {
    if (zone === 'keep') return <Pill bg={C.paperDeep} color={C.ink} border={C.line} icon="👤" label="Keep" />;
    if (zone === 'find') return <Pill bg={C.amberSoft} color={C.amber} border="rgba(183,110,0,0.2)" icon="⚲" label="Find specialist" />;
    return <Pill bg={C.blueSoft} color={C.blue} border="rgba(8,120,216,0.2)" icon="✓" label="Delegate" />;
  }

  function Pill({ bg, color, border, icon, label }) {
    return (
      <span style={{
        display: 'inline-flex', alignItems: 'center', gap: 5,
        padding: '3px 8px', borderRadius: 999,
        fontSize: 10.5, fontWeight: 500,
        background: bg, color, border: `1px solid ${border}`,
        width: 'fit-content',
      }}>
        <span>{icon}</span>{label}
      </span>
    );
  }

  // ---------- Page chrome ----------
  function Page({ children, isCover, pageNum }) {
    return (
      <div data-pdf-page={pageNum || ''} style={{
        width: PAGE_W,
        height: PAGE_H,
        background: '#fff',
        position: 'relative',
        overflow: 'hidden',
        color: C.ink,
      }}>
        {children}
      </div>
    );
  }

  function PagePad({ children, padding = '48px 56px' }) {
    return (
      <div style={{
        padding, height: '100%',
        display: 'flex', flexDirection: 'column',
      }}>
        {children}
      </div>
    );
  }

  function RunHead({ phaseNum, phaseLabel, email, dateStr }) {
    // Left: brand icon + product name + phase. Right: identifier (email) + date.
    const label = phaseNum
      ? `Delegation Playbook · Phase ${phaseNum} · ${phaseLabel}`
      : 'Delegation Playbook';
    return (
      <div style={{
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        paddingBottom: 14,
        borderBottom: `1px solid ${C.lineSoft}`,
        fontSize: 11, color: C.inkMuted, letterSpacing: '0.02em',
      }}>
        <div style={{ display: 'inline-flex', alignItems: 'center', gap: 9, fontFamily: FF_SERIF, fontWeight: 600, color: C.ink, fontSize: 12.5, letterSpacing: '-0.01em' }}>
          <img src="brand/bluemoso-icon.svg" alt="BlueMoso" width="18" height="18" style={{ display: 'block', borderRadius: 3 }} />
          {label}
        </div>
        <div style={{ fontVariantNumeric: 'tabular-nums' }}>
          {email ? <span>{email} · {dateStr}</span> : <span>{dateStr}</span>}
        </div>
      </div>
    );
  }

  function RunFoot({ pageNum, totalPages = 6 }) {
    const pad = (n) => String(n).padStart(2, '0');
    return (
      <div style={{
        marginTop: 'auto',
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        paddingTop: 14,
        borderTop: `1px solid ${C.lineSoft}`,
        fontSize: 10.5, color: C.inkMuted,
      }}>
        <div>The Delegation Playbook · BlueMoso</div>
        <div style={{ fontVariantNumeric: 'tabular-nums' }}>{pad(pageNum)} / {pad(totalPages)}</div>
      </div>
    );
  }

  function PhaseKicker({ num, label }) {
    return (
      <span style={{
        display: 'inline-flex', alignItems: 'center', gap: 8,
        padding: '5px 11px', borderRadius: 999,
        background: C.blueSoft, color: C.blue, fontWeight: 500, fontSize: 11,
        letterSpacing: '0.02em',
        whiteSpace: 'nowrap',
      }}>
        <span style={{ fontFamily: FF_SERIF, fontWeight: 500, fontSize: 10.5, letterSpacing: '0.08em' }}>PHASE {num}</span>
        <span style={{ width: 4, height: 4, borderRadius: 2, background: C.blue }} />
        <span>{label}</span>
      </span>
    );
  }

  function PhaseTitle({ children, italic }) {
    return (
      <h2 style={{
        margin: '14px 0 0',
        fontFamily: FF_SERIF, fontWeight: 600,
        fontSize: 38, lineHeight: 1.04, letterSpacing: '-0.025em',
        color: C.ink,
      }}>
        {children}{italic && <em style={{ color: C.blue, fontWeight: 700, fontStyle: 'italic' }}> {italic}</em>}
      </h2>
    );
  }

  function PhaseSub({ children }) {
    return (
      <p style={{
        margin: '12px 0 0',
        fontSize: 13.5, lineHeight: 1.55, color: C.inkMuted, maxWidth: 580,
      }}>{children}</p>
    );
  }

  // ---------- Page 1: COVER ----------
  // Light cover, blue brand logo, dark navy type.
  function PdfCover({ email, dateStr, taskCount, picksCount }) {
    return (
      <Page isCover pageNum={1}>
        {/* Subtle off-white background with a soft blue glow in the upper right. */}
        <div style={{
          position: 'absolute', inset: 0,
          background: '#F7FAFD',
        }} />
        <div style={{
          position: 'absolute', inset: 0,
          background: 'radial-gradient(70% 55% at 95% 10%, rgba(8,120,216,0.10) 0%, transparent 65%), radial-gradient(50% 50% at 5% 100%, rgba(85,166,229,0.08) 0%, transparent 70%)',
          pointerEvents: 'none',
        }} />
        {/* Bottom accent band */}
        <div style={{
          position: 'absolute', left: 0, right: 0, bottom: 0, height: 8,
          background: `linear-gradient(90deg, ${C.blueDeep} 0%, ${C.blue} 50%, ${C.blueMid} 100%)`,
        }} />
        <div style={{
          position: 'relative',
          padding: 56,
          height: '100%',
          display: 'flex', flexDirection: 'column',
          color: C.ink,
        }}>
          {/* Top: real BlueMoso blue logo + tag */}
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
            <img
              src="brand/bluemoso-logo-blue.svg"
              alt="BlueMoso"
              width="180"
              height="36"
              style={{ display: 'block', height: 36, width: 'auto' }}
            />
            <div style={{ fontSize: 11, color: C.inkMuted, letterSpacing: '0.14em', textTransform: 'uppercase' }}>A WORKBOOK FROM BLUEMOSO</div>
          </div>

          {/* Kicker */}
          <div style={{
            marginTop: 64,
            display: 'inline-flex', alignItems: 'center', gap: 10,
            padding: '6px 14px', borderRadius: 999,
            background: C.blueSoft,
            border: '1px solid rgba(8,120,216,0.18)',
            fontSize: 12, color: C.blue,
            alignSelf: 'flex-start',
          }}>
            <span style={{ width: 6, height: 6, borderRadius: 3, background: C.blue }} />
            Personalized delegation plan
          </div>

          {/* Title */}
          <h1 style={{
            margin: '28px 0 0',
            fontFamily: FF_SERIF, fontWeight: 400,
            fontSize: 88, lineHeight: 0.98, letterSpacing: '-0.035em',
            color: C.ink,
          }}>
            The Delegation<br />
            <em style={{ fontWeight: 700, fontStyle: 'normal', color: C.blue }}>Playbook.</em>
          </h1>
          <p style={{
            margin: '22px 0 0',
            fontSize: 17, lineHeight: 1.55,
            color: C.inkMuted,
            maxWidth: 520,
          }}>
            A four‑phase workbook for founders and executives. Reset the mindset, audit the work, build the plan, equip the assistant.
          </p>

          {/* Meta (no name/title — we only have email) */}
          <div style={{
            marginTop: 'auto',
            display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 24,
            borderTop: `1px solid ${C.line}`,
            paddingTop: 24,
          }}>
            <div>
              <div style={{ fontSize: 10.5, letterSpacing: '0.12em', textTransform: 'uppercase', color: C.inkMuted, marginBottom: 8 }}>Completed</div>
              <div style={{ fontFamily: FF_SERIF, fontWeight: 500, fontSize: 18, letterSpacing: '-0.01em', color: C.ink }}>{dateStr}</div>
            </div>
            <div>
              <div style={{ fontSize: 10.5, letterSpacing: '0.12em', textTransform: 'uppercase', color: C.inkMuted, marginBottom: 8 }}>Your plan in numbers</div>
              <div style={{ fontFamily: FF_SERIF, fontWeight: 500, fontSize: 18, letterSpacing: '-0.01em', color: C.ink }}>
                {taskCount} task{taskCount === 1 ? '' : 's'} · {picksCount} delegation pick{picksCount === 1 ? '' : 's'}
              </div>
            </div>
          </div>

          {/* Foot — email shown subtly here as identifier */}
          <div style={{
            marginTop: 28,
            display: 'flex', alignItems: 'center', justifyContent: 'space-between',
            fontSize: 11, color: C.inkMuted, letterSpacing: '0.06em',
          }}>
            <div style={{ display: 'inline-flex', alignItems: 'center', gap: 8 }}>
              {email ? (
                <>
                  <span style={{
                    width: 18, height: 18, borderRadius: 9,
                    border: `1.5px solid ${C.line}`,
                    color: C.blue,
                    display: 'inline-flex', alignItems: 'center', justifyContent: 'center', fontSize: 9,
                  }}>✓</span>
                  Designed for {email}
                </>
              ) : null}
            </div>
            <div>01 / 06</div>
          </div>
        </div>
      </Page>
    );
  }

  // ---------- Page 2: TOC ----------
  function PdfTOC({ email, dateStr }) {
    const rows = [
      { n: '01', h: 'Reset your mindset & focus', s: 'Three principles, then your hourly rate and the hours you\'d reclaim by delegating.', pg: '03' },
      { n: '02', h: 'Audit your reality', s: 'Your recurring weekly tasks, sorted Keep / Delegate / Find on the Impact × Expertise matrix.', pg: '04' },
      { n: '03', h: 'Your delegation blueprint', s: 'Top three picks, "done" defined for each, and the tool you\'ll hand them off in.', pg: '05' },
      { n: '04', h: 'Equip & act', s: 'Pre-handoff checklist, week-one cadence, and the assets to send your VA on day one.', pg: '06' },
    ];
    return (
      <Page pageNum={2}>
        <PagePad>
          <RunHead phaseNum="00" phaseLabel="Contents" email={email} dateStr={dateStr} />
          <div style={{ marginTop: 30 }}>
            <PhaseKicker num="00" label="Contents · Four phases · 45 minutes" />
            <PhaseTitle italic="inside.">What's</PhaseTitle>
            <PhaseSub>Your playbook is a working document. Sections 1 and 2 give you the lens. Sections 3 and 4 are the plan you hand a virtual assistant on day one.</PhaseSub>
          </div>

          <div style={{ marginTop: 24 }}>
            {rows.map(r => (
              <div key={r.n} style={{
                display: 'grid',
                gridTemplateColumns: '32px 1fr auto 40px',
                alignItems: 'baseline',
                padding: '14px 0',
                borderBottom: `1px solid ${C.lineSoft}`,
                gap: 14,
              }}>
                <div style={{ fontFamily: FF_SERIF, fontWeight: 500, fontSize: 18, color: C.blue, letterSpacing: '-0.02em' }}>{r.n}</div>
                <div>
                  <div style={{ fontSize: 14.5, fontWeight: 600, marginBottom: 3, letterSpacing: '-0.01em' }}>{r.h}</div>
                  <div style={{ fontSize: 11.5, color: C.inkMuted, lineHeight: 1.45 }}>{r.s}</div>
                </div>
                <div style={{ fontSize: 11, color: C.line, letterSpacing: '0.18em', overflow: 'hidden', whiteSpace: 'nowrap' }}>·····················</div>
                <div style={{ fontFamily: FF_SERIF, fontWeight: 500, fontSize: 14, color: C.ink, fontVariantNumeric: 'tabular-nums', textAlign: 'right' }}>{r.pg}</div>
              </div>
            ))}
          </div>

          <div style={{
            marginTop: 28,
            background: C.paperDeep,
            border: `1px solid ${C.lineSoft}`,
            borderRadius: 12, padding: 22,
            display: 'flex', gap: 18, alignItems: 'center',
          }}>
            <div style={{
              width: 48, height: 48, borderRadius: 12,
              background: C.blue, color: '#fff',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              fontFamily: FF_SERIF, fontWeight: 700, fontSize: 22,
            }}>?</div>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 13, fontWeight: 600, marginBottom: 4 }}>How to use this PDF</div>
              <div style={{ fontSize: 11.5, color: C.inkMuted, lineHeight: 1.55 }}>
                Print pages 3–6 and walk through them with your VA in your first kickoff call. Keep the blueprint (page 5) pinned in your project tool. Re‑run the playbook every quarter.
              </div>
            </div>
          </div>

          <RunFoot pageNum={2} />
        </PagePad>
      </Page>
    );
  }

  // ---------- Page 3: Phase 1 ----------
  function PdfPhase1({ hoursPerWeek, annualIncome, hourly, delegatableHours, annualHoursBack, weeksBack, dailyBack, email, dateStr }) {
    const hoursPct = Math.min(100, (hoursPerWeek / 100) * 100);
    const incomePct = Math.min(100, (annualIncome / 1000000) * 100);
    const delegatablePct = Math.min(100, (delegatableHours / 100) * 100);
    const deleg = Math.round(hourly * 0.5);

    return (
      <Page pageNum={3}>
        <PagePad>
          <RunHead phaseNum="01" phaseLabel="Mindset" email={email} dateStr={dateStr} />

          <div style={{ marginTop: 22 }}>
            <PhaseKicker num="01" label="Reset your mindset & focus" />
            <PhaseTitle italic="actually worth?">What's your time</PhaseTitle>
            <PhaseSub>The dollar value is a gut‑check. The real win is the hours you reclaim.</PhaseSub>
          </div>

          {/* Mindset cards */}
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 12, marginTop: 24 }}>
            {[
              { n: '01', t: 'You don\'t need to do everything yourself.', s: 'Excellence isn\'t measured in hours spent, it\'s measured in outcomes.' },
              { n: '02', t: 'Delegation isn\'t giving up control.', s: 'It\'s gaining capacity. The best operators own outcomes, not keystrokes.' },
              { n: '03', t: 'Progress beats perfection.', s: 'Clarity creates momentum. Start messy, then refine.' },
            ].map(c => (
              <div key={c.n} style={{ padding: 16, background: C.paperDeep, border: `1px solid ${C.lineSoft}`, borderRadius: 10 }}>
                <div style={{ fontFamily: FF_SERIF, fontWeight: 500, fontSize: 10.5, letterSpacing: '0.08em', color: C.blue, marginBottom: 10 }}>{c.n}</div>
                <div style={{ fontSize: 13, fontWeight: 600, lineHeight: 1.35, marginBottom: 6 }}>{c.t}</div>
                <div style={{ fontSize: 11.5, lineHeight: 1.5, color: C.inkMuted }}>{c.s}</div>
              </div>
            ))}
          </div>

          {/* Calculator card */}
          <div style={{ marginTop: 22, background: '#fff', border: `1px solid ${C.line}`, borderRadius: 12, overflow: 'hidden' }}>
            <div style={{ padding: '18px 22px', borderBottom: `1px solid ${C.lineSoft}`, display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 14 }}>
              <div>
                <div style={{ fontFamily: FF_SERIF, fontWeight: 500, fontSize: 10, letterSpacing: '0.08em', color: C.blue }}>CALCULATOR</div>
                <div style={{ fontFamily: FF_SERIF, fontWeight: 600, fontSize: 19, letterSpacing: '-0.02em', marginTop: 4 }}>Your hourly rate</div>
              </div>
              <div style={{ fontSize: 11, color: C.inkMuted, maxWidth: 220, textAlign: 'right' }}>Round numbers. A gut‑check, not accounting.</div>
            </div>

            {/* Inputs */}
            <div style={{ padding: '18px 22px', borderBottom: `1px solid ${C.lineSoft}`, display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 24 }}>
              <SliderReadout label="Hours you work per week" value={`${hoursPerWeek || 0} hrs`} pct={hoursPct} hint="Including evenings and weekends if that's real." />
              <SliderReadout label="Annual income" value={`$${(annualIncome || 0).toLocaleString()}`} pct={incomePct} hint="Your take, not company revenue." />
            </div>

            {/* Result */}
            <div style={{ padding: '16px 22px', borderBottom: `1px solid ${C.lineSoft}`, display: 'grid', gridTemplateColumns: '1fr 1px 1fr', gap: 18, alignItems: 'center' }}>
              <StatBlock label="Your hourly rate" value={`$${hourly || 0}`} />
              <div style={{ background: C.lineSoft, height: 50 }} />
              <StatBlock label="Delegate anything under" value={<><span>${deleg}</span><span style={{ fontSize: 18, color: C.inkMuted, fontWeight: 500 }}>/hr</span></>} hint="Rule of thumb: ~50% of your rate" tone="blue" />
            </div>

            {/* Delegatable slider */}
            <div style={{ padding: '16px 22px' }}>
              <SliderReadout label="Hours a VA could take off my plate" value={`${delegatableHours} hrs/wk`} pct={delegatablePct} hint="Inbox, scheduling, research, follow-ups, data entry. The small stuff that adds up." />
            </div>

            {/* Hero result */}
            <div style={{
              position: 'relative', overflow: 'hidden',
              background: 'linear-gradient(160deg, #161B3D 0%, #0A1028 100%)',
              color: '#fff', padding: 28, textAlign: 'center',
            }}>
              <div style={{
                position: 'absolute', bottom: -80, left: -40, width: 240, height: 240,
                borderRadius: '50%',
                background: 'radial-gradient(circle, rgba(85,166,229,0.25) 0%, transparent 70%)',
              }} />
              <div style={{ position: 'relative' }}>
                <div style={{ fontFamily: FF_SERIF, fontWeight: 500, fontSize: 10.5, letterSpacing: '0.14em', textTransform: 'uppercase', color: 'rgba(255,255,255,0.92)' }}>
                  Hours you'd get back by delegating
                </div>
                <div style={{ fontFamily: FF_SERIF, fontWeight: 600, fontSize: 72, lineHeight: 1, letterSpacing: '-0.035em', marginTop: 10 }}>
                  {(annualHoursBack || 0).toLocaleString()}
                  <span style={{ fontSize: 22, color: 'rgba(255,255,255,0.85)', marginLeft: 6, fontWeight: 500 }}>hrs/yr</span>
                </div>
                <div style={{ fontSize: 12.5, color: 'rgba(255,255,255,0.88)', marginTop: 10, lineHeight: 1.55 }}>
                  That's about <b style={{ fontWeight: 600 }}>{weeksBack} full work weeks</b> back, or roughly <b style={{ fontWeight: 600 }}>{dailyBack} hours a day</b> for family, focus, or higher‑leverage work.
                </div>
              </div>
            </div>
          </div>

          <RunFoot pageNum={3} />
        </PagePad>
      </Page>
    );
  }

  function SliderReadout({ label, value, pct, hint }) {
    return (
      <div>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 8 }}>
          <span style={{ fontSize: 11, fontWeight: 500, color: C.inkSoft }}>{label}</span>
          <span style={{ fontFamily: FF_MONO, fontWeight: 500, fontSize: 22, letterSpacing: '-0.02em', color: C.ink, fontVariantNumeric: 'tabular-nums' }}>{value}</span>
        </div>
        <div style={{ height: 4, background: C.lineSoft, borderRadius: 2, overflow: 'hidden' }}>
          <div style={{ height: '100%', width: `${pct}%`, background: C.blue, borderRadius: 2 }} />
        </div>
        {hint && <div style={{ fontSize: 10.5, color: C.inkMuted, marginTop: 8, lineHeight: 1.4 }}>{hint}</div>}
      </div>
    );
  }

  function StatBlock({ label, value, hint, tone = 'ink' }) {
    const color = tone === 'blue' ? C.blue : C.ink;
    return (
      <div>
        <div style={{ fontSize: 10, letterSpacing: '0.08em', textTransform: 'uppercase', color: C.inkMuted, fontWeight: 500, marginBottom: 8 }}>{label}</div>
        <div style={{ fontFamily: FF_SERIF, fontWeight: 600, fontSize: 40, lineHeight: 1, letterSpacing: '-0.03em', color }}>{value}</div>
        {hint && <div style={{ fontSize: 11, color: C.inkMuted, marginTop: 6 }}>{hint}</div>}
      </div>
    );
  }

  // ---------- Page 4: Phase 2 ----------
  function PdfPhase2({ tasks, totals, email, dateStr }) {
    const annualReclaimed = Math.round((totals.delegateHours + totals.findHours) * 50);
    return (
      <Page pageNum={4}>
        <PagePad>
          <RunHead phaseNum="02" phaseLabel="Audit" email={email} dateStr={dateStr} />

          <div style={{ marginTop: 22 }}>
            <PhaseKicker num="02" label="Audit your reality" />
            <PhaseTitle italic="see where your time goes.">List your tasks,</PhaseTitle>
          </div>

          {/* Matrix legend + grid */}
          <div style={{ display: 'grid', gridTemplateColumns: '220px 1fr', gap: 28, marginTop: 22 }}>
            <div>
              <div style={{ fontSize: 13, fontWeight: 600, marginBottom: 10 }}>The Impact Matrix</div>
              <div style={{ fontSize: 11.5, lineHeight: 1.55, color: C.inkMuted }}>
                Only jobs that are <strong style={{ color: C.ink }}>high‑impact</strong> and in your <strong style={{ color: C.ink }}>zone of genius</strong> stay on your plate. Everything else is a delegation candidate.
              </div>
            </div>
            <div style={{
              display: 'grid',
              gridTemplateColumns: '60px 1fr 1fr',
              gridTemplateRows: '28px 1fr 1fr',
              gap: 1,
              background: C.lineSoft,
              borderRadius: 10, overflow: 'hidden',
              border: `1px solid ${C.lineSoft}`,
            }}>
              <MCell head />
              <MCell head>Low Expertise</MCell>
              <MCell head>High Expertise</MCell>
              <MCell axis>High<br />Impact</MCell>
              <MCell deleg><strong style={{ color: C.blue, fontSize: 12 }}>✓ Delegate</strong><div style={{ fontSize: 10.5, color: C.inkMuted, marginTop: 2 }}>Give to VA</div></MCell>
              <MCell><strong style={{ fontSize: 12 }}>👤 Keep</strong><div style={{ fontSize: 10.5, color: C.inkMuted, marginTop: 2 }}>Your zone of genius</div></MCell>
              <MCell axis>Low<br />Impact</MCell>
              <MCell deleg><strong style={{ color: C.blue, fontSize: 12 }}>✓ Delegate</strong><div style={{ fontSize: 10.5, color: C.inkMuted, marginTop: 2 }}>Easy wins</div></MCell>
              <MCell deleg><strong style={{ color: C.blue, fontSize: 12 }}>✓ Delegate</strong><div style={{ fontSize: 10.5, color: C.inkMuted, marginTop: 2 }}>Not worth your rate</div></MCell>
            </div>
          </div>

          {/* Tasks */}
          <div style={{ marginTop: 22, border: `1px solid ${C.line}`, borderRadius: 10, overflow: 'hidden' }}>
            <div style={{
              display: 'grid', gridTemplateColumns: '2.2fr 0.7fr 0.9fr 0.9fr 1fr',
              background: C.paperDeep, padding: '10px 16px', gap: 10,
              fontSize: 9.5, letterSpacing: '0.08em', textTransform: 'uppercase', color: C.inkMuted, fontWeight: 600,
              borderBottom: `1px solid ${C.lineSoft}`,
            }}>
              <div>Task</div><div>Hrs/wk</div><div>Impact</div><div>Expertise</div><div>Verdict</div>
            </div>
            {tasks.length === 0 ? (
              <div style={{ padding: 24, textAlign: 'center', fontSize: 12, color: C.inkMuted }}>
                No tasks logged yet.
              </div>
            ) : tasks.map((t, i) => (
              <div key={t.id || i} style={{
                display: 'grid', gridTemplateColumns: '2.2fr 0.7fr 0.9fr 0.9fr 1fr',
                padding: '11px 16px', gap: 10, alignItems: 'center', fontSize: 12,
                borderTop: i === 0 ? 'none' : `1px solid ${C.lineSoft}`,
              }}>
                <div style={{ fontWeight: 500, color: C.ink }}>{t.name || <em style={{ color: C.inkMuted }}>Unnamed task</em>}</div>
                <div style={{ fontFamily: FF_SERIF, fontWeight: 500, fontVariantNumeric: 'tabular-nums' }}>{Number(t.hours || 0).toFixed(1)}</div>
                <div>{levelDots(t.impact)}</div>
                <div>{levelDots(t.expertise, { blue: t.expertise === 'specialist' })}</div>
                <div>{verdictPill(classify(t))}</div>
              </div>
            ))}
          </div>

          {/* Summary */}
          <div style={{
            marginTop: 18,
            background: C.ink, color: '#fff',
            borderRadius: 12, padding: 22,
            display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 18,
          }}>
            <SumStat label="Tasks tracked" value={tasks.length} sub={`${totals.totalHours.toFixed(1)} hrs / wk total`} />
            <SumStat label="To delegate" value={`${totals.delegateHours.toFixed(1)} hrs`} sub="VA‑ready work" tone="blue" />
            <SumStat label="To specialist" value={`${totals.findHours.toFixed(1)} hrs`} sub="Pros or tools" tone="amber" />
            <SumStat label="Hours reclaimed" value={`${annualReclaimed.toLocaleString()} hrs`} sub="per year, off your plate" tone="green" />
          </div>

          <RunFoot pageNum={4} />
        </PagePad>
      </Page>
    );
  }

  function MCell({ children, head, axis, deleg }) {
    let bg = '#fff';
    if (head || axis) bg = C.paperDeep;
    if (deleg) bg = C.blueSoft;
    return (
      <div style={{
        background: bg,
        padding: head ? '6px 12px' : axis ? '6px 4px' : '12px 14px',
        fontSize: head || axis ? 10 : 12,
        color: (head || axis) ? C.inkMuted : C.ink,
        display: 'flex', flexDirection: deleg || (!head && !axis) ? 'column' : 'row',
        alignItems: deleg || (!head && !axis) ? 'flex-start' : 'center',
        justifyContent: axis ? 'center' : 'flex-start',
        textAlign: axis ? 'center' : 'left',
        gap: 2,
      }}>{children}</div>
    );
  }

  function SumStat({ label, value, sub, tone = 'light' }) {
    const colors = {
      light: '#fff',
      blue: C.blueMid,
      amber: '#FFC670',
      green: '#9FE0AC',
    };
    return (
      <div>
        <div style={{ fontSize: 9.5, textTransform: 'uppercase', letterSpacing: '0.08em', color: 'rgba(255,255,255,0.85)', marginBottom: 8, fontWeight: 500 }}>{label}</div>
        <div style={{ fontFamily: FF_SERIF, fontWeight: 600, fontSize: 28, lineHeight: 1, letterSpacing: '-0.03em', color: colors[tone] }}>{value}</div>
        <div style={{ fontSize: 10.5, color: 'rgba(255,255,255,0.82)', marginTop: 6 }}>{sub}</div>
      </div>
    );
  }

  // ---------- Page 5: Phase 3 ----------
  function PdfPhase3({ picks, email, dateStr }) {
    return (
      <Page pageNum={5}>
        <PagePad>
          <RunHead phaseNum="03" phaseLabel="Blueprint" email={email} dateStr={dateStr} />

          <div style={{ marginTop: 22 }}>
            <PhaseKicker num="03" label="Make your delegation plan" />
            <PhaseTitle italic="Define done.">Pick your top 3.</PhaseTitle>
          </div>

          {/* Blueprint strip */}
          <div style={{
            display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: 8,
            padding: 16, background: C.paperDeep, border: `1px solid ${C.lineSoft}`,
            borderRadius: 10, marginTop: 18,
          }}>
            {[
              { n: 1, t: 'Inventory', s: 'List what you do' },
              { n: 2, t: 'Sort', s: 'Do, delegate, delete' },
              { n: 3, t: 'Prep', s: "Define 'done'" },
              { n: 4, t: 'Assign', s: 'Hand off in a tool' },
              { n: 5, t: 'Review', s: 'Follow up, feedback' },
            ].map(s => (
              <div key={s.n}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 4 }}>
                  <span style={{
                    width: 16, height: 16, borderRadius: 8,
                    background: C.ink, color: '#fff',
                    display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                    fontFamily: FF_SERIF, fontSize: 9, fontWeight: 600,
                  }}>{s.n}</span>
                  <span style={{ fontSize: 11.5, fontWeight: 600 }}>{s.t}</span>
                </div>
                <div style={{ fontSize: 10.5, color: C.inkMuted }}>{s.s}</div>
              </div>
            ))}
          </div>

          {/* Picks */}
          {picks.length === 0 ? (
            <div style={{
              marginTop: 18, padding: 24, borderRadius: 12, border: `1px dashed ${C.line}`,
              background: C.paperDeep, color: C.inkMuted, fontSize: 12.5, textAlign: 'center',
            }}>
              No picks yet — go back to Phase 3 in the playbook and select up to 3 tasks to delegate first.
            </div>
          ) : picks.slice(0, 3).map((p, i) => (
            <div key={p.taskId || i} style={{
              marginTop: 14,
              border: `1px solid ${C.line}`, borderRadius: 12,
              padding: '18px 20px', background: '#fff',
              display: 'grid', gridTemplateColumns: '44px 1fr 110px', gap: 16, alignItems: 'start',
            }}>
              <div style={{ fontFamily: FF_SERIF, fontWeight: 600, fontSize: 30, lineHeight: 1, color: C.blue, letterSpacing: '-0.02em' }}>0{i + 1}</div>
              <div>
                <div style={{ fontSize: 15, fontWeight: 600, marginBottom: 6 }}>{p.task.name}</div>
                <PickRow k="DONE LOOKS LIKE" v={p.doneLooksLike || <em style={{ color: C.inkMuted }}>No "done" defined yet.</em>} />
                {p.tool && <PickRow k="HAND OFF IN" v={p.tool} />}
              </div>
              <div style={{ textAlign: 'right' }}>
                <div style={{ fontFamily: FF_SERIF, fontWeight: 600, fontSize: 24, letterSpacing: '-0.02em', lineHeight: 1 }}>{p.task.hours} hrs</div>
                <div style={{ fontSize: 10, color: C.inkMuted, marginTop: 4 }}>per week back</div>
              </div>
            </div>
          ))}

          <RunFoot pageNum={5} />
        </PagePad>
      </Page>
    );
  }

  function PickRow({ k, v }) {
    return (
      <div style={{ display: 'grid', gridTemplateColumns: '100px 1fr', gap: 12, alignItems: 'baseline', marginTop: 8 }}>
        <div style={{ fontSize: 10, textTransform: 'uppercase', letterSpacing: '0.08em', color: C.inkMuted, fontWeight: 600, paddingTop: 2 }}>{k}</div>
        <div style={{ fontSize: 12.5, color: C.inkSoft, lineHeight: 1.5 }}>{v}</div>
      </div>
    );
  }

  // ---------- Page 6: Phase 4 ----------
  function PdfPhase4({ picks, pickHoursTotal, pickAnnualBack, pickWeeksBack, email, dateStr }) {
    return (
      <Page pageNum={6}>
        <PagePad>
          <RunHead phaseNum="04" phaseLabel="Equip & act" email={email} dateStr={dateStr} />

          <div style={{ marginTop: 22 }}>
            <PhaseKicker num="04" label="Equip & act" />
            <PhaseTitle italic="ready to run.">Your delegation plan,</PhaseTitle>
          </div>

          {/* Hero results */}
          <div style={{
            background: C.ink, color: '#fff',
            borderRadius: 14, padding: 26, marginTop: 22,
            display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 24,
          }}>
            <HeroStat label="Hours back per week" value={pickHoursTotal.toFixed(1)} unit="hrs/wk" />
            <HeroStat label="Hours back per year" value={pickAnnualBack.toLocaleString()} unit="hrs/yr" tone="blue" />
            <HeroStat label="That's roughly" value={pickWeeksBack} unit="full work weeks" />
          </div>

          {/* Checklist + SOP grid */}
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16, marginTop: 20 }}>
            <div style={{ border: `1px solid ${C.line}`, borderRadius: 12, padding: 20 }}>
              <div style={{ fontSize: 12.5, fontWeight: 600, marginBottom: 12 }}>Pre‑handoff checklist</div>
              {[
                'I tracked my recurring tasks honestly',
                'I picked 3 things to delegate first',
                'I gave clear instructions, what "done" looks like',
                'I scheduled a follow‑up in week one',
                "I'll give feedback early, not let it fester",
              ].map((t, i) => (
                <div key={i} style={{ display: 'flex', alignItems: 'flex-start', gap: 10, padding: '8px 0', fontSize: 12.5, color: C.inkSoft }}>
                  <span style={{
                    width: 16, height: 16, borderRadius: 4,
                    border: `1.5px solid ${C.line}`, flexShrink: 0, marginTop: 1, background: '#fff',
                  }} />
                  {t}
                </div>
              ))}
            </div>

            <div style={{ background: C.paperDeep, border: `1px solid ${C.lineSoft}`, borderRadius: 12, padding: '18px 20px' }}>
              <div style={{ fontSize: 12.5, fontWeight: 600, marginBottom: 12 }}>Send your VA on day one</div>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '10px 18px' }}>
                {[
                  'Access list (tools + logins via 1Password)',
                  'Voice samples (5 emails you\'ve written)',
                  'This blueprint, pages 4–5',
                  '30‑min kickoff call, Monday 9am',
                  'Weekly 15‑min review, Fridays 3pm',
                  '"What I\'d love off my plate" Loom video',
                ].map((t, i) => (
                  <div key={i} style={{ display: 'flex', alignItems: 'flex-start', gap: 8, fontSize: 11.5, color: C.inkSoft }}>
                    <span style={{ fontFamily: FF_SERIF, fontWeight: 600, color: C.blue, fontSize: 11 }}>0{i + 1}</span>
                    {t}
                  </div>
                ))}
              </div>
            </div>
          </div>

          {/* Next step CTA */}
          <div style={{
            marginTop: 22, padding: 28,
            borderRadius: 14, border: `1px solid ${C.lineSoft}`,
            background: 'linear-gradient(160deg, #E4F1FB 0%, #FFFFFF 70%)',
          }}>
            <div style={{ fontFamily: FF_SERIF, fontWeight: 500, fontSize: 10.5, letterSpacing: '0.12em', color: C.blue, textTransform: 'uppercase' }}>NEXT STEP</div>
            <div style={{ fontFamily: FF_SERIF, fontWeight: 600, fontSize: 30, letterSpacing: '-0.025em', lineHeight: 1.05, marginTop: 10 }}>
              Don't want to do the delegating yourself?{' '}
              <em style={{ color: C.blue, fontStyle: 'italic', fontWeight: 600 }}>That's what we do.</em>
            </div>
            <div style={{ fontSize: 13, color: C.inkSoft, lineHeight: 1.55, marginTop: 12, maxWidth: 500 }}>
              BlueMoso matches you with a virtual assistant trained to own these exact tasks. Bring this plan to a 20‑minute call and we'll tell you who we'd pair you with.
            </div>
            {/* Block-level <a> so html2canvas renders reliably AND data-pdf-link is picked up
                by savePdfLocally to add a clickable annotation on top of the image. */}
            <a
              href="https://bluemoso.com/#cta"
              data-pdf-link="https://bluemoso.com/#cta"
              style={{
                display: 'inline-block',
                marginTop: 18,
                padding: '14px 22px',
                background: C.ink,
                color: '#ffffff',
                borderRadius: 10,
                fontSize: 14,
                fontWeight: 500,
                textDecoration: 'none',
                lineHeight: 1.2,
                whiteSpace: 'nowrap',
              }}
            >
              Take back your time now&nbsp;&nbsp;→
            </a>
          </div>

          {/* Footer */}
          <div style={{
            marginTop: 'auto',
            borderTop: `1px solid ${C.lineSoft}`,
            paddingTop: 22,
            display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 18,
            fontSize: 11, color: C.inkMuted, lineHeight: 1.55,
          }}>
            <div>
              <div style={{ fontSize: 10, letterSpacing: '0.08em', textTransform: 'uppercase', color: C.ink, fontWeight: 600, marginBottom: 8 }}>Print &amp; share</div>
              Re-run this playbook every quarter. Your tasks change; the framework doesn't.
            </div>
            <div>
              <div style={{ fontSize: 10, letterSpacing: '0.08em', textTransform: 'uppercase', color: C.ink, fontWeight: 600, marginBottom: 8 }}>Find us</div>
              bluemoso.com<br />hello@bluemoso.com<br />linkedin.com/company/bluemosovas
            </div>
            <div>
              <div style={{ fontSize: 10, letterSpacing: '0.08em', textTransform: 'uppercase', color: C.ink, fontWeight: 600, marginBottom: 8 }}>© 2026 BlueMoso Inc.</div>
              The Delegation Playbook v3. Free to share with attribution.
            </div>
          </div>

          <div style={{ display: 'flex', justifyContent: 'space-between', paddingTop: 8, fontSize: 10.5, color: C.inkMuted }}>
            <div>The Delegation Playbook · BlueMoso</div>
            <div style={{ fontVariantNumeric: 'tabular-nums' }}>06 / 06</div>
          </div>
        </PagePad>
      </Page>
    );
  }

  function HeroStat({ label, value, unit, tone = 'light' }) {
    const color = tone === 'blue' ? '#9FCCF5' : '#fff';
    return (
      <div>
        <div style={{ fontSize: 10, textTransform: 'uppercase', letterSpacing: '0.1em', color: 'rgba(255,255,255,0.85)', fontWeight: 500, marginBottom: 10 }}>{label}</div>
        <div style={{ fontFamily: FF_SERIF, fontWeight: 600, fontSize: 48, lineHeight: 1, letterSpacing: '-0.035em', color }}>{value}</div>
        <div style={{ fontSize: 11.5, color: 'rgba(255,255,255,0.85)', marginTop: 8 }}>{unit}</div>
      </div>
    );
  }

  // ---------- Main template component ----------
  function PlaybookPdfTemplate({ state, offscreen = true }) {
    const s = state || {};
    const hoursPerWeek = Number(s.hoursPerWeek) || 0;
    const annualIncome = Number(s.annualIncome) || 0;
    const workHoursPerYear = (hoursPerWeek || 50) * 50;
    const hourly = annualIncome > 0 && workHoursPerYear > 0 ? Math.round(annualIncome / workHoursPerYear) : 0;

    const delegatableHoursRaw = Number(s.delegatableHours);
    const delegatableHours = Math.min(
      Number.isFinite(delegatableHoursRaw) ? delegatableHoursRaw : 10,
      hoursPerWeek || 100
    );
    const phase1AnnualBack = delegatableHours * 50;
    const phase1WeeksBack = Math.round(phase1AnnualBack / 40);
    const phase1DailyBack = (delegatableHours / 5).toFixed(1);

    const tasks = Array.isArray(s.tasks) ? s.tasks : [];
    const totalHours = tasks.reduce((a, t) => a + (Number(t.hours) || 0), 0);
    const delegateHours = tasks.filter(t => classify(t) === 'delegate').reduce((a, t) => a + (Number(t.hours) || 0), 0);
    const findHours     = tasks.filter(t => classify(t) === 'find').reduce((a, t) => a + (Number(t.hours) || 0), 0);
    const keepHours     = tasks.filter(t => classify(t) === 'keep').reduce((a, t) => a + (Number(t.hours) || 0), 0);

    const picks = (Array.isArray(s.blueprintPicks) ? s.blueprintPicks : [])
      .map(p => ({ ...p, task: tasks.find(t => t.id === p.taskId) }))
      .filter(p => p.task);
    const pickHoursTotal = picks.reduce((a, p) => a + (Number(p.task.hours) || 0), 0);
    const pickAnnualBack = Math.round(pickHoursTotal * 50);
    const pickWeeksBack = Math.round(pickAnnualBack / 40);

    const recipientEmail = (s.email && String(s.email).trim()) || '';
    const dateStr = fmtDate(Date.now());

    // Wrapper: off-screen (still in flow) so html2canvas can capture by id.
    // Absolute positioning is OK because the capture targets the element directly.
    const wrapStyle = offscreen ? {
      position: 'absolute',
      left: '-99999px',
      top: 0,
      width: PAGE_W,
      pointerEvents: 'none',
      // Ensure no parent transform / overflow clipping affects layout
      background: '#fff',
      fontFamily: FF_SANS,
      color: C.ink,
    } : {
      width: PAGE_W,
      margin: '0 auto',
      background: '#fff',
      fontFamily: FF_SANS,
      color: C.ink,
    };

    return (
      <div id="playbook-pdf-content" style={wrapStyle} aria-hidden={offscreen ? 'true' : undefined}>
        <PdfCover     email={recipientEmail} dateStr={dateStr} taskCount={tasks.length} picksCount={picks.length} />
        <PdfTOC       email={recipientEmail} dateStr={dateStr} />
        <PdfPhase1
          hoursPerWeek={hoursPerWeek}
          annualIncome={annualIncome}
          hourly={hourly}
          delegatableHours={delegatableHours}
          annualHoursBack={phase1AnnualBack}
          weeksBack={phase1WeeksBack}
          dailyBack={phase1DailyBack}
          email={recipientEmail}
          dateStr={dateStr}
        />
        <PdfPhase2
          tasks={tasks}
          totals={{ totalHours, delegateHours, findHours, keepHours }}
          email={recipientEmail}
          dateStr={dateStr}
        />
        <PdfPhase3
          picks={picks}
          email={recipientEmail}
          dateStr={dateStr}
        />
        <PdfPhase4
          picks={picks}
          pickHoursTotal={pickHoursTotal}
          pickAnnualBack={pickAnnualBack}
          pickWeeksBack={pickWeeksBack}
          email={recipientEmail}
          dateStr={dateStr}
        />
      </div>
    );
  }

  // Export
  Object.assign(window, { PlaybookPdfTemplate });
})();
