// print-view.jsx — read-only "Print" view of Main Sets.
// Every column visible for every set. ZERO editable affordances:
// no <input>, no <button> (except the back chevron in TopBar), no
// row/cell onClick handlers, no checkboxes you can toggle.
//
// Typography is optimized for reading at-a-glance: monospaced numbers,
// generous white space, full names always shown, hairline rules.

function MainSetsPrintScreen({ theme, onBack, circuits, notes, columnPrefs }) {
  const meta = FLOW_SECTIONS.find(s => s.id === 'main');

  // Total stats for the page header
  const totalSets = circuits.reduce(
    (n, c) => n + c.exercises.reduce((m, e) => m + e.sets.length, 0), 0,
  );
  const totalExercises = circuits.reduce((n, c) => n + c.exercises.length, 0);

  // Slightly muted "paper" background so it reads as a different mode at a glance
  const paper = theme.isDark ? '#1a1410' : '#FBFAF7';
  const inkRule = theme.isDark ? 'rgba(255,255,255,0.10)' : 'rgba(26,20,16,0.12)';

  return (
    <div style={{ background: paper, minHeight: '100%' }}>
      <TopBar
        theme={theme}
        title="Main Sets"
        onBack={onBack}
        right={
          <div
            onClick={onBack}
            title="Back to the editable Main Sets"
            style={{
              display: 'inline-flex', alignItems: 'center', gap: 5,
              padding: '5px 11px 5px 9px', borderRadius: 9999,
              cursor: 'pointer', userSelect: 'none',
              background: theme.primary, color: theme.primaryInk,
              border: `1px solid ${theme.primary}`,
              fontFamily: theme.uiFamily, fontSize: 10, fontWeight: 700,
              textTransform: 'uppercase', letterSpacing: 0.5,
            }}>
            <span style={{ display: 'inline-flex', transform: 'rotate(180deg)' }}>
              <Icon name="chevron" size={11} color={theme.primaryInk} strokeWidth={2.4}/>
            </span>
            Back to sets
          </div>
        }
      />

      {/* Page header — meta line + compact read-only tagline */}
      <div style={{ padding: '0 22px 14px' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap' }}>
          <DepthDots depth={meta.depth} theme={theme} active/>
          <div style={{ fontFamily: theme.uiFamily, fontSize: 12, color: theme.muted }}>
            {circuits.length} circuits · {totalExercises} exercises · {totalSets} sets · {meta.est}
          </div>
          <span style={{
            marginLeft: 'auto',
            fontFamily: theme.uiFamily, fontSize: 10, fontWeight: 700,
            color: theme.muted, textTransform: 'uppercase', letterSpacing: 0.6,
          }}>Read only view.</span>
        </div>
      </div>

      {/* Session note (read-only) */}
      {notes.session && notes.session.trim() && (
        <div style={{ padding: '0 22px 14px' }}>
          <PrintNote theme={theme} scope="Session" text={notes.session}/>
        </div>
      )}

      {/* Circuits */}
      <div style={{ padding: '0 22px 120px', display: 'flex', flexDirection: 'column', gap: 22 }}>
        {circuits.map((c, i) => (
          <PrintCircuit
            key={c.id} theme={theme} circuit={c} index={i}
            inkRule={inkRule}
            columnPrefs={columnPrefs}
            circuitNote={notes.circuit[c.id]}
            exerciseNotes={notes.exercise}
          />
        ))}
        <PrintEndCap theme={theme}/>
      </div>
    </div>
  );
}

// ─── Circuit block ───────────────────────────────────────────────────────
function PrintCircuit({ theme, circuit, index, inkRule, circuitNote, exerciseNotes, columnPrefs }) {
  const cols = effectiveColumns(smartColumns(circuit), columnPrefs, 'detailed', circuitFocusCols(circuit));
  const completed = circuit.exercises.reduce((n, ex) => n + ex.sets.filter(s => s.done).length, 0);
  const total = circuit.exercises.reduce((n, ex) => n + ex.sets.length, 0);
  const interleave = circuit.exercises.length > 1;
  const weightUnit = (columnPrefs && columnPrefs.weightUnit) || 'lb';

  return (
    <section>
      {/* Circuit heading — slab style */}
      <header style={{ marginBottom: 12 }}>
        <div style={{ display: 'flex', alignItems: 'baseline', gap: 10, marginBottom: 4 }}>
          <span style={{
            fontFamily: theme.displayFamily, fontSize: 28, fontWeight: 700,
            color: theme.primary, letterSpacing: -0.5, lineHeight: 1,
          }}>{String(index + 1).padStart(2, '0')}</span>
          <span style={{
            fontFamily: theme.uiFamily, fontSize: 9, fontWeight: 700,
            letterSpacing: 0.6, textTransform: 'uppercase',
            color: theme.muted, padding: '3px 7px', borderRadius: 4,
            background: theme.isDark ? 'rgba(255,255,255,0.06)' : 'rgba(0,0,0,0.05)',
          }}>{KIND_LABEL[circuit.kind]}</span>
          <span style={{ flex: 1 }}/>
          <span style={{ fontFamily: theme.monoFamily, fontSize: 11, color: theme.muted }}>
            {completed}/{total} done
          </span>
        </div>
        <h2 style={{
          margin: 0, fontFamily: theme.displayFamily,
          fontSize: 19, fontWeight: 600, color: theme.text, lineHeight: 1.2,
        }}>{circuit.label}</h2>
        <div style={{
          marginTop: 4, fontFamily: theme.uiFamily, fontSize: 12, color: theme.muted,
        }}>
          ×{circuit.rounds} rounds · rest {circuit.rest}
          {interleave && <span style={{ marginLeft: 6, opacity: 0.7 }}>· interleaved</span>}
        </div>
      </header>

      {interleave ? (
        <>
          {/* Roster — A/B/C exercises with full + system names */}
          <PrintRoster theme={theme} circuit={circuit} exerciseNotes={exerciseNotes}/>
          {/* Single interleaved set table */}
          <PrintInterleavedTable theme={theme} circuit={circuit} cols={cols} weightUnit={weightUnit} inkRule={inkRule}/>
        </>
      ) : (
        /* Single-exercise circuit — keep the original per-exercise layout */
        <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
          {circuit.exercises.map((ex, exIdx) => (
            <PrintExercise
              key={ex.id} theme={theme} exercise={ex} exIdx={exIdx} cols={cols}
              inkRule={inkRule}
              weightUnit={weightUnit}
              position={`${exIdx + 1}/${circuit.exercises.length}`}
              note={exerciseNotes[ex.id]}
            />
          ))}
        </div>
      )}

      {/* Circuit note */}
      {circuitNote && circuitNote.trim() && (
        <div style={{ marginTop: 14 }}>
          <PrintNote theme={theme} scope="Circuit note" text={circuitNote}/>
        </div>
      )}
    </section>
  );
}

// ─── Roster: A/B/C exercises with full names + notes (read-only) ─────────
function PrintRoster({ theme, circuit, exerciseNotes }) {
  return (
    <div style={{
      display: 'flex', flexDirection: 'column', gap: 10,
      padding: '12px 14px', marginBottom: 14,
      background: theme.isDark ? 'rgba(255,255,255,0.025)' : 'rgba(0,0,0,0.02)',
      borderRadius: 8,
      border: `1px solid ${theme.border}`,
    }}>
      <div style={{
        fontFamily: theme.uiFamily, fontSize: 9, fontWeight: 700,
        color: theme.muted, textTransform: 'uppercase', letterSpacing: 0.6,
      }}>Exercises in this circuit</div>
      {circuit.exercises.map((ex, exIdx) => {
        const note = exerciseNotes[ex.id];
        return (
          <div key={ex.id} style={{
            display: 'flex', alignItems: 'flex-start', gap: 10,
            paddingLeft: 8,
            borderLeft: `3px solid ${exerciseColor(theme, exIdx)}`,
          }}>
            <PrintExBadge theme={theme} exIdx={exIdx}/>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{
                fontFamily: theme.uiFamily, fontSize: 14, fontWeight: 600, color: theme.text,
                lineHeight: 1.3,
              }}>
                {ex.fullName}
                {ex.flagged && (
                  <span style={{
                    display: 'inline-block', marginLeft: 8, verticalAlign: 'middle',
                    width: 7, height: 7, borderRadius: 9999, background: theme.danger,
                  }}/>
                )}
                {(ex.focusColumns || []).length > 0 && (
                  <span
                    title="Focus column — always shown for this exercise"
                    style={{
                      display: 'inline-flex', alignItems: 'center', gap: 4,
                      marginLeft: 8, verticalAlign: 'middle',
                      padding: '1px 7px 2px 5px', borderRadius: 9999,
                      background: exerciseColor(theme, exIdx),
                      color: exerciseChipInk(theme, exIdx),
                      fontFamily: theme.uiFamily, fontSize: 9, fontWeight: 700,
                      textTransform: 'uppercase', letterSpacing: 0.5,
                    }}>
                    <span style={{ fontSize: 10, lineHeight: 1 }}>★</span>
                    Focus · {ex.focusColumns.map(k => ({equip:'Equip',tempo:'Tempo',rpe:'RPE'}[k] || k)).join(' · ')}
                  </span>
                )}
              </div>
              <div style={{
                marginTop: 2, fontFamily: theme.monoFamily, fontSize: 10,
                color: theme.muted, opacity: 0.8,
              }}>{ex.systemName}</div>
              {note && note.trim() && (
                <div style={{
                  marginTop: 6, padding: '6px 10px',
                  background: theme.isDark ? 'rgba(255,182,39,0.08)' : 'rgba(255,182,39,0.10)',
                  borderLeft: `2px solid ${theme.primary}`,
                  borderRadius: '0 6px 6px 0',
                  fontFamily: theme.uiFamily, fontSize: 12, color: theme.text, lineHeight: 1.4,
                }}>{note}</div>
              )}
            </div>
          </div>
        );
      })}
    </div>
  );
}

// ─── Interleaved set table (read-only) ───────────────────────────────────
function PrintInterleavedTable({ theme, circuit, cols, weightUnit, inkRule }) {
  const rows = buildInterleavedRows(circuit);
  const wtLabel = `Wt (${weightUnit || 'lb'})`;

  // Same column model as the live screen: Equipment is out of the row; it
  // appears (read-only) in the breakdown box beneath each set.
  const colsList = [
    { k: 'round',  label: 'R',    align: 'left', w: '26px' },
    { k: 'ex',     label: 'Ex',   align: 'left', w: '26px' },
    { k: 'name',   label: 'Exercise', align: 'left', w: '1fr' },
    { k: 'reps',   label: 'Reps', align: 'left',   w: '0.7fr' },
    { k: 'weight', label: wtLabel, align: 'left',  w: '1.1fr' },
  ];
  if (cols.tempo) colsList.push({ k: 'tempo', label: 'Tempo', align: 'left', w: '0.7fr' });
  if (cols.rpe)   colsList.push({ k: 'rpe',   label: 'RPE',   align: 'left', w: '40px' });
  colsList.push({ k: 'done', label: '✓', align: 'left', w: '30px' });

  const grid = colsList.map(c => c.w).join(' ');

  return (
    <div style={{
      borderTop: `1px solid ${inkRule}`,
      borderBottom: `1px solid ${inkRule}`,
    }}>
      {/* Header */}
      <div style={{
        display: 'grid', gridTemplateColumns: grid, gap: 8,
        padding: '8px 4px',
        fontFamily: theme.uiFamily, fontSize: 9, fontWeight: 700,
        color: theme.muted, textTransform: 'uppercase', letterSpacing: 0.5,
        borderBottom: `1px solid ${inkRule}`,
      }}>
        {colsList.map(c => (
          <div key={c.k} style={{ textAlign: 'left' }}>{c.label}</div>
        ))}
      </div>

      {/* Rows */}
      {rows.map((row, i) => {
        const prev = i > 0 ? rows[i - 1] : null;
        const newRound = prev && row.round !== prev.round;
        const accent = exerciseColor(theme, row.exIdx);
        const { tempoParts, weights, equips, rowSpan } = expandSet(row.set);
        const groupBg = row.set.done
          ? (theme.isDark ? 'rgba(52,211,153,0.10)' : 'rgba(46,125,50,0.07)')
          : exerciseSetTint(theme, row.exIdx, row.setIdx);
        return (
          <React.Fragment key={`${row.exIdx}-${row.setIdx}`}>
            {newRound && (
              <div style={{
                display: 'flex', alignItems: 'center', gap: 8,
                padding: '5px 4px',
                background: theme.isDark ? 'rgba(255,255,255,0.03)' : 'rgba(0,0,0,0.025)',
                borderTop: `0.5px solid ${inkRule}`, borderBottom: `0.5px solid ${inkRule}`,
                fontFamily: theme.uiFamily, fontSize: 9, fontWeight: 700,
                color: theme.muted, textTransform: 'uppercase', letterSpacing: 0.6,
              }}>
                <span>Round {row.round}</span>
                <div style={{ flex: 1, height: 1, background: inkRule, opacity: 0.7 }}/>
              </div>
            )}
            <div style={{
              borderLeft: `3px solid ${accent}`,
              background: groupBg,
              borderBottom: i === rows.length - 1 ? 'none' : `0.5px dashed ${inkRule}`,
            }}>
              {Array.from({ length: rowSpan }).map((_, rowIdx) => {
                const primary = rowIdx === 0;
                return (
                  <div key={rowIdx} style={{
                    display: 'grid', gridTemplateColumns: grid, gap: 8,
                    padding: rowIdx === 0 ? '9px 6px 6px 4px' : '4px 6px 4px 4px',
                    alignItems: 'center',
                    borderTop: rowIdx === 0 ? 'none' : `0.5px dotted ${inkRule}`,
                  }}>
                    {/* Round # — only on primary row */}
                    <PrintRowCell theme={theme} value={primary ? row.round : null}
                      mono accentValue accent={accent}/>
                    {/* Exercise badge — only on primary row */}
                    <div>
                      {primary ? <PrintExBadge theme={theme} exIdx={row.exIdx}/> : <PrintDash theme={theme}/>}
                    </div>
                    {/* Exercise name — only on primary row */}
                    <div style={{ minWidth: 0 }}>
                      {primary ? (
                        <div style={{
                          fontFamily: theme.uiFamily, fontSize: 12, fontWeight: 500, color: theme.text,
                          whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
                        }} title={row.ex.fullName}>{row.ex.shortName}</div>
                      ) : <PrintDash theme={theme}/>}
                    </div>
                    <PrintRowCell theme={theme} value={primary ? row.set.reps : null} mono/>
                    {/* Weight cell — comma list for multi-weight, value for single */}
                    <div>
                      {primary ? (
                        weights.length > 1
                          ? <PrintRowCell theme={theme} value={weightRowText(weights)} mono/>
                          : <PrintRowCell theme={theme} value={weights.length === 1 ? weights[0].value : null} mono/>
                      ) : <PrintDash theme={theme}/>}
                    </div>
                    {cols.tempo && <PrintRowCell theme={theme} value={tempoParts[rowIdx] != null ? tempoParts[rowIdx] : null} mono/>}
                    {cols.rpe   && <PrintRowCell theme={theme} value={primary ? row.set.rpe : null} mono/>}
                    {/* Done checkbox — only on primary row */}
                    <div style={{ display: 'flex', alignItems: 'center' }}>
                      {primary ? (
                        row.set.done ? (
                          <div style={{
                            width: 16, height: 16, borderRadius: 4,
                            background: theme.success,
                            display: 'flex', alignItems: 'center', justifyContent: 'center',
                          }}>
                            <Icon name="check" size={10} color="#fff" strokeWidth={3}/>
                          </div>
                        ) : (
                          <div style={{ width: 16, height: 16, borderRadius: 4, border: `1px solid ${theme.border}` }}/>
                        )
                      ) : <PrintDash theme={theme}/>}
                    </div>
                  </div>
                );
              })}
              {(() => {
                const showW = weights.length > 1 || weights.some(w => w.label);
                const showE = equips.length > 0;
                if (!showW && !showE) return null;
                return (
                  <PrintBreakdown theme={theme} accent={accent}
                    weights={showW ? weights : []}
                    equips={equips}/>
                );
              })()}
            </div>
          </React.Fragment>
        );
      })}
    </div>
  );
}

function PrintRowCell({ theme, value, mono, accentValue, accent }) {
  if (value === null || value === undefined || value === '') return <PrintDash theme={theme}/>;
  return (
    <div style={{
      fontFamily: mono ? theme.monoFamily : theme.uiFamily,
      fontSize: 12, fontWeight: accentValue ? 700 : 600,
      color: accentValue && accent ? accent : theme.text,
      textAlign: 'left',
      whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
    }}>{String(value)}</div>
  );
}

function PrintDash({ theme }) {
  return (
    <div style={{
      fontFamily: theme.monoFamily, fontSize: 12, fontWeight: 600,
      color: theme.muted, opacity: 0.4, textAlign: 'left',
      userSelect: 'none',
    }}>—</div>
  );
}

// Read-only twin of <ExpandedBreakdown> for the print sheet. Always visible
// (no tap-to-expand on paper) and styled with quieter chrome.
function PrintBreakdown({ theme, accent, weights, equips }) {
  const showBoth = weights.length > 0 && equips.length > 0;
  return (
    <div style={{
      padding: '8px 12px 10px 14px',
      borderTop: `0.5px dashed ${theme.border}`,
      display: 'grid',
      gridTemplateColumns: showBoth ? '1fr 1fr' : '1fr',
      gap: 14,
    }}>
      {weights.length > 0 && (
        <PrintBreakdownColumn theme={theme} accent={accent} title="Weight"
          entries={weights} slotPrefix="Weight"/>
      )}
      {equips.length > 0 && (
        <PrintBreakdownColumn theme={theme} accent={accent} title="Equipment"
          entries={equips}/>
      )}
    </div>
  );
}

function PrintBreakdownColumn({ theme, accent, title, entries, slotPrefix }) {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
      <div style={{
        fontFamily: theme.uiFamily, fontSize: 9, fontWeight: 700,
        color: theme.muted, textTransform: 'uppercase', letterSpacing: 0.6,
      }}>{title}</div>
      {entries.map((e, i) => (
        <div key={i} style={{
          display: 'flex', alignItems: 'baseline', gap: 8,
          fontFamily: theme.uiFamily, fontSize: 11, color: theme.text,
        }}>
          {slotPrefix && (
            <span style={{ fontWeight: 700, color: accent, whiteSpace: 'nowrap' }}>
              {slotPrefix} {i + 1}
            </span>
          )}
          {e.label && (
            <span style={{ flex: 1, color: theme.text }}>
              {slotPrefix ? `— ${e.label}` : e.label}
            </span>
          )}
          {!e.label && !slotPrefix && <span style={{ flex: 1 }}/>}
          <span style={{
            fontFamily: theme.monoFamily, fontSize: 12, fontWeight: 700,
            color: theme.text, whiteSpace: 'nowrap',
          }}>{e.value}</span>
        </div>
      ))}
    </div>
  );
}

// Legacy cell renderer kept for any straggler call sites.
function PrintInterleavedCell({ theme, col, row }) {
  if (col.k === 'round') {
    return (
      <div style={{
        textAlign: 'left', fontFamily: theme.monoFamily,
        fontSize: 11, fontWeight: 700,
        color: exerciseColor(theme, row.exIdx),
      }}>{row.round}</div>
    );
  }
  if (col.k === 'ex') {
    return <PrintExBadge theme={theme} exIdx={row.exIdx}/>;
  }
  if (col.k === 'name') {
    return (
      <div style={{
        fontFamily: theme.uiFamily, fontSize: 12, fontWeight: 500, color: theme.text,
        whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', minWidth: 0,
      }} title={row.ex.fullName}>{row.ex.shortName}</div>
    );
  }
  if (col.k === 'done') {
    return (
      <div style={{ display: 'flex', justifyContent: 'flex-start', alignItems: 'center' }}>
        {row.set.done ? (
          <div style={{
            width: 16, height: 16, borderRadius: 4,
            background: theme.success,
            display: 'flex', alignItems: 'center', justifyContent: 'center',
          }}>
            <Icon name="check" size={10} color="#fff" strokeWidth={3}/>
          </div>
        ) : (
          <div style={{ width: 16, height: 16, borderRadius: 4, border: `1px solid ${theme.border}` }}/>
        )}
      </div>
    );
  }
  const value = row.set[col.k];
  const empty = value === null || value === undefined || value === '';
  return (
    <div style={{
      fontFamily: theme.monoFamily, fontSize: 12, fontWeight: 600,
      color: empty ? theme.muted : theme.text,
      opacity: empty ? 0.4 : 1,
      textAlign: 'left',
      whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
    }}>{empty ? '—' : String(value)}</div>
  );
}

function PrintExBadge({ theme, exIdx }) {
  const color = exerciseColor(theme, exIdx);
  return (
    <div style={{
      width: 22, height: 22, borderRadius: 5, margin: '0 auto',
      background: color, color: exerciseChipInk(theme, exIdx),
      fontFamily: theme.monoFamily, fontSize: 11, fontWeight: 700,
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      flexShrink: 0,
      boxShadow: theme.isDark ? '0 0 0 1px rgba(0,0,0,0.25) inset' : 'none',
    }}>{exLetter(exIdx)}</div>
  );
}

// ─── Exercise + its set table (read-only) ────────────────────────────────
function PrintExercise({ theme, exercise, exIdx = 0, cols, inkRule, weightUnit, position, note }) {
  const ex = exercise;
  const accent = exerciseColor(theme, exIdx);
  const wtLabel = `Wt (${weightUnit || 'lb'})`;

  // Per-exercise column presence. Equipment moves to the breakdown box and
  // is no longer a row column, even when present in data.
  const exCols = {
    tempo: cols.tempo && ex.sets.some(s => s.tempo != null && s.tempo !== ''),
    rpe:   cols.rpe   && ex.sets.some(s => s.rpe   != null && s.rpe   !== ''),
  };

  // Column list — all visible, no swiping. Left-aligned everywhere.
  const colsList = [
    { k: 'idx',    label: 'Set',   align: 'left', w: '34px'  },
    { k: 'reps',   label: 'Reps',  align: 'left', w: '0.8fr' },
    { k: 'weight', label: wtLabel, align: 'left', w: '1.4fr' },
  ];
  if (exCols.tempo) colsList.push({ k: 'tempo', label: 'Tempo', align: 'left', w: '0.7fr' });
  if (exCols.rpe)   colsList.push({ k: 'rpe',   label: 'RPE',   align: 'left', w: '50px'  });
  colsList.push({ k: 'done', label: '✓', align: 'left', w: '34px' });

  const grid = colsList.map(c => c.w).join(' ');

  return (
    <article>
      {/* Exercise header — full name always shown, plus system name reference */}
      <div style={{
        display: 'flex', alignItems: 'flex-start', gap: 10, marginBottom: 8,
      }}>
        <span style={{
          fontFamily: theme.monoFamily, fontSize: 10, fontWeight: 700,
          color: theme.muted, marginTop: 4, minWidth: 26, textAlign: 'left',
        }}>{position}</span>
        <div style={{ flex: 1, minWidth: 0 }}>
          <h3 style={{
            margin: 0, fontFamily: theme.uiFamily, fontSize: 15, fontWeight: 600,
            color: theme.text, lineHeight: 1.3,
          }}>
            {ex.fullName}
            {ex.flagged && (
              <span style={{
                display: 'inline-block', marginLeft: 8,
                width: 7, height: 7, borderRadius: 9999, background: theme.danger,
                verticalAlign: 'middle',
              }}/>
            )}
          </h3>
          <div style={{
            marginTop: 2, fontFamily: theme.uiFamily, fontSize: 11, color: theme.muted,
          }}>
            <span style={{ fontWeight: 600 }}>{ex.shortName}</span>
            <span style={{ margin: '0 6px', opacity: 0.5 }}>·</span>
            <span style={{ fontFamily: theme.monoFamily, fontSize: 10, opacity: 0.75 }}>
              {ex.systemName}
            </span>
          </div>
        </div>
      </div>

      {/* Exercise-level note (read-only) */}
      {note && note.trim() && (
        <div style={{
          marginLeft: 36, marginBottom: 10,
          padding: '7px 11px',
          background: theme.isDark ? 'rgba(255,182,39,0.08)' : 'rgba(255,182,39,0.10)',
          borderLeft: `2px solid ${theme.primary}`,
          borderRadius: '0 6px 6px 0',
          fontFamily: theme.uiFamily, fontSize: 12, color: theme.text,
          lineHeight: 1.45,
        }}>{note}</div>
      )}

      {/* The table — no inputs, no buttons, no row click handlers */}
      <div style={{
        marginLeft: 36,
        borderTop: `1px solid ${inkRule}`,
        borderBottom: `1px solid ${inkRule}`,
      }}>
        {/* Header row */}
        <div style={{
          display: 'grid', gridTemplateColumns: grid, gap: 8,
          padding: '8px 4px',
          fontFamily: theme.uiFamily, fontSize: 9, fontWeight: 700,
          color: theme.muted, textTransform: 'uppercase', letterSpacing: 0.5,
          borderBottom: `1px solid ${inkRule}`,
        }}>
          {colsList.map(c => (
            <div key={c.k} style={{ textAlign: c.align }}>{c.label}</div>
          ))}
        </div>

        {/* Data rows — plain text, never editable. Each set is a vertical
            group: tempo expands DOWNWARD inside the group. Multi-value
            weight + equipment surface in a labelled breakdown box. */}
        {ex.sets.map((s, i) => {
          const { tempoParts, weights, equips, rowSpan } = expandSet(s);
          const groupBg = s.done
            ? (theme.isDark ? 'rgba(52,211,153,0.08)' : 'rgba(46,125,50,0.06)')
            : exerciseSetTint(theme, exIdx, i);
          return (
            <div key={i} style={{
              borderBottom: i === ex.sets.length - 1 ? 'none' : `0.5px dashed ${inkRule}`,
              borderLeft: `3px solid ${accent}`,
              background: groupBg,
            }}>
              {Array.from({ length: rowSpan }).map((_, rowIdx) => {
                const primary = rowIdx === 0;
                return (
                  <div key={rowIdx} style={{
                    display: 'grid', gridTemplateColumns: grid, gap: 8,
                    padding: rowIdx === 0 ? '9px 6px 5px 4px' : '4px 6px 4px 4px',
                    alignItems: 'center',
                    borderTop: rowIdx === 0 ? 'none' : `0.5px dotted ${inkRule}`,
                  }}>
                    {colsList.map(c => {
                      let val;
                      if (c.k === 'idx')         val = primary ? i + 1 : null;
                      else if (c.k === 'done')   val = primary ? s.done : null;
                      else if (c.k === 'tempo')  val = tempoParts[rowIdx] != null ? tempoParts[rowIdx] : null;
                      else if (c.k === 'weight') val = primary
                        ? (weights.length > 1 ? weightRowText(weights) : (weights.length === 1 ? weights[0].value : null))
                        : null;
                      else                       val = primary ? s[c.k] : null;
                      return <PrintCell key={c.k} theme={theme} colKey={c.k} value={val} align="left"/>;
                    })}
                  </div>
                );
              })}
              {(() => {
                const showW = weights.length > 1 || weights.some(w => w.label);
                const showE = equips.length > 0;
                if (!showW && !showE) return null;
                return (
                  <PrintBreakdown theme={theme} accent={accent}
                    weights={showW ? weights : []}
                    equips={equips}/>
                );
              })()}
            </div>
          );
        })}
      </div>
    </article>
  );
}

// ─── Single read-only cell ───────────────────────────────────────────────
function PrintCell({ theme, colKey, value, align }) {
  if (colKey === 'done') {
    if (value === null || value === undefined) {
      return (
        <div style={{
          fontFamily: theme.monoFamily, fontSize: 12, fontWeight: 600,
          color: theme.muted, opacity: 0.4, textAlign: 'left',
        }}>—</div>
      );
    }
    return (
      <div style={{ display: 'flex', justifyContent: 'flex-start', alignItems: 'center' }}>
        {value ? (
          <div style={{
            width: 18, height: 18, borderRadius: 4,
            background: theme.success,
            display: 'flex', alignItems: 'center', justifyContent: 'center',
          }}>
            <Icon name="check" size={11} color="#fff" strokeWidth={3}/>
          </div>
        ) : (
          <div style={{
            width: 18, height: 18, borderRadius: 4,
            border: `1px solid ${theme.border}`,
          }}/>
        )}
      </div>
    );
  }

  const isIdx = colKey === 'idx';
  const empty = value === null || value === undefined || value === '';

  return (
    <div style={{
      fontFamily: theme.monoFamily,
      fontSize: isIdx ? 11 : 13,
      fontWeight: isIdx ? 700 : 600,
      color: empty ? theme.muted : theme.text,
      opacity: empty ? 0.4 : 1,
      textAlign: 'left',
      whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
    }}>
      {empty ? '—' : String(value)}
    </div>
  );
}

// ─── Note block, shared ──────────────────────────────────────────────────
function PrintNote({ theme, scope, text }) {
  return (
    <div style={{
      padding: '10px 14px',
      background: theme.isDark ? 'rgba(255,255,255,0.04)' : 'rgba(0,0,0,0.025)',
      borderLeft: `3px solid ${theme.primary}`,
      borderRadius: '0 8px 8px 0',
    }}>
      <div style={{
        fontFamily: theme.uiFamily, fontSize: 9, fontWeight: 700,
        letterSpacing: 0.6, textTransform: 'uppercase', color: theme.muted,
        marginBottom: 4,
      }}>{scope}</div>
      <div style={{
        fontFamily: theme.uiFamily, fontSize: 13, color: theme.text,
        lineHeight: 1.5, whiteSpace: 'pre-wrap',
      }}>{text}</div>
    </div>
  );
}

// ─── End-of-workout cap ──────────────────────────────────────────────────
function PrintEndCap({ theme }) {
  return (
    <div style={{
      display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 10,
      paddingTop: 8,
    }}>
      <div style={{ flex: 1, height: 1, background: theme.border }}/>
      <span style={{
        fontFamily: theme.uiFamily, fontSize: 10, fontWeight: 700,
        letterSpacing: 1.2, textTransform: 'uppercase', color: theme.muted,
      }}>End of Main Sets</span>
      <div style={{ flex: 1, height: 1, background: theme.border }}/>
    </div>
  );
}

Object.assign(window, { MainSetsPrintScreen });
