// The AI-or-Human Worksheet - a free, gated, interactive worksheet
// that helps founders sort customer interactions into "let AI handle it" vs
// "keep a human on it." Mirrors the Delegation Playbook pattern:
//   - shared Nav / Footer / CTA / BookingModal chrome
//   - email gate wired through window.bluemoso.api.submitLead (NOT raw fetch)
//   - inputs persisted to localStorage so a refresh doesn't wipe the work
//   - "Print / Save as PDF" uses window.print() (browser print, not the
//     jsPDF/html2canvas lib path, which is reserved for the playbook PDF flow)
//
// v2 - item-centric flow. Instead of a brain-dump column followed by three
// disconnected exercises, the whole worksheet revolves around ONE list of
// interactions the user types. Every later decision (human exit? premium?
// what AI preps first?) hangs off the specific items they sorted, and a live
// summary card at the bottom is the printable payoff.

const LS_KEY = 'bm-worksheet-two-column-v1';

function loadSaved() {
  try { return JSON.parse(localStorage.getItem(LS_KEY) || '{}') || {}; }
  catch (e) { return {}; }
}
function saveField(patch) {
  try {
    const next = { ...loadSaved(), ...patch };
    localStorage.setItem(LS_KEY, JSON.stringify(next));
  } catch (e) { /* private mode / quota - non-fatal */ }
}
function uid() { return 'i' + Math.random().toString(36).slice(2, 9); }

const wsStyles = {
  // ===== Page shell =====
  page: { position: 'relative', padding: '64px 24px 96px', overflow: 'hidden' },
  pageBg: { position: 'absolute', inset: 0, pointerEvents: 'none', background: 'radial-gradient(55% 45% at 88% 4%, rgba(8,120,216,0.07) 0%, transparent 60%), radial-gradient(40% 42% at 0% 92%, rgba(214,230,245,0.5) 0%, transparent 70%)' },
  wrap: { maxWidth: 920, margin: '0 auto', position: 'relative' },

  // ===== Hero / lede =====
  eyebrow: { display: 'inline-flex', alignItems: 'center', gap: 8, fontSize: 13, color: 'var(--blue)', fontWeight: 500, padding: '6px 13px', borderRadius: 999, background: 'var(--blue-soft)', border: '1px solid rgba(8,120,216,0.12)', marginBottom: 22, whiteSpace: 'nowrap' },
  eyebrowDot: { width: 6, height: 6, borderRadius: 3, background: 'var(--coral)' },
  h1: { fontFamily: "'Outfit', system-ui, sans-serif", fontSize: 'clamp(32px, 5vw, 52px)', lineHeight: 1.04, letterSpacing: '-0.03em', fontWeight: 600, color: 'var(--ink)', margin: 0, maxWidth: 'none', textWrap: 'balance' },
  h1Accent: { color: 'var(--blue)' },
  lede: { fontSize: 18, lineHeight: 1.6, color: 'var(--ink-muted)', maxWidth: 'none', margin: '18px 0 0', textWrap: 'pretty' },

  // ===== Landing card (about + gate) =====
  landing: { background: '#fff', border: '1px solid var(--line-soft)', borderRadius: 22, boxShadow: 'var(--shadow-lg)', marginTop: 36, overflow: 'hidden' },
  about: { display: 'grid', gridTemplateColumns: '1fr 1fr' },
  aboutLeft: { padding: '40px 38px' },
  aboutRight: { padding: '40px 38px', borderLeft: '1px solid var(--line-soft)' },
  miniEyebrow: { fontFamily: "'Outfit', system-ui, sans-serif", fontSize: 11, fontWeight: 600, letterSpacing: '0.12em', textTransform: 'uppercase', color: 'var(--ink-muted)', marginBottom: 16 },
  aboutH2: { fontFamily: "'Outfit', system-ui, sans-serif", fontSize: 23, fontWeight: 600, letterSpacing: '-0.02em', lineHeight: 1.2, color: 'var(--ink)', margin: '0 0 12px' },
  aboutP: { fontSize: 15, color: 'var(--ink-muted)', lineHeight: 1.6, margin: 0 },
  who: { marginTop: 18, paddingTop: 18, borderTop: '1px solid var(--line-soft)', fontSize: 14, color: 'var(--ink-muted)', lineHeight: 1.55 },
  whoB: { color: 'var(--ink)', fontWeight: 600 },
  getList: { listStyle: 'none', padding: 0, margin: 0, display: 'flex', flexDirection: 'column', gap: 4 },
  getItem: { display: 'flex', alignItems: 'flex-start', gap: 12, padding: '9px 0', fontSize: 14.5, color: 'var(--ink-soft)', lineHeight: 1.5 },
  getDot: { width: 20, height: 20, borderRadius: 10, background: 'var(--blue-soft)', color: 'var(--blue-deep)', display: 'grid', placeItems: 'center', flex: 'none', marginTop: 1 },
  getB: { color: 'var(--ink)', fontWeight: 600 },

  // ===== Gate =====
  gate: { borderTop: '1px solid var(--line-soft)', padding: '48px 38px 52px', background: 'var(--blue-soft)', textAlign: 'center' },
  gateInner: { maxWidth: 460, margin: '0 auto' },
  gateH2: { fontFamily: "'Outfit', system-ui, sans-serif", fontSize: 27, fontWeight: 600, letterSpacing: '-0.02em', color: 'var(--ink)', margin: '0 0 10px' },
  gateP: { color: 'var(--ink-muted)', fontSize: 15, lineHeight: 1.55, margin: '0 auto 24px', maxWidth: 410 },
  field: { width: '100%', fontSize: 16, padding: '15px 16px', border: '1px solid var(--line)', borderRadius: 12, background: '#fff', color: 'var(--ink)', marginBottom: 12 },
  btn: { fontFamily: "'Outfit', system-ui, sans-serif", fontWeight: 600, fontSize: 16, border: 'none', cursor: 'pointer', color: '#fff', background: 'var(--ink)', padding: '16px 24px', borderRadius: 12, width: '100%', marginTop: 2, transition: 'background .2s, transform .05s', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 8 },
  gateError: { color: 'var(--coral-ink)', fontSize: 13.5, marginTop: 12, minHeight: 16 },
  gateFine: { fontSize: 12.5, color: 'var(--ink-muted)', marginTop: 16, lineHeight: 1.5 },

  // ===== Tool =====
  tool: { marginTop: 40 },
  intro: { background: 'var(--sand-soft)', border: '1px solid var(--sand)', borderLeft: '4px solid var(--coral)', borderRadius: 16, padding: '22px 26px', marginBottom: 28, fontSize: 15.5, lineHeight: 1.62, color: 'var(--ink-soft)' },
  introStrong: { color: 'var(--ink)', fontWeight: 600 },

  step: { background: '#fff', border: '1px solid var(--line-soft)', borderRadius: 20, boxShadow: 'var(--shadow-md)', padding: '30px 32px 34px', marginBottom: 20 },
  stepHead: { display: 'flex', alignItems: 'baseline', gap: 12, marginBottom: 6, flexWrap: 'wrap' },
  stepNum: { fontFamily: "'Outfit', system-ui, sans-serif", fontSize: 12, fontWeight: 700, letterSpacing: '0.04em', color: '#fff', background: 'var(--blue)', borderRadius: 8, padding: '4px 9px', flex: 'none' },
  stepH3: { fontFamily: "'Outfit', system-ui, sans-serif", fontSize: 22, fontWeight: 600, letterSpacing: '-0.02em', color: 'var(--ink)', margin: 0 },
  hint: { color: 'var(--ink-muted)', fontSize: 14.5, lineHeight: 1.55, margin: '4px 0 20px' },

  // ----- Step 1: add + sort -----
  addRow: { display: 'flex', gap: 10, marginBottom: 14 },
  addInput: { flex: 1, fontSize: 15.5, padding: '13px 15px', border: '1px solid var(--line)', borderRadius: 12, background: '#fff', color: 'var(--ink)' },
  addBtn: { fontFamily: "'Outfit', system-ui, sans-serif", fontWeight: 600, fontSize: 15, color: '#fff', background: 'var(--ink)', border: 'none', borderRadius: 12, padding: '0 20px', display: 'inline-flex', alignItems: 'center', gap: 7, transition: 'background .2s', whiteSpace: 'nowrap', cursor: 'pointer' },
  chipLabel: { fontSize: 12.5, color: 'var(--ink-muted)', margin: '2px 0 9px' },
  chipRow: { display: 'flex', flexWrap: 'wrap', gap: 7, marginBottom: 22 },
  chip: { fontSize: 13, color: 'var(--ink-soft)', background: 'var(--paper-deep)', border: '1px solid var(--line)', borderRadius: 999, padding: '6px 13px', cursor: 'pointer', transition: 'all .15s', display: 'inline-flex', alignItems: 'center', gap: 6 },
  chipUsed: { opacity: 0.4, pointerEvents: 'none' },

  itemList: { display: 'flex', flexDirection: 'column', gap: 9 },
  itemRow: { display: 'flex', alignItems: 'center', gap: 12, padding: '8px 10px 8px 14px', borderRadius: 12, border: '1px solid var(--line)', borderLeft: '3px solid var(--line)', background: '#fff', transition: 'border-color .15s, background .15s' },
  itemRowUnsorted: { borderStyle: 'dashed' },
  itemInput: { flex: 1, fontSize: 15, border: 'none', background: 'transparent', color: 'var(--ink)', padding: '6px 2px', minWidth: 0 },
  removeBtn: { width: 28, height: 28, borderRadius: 8, display: 'grid', placeItems: 'center', color: 'var(--ink-muted)', background: 'transparent', border: 'none', cursor: 'pointer', flex: 'none', transition: 'background .15s, color .15s' },

  laneToggle: { display: 'inline-flex', background: 'var(--paper-deep)', border: '1px solid var(--line)', borderRadius: 9, padding: 2, flex: 'none' },
  laneBtn: { fontFamily: "'Outfit', system-ui, sans-serif", fontSize: 12.5, fontWeight: 600, padding: '6px 12px', borderRadius: 7, border: 'none', background: 'transparent', color: 'var(--ink-muted)', cursor: 'pointer', transition: 'all .15s', whiteSpace: 'nowrap' },
  laneBtnAi: { background: 'var(--ink)', color: '#fff' },
  laneBtnHuman: { background: 'var(--blue)', color: '#fff' },

  counter: { display: 'flex', gap: 16, flexWrap: 'wrap', marginTop: 16, paddingTop: 16, borderTop: '1px solid var(--line-soft)', fontSize: 13, color: 'var(--ink-muted)' },
  counterB: { color: 'var(--ink)', fontWeight: 600 },

  emptyHint: { fontSize: 14, color: 'var(--ink-muted)', background: 'var(--paper-deep)', border: '1px dashed var(--line)', borderRadius: 12, padding: '18px 20px', lineHeight: 1.55, textAlign: 'center' },

  // ----- Step 2: exits -----
  exitRow: { display: 'flex', alignItems: 'center', gap: 12, padding: '12px 4px', borderBottom: '1px solid var(--line-soft)', flexWrap: 'wrap' },
  exitText: { flex: 1, fontSize: 15, color: 'var(--ink)', minWidth: 140 },
  exitToggle: { display: 'inline-flex', background: 'var(--paper-deep)', border: '1px solid var(--line)', borderRadius: 9, padding: 2, flex: 'none' },
  exitBtn: { fontFamily: "'Outfit', system-ui, sans-serif", fontSize: 12.5, fontWeight: 600, padding: '6px 13px', borderRadius: 7, border: 'none', background: 'transparent', color: 'var(--ink-muted)', cursor: 'pointer', transition: 'all .15s', whiteSpace: 'nowrap' },
  exitBtnYes: { background: 'var(--green-ok)', color: '#fff' },
  exitBtnNo: { background: 'var(--coral)', color: '#fff' },
  premBtnStandard: { background: 'var(--ink-muted)', color: '#fff' },
  premBtnPremium: { background: 'var(--blue)', color: '#fff' },

  exitLegend: { display: 'flex', flexWrap: 'wrap', gap: '6px 26px', background: 'transparent', border: 'none', borderRadius: 0, padding: 0, margin: '-6px 0 20px' },
  exitLegendItem: { display: 'flex', alignItems: 'baseline', gap: 8, fontSize: 13.5, lineHeight: 1.5, color: 'var(--ink-muted)', flex: '1 1 240px' },
  exitLegendTag: { fontFamily: "'Outfit', system-ui, sans-serif", fontSize: 11, fontWeight: 700, letterSpacing: '0.03em', textTransform: 'uppercase', borderRadius: 5, padding: '2px 7px', flex: 'none', whiteSpace: 'nowrap', background: 'transparent', border: '1px solid currentColor' },

  trapWarn: { marginTop: 20, background: 'var(--coral-soft)', border: '1px solid rgba(242,107,92,0.35)', borderRadius: 14, padding: '16px 20px', display: 'flex', gap: 13, alignItems: 'flex-start' },
  trapWarnIcon: { color: 'var(--coral-ink)', flex: 'none', marginTop: 1 },
  trapWarnTitle: { fontFamily: "'Outfit', system-ui, sans-serif", fontWeight: 600, fontSize: 15, color: 'var(--coral-ink)', margin: '0 0 4px' },
  trapWarnP: { fontSize: 13.5, color: 'var(--ink-soft)', lineHeight: 1.5, margin: 0 },
  allClear: { marginTop: 20, background: 'rgba(47,107,62,0.08)', border: '1px solid rgba(47,107,62,0.25)', borderRadius: 14, padding: '14px 18px', display: 'flex', gap: 11, alignItems: 'center', fontSize: 14, color: 'var(--green-ok)', fontWeight: 500 },

  // ----- Step 3: premium -----
  premRow: { padding: '14px 0', borderBottom: '1px solid var(--line-soft)' },
  premHeadRow: { display: 'flex', alignItems: 'center', gap: 12, flexWrap: 'wrap' },
  premText: { flex: 1, fontSize: 15, color: 'var(--ink)', minWidth: 140 },
  starBtn: { display: 'inline-flex', alignItems: 'center', gap: 7, fontFamily: "'Outfit', system-ui, sans-serif", fontSize: 12.5, fontWeight: 600, padding: '7px 13px', borderRadius: 9, border: '1px solid var(--line)', background: 'var(--paper-deep)', color: 'var(--ink-muted)', cursor: 'pointer', transition: 'all .15s', whiteSpace: 'nowrap', flex: 'none' },
  starBtnActive: { background: '#fff', border: '1px solid var(--blue)', color: 'var(--blue-deep)', boxShadow: 'inset 0 0 0 1px var(--blue)' },
  premReveal: { marginTop: 14, marginLeft: 2, paddingLeft: 16, borderLeft: '2px solid var(--blue-soft)', display: 'flex', flexDirection: 'column', gap: 14 },
  miniField: {},
  miniLabel: { display: 'block', fontSize: 13, fontWeight: 600, color: 'var(--ink)', marginBottom: 6 },
  miniInput: { width: '100%', fontFamily: "'Inter', system-ui, sans-serif", fontSize: 14.5, border: '1px solid var(--line)', borderRadius: 10, padding: '10px 13px', minHeight: 60, background: '#fff', color: 'var(--ink)', lineHeight: 1.55, resize: 'vertical' },

  // ----- Step 5: measure -----
  measureCard: { background: 'var(--ink)', borderRadius: 20, padding: '30px 32px', marginBottom: 20, color: '#fff' },
  measureEyebrow: { fontFamily: "'Outfit', system-ui, sans-serif", fontSize: 11, fontWeight: 600, letterSpacing: '0.12em', textTransform: 'uppercase', color: 'var(--blue-mid)', marginBottom: 12 },
  measureH3: { fontFamily: "'Outfit', system-ui, sans-serif", fontSize: 22, fontWeight: 600, letterSpacing: '-0.02em', margin: '0 0 10px', color: '#fff' },
  measureP: { fontSize: 15, lineHeight: 1.6, color: 'rgba(255,255,255,0.78)', margin: '0 0 20px', maxWidth: 620 },
  measureCheck: { display: 'flex', alignItems: 'flex-start', gap: 13, padding: '16px 18px', background: 'rgba(255,255,255,0.06)', border: '1px solid rgba(255,255,255,0.14)', borderRadius: 13, cursor: 'pointer' },
  measureBox: { width: 22, height: 22, borderRadius: 6, border: '2px solid rgba(255,255,255,0.4)', display: 'grid', placeItems: 'center', flex: 'none', marginTop: 1, transition: 'all .15s' },
  measureBoxOn: { background: 'var(--blue)', border: '2px solid var(--blue)' },
  measureCheckText: { fontSize: 15, lineHeight: 1.5, color: '#fff' },

  // ===== Summary (printable payoff) =====
  summary: { marginTop: 8, background: '#fff', border: '1px solid var(--line)', borderRadius: 22, boxShadow: 'var(--shadow-lg)', padding: '38px 40px 40px', position: 'relative', overflow: 'hidden' },
  sumEyebrow: { fontFamily: "'Outfit', system-ui, sans-serif", fontSize: 11, fontWeight: 600, letterSpacing: '0.14em', textTransform: 'uppercase', color: 'var(--blue)', marginBottom: 10 },
  sumH2: { fontFamily: "'Outfit', system-ui, sans-serif", fontSize: 27, fontWeight: 600, letterSpacing: '-0.02em', lineHeight: 1.15, color: 'var(--ink)', margin: '0 0 6px', maxWidth: 560 },
  sumPrepared: { fontSize: 13.5, color: 'var(--ink-muted)', margin: '0 0 28px' },
  sumCols: { display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 18, marginBottom: 22 },
  sumCol: { border: '1px solid var(--line)', borderRadius: 14, overflow: 'hidden' },
  sumColHead: { padding: '12px 16px', fontFamily: "'Outfit', system-ui, sans-serif", fontWeight: 600, fontSize: 14.5, color: '#fff', display: 'flex', alignItems: 'center', gap: 8, whiteSpace: 'nowrap' },
  sumColBody: { padding: '8px 16px 14px' },
  sumLi: { display: 'flex', alignItems: 'center', gap: 9, padding: '7px 0', fontSize: 14.5, color: 'var(--ink)', borderBottom: '1px solid var(--line-soft)', lineHeight: 1.4 },
  sumStar: { color: 'var(--blue)', flex: 'none' },
  sumEmpty: { fontSize: 13.5, color: 'var(--ink-muted)', padding: '8px 0', fontStyle: 'italic' },

  sumBlock: { borderRadius: 14, padding: '18px 20px', marginBottom: 16 },
  sumBlockTitle: { fontFamily: "'Outfit', system-ui, sans-serif", fontWeight: 600, fontSize: 15, margin: '0 0 10px', display: 'flex', alignItems: 'center', gap: 8, whiteSpace: 'nowrap' },
  sumTrapBlock: { background: 'var(--coral-soft)', border: '1px solid rgba(242,107,92,0.3)' },
  sumTrapItem: { fontSize: 14, color: 'var(--ink-soft)', padding: '5px 0', display: 'flex', gap: 8, alignItems: 'center' },
  sumPremBlock: { background: 'var(--blue-soft)', border: '1px solid rgba(8,120,216,0.18)' },
  sumPremItem: { padding: '10px 0', borderBottom: '1px solid rgba(8,120,216,0.12)' },
  sumPremName: { fontWeight: 600, fontSize: 14.5, color: 'var(--ink)', marginBottom: 4 },
  sumPremLine: { fontSize: 13.5, color: 'var(--ink-soft)', lineHeight: 1.5, margin: '2px 0' },
  sumPremTag: { fontWeight: 600, color: 'var(--blue-deep)' },
  sumMeasure: { background: 'var(--sand-soft)', border: '1px solid var(--sand)', borderRadius: 14, padding: '18px 20px', fontSize: 14.5, lineHeight: 1.55, color: 'var(--ink-soft)' },
  sumMeasureB: { color: 'var(--ink)', fontWeight: 600 },

  // ----- Step 4 metric picker (on the dark card) -----
  metricGrid: { display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10, marginTop: 4 },
  metricCard: { display: 'flex', alignItems: 'flex-start', gap: 11, textAlign: 'left', padding: '13px 15px', borderRadius: 13, border: '1px solid var(--line)', background: '#fff', cursor: 'pointer', transition: 'all .15s', color: 'var(--ink)', width: '100%', font: 'inherit' },
  metricCardGood: { background: 'var(--blue-soft)', border: '1px solid var(--blue-mid)' },
  metricCardTrap: { background: 'var(--coral-soft)', border: '1px solid rgba(242,107,92,0.55)' },
  metricBox: { width: 20, height: 20, borderRadius: 6, border: '2px solid var(--line)', display: 'grid', placeItems: 'center', flex: 'none', marginTop: 1, transition: 'all .15s' },
  metricBoxGood: { background: 'var(--blue)', border: '2px solid var(--blue)' },
  metricBoxTrap: { background: 'var(--coral)', border: '2px solid var(--coral)' },
  metricText: { display: 'flex', flexDirection: 'column', gap: 2, minWidth: 0 },
  metricLabel: { fontFamily: "'Outfit', system-ui, sans-serif", fontWeight: 600, fontSize: 14.5, color: 'var(--ink)', lineHeight: 1.3 },
  metricNote: { fontSize: 12.5, color: 'var(--ink-muted)', lineHeight: 1.4 },
  metricCaution: { marginTop: 14, display: 'flex', gap: 10, alignItems: 'flex-start', background: 'var(--coral-soft)', border: '1px solid rgba(242,107,92,0.4)', borderRadius: 12, padding: '13px 16px', fontSize: 13.5, lineHeight: 1.5, color: 'var(--ink-soft)' },
  metricCautionIcon: { color: 'var(--coral-ink)', flex: 'none', marginTop: 1 },
  metricAddRow: { display: 'flex', gap: 9, marginTop: 10 },
  metricAddPrompt: { fontSize: 14, fontWeight: 600, color: 'var(--ink)', marginTop: 22 },
  metricAddInput: { flex: 1, fontSize: 14.5, padding: '11px 14px', borderRadius: 11, border: '1px solid var(--line)', background: '#fff', color: 'var(--ink)' },
  metricAddBtn: { fontFamily: "'Outfit', system-ui, sans-serif", fontWeight: 600, fontSize: 14.5, color: '#fff', background: 'var(--ink)', border: 'none', borderRadius: 11, padding: '0 18px', display: 'inline-flex', alignItems: 'center', gap: 7, cursor: 'pointer', whiteSpace: 'nowrap' },
  metricRemove: { position: 'absolute', top: 9, right: 9, width: 24, height: 24, borderRadius: 7, display: 'grid', placeItems: 'center', background: 'var(--paper-deep)', border: 'none', color: 'var(--ink-muted)', cursor: 'pointer', transition: 'all .15s' },

  actions: { display: 'flex', gap: 12, flexWrap: 'wrap', marginTop: 26 },
  printBtn: { fontFamily: "'Outfit', system-ui, sans-serif", fontWeight: 600, fontSize: 15, cursor: 'pointer', color: '#fff', background: 'var(--ink)', border: 'none', padding: '14px 26px', borderRadius: 12, display: 'inline-flex', alignItems: 'center', gap: 9, transition: 'background .2s', whiteSpace: 'nowrap' },
  footerNote: { textAlign: 'center', fontSize: 14, color: 'var(--ink-muted)', marginTop: 36, lineHeight: 1.6 },
  footerNoteB: { color: 'var(--ink)', fontWeight: 600 },
};

const GET_ITEMS = [
  ['One simple list', ' of every way customers reach you, split into "AI can handle this" and "a person should handle this."'],
  ['The gaps spotted', ', the places where a stuck customer cannot reach a real person, so you can fix them.'],
  ['Your best moments named', ', the times a real person is worth paying for, so you can offer them as a premium service.'],
  ['A one-page plan', ' you can print or save as a PDF, showing what to automate, what to protect, and what to charge for.'],
];

const EXAMPLES = [
  'Order / shipping status',
  'Password reset',
  'Business hours & FAQs',
  'Booking or rescheduling',
  'A billing dispute',
  'A cancellation',
  'A complaint',
  'A big new purchase decision',
  'Onboarding a new customer',
];

// Step 4 - what to measure. The "trap" metrics reward keeping customers away
// from your team; picking one surfaces a gentle caution.
const METRICS = [
  { id: 'resolution', label: 'Problems actually solved', note: 'Did they leave with the issue fixed?', good: true },
  { id: 'retention', label: 'Customers who stay', note: 'Are people sticking with you over time?', good: true },
  { id: 'repeat', label: 'Repeat business', note: 'Do they come back and buy again?', good: true },
  { id: 'referrals', label: 'Referrals & word of mouth', note: 'Are happy customers sending you others?', good: true },
  { id: 'satisfaction', label: 'How happy people feel after', note: 'A quick "how did we do?" after each contact.', good: true },
  { id: 'deflection', label: 'How many we kept away from a person', note: 'Rewards avoiding customers, not helping them.', good: false },
  { id: 'containment', label: 'Chats the bot handled alone', note: 'A high number can just mean people gave up.', good: false },
];

function validEmail(v) { return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v); }

// ---- Email gate ----
function Gate({ onUnlock }) {
  const saved = loadSaved();
  const [firstName, setFirstName] = React.useState(saved.firstName || '');
  const [email, setEmail] = React.useState(saved.email || '');
  const [status, setStatus] = React.useState('idle');
  const [error, setError] = React.useState('');

  const submit = async () => {
    const fn = firstName.trim();
    const em = email.trim();
    setError('');
    if (!fn) { setError('Please enter your first name.'); return; }
    if (!validEmail(em)) { setError('Please enter a valid email address.'); return; }

    setStatus('sending');
    try {
      await window.bluemoso.api.submitLead({
        firstName: fn,
        email: em,
        turnstileMount: '#cf-turnstile-worksheet',
      });
      saveField({ firstName: fn, email: em, unlocked: true });
      try {
        if (window.bluemoso && window.bluemoso.analytics) {
          window.bluemoso.analytics.track('worksheet_unlocked', { tool: 'two_column_journey' });
        }
      } catch (e) {}
      onUnlock();
    } catch (e) {
      setStatus('idle');
      setError('Something went wrong. Please try again.');
    }
  };

  return (
    <div style={wsStyles.gate} id="worksheet-gate">
      <div style={wsStyles.gateInner}>
        <h2 style={wsStyles.gateH2}>Get the worksheet</h2>
        <p style={wsStyles.gateP}>Enter your name and email and the worksheet opens right here. Fill it in on screen, then print it or save it as a PDF.</p>
        <label htmlFor="ws-fname" className="bm-sr-only">First name</label>
        <input id="ws-fname" type="text" style={wsStyles.field} placeholder="First name" autoComplete="given-name"
          value={firstName} onChange={(e) => setFirstName(e.target.value)} />
        <label htmlFor="ws-email" className="bm-sr-only">Work email</label>
        <input id="ws-email" type="email" style={wsStyles.field} placeholder="you@company.com" autoComplete="email"
          value={email} onChange={(e) => setEmail(e.target.value)}
          onKeyDown={(e) => { if (e.key === 'Enter') submit(); }} />
        <button type="button" style={{ ...wsStyles.btn, opacity: status === 'sending' ? 0.6 : 1 }}
          disabled={status === 'sending'} onClick={submit}
          onMouseEnter={(e) => { if (status !== 'sending') e.currentTarget.style.background = 'var(--blue)'; }}
          onMouseLeave={(e) => { e.currentTarget.style.background = 'var(--ink)'; }}>
          {status === 'sending' ? 'Unlocking…' : 'Unlock the worksheet'}
          {status !== 'sending' && <Icon name="arrow" size={16} />}
        </button>
        {/* Turnstile renders inline here only if Cloudflare needs a human check. */}
        <div id="cf-turnstile-worksheet" style={{ display: 'flex', justifyContent: 'center', marginTop: error ? 4 : 0 }}></div>
        <div style={wsStyles.gateError} role="alert">{error}</div>
        <p style={wsStyles.gateFine}>No spam. We’ll send you the occasional thing worth reading on delegation and customer-experience systems.</p>
      </div>
    </div>
  );
}

// ---- Premium toggle (Standard / Premium) used on each human item in Step 3.
// Mirrors the AI/Human and Reachable/Stuck segmented toggles. `premium` is a
// boolean; Standard is the resting default, Premium is the upgrade. ----
function PremiumToggle({ premium, onChange }) {
  return (
    <div style={wsStyles.exitToggle} role="group" aria-label="Is this a premium moment?">
      <button type="button"
        style={{ ...wsStyles.exitBtn, ...(!premium ? wsStyles.premBtnStandard : {}) }}
        aria-pressed={!premium}
        onClick={() => onChange(false)}>Standard</button>
      <button type="button"
        style={{ ...wsStyles.exitBtn, ...(premium ? wsStyles.premBtnPremium : {}) }}
        aria-pressed={premium}
        onClick={() => onChange(true)}>Premium</button>
    </div>
  );
}

// ---- Lane toggle (AI / Human) used on each item in Step 1 ----
function LaneToggle({ lane, onChange }) {
  return (
    <div style={wsStyles.laneToggle} role="group" aria-label="Sort this interaction">
      <button type="button"
        style={{ ...wsStyles.laneBtn, ...(lane === 'ai' ? wsStyles.laneBtnAi : {}) }}
        aria-pressed={lane === 'ai'}
        onClick={() => onChange(lane === 'ai' ? null : 'ai')}>AI</button>
      <button type="button"
        style={{ ...wsStyles.laneBtn, ...(lane === 'human' ? wsStyles.laneBtnHuman : {}) }}
        aria-pressed={lane === 'human'}
        onClick={() => onChange(lane === 'human' ? null : 'human')}>Human</button>
    </div>
  );
}

// ---- The worksheet itself ----
function Tool() {
  const saved = loadSaved();
  const [items, setItems] = React.useState(() => Array.isArray(saved.items) ? saved.items : []);
  const [draft, setDraft] = React.useState('');
  const [metrics, setMetrics] = React.useState(() => (saved.metrics && typeof saved.metrics === 'object') ? saved.metrics : {});
  const [customMetrics, setCustomMetrics] = React.useState(() => Array.isArray(saved.customMetrics) ? saved.customMetrics : []);
  const [metricDraft, setMetricDraft] = React.useState('');
  const [pdfStatus, setPdfStatus] = React.useState('idle'); // idle | working

  // Persist on every change.
  React.useEffect(() => { saveField({ items }); }, [items]);
  React.useEffect(() => { saveField({ metrics }); }, [metrics]);
  React.useEffect(() => { saveField({ customMetrics }); }, [customMetrics]);

  const addItem = (text) => {
    const t = (text || '').trim();
    if (!t) return;
    setItems((arr) => [...arr, { id: uid(), text: t, lane: null, exit: null, premium: false, seen: '', brief: '' }]);
  };
  const update = (id, patch) => setItems((arr) => arr.map((it) => (it.id === id ? { ...it, ...patch } : it)));
  const remove = (id) => setItems((arr) => arr.filter((it) => it.id !== id));

  const usedTexts = items.map((i) => i.text.toLowerCase());
  const aiItems = items.filter((i) => i.lane === 'ai');
  const humanItems = items.filter((i) => i.lane === 'human');
  const unsorted = items.filter((i) => !i.lane);
  const trapDoors = aiItems.filter((i) => i.exit === false);
  const premiumItems = humanItems.filter((i) => i.premium);
  const allMetrics = [...METRICS, ...customMetrics.map((c) => ({ ...c, good: true, custom: true, note: c.note || '' }))];
  const toggleMetric = (id) => setMetrics((m) => ({ ...m, [id]: !m[id] }));
  const addMetric = (label) => {
    const t = (label || '').trim();
    if (!t) return;
    const id = 'custom:' + uid();
    setCustomMetrics((arr) => [...arr, { id, label: t }]);
    setMetrics((m) => ({ ...m, [id]: true }));
  };
  const removeMetric = (id) => {
    setCustomMetrics((arr) => arr.filter((c) => c.id !== id));
    setMetrics((m) => { const n = { ...m }; delete n[id]; return n; });
  };
  const chosenGood = allMetrics.filter((m) => m.good && metrics[m.id]);
  const chosenTrap = allMetrics.filter((m) => !m.good && metrics[m.id]);
  const firstName = (saved.firstName || '').trim();

  // Build + download a formatted PDF from the off-screen WorksheetPdfTemplate,
  // mirroring the Delegation Playbook's PDF flow. PDF assembly lives in
  // window.bluemoso.pdf (see /website/lib/) — never a raw html2canvas/jsPDF call.
  const downloadPdf = async () => {
    if (pdfStatus === 'working') return;
    setPdfStatus('working');
    try {
      const fname = `AI-or-Human Worksheet${firstName ? ' \u2014 ' + firstName : ''}.pdf`;
      await window.bluemoso.pdf.saveLocallyFromElement('worksheet-pdf-content', fname);
      try {
        if (window.bluemoso && window.bluemoso.analytics) {
          window.bluemoso.analytics.track('worksheet_pdf_downloaded', { tool: 'two_column_journey', items: items.length });
        }
      } catch (e) {}
    } catch (err) {
      console.error('Worksheet PDF failed:', err);
      alert(`Couldn't build the PDF: ${err && err.message ? err.message : 'unknown error'}. Please try again in a moment.`);
    } finally {
      setPdfStatus('idle');
    }
  };

  return (
    <div style={wsStyles.tool}>
      <div style={wsStyles.intro}>
        The idea is simple: <strong style={wsStyles.introStrong}>let AI handle the quick, repeating questions, and keep a real person on the moments that matter.</strong> List the ways customers reach you below. Every step after that uses your list, and your finished plan shows up at the bottom.
      </div>

      {/* ===== STEP 1 - list & sort ===== */}
      <div style={wsStyles.step}>
        <div style={wsStyles.stepHead}>
          <span style={wsStyles.stepNum}>STEP 1</span>
          <h3 style={wsStyles.stepH3}>List how customers reach you, then choose AI or Human</h3>
        </div>
        <p style={wsStyles.hint}>Add the different reasons customers contact you, one at a time, then sort each. Quick, repeating questions a computer can answer in seconds, like order status, password resets, and business hours, go to <strong style={{ color: 'var(--ink)' }}>AI</strong>. Emotional, tricky, or high-stakes moments, like complaints, cancellations, and big decisions, stay with a <strong style={{ color: 'var(--blue)' }}>Human</strong>.</p>

        <div style={wsStyles.addRow}>
          <input
            style={wsStyles.addInput}
            placeholder="e.g. Customer wants to cancel"
            value={draft}
            onChange={(e) => setDraft(e.target.value)}
            onKeyDown={(e) => { if (e.key === 'Enter') { addItem(draft); setDraft(''); } }}
            aria-label="Add a customer interaction"
          />
          <button type="button" style={wsStyles.addBtn}
            onClick={() => { addItem(draft); setDraft(''); }}
            onMouseEnter={(e) => (e.currentTarget.style.background = 'var(--blue)')}
            onMouseLeave={(e) => (e.currentTarget.style.background = 'var(--ink)')}>
            <Icon name="plus" size={15} /> Add
          </button>
        </div>

        <p style={wsStyles.chipLabel}>Not sure where to start? Tap one to add it:</p>
        <div style={wsStyles.chipRow}>
          {EXAMPLES.map((ex) => {
            const used = usedTexts.includes(ex.toLowerCase());
            return (
              <button key={ex} type="button"
                style={{ ...wsStyles.chip, ...(used ? wsStyles.chipUsed : {}) }}
                onClick={() => addItem(ex)}
                onMouseEnter={(e) => { if (!used) { e.currentTarget.style.background = 'var(--blue-soft)'; e.currentTarget.style.borderColor = 'var(--blue-mid)'; } }}
                onMouseLeave={(e) => { e.currentTarget.style.background = 'var(--paper-deep)'; e.currentTarget.style.borderColor = 'var(--line)'; }}>
                <Icon name="plus" size={12} /> {ex}
              </button>
            );
          })}
        </div>

        {items.length === 0 ? (
          <div style={wsStyles.emptyHint}>Add your first one above, or tap a suggestion. Most businesses come up with 8 to 20.</div>
        ) : (
          <div style={wsStyles.itemList}>
            {items.map((it) => {
              const accent = it.lane === 'ai' ? 'var(--ink)' : it.lane === 'human' ? 'var(--blue)' : 'var(--line)';
              const bg = it.lane === 'ai' ? 'var(--paper-deep)' : it.lane === 'human' ? 'var(--blue-soft)' : '#fff';
              return (
                <div key={it.id} style={{ ...wsStyles.itemRow, ...(it.lane ? {} : wsStyles.itemRowUnsorted), borderLeftColor: accent, background: bg }}>
                  <input
                    style={wsStyles.itemInput}
                    value={it.text}
                    onChange={(e) => update(it.id, { text: e.target.value })}
                    aria-label="Interaction"
                  />
                  <LaneToggle lane={it.lane} onChange={(lane) => update(it.id, { lane })} />
                  <button type="button" style={wsStyles.removeBtn} aria-label="Remove"
                    onClick={() => remove(it.id)}
                    onMouseEnter={(e) => { e.currentTarget.style.background = 'var(--coral-soft)'; e.currentTarget.style.color = 'var(--coral-ink)'; }}
                    onMouseLeave={(e) => { e.currentTarget.style.background = 'transparent'; e.currentTarget.style.color = 'var(--ink-muted)'; }}>
                    <Icon name="minus" size={16} />
                  </button>
                </div>
              );
            })}
          </div>
        )}

        {items.length > 0 && (
          <div style={wsStyles.counter}>
            <span><span style={wsStyles.counterB}>{aiItems.length}</span> to AI</span>
            <span><span style={wsStyles.counterB}>{humanItems.length}</span> to a human</span>
            {unsorted.length > 0 && <span style={{ color: 'var(--coral-ink)' }}><span style={{ ...wsStyles.counterB, color: 'var(--coral-ink)' }}>{unsorted.length}</span> still to sort</span>}
          </div>
        )}
      </div>

      {/* ===== STEP 2 - exits / trap doors ===== */}
      <div style={wsStyles.step}>
        <div style={wsStyles.stepHead}>
          <span style={wsStyles.stepNum}>STEP 2</span>
          <h3 style={wsStyles.stepH3}>Make sure people can always reach a person</h3>
        </div>
        <p style={wsStyles.hint}>For everything you gave to AI, ask one thing: if a customer gets stuck, can they quickly reach a real person? Mark it <strong style={{ color: 'var(--green-ok)' }}>Reachable</strong> when there's a fast way out, like a “talk to a human” button, a live-chat handoff, or a phone number. Mark it <strong style={{ color: 'var(--coral-ink)' }}>Stuck</strong> when the bot is the only option. It's fine for AI to answer first; it's not fine to leave someone with no way out.</p>

        {aiItems.length === 0 ? (
          <div style={wsStyles.emptyHint}>Mark a few items as <strong>AI</strong> in Step 1 and they'll show up here to check.</div>
        ) : (
          <div>
            {aiItems.map((it) => (
              <div key={it.id} style={wsStyles.exitRow}>
                <span style={wsStyles.exitText}>{it.text}</span>
                <div style={wsStyles.exitToggle} role="group" aria-label="Can a customer reach a human fast?">
                  <button type="button"
                    style={{ ...wsStyles.exitBtn, ...(it.exit === true ? wsStyles.exitBtnYes : {}) }}
                    aria-pressed={it.exit === true}
                    onClick={() => update(it.id, { exit: it.exit === true ? null : true })}>Reachable</button>
                  <button type="button"
                    style={{ ...wsStyles.exitBtn, ...(it.exit === false ? wsStyles.exitBtnNo : {}) }}
                    aria-pressed={it.exit === false}
                    onClick={() => update(it.id, { exit: it.exit === false ? null : false })}>Stuck</button>
                </div>
              </div>
            ))}

            {trapDoors.length > 0 ? (
              <div style={wsStyles.trapWarn}>
                <span style={wsStyles.trapWarnIcon}><Icon name="shield" size={20} /></span>
                <div>
                  <p style={wsStyles.trapWarnTitle}>{trapDoors.length} {trapDoors.length === 1 ? 'place' : 'places'} where customers get stuck</p>
                  <p style={wsStyles.trapWarnP}>{trapDoors.map((t) => t.text).join(', ')}. A frustrated customer here can't reach anyone. Give them a quick, obvious way to talk to a person before you lean on AI for this.</p>
                </div>
              </div>
            ) : (
              aiItems.every((i) => i.exit === true) && (
                <div style={wsStyles.allClear}><Icon name="check" size={18} /> Every AI answer has a quick way to reach a person. That's exactly right.</div>
              )
            )}
          </div>
        )}
      </div>

      {/* ===== STEP 3 - premium moments + briefing ===== */}
      <div style={wsStyles.step}>
        <div style={wsStyles.stepHead}>
          <span style={wsStyles.stepNum}>STEP 3</span>
          <h3 style={wsStyles.stepH3}>Make your personal touch worth paying for</h3>
        </div>
        <p style={wsStyles.hint}>Look at what you kept with a person. Most of it is <strong style={{ color: 'var(--ink-soft)' }}>Standard</strong>, part of your normal service. Mark only your best 2 or 3 as <strong style={{ color: 'var(--blue)' }}>Premium</strong>: the moments a customer would gladly pay extra to have a real, named person own. For each premium moment, decide how customers will <em>know</em> it's the upgrade, and what AI should gather before your person steps in.</p>

        {humanItems.length === 0 ? (
          <div style={wsStyles.emptyHint}>Mark a few items as <strong>Human</strong> in Step 1 and they'll show up here.</div>
        ) : (
          <div>
            {humanItems.map((it) => (
              <div key={it.id} style={wsStyles.premRow}>
                <div style={wsStyles.premHeadRow}>
                  <span style={wsStyles.premText}>{it.text}</span>
                  <PremiumToggle premium={it.premium} onChange={(premium) => update(it.id, { premium })} />
                </div>
                {it.premium && (
                  <div style={wsStyles.premReveal}>
                    <div style={wsStyles.miniField}>
                      <label style={wsStyles.miniLabel}>How will customers know this is a premium service?</label>
                      <textarea style={wsStyles.miniInput}
                        placeholder="e.g. A named contact for your best customers. Priority support. A clear upgrade people can see and choose, not a hidden backup."
                        value={it.seen}
                        onChange={(e) => update(it.id, { seen: e.target.value })} />
                    </div>
                    <div style={wsStyles.miniField}>
                      <label style={wsStyles.miniLabel}>What should AI gather before your person steps in?</label>
                      <textarea style={wsStyles.miniInput}
                        placeholder="e.g. The customer's history, a short summary of the problem, and the issue sent to the right person, so your team starts already up to speed."
                        value={it.brief}
                        onChange={(e) => update(it.id, { brief: e.target.value })} />
                    </div>
                  </div>
                )}
              </div>
            ))}
          </div>
        )}
      </div>

      {/* ===== STEP 4 - what to measure ===== */}
      <div style={wsStyles.step}>
        <div style={wsStyles.stepHead}>
          <span style={wsStyles.stepNum}>STEP 4</span>
          <h3 style={wsStyles.stepH3}>Decide what you'll measure</h3>
        </div>
        <p style={wsStyles.hint}>Whatever you measure is what your team will chase, so pick on purpose. <strong style={{ color: 'var(--ink)' }}>Tap 2 or 3 numbers you'll actually report on each week</strong>, the ones tied to whether customers left helped and stuck around. Be wary of any that simply count how many people you kept <em>away</em> from a person, or you'll get good at pushing customers away from help.</p>
        <div style={wsStyles.metricGrid} className="bm-metric-grid">
          {allMetrics.map((m) => {
            const on = !!metrics[m.id];
            const card = (
              <button key={m.id} type="button"
                style={{ ...wsStyles.metricCard, ...(m.custom ? { paddingRight: 40 } : {}), ...(on ? (m.good ? wsStyles.metricCardGood : wsStyles.metricCardTrap) : {}) }}
                aria-pressed={on}
                onClick={() => toggleMetric(m.id)}
                onMouseEnter={(e) => { if (!on) e.currentTarget.style.background = 'var(--paper-deep)'; }}
                onMouseLeave={(e) => { if (!on) e.currentTarget.style.background = '#fff'; }}>
                <span style={{ ...wsStyles.metricBox, ...(on ? (m.good ? wsStyles.metricBoxGood : wsStyles.metricBoxTrap) : {}) }}>
                  {on && <Icon name="check" size={13} color="#fff" />}
                </span>
                <span style={wsStyles.metricText}>
                  <span style={wsStyles.metricLabel}>{m.label}</span>
                  {m.note && <span style={wsStyles.metricNote}>{m.note}</span>}
                </span>
              </button>
            );
            if (!m.custom) return card;
            return (
              <div key={m.id} style={{ position: 'relative' }}>
                {card}
                <button type="button" aria-label="Remove this metric" style={wsStyles.metricRemove}
                  onClick={() => removeMetric(m.id)}
                  onMouseEnter={(e) => { e.currentTarget.style.background = 'var(--coral)'; e.currentTarget.style.color = '#fff'; }}
                  onMouseLeave={(e) => { e.currentTarget.style.background = 'var(--paper-deep)'; e.currentTarget.style.color = 'var(--ink-muted)'; }}>
                  <Icon name="minus" size={13} />
                </button>
              </div>
            );
          })}
        </div>
        <div style={wsStyles.metricAddPrompt}>Don't see what you track? Add your own:</div>
        <div style={wsStyles.metricAddRow}>
          <input className="bm-metric-input" style={wsStyles.metricAddInput}
            placeholder="Add your own (e.g. time to first reply)"
            value={metricDraft}
            onChange={(e) => setMetricDraft(e.target.value)}
            onKeyDown={(e) => { if (e.key === 'Enter') { addMetric(metricDraft); setMetricDraft(''); } }}
            aria-label="Add your own metric" />
          <button type="button" style={wsStyles.metricAddBtn}
            onClick={() => { addMetric(metricDraft); setMetricDraft(''); }}>
            <Icon name="plus" size={15} /> Add
          </button>
        </div>
        {chosenTrap.length > 0 && (
          <div style={wsStyles.metricCaution}>
            <span style={wsStyles.metricCautionIcon}><Icon name="shield" size={16} /></span>
            <span>Heads up: you picked {chosenTrap.map((m) => `“${m.label.toLowerCase()}”`).join(' and ')}. That rewards keeping people away from your team. Keep a real “did we help them?” number above it.</span>
          </div>
        )}
      </div>

      {/* ===== SUMMARY - printable payoff ===== */}
      <div id="worksheet-print-area" style={wsStyles.summary}>
        <div style={wsStyles.sumEyebrow}>Your plan</div>
        <h2 style={wsStyles.sumH2}>What AI handles, and what a person handles</h2>
        <p style={wsStyles.sumPrepared}>{firstName ? `Prepared for ${firstName} · ` : ''}The AI-or-Human Worksheet · BlueMoso</p>

        {items.length === 0 ? (
          <div style={wsStyles.emptyHint}>Your plan builds itself as you fill in the steps above. Add a few interactions to get started.</div>
        ) : (
          <div>
            <div style={wsStyles.sumCols} className="bm-sum-cols">
              <div style={wsStyles.sumCol}>
                <div style={{ ...wsStyles.sumColHead, background: 'var(--ink)' }}><Icon name="sparkle" size={16} /> AI handles this</div>
                <div style={wsStyles.sumColBody}>
                  {aiItems.length === 0 ? <div style={wsStyles.sumEmpty}>Nothing sorted here yet.</div> :
                    aiItems.map((it, i) => (
                      <div key={it.id} style={{ ...wsStyles.sumLi, borderBottom: i === aiItems.length - 1 ? 'none' : wsStyles.sumLi.borderBottom }}>
                        {it.exit === false
                          ? <span style={{ color: 'var(--coral)', flex: 'none' }} title="No human exit"><Icon name="shield" size={15} /></span>
                          : <span style={{ color: 'var(--green-ok)', flex: 'none' }}><Icon name="check" size={15} /></span>}
                        {it.text}
                      </div>
                    ))}
                </div>
              </div>
              <div style={wsStyles.sumCol}>
                <div style={{ ...wsStyles.sumColHead, background: 'var(--blue)' }}><Icon name="users" size={16} /> A person handles this</div>
                <div style={wsStyles.sumColBody}>
                  {humanItems.length === 0 ? <div style={wsStyles.sumEmpty}>Nothing sorted here yet.</div> :
                    humanItems.map((it, i) => (
                      <div key={it.id} style={{ ...wsStyles.sumLi, borderBottom: i === humanItems.length - 1 ? 'none' : wsStyles.sumLi.borderBottom }}>
                        {it.premium ? <span style={wsStyles.sumStar}><Icon name="star" size={15} /></span> : <span style={{ width: 15, flex: 'none' }}></span>}
                        {it.text}
                      </div>
                    ))}
                </div>
              </div>
            </div>

            {trapDoors.length > 0 && (
              <div style={{ ...wsStyles.sumBlock, ...wsStyles.sumTrapBlock }}>
                <p style={{ ...wsStyles.sumBlockTitle, color: 'var(--coral-ink)' }}><Icon name="shield" size={17} /> Fix these gaps first</p>
                {trapDoors.map((t) => (
                  <div key={t.id} style={wsStyles.sumTrapItem}><Icon name="arrow" size={13} /> {t.text}: give customers a quick way to reach a person.</div>
                ))}
              </div>
            )}

            {premiumItems.length > 0 && (
              <div style={{ ...wsStyles.sumBlock, ...wsStyles.sumPremBlock }}>
                <p style={{ ...wsStyles.sumBlockTitle, color: 'var(--blue-deep)' }}><Icon name="star" size={17} /> Premium moments to charge for</p>
                {/* simple, plain-language summary of the moments worth paying for */}
                {premiumItems.map((t, i) => (
                  <div key={t.id} style={{ ...wsStyles.sumPremItem, borderBottom: i === premiumItems.length - 1 ? 'none' : wsStyles.sumPremItem.borderBottom }}>
                    <div style={wsStyles.sumPremName}>{t.text}</div>
                    {t.seen && <p style={wsStyles.sumPremLine}><span style={wsStyles.sumPremTag}>Customers see:</span> {t.seen}</p>}
                    {t.brief && <p style={wsStyles.sumPremLine}><span style={wsStyles.sumPremTag}>AI gathers:</span> {t.brief}</p>}
                  </div>
                ))}
              </div>
            )}

            <div style={wsStyles.sumMeasure}>
              <p style={{ ...wsStyles.sumBlockTitle, color: 'var(--ink)', margin: '0 0 8px' }}><Icon name="chart" size={17} /> What we'll measure</p>
              {chosenGood.length === 0 && chosenTrap.length === 0 ? (
                <span>Pick the numbers you'll track back in Step 4. Aim for whether problems get solved and whether customers stay.</span>
              ) : (
                <div>
                  {chosenGood.length > 0 && <p style={{ ...wsStyles.sumPremLine, margin: '0 0 4px' }}><span style={wsStyles.sumMeasureB}>Tracking:</span> {chosenGood.map((m) => m.label).join(', ')}.</p>}
                  {chosenTrap.length > 0 && <p style={{ ...wsStyles.sumPremLine, margin: 0, color: 'var(--coral-ink)' }}><span style={{ ...wsStyles.sumMeasureB, color: 'var(--coral-ink)' }}>Be careful with:</span> {chosenTrap.map((m) => m.label).join(', ')}. This rewards avoiding customers, not helping them.</p>}
                </div>
              )}
            </div>
          </div>
        )}

        <div style={wsStyles.actions} className="no-print">
          <button type="button" style={{ ...wsStyles.printBtn, opacity: pdfStatus === 'working' ? 0.65 : 1, cursor: pdfStatus === 'working' ? 'wait' : 'pointer' }}
            disabled={pdfStatus === 'working'} onClick={downloadPdf}
            onMouseEnter={(e) => { if (pdfStatus !== 'working') e.currentTarget.style.background = 'var(--blue)'; }}
            onMouseLeave={(e) => (e.currentTarget.style.background = 'var(--ink)')}>
            {pdfStatus === 'working'
              ? <>Building your PDF…</>
              : <><Icon name="arrow" size={16} /> Download as PDF</>}
          </button>
        </div>
      </div>

      <p style={wsStyles.footerNote}>Cheap service is about to be everywhere. A real human who cares is about to be rare. <span style={wsStyles.footerNoteB}>Rare is what people pay for.</span></p>

      {/* Off-screen PDF template, captured by window.bluemoso.pdf via #worksheet-pdf-content */}
      {typeof WorksheetPdfTemplate === 'function' && (
        <WorksheetPdfTemplate
          firstName={firstName}
          email={(saved.email || '').trim()}
          aiItems={aiItems}
          humanItems={humanItems}
          trapDoors={trapDoors}
          premiumItems={premiumItems}
          good={chosenGood.map((m) => m.label)}
          trap={chosenTrap.map((m) => m.label)}
          reachableAll={aiItems.length > 0 && aiItems.every((i) => i.exit === true)}
        />
      )}
    </div>
  );
}

function WorksheetApp() {
  const [unlocked, setUnlocked] = React.useState(() => !!loadSaved().unlocked);

  return (
    <div>
      <Nav baseHref="index.html" />
      <main>
        <section style={wsStyles.page}>
          <div style={wsStyles.pageBg}></div>
          <div style={wsStyles.wrap}>
            <h1 className="serif" style={wsStyles.h1}>
              Which conversations should be AI, <span style={wsStyles.h1Accent}>and which should be human?</span>
            </h1>
            <p style={wsStyles.lede}>Some questions a computer can answer in seconds. Some need a real person. This worksheet helps you decide which is which, so you give faster service without losing the personal touch. You'll end up with a simple one-page plan you can print.</p>

            {!unlocked && (
              <div style={wsStyles.landing}>
                <div style={wsStyles.about} className="bm-ws-about">
                  <div style={wsStyles.aboutLeft}>
                    <div style={wsStyles.miniEyebrow}>What this worksheet does</div>
                    <h2 style={wsStyles.aboutH2}>Make three decisions most businesses never make on purpose.</h2>
                    <p style={wsStyles.aboutP}>In a few minutes, you'll list the ways customers reach you and decide, one by one, where AI helps, where it's quietly costing you customers, and where a real person is worth paying for.</p>
                    <p style={wsStyles.who}><span style={wsStyles.whoB}>Who it's for:</span> any business owner deciding how much of their customer service to automate, and how much to keep human.</p>
                  </div>
                  <div style={wsStyles.aboutRight} className="bm-ws-about-right">
                    <div style={wsStyles.miniEyebrow}>What you’ll walk away with</div>
                    <ul style={wsStyles.getList}>
                      {GET_ITEMS.map(([b, rest]) => (
                        <li key={b} style={wsStyles.getItem}>
                          <span style={wsStyles.getDot}><Icon name="check" size={11} /></span>
                          <span><span style={wsStyles.getB}>{b}</span>{rest}</span>
                        </li>
                      ))}
                    </ul>
                  </div>
                </div>
                <Gate onUnlock={() => setUnlocked(true)} />
              </div>
            )}

            {unlocked && <Tool />}
          </div>
        </section>
      </main>
      <Footer
        baseHref="index.html"
        preCta={{
          eyebrow: 'For the moments that matter',
          headLead: 'Keep the human moments',
          headAccent: 'human.',
          sub: "Book a 30-minute call, bring your list, and we'll match you with a vetted assistant for the human side.",
          button: 'Talk to a human now',
          source: 'worksheet_pre_cta',
        }}
      />

      <style>{`
        .bm-sr-only { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; border: 0; }
        #cf-turnstile-worksheet:empty { margin-top: 0 !important; }
        .bm-metric-input::placeholder { color: rgba(255,255,255,0.5); }
        @media (max-width: 720px) {
          .bm-ws-about { grid-template-columns: 1fr !important; }
          .bm-ws-about-right { border-left: none !important; border-top: 1px solid var(--line-soft); }
        }
        @media (max-width: 600px) {
          .bm-sum-cols { grid-template-columns: 1fr !important; }
          .bm-metric-grid { grid-template-columns: 1fr !important; }
        }
      `}</style>
    </div>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<WorksheetApp />);
