// TrainingScreen.jsx — Training tab on iPad app.
// Flow:
//   1. Staff picker (avatar grid). Each avatar shows a NEW count badge.
//   2. After picking → list view with NEW / Completed tabs.
//   3. Tap a training item → fullscreen reader (rich text + media placeholders).
//   4. Tap Complete → confirm own PIN → trainer picker → trainer PIN → done.

const { useState: useTrn, useMemo: useMemoTrn, useEffect: useEffectTrn, useRef: useRefTrn } = React;

// ------------------------------------------------------------------
// Top-level Training screen — manages picker / list / reader state
// ------------------------------------------------------------------
const TrainingScreen = ({ completions, setCompletions, currentStaff, showToast }) => {
  // currentStaff is unused now — Training always starts at staff picker because
  // iPad is shared (no logged-in user). Kept the prop only for backward compat.
  const [pickedStaff, setPickedStaff] = useTrn(null);
  const [openItem, setOpenItem] = useTrn(null); // training item id

  if (!pickedStaff) {
    return (
      <TrainingStaffPicker
        completions={completions}
        onPick={setPickedStaff}
      />
    );
  }

  const item = openItem ? window.SAMPLE_TRAINING_ITEMS.find(i => i.id === openItem) : null;

  return (
    <>
      <TrainingList
        staff={pickedStaff}
        completions={completions}
        onOpen={(id) => setOpenItem(id)}
        onSwitchStaff={() => { setPickedStaff(null); setOpenItem(null); }}
      />
      {item && (
        <TrainingReader
          item={item}
          staff={pickedStaff}
          completions={completions}
          setCompletions={setCompletions}
          onClose={() => setOpenItem(null)}
          showToast={showToast}
        />
      )}
    </>
  );
};

// ------------------------------------------------------------------
// Staff picker — avatar grid, each tile shows NEW count badge
// ------------------------------------------------------------------
const TrainingStaffPicker = ({ completions, onPick }) => {
  const items = window.SAMPLE_TRAINING_ITEMS;
  const newCountFor = (staff) => items
    .filter(i => window.isAssignedTraining(i, staff))
    .filter(i => !window.hasCompletedTraining(i, staff, completions))
    .length;

  return (
    <div style={{ height: '100%', display: 'flex', flexDirection: 'column', padding: '16px 28px 28px' }}>
      <div style={{ padding: '8px 0 24px' }}>
        <div style={{ fontSize: 13, fontWeight: 600, letterSpacing: '0.12em', textTransform: 'uppercase', color: 'var(--fg-3)' }}>
          Training
        </div>
        <div style={{ fontSize: 30, fontWeight: 600, letterSpacing: '-0.025em', color: 'var(--fg-1)', marginTop: 4 }}>
          Who's training today?
        </div>
        <div style={{ fontSize: 15, color: 'var(--fg-2)', marginTop: 4 }}>
          Tap your name to see your assigned items.
        </div>
      </div>
      <div style={{
        flex: 1,
        display: 'grid',
        gridTemplateColumns: 'repeat(3, 1fr)',
        gap: 12,
        alignContent: 'start',
      }}>
        {window.SAMPLE_STAFF.map(s => {
          const newCount = newCountFor(s);
          return (
            <button key={s.id} onClick={() => onPick(s)} style={{
              position: 'relative',
              display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 12,
              padding: '20px 12px',
              background: '#FFFFFF',
              border: '1px solid var(--border-2)',
              borderRadius: 14,
              transition: 'transform 140ms var(--ease-snap)',
            }}
            onMouseDown={e => e.currentTarget.style.transform = 'scale(0.97)'}
            onMouseUp={e => e.currentTarget.style.transform = ''}
            onMouseLeave={e => e.currentTarget.style.transform = ''}
            >
              <Avatar staff={s} size={64} />
              <div style={{ textAlign: 'center' }}>
                <div style={{ fontSize: 14, fontWeight: 600, color: 'var(--fg-1)', letterSpacing: '-0.005em' }}>
                  {s.name}
                </div>
                <div style={{ fontSize: 11, color: 'var(--fg-3)', fontWeight: 500, letterSpacing: '0.04em', textTransform: 'uppercase', marginTop: 2 }}>
                  {s.role}
                </div>
              </div>
              {newCount > 0 && (
                <div style={{
                  position: 'absolute', top: 12, right: 12,
                  minWidth: 22, height: 22, padding: '0 7px',
                  borderRadius: 999,
                  background: '#2563EB', color: '#fff',
                  fontSize: 11, fontWeight: 700,
                  fontFamily: 'var(--font-num)',
                  display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                }}>
                  {newCount}
                </div>
              )}
            </button>
          );
        })}
      </div>
    </div>
  );
};

// ------------------------------------------------------------------
// Training list (NEW / Completed tabs)
// Now includes category filter chips with per-category progress.
// ------------------------------------------------------------------
const TrainingList = ({ staff, completions, onOpen, onSwitchStaff }) => {
  const [tab, setTab]               = useTrn('new');
  const [categoryFilter, setCatFil] = useTrn('all');

  const categories = window.SAMPLE_TRAINING_CATEGORIES || [];
  const allItems   = window.SAMPLE_TRAINING_ITEMS.filter(i => window.isAssignedTraining(i, staff));

  // Stats per category (and overall) for the chip row + summary.
  const stats = useMemoTrn(() => {
    const byCat = { all: { done: 0, total: 0 } };
    categories.forEach(c => byCat[c.id] = { done: 0, total: 0, color: c.color, name: c.name });
    byCat['__none'] = { done: 0, total: 0, name: 'Uncategorized' };
    allItems.forEach(it => {
      const key = (it.categoryId && byCat[it.categoryId]) ? it.categoryId : '__none';
      const done = window.hasCompletedTraining(it, staff, completions);
      byCat[key].total += 1;
      byCat.all.total += 1;
      if (done) {
        byCat[key].done += 1;
        byCat.all.done += 1;
      }
    });
    return byCat;
  }, [allItems, completions, categories, staff]);

  // Items filtered by both NEW/Completed tab AND active category chip.
  const filtered = useMemoTrn(() => {
    let list = allItems;
    if (categoryFilter !== 'all') {
      list = list.filter(i => (categoryFilter === '__none')
        ? !i.categoryId
        : i.categoryId === categoryFilter);
    }
    const done = list.filter(i => window.hasCompletedTraining(i, staff, completions));
    const pending = list.filter(i => !window.hasCompletedTraining(i, staff, completions));
    return tab === 'new' ? pending : done;
  }, [allItems, categoryFilter, tab, completions, staff]);

  // Category counts for the chip row, scoped to current tab (new vs completed).
  const chipCount = (catId) => {
    const s = stats[catId];
    if (!s) return 0;
    return tab === 'new' ? (s.total - s.done) : s.done;
  };

  const overallPct = stats.all.total === 0 ? 0 : Math.round((stats.all.done / stats.all.total) * 100);

  // Visible chips: 'all' first, then each category that has at least one
  // assigned item for this staff. Skip empty categories so the strip isn't noisy.
  const visibleCategories = categories.filter(c => stats[c.id] && stats[c.id].total > 0);
  const hasUncategorized  = stats['__none'].total > 0;

  return (
    <div style={{ height: '100%', display: 'flex', flexDirection: 'column' }}>
      <div style={{ padding: '12px 24px 16px', borderBottom: '1px solid var(--border-2)' }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 12 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
            <Avatar staff={staff} size={40} />
            <div>
              <div style={{ fontSize: 11, color: 'var(--fg-3)', fontWeight: 500, letterSpacing: '0.06em', textTransform: 'uppercase' }}>Training for</div>
              <div style={{ fontSize: 20, fontWeight: 600, color: 'var(--fg-1)', letterSpacing: '-0.02em' }}>{staff.name}</div>
            </div>
          </div>
          {/* Overall progress badge */}
          <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
            <div style={{
              display: 'flex', alignItems: 'baseline', gap: 4,
              padding: '6px 12px',
              background: overallPct === 100 ? '#E7F0E0' : 'var(--bg-sunken)',
              borderRadius: 999,
            }}>
              <span style={{
                fontSize: 16, fontWeight: 700,
                color: overallPct === 100 ? '#2D6A2A' : 'var(--fg-1)',
                fontFamily: 'var(--font-num)', letterSpacing: '-0.01em',
              }}>{overallPct}%</span>
              <span style={{ fontSize: 10.5, color: 'var(--fg-3)', fontWeight: 500, fontFamily: 'var(--font-num)' }}>
                {stats.all.done}/{stats.all.total}
              </span>
            </div>
            <button onClick={onSwitchStaff} style={{
              padding: '8px 14px',
              background: 'var(--bg-sunken)',
              borderRadius: 999,
              fontSize: 13, fontWeight: 500, color: 'var(--fg-2)',
            }}>Switch</button>
          </div>
        </div>

        {/* New / Completed tabs */}
        <div style={{ display: 'flex', gap: 4, padding: 3, background: 'var(--bg-sunken)', borderRadius: 10 }}>
          <TabBtn active={tab === 'new'} onClick={() => setTab('new')} label="New" count={stats.all.total - stats.all.done} />
          <TabBtn active={tab === 'completed'} onClick={() => setTab('completed')} label="Completed" count={stats.all.done} />
        </div>
      </div>

      {/* Category filter chip row with mini progress per chip */}
      {visibleCategories.length > 0 && (
        <div className="scroll-soft" style={{
          flexShrink: 0,
          padding: '10px 24px',
          borderBottom: '1px solid var(--border-2)',
          display: 'flex', gap: 8, overflowX: 'auto', overflowY: 'hidden',
        }}>
          <CategoryChipBtn
            active={categoryFilter === 'all'}
            onClick={() => setCatFil('all')}
            label="All"
            count={chipCount('all')}
            total={stats.all.total}
            done={stats.all.done}
          />
          {visibleCategories.map(c => (
            <CategoryChipBtn
              key={c.id}
              active={categoryFilter === c.id}
              onClick={() => setCatFil(c.id)}
              label={c.name}
              color={c.color}
              count={chipCount(c.id)}
              total={stats[c.id].total}
              done={stats[c.id].done}
            />
          ))}
          {hasUncategorized && (
            <CategoryChipBtn
              active={categoryFilter === '__none'}
              onClick={() => setCatFil('__none')}
              label="Uncategorized"
              count={chipCount('__none')}
              total={stats['__none'].total}
              done={stats['__none'].done}
            />
          )}
        </div>
      )}

      <div style={{ flex: 1, overflow: 'auto', padding: '16px 24px 28px' }}>
        {filtered.length === 0 ? (
          <div style={{ padding: '60px 20px', textAlign: 'center' }}>
            <div style={{ fontSize: 36, marginBottom: 12, opacity: 0.6 }}>{tab === 'new' ? '✓' : '◌'}</div>
            <div style={{ fontSize: 17, fontWeight: 600, color: 'var(--fg-1)', letterSpacing: '-0.01em' }}>
              {tab === 'new'
                ? (categoryFilter === 'all' ? "You're all caught up" : "Nothing left in this category")
                : 'Nothing completed yet'}
            </div>
            <div style={{ fontSize: 14, color: 'var(--fg-2)', marginTop: 6 }}>
              {tab === 'new' ? 'No assigned training items left.' : 'Complete items appear here.'}
            </div>
          </div>
        ) : (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
            {filtered.map(item => {
              const completion = (completions?.[item.id] || []).find(c => c.staffId === staff.id);
              const cat = categories.find(c => c.id === item.categoryId);
              return (
                <TrainingCard
                  key={item.id}
                  item={item}
                  completion={completion}
                  category={cat}
                  onClick={() => onOpen(item.id)}
                />
              );
            })}
          </div>
        )}
      </div>
    </div>
  );
};

// Chip with optional color dot + progress fraction. Doubles as filter button.
const CategoryChipBtn = ({ active, onClick, label, color, count, total, done }) => {
  const pct = total === 0 ? 0 : Math.round((done / total) * 100);
  const allDone = total > 0 && done === total;
  return (
    <button onClick={onClick} style={{
      display: 'inline-flex', flexDirection: 'column', alignItems: 'flex-start', gap: 4,
      flexShrink: 0,
      padding: '8px 14px',
      background: active ? 'var(--fg-1)' : '#FFFFFF',
      color: active ? '#FFFFFF' : 'var(--fg-1)',
      border: '1px solid ' + (active ? 'var(--fg-1)' : 'var(--border-2)'),
      borderRadius: 14,
      cursor: 'pointer',
      minWidth: 96,
    }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
        {color && (
          <span style={{ width: 7, height: 7, borderRadius: 999, background: active ? '#FFFFFF' : color }} />
        )}
        <span style={{ fontSize: 13, fontWeight: 600, letterSpacing: '-0.005em', whiteSpace: 'nowrap' }}>
          {label}
        </span>
      </div>
      <div style={{
        display: 'flex', alignItems: 'center', gap: 6,
        fontSize: 11, fontFamily: 'var(--font-num)',
        color: active ? 'rgba(255,255,255,0.8)' : 'var(--fg-3)',
      }}>
        <span style={{ fontWeight: 600 }}>{done}/{total}</span>
        {/* mini progress bar */}
        <div style={{
          width: 36, height: 3, borderRadius: 999,
          background: active ? 'rgba(255,255,255,0.25)' : 'var(--bg-sunken)',
          overflow: 'hidden',
        }}>
          <div style={{
            width: pct + '%', height: '100%',
            background: active ? '#FFFFFF' : (allDone ? '#2D6A2A' : (color || 'var(--fg-1)')),
          }} />
        </div>
      </div>
    </button>
  );
};

const TabBtn = ({ active, onClick, label, count }) => (
  <button onClick={onClick} style={{
    flex: 1, height: 36, borderRadius: 8,
    background: active ? '#fff' : 'transparent',
    color: active ? 'var(--fg-1)' : 'var(--fg-2)',
    fontSize: 14, fontWeight: 600,
    boxShadow: active ? 'var(--shadow-1)' : 'none',
    display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 8,
    letterSpacing: '-0.005em',
  }}>
    {label}
    <span style={{
      display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
      minWidth: 20, height: 20, padding: '0 6px',
      borderRadius: 999,
      background: active ? 'var(--fg-1)' : 'var(--bg-sunken)',
      color: active ? '#fff' : 'var(--fg-2)',
      fontSize: 11, fontWeight: 700,
      fontFamily: 'var(--font-num)',
    }}>{count}</span>
  </button>
);

// ------------------------------------------------------------------
// Training card (in list) — shows category pill if assigned
// ------------------------------------------------------------------
const TrainingCard = ({ item, completion, category, onClick }) => {
  const hasMedia = (item.media || []).length > 0;
  const completedAt = completion ? new Date(completion.completedAt) : null;
  const approver = completion ? window.SAMPLE_STAFF.find(s => s.id === completion.approvedBy) : null;

  return (
    <button onClick={onClick} style={{
      textAlign: 'left',
      padding: '16px 18px',
      background: '#FFFFFF',
      border: '1px solid var(--border-2)',
      borderRadius: 14,
      display: 'flex', alignItems: 'flex-start', gap: 14,
      transition: 'transform 140ms var(--ease-snap)',
    }}
    onMouseDown={e => e.currentTarget.style.transform = 'scale(0.992)'}
    onMouseUp={e => e.currentTarget.style.transform = ''}
    onMouseLeave={e => e.currentTarget.style.transform = ''}
    >
      <div style={{
        width: 44, height: 44, borderRadius: 10,
        background: completion ? '#E7F0E0' : 'var(--bg-sunken)',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        flexShrink: 0,
      }}>
        <Icon name={completion ? 'check' : 'clipboard'} size={20} color={completion ? '#2D6A2A' : 'var(--fg-1)'} strokeWidth={completion ? 2.4 : 1.6} />
      </div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 16, fontWeight: 600, color: 'var(--fg-1)', letterSpacing: '-0.01em', lineHeight: 1.25 }}>
          {item.title}
        </div>
        <div style={{ fontSize: 13, color: 'var(--fg-2)', marginTop: 3, lineHeight: 1.35 }}>
          {item.summary}
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginTop: 8, flexWrap: 'wrap' }}>
          {category && (
            <span style={{
              display: 'inline-flex', alignItems: 'center', gap: 5,
              fontSize: 11, fontWeight: 600,
              color: category.color,
              padding: '3px 8px',
              background: category.color + '14',
              borderRadius: 999,
            }}>
              <span style={{ width: 6, height: 6, borderRadius: 999, background: category.color }} />
              {category.name}
            </span>
          )}
          {hasMedia && (
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4, fontSize: 11, fontWeight: 500, color: 'var(--fg-3)' }}>
              <Icon name="eye" size={12} color="var(--fg-3)" strokeWidth={1.8} />
              {item.media.length} {item.media.length === 1 ? 'attachment' : 'attachments'}
            </span>
          )}
          {completedAt && approver && (
            <span style={{ fontSize: 11, fontWeight: 500, color: 'var(--fg-3)' }}>
              Approved by {approver.name} · {completedAt.toLocaleDateString('en-US', { month: 'short', day: 'numeric' })}
            </span>
          )}
        </div>
      </div>
      <Icon name="chevron" size={16} color="var(--fg-3)" strokeWidth={1.8} style={{ marginTop: 12 }} />
    </button>
  );
};

// ------------------------------------------------------------------
// Training reader — fullscreen popup with rich text + media
// ------------------------------------------------------------------
const TrainingReader = ({ item, staff, completions, setCompletions, onClose, showToast }) => {
  // approval flow phase: 'view' | 'self-pin' | 'trainer-pick' | 'trainer-pin' | 'done'
  const [phase, setPhase] = useTrn('view');
  const [trainer, setTrainer] = useTrn(null);

  const alreadyDone = window.hasCompletedTraining(item, staff, completions);

  const certifiedTrainers = window.getCertifiedTrainers(item, completions);

  const finishApproval = (approver) => {
    const entry = {
      staffId: staff.id,
      completedAt: new Date().toISOString(),
      approvedBy: approver.id,
    };
    setCompletions(prev => ({
      ...prev,
      [item.id]: [...(prev[item.id] || []), entry],
    }));
    setPhase('done');
    setTimeout(() => {
      showToast && showToast({ message: `Training completed — approved by ${approver.name}`, staff });
      onClose();
    }, 1400);
  };

  return (
    <div style={{
      position: 'absolute', inset: 0, zIndex: 50,
      background: '#FFFFFF',
      display: 'flex', flexDirection: 'column',
      animation: 'pop-in 240ms var(--ease-snap)',
    }}>
      {/* Header */}
      <div style={{
        padding: '14px 18px',
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        borderBottom: '1px solid var(--border-2)',
      }}>
        <button onClick={onClose} style={{
          width: 36, height: 36, borderRadius: 999,
          background: 'var(--bg-sunken)',
          display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
        }}>
          <Icon name="x" size={18} />
        </button>
        <div style={{ fontSize: 13, color: 'var(--fg-3)', fontWeight: 500 }}>Training</div>
        <div style={{ width: 36 }} />
      </div>

      {/* Body */}
      <div style={{ flex: 1, overflow: 'auto', padding: '24px 28px 120px' }}>
        <div style={{ fontSize: 28, fontWeight: 600, letterSpacing: '-0.025em', color: 'var(--fg-1)', lineHeight: 1.18 }}>
          {item.title}
        </div>
        <div style={{ fontSize: 16, color: 'var(--fg-2)', marginTop: 8, lineHeight: 1.4 }}>
          {item.summary}
        </div>

        {/* Media row */}
        {(item.media || []).length > 0 && (
          <div style={{ marginTop: 22, display: 'flex', flexDirection: 'column', gap: 12 }}>
            {item.media.map((m, i) => (
              <div key={i} style={{
                width: '100%',
                aspectRatio: m.type === 'video' ? '16 / 9' : '4 / 3',
                background: '#0F1115',
                borderRadius: 14,
                overflow: 'hidden',
                position: 'relative',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                color: '#9CA3AF', fontSize: 13, fontWeight: 500,
                backgroundImage: 'repeating-linear-gradient(45deg, transparent 0 18px, rgba(255,255,255,0.03) 18px 19px)',
              }}>
                {m.type === 'video' && (
                  <div style={{
                    width: 64, height: 64, borderRadius: 999,
                    background: 'rgba(255,255,255,0.18)',
                    display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                    backdropFilter: 'blur(8px)',
                  }}>
                    <svg width="22" height="22" viewBox="0 0 24 24" fill="#FFFFFF"><path d="M8 5v14l11-7z"/></svg>
                  </div>
                )}
                <div style={{ position: 'absolute', bottom: 12, left: 14, color: '#E5E7EB', fontSize: 12, fontWeight: 500 }}>
                  {m.placeholder}
                </div>
              </div>
            ))}
          </div>
        )}

        {/* Rich text body */}
        <div
          style={{ marginTop: 22, fontSize: 16, color: 'var(--fg-1)', lineHeight: 1.55 }}
          className="training-body"
          dangerouslySetInnerHTML={{ __html: item.bodyHtml }}
        />

        <style>{`
          .training-body h3 { font-size: 17px; font-weight: 600; letter-spacing: -0.015em; margin: 22px 0 8px; color: var(--fg-1); }
          .training-body p { margin: 0 0 12px; }
          .training-body ol, .training-body ul { padding-left: 22px; margin: 8px 0 14px; }
          .training-body li { margin-bottom: 6px; }
          .training-body b { font-weight: 600; color: var(--fg-1); }
        `}</style>
      </div>

      {/* Footer / CTA */}
      {!alreadyDone && phase === 'view' && (
        <div style={{
          position: 'absolute', bottom: 0, left: 0, right: 0,
          padding: '14px 22px 22px',
          background: 'linear-gradient(to top, #FFFFFF 70%, rgba(255,255,255,0))',
        }}>
          <Btn variant="primary" size="xl" fullWidth onClick={() => setPhase('self-pin')}>
            Mark as completed
          </Btn>
        </div>
      )}
      {alreadyDone && phase === 'view' && (() => {
        const c = (completions[item.id] || []).find(x => x.staffId === staff.id);
        const approver = c ? window.SAMPLE_STAFF.find(s => s.id === c.approvedBy) : null;
        return (
          <div style={{
            position: 'absolute', bottom: 0, left: 0, right: 0,
            padding: '14px 22px 22px',
            background: '#FFFFFF',
            borderTop: '1px solid var(--border-2)',
            display: 'flex', alignItems: 'center', gap: 12,
          }}>
            <div style={{
              width: 40, height: 40, borderRadius: 999,
              background: '#E7F0E0',
              display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
            }}>
              <Icon name="check" size={20} color="#2D6A2A" strokeWidth={2.4} />
            </div>
            <div>
              <div style={{ fontSize: 15, fontWeight: 600, color: 'var(--fg-1)', letterSpacing: '-0.005em' }}>Completed</div>
              <div style={{ fontSize: 12, color: 'var(--fg-2)' }}>
                {c && new Date(c.completedAt).toLocaleDateString('en-US', { month: 'short', day: 'numeric' })}
                {approver && ` · approved by ${approver.name}`}
              </div>
            </div>
          </div>
        );
      })()}

      {/* Approval modals */}
      {phase === 'self-pin' && (
        <PinConfirmSheet
          title="Confirm it's you"
          subtitle={<>Enter <b>{staff.name}'s</b> 4-digit PIN to start completion.</>}
          who={staff}
          expectedPin={staff.pin}
          onCancel={() => setPhase('view')}
          onSuccess={() => setPhase('trainer-pick')}
        />
      )}
      {phase === 'trainer-pick' && (
        <TrainerPickerSheet
          item={item}
          trainers={certifiedTrainers}
          onCancel={() => setPhase('view')}
          onPick={(t) => { setTrainer(t); setPhase('trainer-pin'); }}
        />
      )}
      {phase === 'trainer-pin' && trainer && (
        <PinConfirmSheet
          title="Trainer approval"
          subtitle={<><b>{trainer.name}</b>, enter your PIN to approve <b>{staff.name}</b>'s completion.</>}
          who={trainer}
          expectedPin={trainer.pin}
          accent="#2D6A2A"
          confirmLabel="Approve"
          onCancel={() => setPhase('trainer-pick')}
          onSuccess={() => finishApproval(trainer)}
        />
      )}
      {phase === 'done' && (
        <div style={{
          position: 'absolute', inset: 0, zIndex: 60,
          background: 'rgba(255,255,255,0.96)',
          display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 16,
          animation: 'fade-in 200ms var(--ease-out)',
        }}>
          <div style={{
            width: 88, height: 88, borderRadius: 999,
            background: '#E7F0E0',
            display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
            animation: 'pop-in 320ms var(--ease-snap)',
          }}>
            <Icon name="check" size={48} color="#2D6A2A" strokeWidth={2.4} />
          </div>
          <div style={{ fontSize: 22, fontWeight: 600, letterSpacing: '-0.02em', color: 'var(--fg-1)' }}>Training completed</div>
          <div style={{ fontSize: 14, color: 'var(--fg-2)' }}>Approved by {trainer?.name}</div>
        </div>
      )}
    </div>
  );
};

// ------------------------------------------------------------------
// Pin confirmation sheet — used twice (self + trainer)
// ------------------------------------------------------------------
const PinConfirmSheet = ({ title, subtitle, who, expectedPin, onCancel, onSuccess, accent = '#1D4ED8', confirmLabel = 'Continue' }) => {
  const [pin, setPin] = useTrn('');
  const [err, setErr] = useTrn(false);
  const [shake, setShake] = useTrn(false);

  const tryPin = (p) => {
    if (p === expectedPin) {
      onSuccess();
    } else {
      setErr(true); setShake(true);
      setTimeout(() => { setPin(''); setShake(false); }, 480);
      setTimeout(() => setErr(false), 2000);
    }
  };

  const dots = Array.from({ length: 4 }).map((_, i) => (
    <div key={i} style={{
      width: 18, height: 18, borderRadius: 999,
      background: i < pin.length ? 'var(--fg-1)' : 'transparent',
      border: '2px solid ' + (i < pin.length ? 'var(--fg-1)' : 'var(--border-1)'),
      transition: 'all 140ms var(--ease-snap)',
    }} />
  ));

  return (
    <div style={{
      position: 'absolute', inset: 0, zIndex: 70,
      background: 'rgba(0,0,0,0.40)',
      display: 'flex', alignItems: 'flex-end', justifyContent: 'center',
      animation: 'fade-in 180ms var(--ease-out)',
    }}>
      <div style={{
        width: '100%',
        background: '#FFFFFF',
        borderTopLeftRadius: 24, borderTopRightRadius: 24,
        padding: '18px 28px 28px',
        display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 18,
        animation: 'slide-up 280ms var(--ease-snap)',
        boxShadow: '0 -10px 40px rgba(0,0,0,0.18)',
      }}>
        <div style={{ width: 40, height: 4, background: 'var(--border-2)', borderRadius: 999, marginTop: -4 }} />
        <div style={{ textAlign: 'center', maxWidth: 440 }}>
          <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: '0.12em', textTransform: 'uppercase', color: accent }}>
            {title}
          </div>
          <div style={{ fontSize: 19, fontWeight: 500, color: 'var(--fg-1)', letterSpacing: '-0.01em', marginTop: 8, lineHeight: 1.4 }}>
            {subtitle}
          </div>
        </div>
        <Avatar staff={who} size={56} />
        <div style={{ display: 'flex', gap: 22, animation: shake ? 'shake 450ms' : 'none' }}>{dots}</div>
        <div style={{ fontSize: 13, height: 16, color: err ? 'var(--danger)' : 'var(--fg-3)', fontWeight: 500 }}>
          {err ? 'PIN does not match' : ''}
        </div>
        <NumPad value={pin} onChange={setPin} onEnter={tryPin} maxLen={4} big />
        <button onClick={onCancel} style={{
          padding: '12px 24px', marginTop: 4, fontSize: 14, fontWeight: 500, color: 'var(--fg-2)',
        }}>Cancel</button>
      </div>
    </div>
  );
};

// ------------------------------------------------------------------
// Trainer picker sheet — pick from certified trainers
// ------------------------------------------------------------------
const TrainerPickerSheet = ({ item, trainers, onCancel, onPick }) => {
  return (
    <div style={{
      position: 'absolute', inset: 0, zIndex: 70,
      background: 'rgba(0,0,0,0.40)',
      display: 'flex', alignItems: 'flex-end', justifyContent: 'center',
      animation: 'fade-in 180ms var(--ease-out)',
    }}>
      <div style={{
        width: '100%',
        background: '#FFFFFF',
        borderTopLeftRadius: 24, borderTopRightRadius: 24,
        padding: '20px 24px 28px',
        animation: 'slide-up 280ms var(--ease-snap)',
        boxShadow: '0 -10px 40px rgba(0,0,0,0.18)',
        maxHeight: '80%',
        overflow: 'auto',
      }}>
        <div style={{ width: 40, height: 4, background: 'var(--border-2)', borderRadius: 999, margin: '0 auto 14px' }} />
        <div style={{ textAlign: 'center', marginBottom: 16 }}>
          <div style={{ fontSize: 11, fontWeight: 600, letterSpacing: '0.1em', textTransform: 'uppercase', color: '#1D4ED8' }}>
            Find a trainer
          </div>
          <div style={{ fontSize: 18, fontWeight: 600, color: 'var(--fg-1)', letterSpacing: '-0.01em', marginTop: 6 }}>
            Who's approving your completion?
          </div>
          <div style={{ fontSize: 13, color: 'var(--fg-2)', marginTop: 4 }}>
            Only certified trainers for this item can approve.
          </div>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 10, marginBottom: 12 }}>
          {trainers.map(t => (
            <button key={t.id} onClick={() => onPick(t)} style={{
              display: 'flex', alignItems: 'center', gap: 12,
              padding: '12px 14px',
              background: 'var(--bg-sunken)',
              borderRadius: 12,
              textAlign: 'left',
              transition: 'transform 120ms var(--ease-snap)',
            }}
            onMouseDown={e => e.currentTarget.style.transform = 'scale(0.97)'}
            onMouseUp={e => e.currentTarget.style.transform = ''}
            onMouseLeave={e => e.currentTarget.style.transform = ''}
            >
              <Avatar staff={t} size={40} />
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 14, fontWeight: 600, color: 'var(--fg-1)' }}>{t.name}</div>
                <div style={{ fontSize: 11, color: 'var(--fg-3)', fontWeight: 500, letterSpacing: '0.04em', textTransform: 'uppercase' }}>
                  {t.id === 'ryan' ? 'Admin' : 'Certified'}
                </div>
              </div>
            </button>
          ))}
        </div>
        {trainers.length === 1 && trainers[0].id === 'ryan' && (
          <div style={{ fontSize: 12, color: 'var(--fg-3)', textAlign: 'center', padding: '4px 12px 8px' }}>
            No other trainers are certified for this item yet — only Ryan can approve.
          </div>
        )}
        <button onClick={onCancel} style={{
          width: '100%', padding: '14px', marginTop: 4,
          fontSize: 14, fontWeight: 500, color: 'var(--fg-2)',
          background: 'transparent',
        }}>Cancel</button>
      </div>
    </div>
  );
};

Object.assign(window, { TrainingScreen });
