// WorksheetPdfTemplate
// Renders a multi-page, print-formatted version of the user's completed
// AI-or-Human Worksheet, captured by html2canvas + jsPDF (via the lib helper
// window.bluemoso.pdf.saveLocallyFromElement). Mirrors the visual system of
// playbook/playbook-pdf-template.jsx so both downloads feel like the same set.
//
// Constraints (html2canvas-safe):
//   - Inline styles only. No CSS variables, no external CSS.
//   - No position: fixed, no transforms on captured content.
//   - No url() background images. Linear/radial gradients are OK.
//   - Fonts (Outfit, Inter) are loaded by the host page via Google Fonts.
//   - The global <Icon> (components/Placeholder.jsx) is reused for glyphs.
//
// The whole component renders into a wrapper <div id="worksheet-pdf-content">
// positioned off-screen via absolute + negative left. Each [data-pdf-page]
// child becomes one Letter-sized page in the lib's buildPdfFromElement().

(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',
    sand: '#D6E6F5',
    sandSoft: '#EAF2FA',
    greenOk: '#2F6B3E',
    greenSoft: 'rgba(47,107,62,0.08)',
    coral: '#F26B5C',
    coralSoft: 'rgba(242,107,92,0.13)',
    coralInk: '#B73A2A',
  };

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

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

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

  // ---------- Page chrome ----------
  function Page({ children, 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({ label, email, dateStr }) {
    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 = 3 }) {
    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 AI-or-Human Worksheet · BlueMoso</div>
        <div style={{ fontVariantNumeric: 'tabular-nums' }}>{pad(pageNum)} / {pad(totalPages)}</div>
      </div>
    );
  }

  function Kicker({ children }) {
    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={{ width: 4, height: 4, borderRadius: 2, background: C.coral }} />
        {children}
      </span>
    );
  }

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

  // ---------- Page 1: COVER ----------
  function PdfCover({ firstName, email, dateStr, aiCount, humanCount, premiumCount }) {
    return (
      <Page pageNum={1}>
        <div style={{ position: 'absolute', inset: 0, background: '#F7FAFD' }} />
        <div style={{
          position: 'absolute', inset: 0, pointerEvents: 'none',
          background: 'radial-gradient(70% 55% at 95% 8%, rgba(8,120,216,0.10) 0%, transparent 65%), radial-gradient(50% 50% at 4% 100%, rgba(85,166,229,0.08) 0%, transparent 70%)',
        }} />
        <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 }}>
          <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 WORKSHEET FROM BLUEMOSO</div>
          </div>

          <div style={{
            marginTop: 60, 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.coral }} />
            Your customer-experience plan
          </div>

          <h1 style={{
            margin: '28px 0 0', fontFamily: FF_SERIF, fontWeight: 400,
            fontSize: 90, lineHeight: 0.96, letterSpacing: '-0.035em', color: C.ink,
          }}>
            AI, or a<br />
            <em style={{ fontWeight: 700, fontStyle: 'normal', color: C.blue }}>human?</em>
          </h1>
          <p style={{ margin: '22px 0 0', fontSize: 17, lineHeight: 1.55, color: C.inkMuted, maxWidth: 520 }}>
            Your plan for which customer conversations to hand to AI, which to keep with a real person, and which moments are worth charging for.
          </p>

          <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 }}>Prepared for</div>
              <div style={{ fontFamily: FF_SERIF, fontWeight: 500, fontSize: 18, letterSpacing: '-0.01em', color: C.ink }}>{firstName || 'You'}</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 }}>
                {aiCount} to AI · {humanCount} to a person · {premiumCount} premium
              </div>
            </div>
          </div>

          <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}
                </>
              ) : <span>Completed {dateStr}</span>}
            </div>
            <div>01 / 03</div>
          </div>
        </div>
      </Page>
    );
  }

  // ---------- Page 2: The map ----------
  function ColHead({ bg, icon, children }) {
    return (
      <div style={{
        padding: '12px 16px', fontFamily: FF_SERIF, fontWeight: 600, fontSize: 14.5,
        color: '#fff', background: bg, display: 'flex', alignItems: 'center', gap: 8, whiteSpace: 'nowrap',
      }}>
        <Icon name={icon} size={16} color="#fff" /> {children}
      </div>
    );
  }

  function PdfMap({ aiItems, humanItems, trapCount, premiumCount, email, dateStr }) {
    const rowStyle = (last) => ({
      display: 'flex', alignItems: 'flex-start', gap: 9, padding: '8px 0',
      fontSize: 13, color: C.ink, lineHeight: 1.35,
      borderBottom: last ? 'none' : `1px solid ${C.lineSoft}`,
    });
    return (
      <Page pageNum={2}>
        <PagePad>
          <RunHead label="The AI-or-Human Worksheet · Your map" email={email} dateStr={dateStr} />

          <div style={{ marginTop: 22 }}>
            <Kicker>Your plan</Kicker>
            <PageTitle italic="and what a person handles.">What AI handles,</PageTitle>
            <p style={{ margin: '12px 0 0', fontSize: 13.5, lineHeight: 1.55, color: C.inkMuted, maxWidth: 600 }}>
              Every way customers reach you, sorted. AI takes the quick, repeating questions; a real person owns the moments that matter.
            </p>
          </div>

          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 18, marginTop: 24 }}>
            <div style={{ border: `1px solid ${C.line}`, borderRadius: 14, overflow: 'hidden' }}>
              <ColHead bg={C.ink} icon="sparkle">AI handles this</ColHead>
              <div style={{ padding: '8px 16px 14px' }}>
                {aiItems.length === 0
                  ? <div style={{ fontSize: 13, color: C.inkMuted, padding: '10px 0', fontStyle: 'italic' }}>Nothing sorted here yet.</div>
                  : aiItems.map((it, i) => (
                    <div key={it.id} style={rowStyle(i === aiItems.length - 1)}>
                      {it.exit === false
                        ? <span style={{ color: C.coral, flex: 'none', marginTop: 1 }}><Icon name="shield" size={15} color={C.coral} /></span>
                        : <span style={{ color: C.greenOk, flex: 'none', marginTop: 1 }}><Icon name="check" size={15} color={C.greenOk} /></span>}
                      <span>{it.text}</span>
                    </div>
                  ))}
              </div>
            </div>
            <div style={{ border: `1px solid ${C.line}`, borderRadius: 14, overflow: 'hidden' }}>
              <ColHead bg={C.blue} icon="users">A person handles this</ColHead>
              <div style={{ padding: '8px 16px 14px' }}>
                {humanItems.length === 0
                  ? <div style={{ fontSize: 13, color: C.inkMuted, padding: '10px 0', fontStyle: 'italic' }}>Nothing sorted here yet.</div>
                  : humanItems.map((it, i) => (
                    <div key={it.id} style={rowStyle(i === humanItems.length - 1)}>
                      {it.premium
                        ? <span style={{ color: C.blue, flex: 'none', marginTop: 1 }}><Icon name="star" size={15} color={C.blue} /></span>
                        : <span style={{ width: 15, flex: 'none' }}></span>}
                      <span>{it.text}</span>
                    </div>
                  ))}
              </div>
            </div>
          </div>

          {/* Legend / counters */}
          <div style={{
            marginTop: 20, display: 'flex', flexWrap: 'wrap', gap: '8px 28px',
            padding: '16px 20px', background: C.paperDeep, border: `1px solid ${C.lineSoft}`, borderRadius: 12,
            fontSize: 12.5, color: C.inkMuted,
          }}>
            <span><strong style={{ color: C.ink, fontWeight: 600 }}>{aiItems.length}</strong> to AI</span>
            <span><strong style={{ color: C.ink, fontWeight: 600 }}>{humanItems.length}</strong> to a person</span>
            <span style={{ color: trapCount > 0 ? C.coralInk : C.inkMuted }}><strong style={{ color: trapCount > 0 ? C.coralInk : C.ink, fontWeight: 600 }}>{trapCount}</strong> gap{trapCount === 1 ? '' : 's'} to fix</span>
            <span><strong style={{ color: C.blueDeep, fontWeight: 600 }}>{premiumCount}</strong> premium moment{premiumCount === 1 ? '' : 's'}</span>
          </div>

          <div style={{
            marginTop: 16, display: 'flex', gap: 16, alignItems: 'center', flexWrap: 'wrap',
            fontSize: 11.5, color: C.inkMuted,
          }}>
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}><Icon name="check" size={13} color={C.greenOk} /> Customers can reach a person</span>
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}><Icon name="shield" size={13} color={C.coral} /> No quick way to a person</span>
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}><Icon name="star" size={13} color={C.blue} /> Premium moment</span>
          </div>

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

  // ---------- Page 3: Protect & charge ----------
  function PdfProtect({ trapDoors, reachableAll, premiumItems, good, trap, email, dateStr }) {
    return (
      <Page pageNum={3}>
        <PagePad>
          <RunHead label="The AI-or-Human Worksheet · Protect & charge" email={email} dateStr={dateStr} />

          <div style={{ marginTop: 22 }}>
            <Kicker>Protect &amp; charge</Kicker>
            <PageTitle italic="charge for the magic.">Fix the gaps,</PageTitle>
          </div>

          {/* Gaps */}
          {trapDoors.length > 0 ? (
            <div style={{ marginTop: 22, background: C.coralSoft, border: '1px solid rgba(242,107,92,0.3)', borderRadius: 14, padding: '18px 20px' }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 8, fontFamily: FF_SERIF, fontWeight: 600, fontSize: 15, color: C.coralInk, marginBottom: 10, whiteSpace: 'nowrap' }}>
                <Icon name="shield" size={17} color={C.coralInk} /> Fix these gaps first
              </div>
              {trapDoors.map((t) => (
                <div key={t.id} style={{ display: 'flex', gap: 8, alignItems: 'flex-start', padding: '5px 0', fontSize: 13, color: C.inkSoft, lineHeight: 1.45 }}>
                  <span style={{ flex: 'none', marginTop: 2 }}><Icon name="arrow" size={13} color={C.coralInk} /></span>
                  <span><strong style={{ color: C.ink, fontWeight: 600 }}>{t.text}:</strong> give customers a quick, obvious way to reach a person before you lean on AI here.</span>
                </div>
              ))}
            </div>
          ) : (
            <div style={{ marginTop: 22, background: C.greenSoft, border: '1px solid rgba(47,107,62,0.25)', borderRadius: 14, padding: '16px 20px', display: 'flex', gap: 11, alignItems: 'center', fontSize: 13.5, color: C.greenOk, fontWeight: 500 }}>
              <Icon name="check" size={18} color={C.greenOk} /> {reachableAll ? 'Every AI answer has a quick way to reach a person. That\u2019s exactly right.' : 'No trap doors yet \u2014 keep a fast way to a person on every AI flow.'}
            </div>
          )}

          {/* Premium */}
          <div style={{ marginTop: 16, background: C.blueSoft, border: '1px solid rgba(8,120,216,0.18)', borderRadius: 14, padding: '18px 20px' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, fontFamily: FF_SERIF, fontWeight: 600, fontSize: 15, color: C.blueDeep, marginBottom: 10, whiteSpace: 'nowrap' }}>
              <Icon name="star" size={17} color={C.blueDeep} /> Premium moments to charge for
            </div>
            {premiumItems.length === 0 ? (
              <div style={{ fontSize: 13, color: C.inkMuted, lineHeight: 1.5 }}>
                None marked yet. Pick the 2\u20133 moments a customer would gladly pay to have a real, named person own, and make that tier visible.
              </div>
            ) : premiumItems.map((t, i) => (
              <div key={t.id} style={{ padding: '10px 0', borderBottom: i === premiumItems.length - 1 ? 'none' : '1px solid rgba(8,120,216,0.12)' }}>
                <div style={{ fontWeight: 600, fontSize: 14, color: C.ink, marginBottom: 4 }}>{t.text}</div>
                {t.seen && <p style={{ fontSize: 12.5, color: C.inkSoft, lineHeight: 1.5, margin: '2px 0' }}><span style={{ fontWeight: 600, color: C.blueDeep }}>Customers see:</span> {t.seen}</p>}
                {t.brief && <p style={{ fontSize: 12.5, color: C.inkSoft, lineHeight: 1.5, margin: '2px 0' }}><span style={{ fontWeight: 600, color: C.blueDeep }}>AI gathers:</span> {t.brief}</p>}
              </div>
            ))}
          </div>

          {/* Measure */}
          <div style={{ marginTop: 16, background: C.sandSoft, border: `1px solid ${C.sand}`, borderRadius: 14, padding: '18px 20px' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, fontFamily: FF_SERIF, fontWeight: 600, fontSize: 15, color: C.ink, marginBottom: 8, whiteSpace: 'nowrap' }}>
              <Icon name="chart" size={17} color={C.ink} /> What we'll measure
            </div>
            {good.length === 0 && trap.length === 0 ? (
              <div style={{ fontSize: 13, color: C.inkSoft, lineHeight: 1.55 }}>
                Pick the numbers you'll track. Aim for whether problems get solved and whether customers stay.
              </div>
            ) : (
              <div>
                {good.length > 0 && <p style={{ fontSize: 13, color: C.inkSoft, lineHeight: 1.5, margin: '0 0 4px' }}><span style={{ fontWeight: 600, color: C.ink }}>Tracking:</span> {good.join(', ')}.</p>}
                {trap.length > 0 && <p style={{ fontSize: 13, color: C.coralInk, lineHeight: 1.5, margin: 0 }}><span style={{ fontWeight: 600 }}>Be careful with:</span> {trap.join(', ')}. This rewards avoiding customers, not helping them.</p>}
              </div>
            )}
          </div>

          {/* CTA */}
          <div style={{
            marginTop: 22, padding: 26, 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: 26, letterSpacing: '-0.025em', lineHeight: 1.08, marginTop: 10 }}>
              Want a real person on your premium moments?{' '}
              <em style={{ color: C.blue, fontStyle: 'italic', fontWeight: 600 }}>That's what we do.</em>
            </div>
            <div style={{ fontSize: 12.5, color: C.inkSoft, lineHeight: 1.55, marginTop: 10, maxWidth: 520 }}>
              BlueMoso matches you with a trained virtual assistant who can own the human moments on this plan. Bring it to a 20-minute call and we'll show you who we'd pair you with.
            </div>
            <a
              href="https://schedule.bluemoso.com/intro-meeting-m5ww00z"
              data-pdf-link="https://schedule.bluemoso.com/intro-meeting-m5ww00z"
              style={{
                display: 'inline-block', marginTop: 16, padding: '13px 22px',
                background: C.ink, color: '#ffffff', borderRadius: 10,
                fontSize: 13.5, fontWeight: 500, textDecoration: 'none', lineHeight: 1.2, whiteSpace: 'nowrap',
              }}
            >
              Book a call with BlueMoso&nbsp;&nbsp;→
            </a>
          </div>

          {/* Footer */}
          <div style={{
            marginTop: 'auto', borderTop: `1px solid ${C.lineSoft}`, paddingTop: 20,
            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 }}>Revisit &amp; share</div>
              Re-run this as your service changes. Cheap is about to be everywhere; a human who cares is about to be rare.
            </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 AI-or-Human Worksheet. Free to share with attribution.
            </div>
          </div>

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

  // ---------- Main template component ----------
  function WorksheetPdfTemplate({
    firstName, email, aiItems = [], humanItems = [], trapDoors = [], premiumItems = [],
    good = [], trap = [], reachableAll = false, offscreen = true,
  }) {
    const dateStr = fmtDate(Date.now());

    const wrapStyle = offscreen ? {
      position: 'absolute', left: '-99999px', top: 0, width: PAGE_W,
      pointerEvents: 'none', 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="worksheet-pdf-content" style={wrapStyle} aria-hidden={offscreen ? 'true' : undefined}>
        <PdfCover
          firstName={firstName} email={email} dateStr={dateStr}
          aiCount={aiItems.length} humanCount={humanItems.length} premiumCount={premiumItems.length}
        />
        <PdfMap
          aiItems={aiItems} humanItems={humanItems}
          trapCount={trapDoors.length} premiumCount={premiumItems.length}
          email={email} dateStr={dateStr}
        />
        <PdfProtect
          trapDoors={trapDoors} reachableAll={reachableAll} premiumItems={premiumItems}
          good={good} trap={trap} email={email} dateStr={dateStr}
        />
      </div>
    );
  }

  Object.assign(window, { WorksheetPdfTemplate });
})();
