// settings.jsx — Settings screen + column-preference persistence.
//
// "Push all of the extras to settings": this is the global gate where
// the trainer decides whether Equip / Tempo / RPE columns show at all
// across every workout. Toggle off → column hidden everywhere (Main Sets
// + Print view, Basic + Detailed). Toggle on → column shows if a set has
// data for it.
//
// Non-negotiables (Set / Reps / Weight / Done) are listed but locked.
// New columns can be added to OPTIONAL_COLUMNS without touching consumers.

const STORAGE_KEY = 'trainerMike.columnPrefs';

// Optional columns the trainer can hide globally.
// Designed for extension — add a new entry and every render path picks it up
// automatically (smartColumns + effectiveColumns are both data-driven).
const OPTIONAL_COLUMNS = [
  {
    key: 'equip', label: 'Equipment',
    description: 'Cable column, weight peg, band level — whichever applies.',
    icon: 'weight',
  },
  {
    key: 'tempo', label: 'Tempo',
    description: 'Eccentric · pause · concentric counts, e.g. 2-1-2.',
    icon: 'timer',
  },
  {
    key: 'rpe', label: 'RPE',
    description: 'Rate of Perceived Exertion — effort on a 1–10 scale.',
    icon: 'energy',
  },
];

// Pinned columns — UI shows them as locked-on so the trainer sees the
// full information model.
const PINNED_COLUMNS = [
  { key: 'set',    label: 'Set #',  description: 'Sequential set number.',         icon: 'history' },
  { key: 'reps',   label: 'Reps',   description: 'Reps or time per set.',          icon: 'arrowUp' },
  { key: 'weight', label: 'Weight', description: 'Resistance per set.',            icon: 'weight'  },
  { key: 'done',   label: 'Done',   description: 'Per-set completion checkmark.',  icon: 'check'   },
];

function loadColumnPrefs() {
  const defaults = Object.fromEntries(OPTIONAL_COLUMNS.map(c => [c.key, true]));
  defaults.weightUnit = 'lb';
  try {
    const raw = localStorage.getItem(STORAGE_KEY);
    if (!raw) return defaults;
    const parsed = JSON.parse(raw);
    // Merge with defaults so new optional columns default to ON if added later.
    return { ...defaults, ...parsed };
  } catch (e) {
    return defaults;
  }
}

function saveColumnPrefs(prefs) {
  try { localStorage.setItem(STORAGE_KEY, JSON.stringify(prefs)); } catch (e) {}
}

// Combine data-presence detection, user prefs, view mode, AND per-exercise
// focus overrides. One function so every consumer (interleaved, by-exercise,
// print) is guaranteed to honor the same rules.
//
// Focus columns are the safety net for global hides: when an exercise's
// focusColumns list includes a column AND that column has data, the column
// shows even in Basic view and even if the user toggled it off in Settings.
// "What if the focus of the movement is RPE? Basic view should show RPE."
function effectiveColumns(dataCols, columnPrefs, mode, focusCols) {
  const focus = focusCols || {};
  const prefs = columnPrefs || { equip: true, tempo: true, rpe: true };
  const result = {};
  for (const k of ['equip', 'tempo', 'rpe']) {
    if (focus[k] && dataCols[k]) {
      // Focus override: data is present and exercise declares this column
      // is the point — always show, regardless of mode or settings.
      result[k] = true;
    } else if (mode === 'basic') {
      result[k] = false;
    } else {
      result[k] = !!(dataCols[k] && prefs[k]);
    }
  }
  return result;
}

// Reduce an exercise's focusColumns list to a {equip, tempo, rpe} bag.
function exerciseFocusCols(ex) {
  const out = { equip: false, tempo: false, rpe: false };
  (ex && ex.focusColumns || []).forEach(k => { if (k in out) out[k] = true; });
  return out;
}

// Union of focus columns across every exercise in a circuit (used by
// interleaved view which renders all exercises in one table).
function circuitFocusCols(circuit) {
  const out = { equip: false, tempo: false, rpe: false };
  circuit.exercises.forEach(ex => {
    (ex.focusColumns || []).forEach(k => { if (k in out) out[k] = true; });
  });
  return out;
}

// ─── Settings screen ─────────────────────────────────────────────────────
function SettingsScreen({ theme, cardStyle, onBack, columnPrefs, onChangePref, onToast }) {
  return (
    <>
      <TopBar theme={theme} title="Settings" onBack={onBack}/>
      <div style={{ padding: '0 18px 100px', display: 'flex', flexDirection: 'column', gap: 18 }}>

        {/* Section: Weight units */}
        <Section theme={theme} title="Weight units"
          blurb="Sets log the number only — the unit is shown in the Wt column header so it never has to repeat on every cell.">
          <UnitRow theme={theme}
            value={columnPrefs.weightUnit || 'lb'}
            options={[
              { v: 'lb', label: 'Pounds',    hint: 'lb' },
              { v: 'kg', label: 'Kilograms', hint: 'kg' },
            ]}
            onChange={(v) => {
              onChangePref('weightUnit', v);
              onToast(`Weight unit → ${v === 'lb' ? 'pounds' : 'kilograms'}`);
            }}
          />
        </Section>

        {/* Section: Main Sets columns */}
        <Section theme={theme} title="Main Sets columns"
          blurb="Hide optional columns globally. Hidden columns still record data — they just don't take up space in the table. The ⋯ indicator on a row tells you data is parked behind the toggle.">
          {OPTIONAL_COLUMNS.map((col, i) => (
            <ColumnRow key={col.key} theme={theme} cardStyle={cardStyle}
              col={col}
              value={columnPrefs[col.key]}
              onChange={(v) => {
                onChangePref(col.key, v);
                onToast(`${col.label} ${v ? 'shown' : 'hidden'}`);
              }}
              isFirst={i === 0}
              isLast={i === OPTIONAL_COLUMNS.length - 1}
            />
          ))}
        </Section>

        {/* Section: Pinned columns */}
        <Section theme={theme} title="Always shown"
          blurb="The non-negotiables. These columns are core to logging a set and can't be hidden.">
          {PINNED_COLUMNS.map((col, i) => (
            <ColumnRow key={col.key} theme={theme} cardStyle={cardStyle}
              col={col}
              value={true} locked
              isFirst={i === 0}
              isLast={i === PINNED_COLUMNS.length - 1}
            />
          ))}
        </Section>

        <div style={{
          fontFamily: theme.uiFamily, fontSize: 11, color: theme.muted,
          textAlign: 'left', paddingTop: 8, lineHeight: 1.5,
        }}>
          Preferences sync to this device.<br/>
          Future: per-client column overrides on the client profile.
        </div>
      </div>
    </>
  );
}

// ─── Helpers ─────────────────────────────────────────────────────────────
function Section({ theme, title, blurb, children }) {
  return (
    <div>
      <div style={{
        padding: '0 4px 8px',
        fontFamily: theme.uiFamily, fontSize: 10, fontWeight: 700,
        color: theme.muted, textTransform: 'uppercase', letterSpacing: 0.6,
      }}>{title}</div>
      {blurb && (
        <div style={{
          padding: '0 4px 12px',
          fontFamily: theme.uiFamily, fontSize: 12, color: theme.muted,
          lineHeight: 1.5, maxWidth: 320,
        }}>{blurb}</div>
      )}
      <div style={{
        background: theme.surface,
        border: `1px solid ${theme.border}`,
        borderRadius: 12, overflow: 'hidden',
      }}>{children}</div>
    </div>
  );
}

// Weight-units segmented picker. Lives in its own section because the
// concept is unit-of-measure, not show/hide — a different control idiom.
function UnitRow({ theme, value, options, onChange }) {
  return (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 12,
      padding: '14px 16px',
    }}>
      <div style={{
        width: 32, height: 32, borderRadius: 8, flexShrink: 0,
        background: theme.isDark ? 'rgba(232,131,11,0.16)' : 'rgba(232,131,11,0.10)',
        color: theme.primary,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
      }}>
        <Icon name="weight" size={15} color={theme.primary} strokeWidth={1.8}/>
      </div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{
          fontFamily: theme.uiFamily, fontSize: 14, fontWeight: 600, color: theme.text,
        }}>Display unit</div>
        <div style={{
          fontFamily: theme.uiFamily, fontSize: 11, color: theme.muted,
          marginTop: 2, lineHeight: 1.4,
        }}>Shown once in the Wt column header. Switches every table at once.</div>
      </div>
      <div style={{
        display: 'inline-flex', gap: 2, padding: 2, borderRadius: 9999, flexShrink: 0,
        background: theme.isDark ? 'rgba(255,255,255,0.06)' : 'rgba(0,0,0,0.05)',
      }}>
        {options.map(o => {
          const on = value === o.v;
          return (
            <div key={o.v} onClick={() => onChange(o.v)} style={{
              padding: '5px 12px', borderRadius: 9999, cursor: 'pointer',
              background: on ? theme.primary : 'transparent',
              color: on ? theme.primaryInk : theme.muted,
              fontFamily: theme.uiFamily, fontSize: 11, fontWeight: 700,
              textTransform: 'uppercase', letterSpacing: 0.4,
              whiteSpace: 'nowrap',
            }}>{o.label}</div>
          );
        })}
      </div>
    </div>
  );
}

function ColumnRow({ theme, cardStyle, col, value, onChange, locked, isFirst, isLast }) {
  return (
    <div
      onClick={locked ? undefined : () => onChange(!value)}
      style={{
        display: 'flex', alignItems: 'center', gap: 12,
        padding: '14px 16px',
        cursor: locked ? 'default' : 'pointer',
        borderTop: isFirst ? 'none' : `1px solid ${theme.border}`,
        opacity: locked ? 0.7 : 1,
      }}>
      <div style={{
        width: 32, height: 32, borderRadius: 8, flexShrink: 0,
        background: value
          ? (theme.isDark ? 'rgba(232,131,11,0.16)' : 'rgba(232,131,11,0.10)')
          : (theme.isDark ? 'rgba(255,255,255,0.04)' : 'rgba(0,0,0,0.04)'),
        color: value ? theme.primary : theme.muted,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
      }}>
        <Icon name={col.icon} size={15} color={value ? theme.primary : theme.muted} strokeWidth={1.8}/>
      </div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{
          display: 'flex', alignItems: 'center', gap: 6,
          fontFamily: theme.uiFamily, fontSize: 14, fontWeight: 600, color: theme.text,
        }}>
          <span>{col.label}</span>
          {locked && (
            <span style={{
              fontFamily: theme.uiFamily, fontSize: 8, fontWeight: 700,
              padding: '2px 6px', borderRadius: 4,
              background: theme.isDark ? 'rgba(255,255,255,0.06)' : 'rgba(0,0,0,0.05)',
              color: theme.muted, textTransform: 'uppercase', letterSpacing: 0.5,
            }}>Always on</span>
          )}
        </div>
        <div style={{
          fontFamily: theme.uiFamily, fontSize: 11, color: theme.muted,
          marginTop: 2, lineHeight: 1.4,
        }}>{col.description}</div>
      </div>
      <SettingsToggle theme={theme} value={value} locked={locked}/>
    </div>
  );
}

function SettingsToggle({ theme, value, locked }) {
  const on = !!value;
  return (
    <div style={{
      width: 42, height: 24, borderRadius: 9999, flexShrink: 0,
      background: on ? theme.primary : (theme.isDark ? 'rgba(255,255,255,0.10)' : 'rgba(0,0,0,0.12)'),
      position: 'relative',
      transition: 'background 0.18s',
      opacity: locked ? 0.85 : 1,
    }}>
      <div style={{
        position: 'absolute', top: 2, left: on ? 20 : 2,
        width: 20, height: 20, borderRadius: 9999,
        background: '#fff',
        transition: 'left 0.18s',
        boxShadow: '0 1px 3px rgba(0,0,0,0.25)',
      }}/>
    </div>
  );
}

Object.assign(window, {
  OPTIONAL_COLUMNS, PINNED_COLUMNS,
  loadColumnPrefs, saveColumnPrefs, effectiveColumns,
  exerciseFocusCols, circuitFocusCols,
  SettingsScreen,
});
