// 13-Week Scorecard view + Issues (IDS) view
// Design system: see DESIGN.md ("The Climbing Wall")
// useMedia is provided globally from ui.jsx

// For monthly metrics, null-out any slot that isn't the month-close Thursday
// for its own calendar month. Non-close slots should show — not a stale value.
function applyMonthlyMask(rawData) {
  const ends = window.NORWILL_DATA.rollingWeekEndings();
  return rawData.map((v, i) => {
    const t = ends[i];
    if (!t) return null;
    const close = window.NORWILL_DATA.monthCloseThursday(t);
    return close.getTime() === t.getTime() ? v : null;
  });
}

// Count consecutive trailing weeks where the metric was on-target.
function trailingGreenStreak(metric, weeks) {
  let count = 0;
  for (let i = weeks.length - 1; i >= 0; i--) {
    if (metricStatus(metric, weeks[i]) === 'good') count++;
    else if (weeks[i] != null) break;
    else break;
  }
  return count;
}

// Format a numeric value for the dense grid (no $/%/, separators — legible at small sizes).
function fmtCell(v, m) {
  if (v == null || isNaN(v)) return '—';
  if (m && m.label.includes('%')) return Math.round(v * 10) / 10;
  if (m && (m.fn === 'Finance' || m.id === 'cash' || m.id === 'ar60')) {
    if (v >= 1000) return Math.round(v / 100) / 10 + 'k';
    return Math.round(v);
  }
  return Math.round(v);
}

// ─── Scorecard view ────────────────────────────────────────────
function Scorecard({ persona, mode = 'working' }) {
  const isMobile = useMedia('(max-width: 760px)');
  const [filter, setFilter] = React.useState('all');
  const currentWeekIdx = window.NORWILL_DATA.CURRENT_WEEK_IDX;
  const isMeeting = mode === 'meeting';

  const metricsShown = METRICS.filter(m => {
    if (filter === 'mine') return m.ownerId === persona.id;
    if (filter === 'red') {
      const val = HISTORY[m.id]?.[currentWeekIdx];
      return metricStatus(m, val) === 'bad';
    }
    return true;
  });

  return (
    <div style={{ padding: isMobile ? '20px 16px 32px' : '28px 32px 40px' }}>
      <div className="view-header" style={{ flexWrap: 'wrap' }}>
        <div>
          <div className="eyebrow">Rolling 13 weeks · ending {window.NORWILL_DATA.rollingWeekLabels().slice(-1)[0]}</div>
          <h2 className="view-title">Weekly Scorecard</h2>
          <div className="view-sub">
            {isMeeting
              ? 'Meeting view. Read across; click a cell to see its 13-week trend.'
              : 'Working view. Tap a cell to enter or correct your number.'}
          </div>
        </div>
        <span style={{ flex: 1 }}/>
        <ScorecardFilter value={filter} onChange={setFilter} count={metricsShown.length}/>
      </div>

      {metricsShown.length === 0 ? (
        <ScorecardEmpty filter={filter} onReset={() => setFilter('all')}/>
      ) : isMobile ? (
        <ScorecardMobile metrics={metricsShown} currentWeekIdx={currentWeekIdx}/>
      ) : (
        <ScorecardDesktop metrics={metricsShown} currentWeekIdx={currentWeekIdx} mode={mode}/>
      )}

      <Legend mode={mode}/>
    </div>
  );
}

function ScorecardFilter({ value, onChange, count }) {
  return (
    <div style={{ display: 'flex', gap: 12, alignItems: 'center' }}>
      <span style={{ fontSize: 12, color: 'var(--ink-500)' }}>
        <span className="numeric" style={{ fontWeight: 600, color: 'var(--ink-700)' }}>{count}</span>{' '}
        {count === 1 ? 'metric' : 'metrics'}
      </span>
      <div style={{
        display: 'inline-flex', padding: 3, borderRadius: 99,
        background: 'var(--surface-sunk)', border: '1px solid var(--hairline)',
      }}>
        {[['all','All'],['mine','Mine'],['red','Off pace']].map(([k,v]) => (
          <button key={k} onClick={() => onChange(k)} style={{
            padding: '6px 14px', borderRadius: 99, border: 'none',
            background: value === k ? 'var(--surface-card)' : 'transparent',
            color: value === k ? 'var(--ink-900)' : 'var(--ink-600)',
            fontSize: 12, fontWeight: 600,
            boxShadow: value === k ? 'var(--shadow-sm)' : 'none',
            cursor: 'pointer',
            transition: 'background 160ms var(--ease-out)',
          }}>{v}</button>
        ))}
      </div>
    </div>
  );
}

function ScorecardEmpty({ filter, onReset }) {
  const reasons = {
    all:  { title: 'No metrics yet.', body: 'Add your first metric to start tracking the team’s 13-week trend.' },
    mine: { title: 'No metrics assigned to you.', body: 'You don’t own any metrics in this quarter. Try the All view to see the full team scorecard.' },
    red:  { title: 'Nothing off pace this week.', body: 'Every metric is on target right now. Switch back to All to see the full picture.' },
  };
  const r = reasons[filter] || reasons.all;
  return (
    <div className="card" style={{ padding: '36px 28px', textAlign: 'center' }}>
      <div style={{ fontFamily: 'var(--font-display)', fontWeight: 500, fontSize: 22, color: 'var(--ink-900)' }}>{r.title}</div>
      <div style={{ color: 'var(--ink-600)', marginTop: 6, fontSize: 14, maxWidth: 420, margin: '6px auto 16px' }}>{r.body}</div>
      {filter !== 'all' && (
        <button className="btn btn-ghost btn-sm" onClick={onReset}>See all metrics</button>
      )}
    </div>
  );
}

function ScorecardDesktop({ metrics, currentWeekIdx, mode }) {
  const weeks = window.NORWILL_DATA.rollingWeekLabels();
  const [hoverMetric, setHoverMetric] = React.useState(null);
  const isMeeting = mode === 'meeting';

  return (
    <div className="card" style={{ overflow: 'auto', padding: 0 }}>
      <table className="sc-table" role="grid">
        <thead>
          <tr>
            <th className="sc-metric-cell" style={{ textAlign: 'left' }}>Metric</th>
            <th>Owner</th>
            <th>Goal</th>
            {weeks.map((w, i) => (
              <th
                key={w}
                className={i === currentWeekIdx ? 'sc-now-th' : undefined}
                aria-current={i === currentWeekIdx ? 'true' : undefined}
              >
                {w}
                {i === currentWeekIdx && (
                  <span style={{ display: 'block', fontSize: 9, color: 'var(--norwill-forest)', marginTop: 2, letterSpacing: 0.06 }}>NOW</span>
                )}
              </th>
            ))}
            <th>Trend</th>
          </tr>
        </thead>
        <tbody>
          {metrics.map((m) => {
            const owner = PEOPLE.find(p => p.id === m.ownerId);
            const rawData = HISTORY[m.id] || [];
            const weeksData = window.metricCadence(m) === 'monthly' ? applyMonthlyMask(rawData) : rawData;
            const streak = trailingGreenStreak(m, weeksData);
            return (
              <tr
                key={m.id}
                onMouseEnter={() => setHoverMetric(m.id)}
                onMouseLeave={() => setHoverMetric(prev => prev === m.id ? null : prev)}
              >
                <td className="sc-metric-cell">
                  <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                    {streak >= 4 && (
                      <span className="streak-mark" title={streak + ' green weeks in a row'} aria-label={streak + ' green weeks in a row'}>
                        ▲
                      </span>
                    )}
                    <div style={{ minWidth: 0 }}>
                      <div style={{ fontWeight: 600, color: 'var(--ink-900)', fontSize: isMeeting ? 16 : 14 }}>{m.label}</div>
                      <div style={{ fontSize: 11, color: 'var(--ink-500)', marginTop: 2 }}>
                        {m.fn} · {window.metricAgg(m)}
                      </div>
                    </div>
                  </div>
                </td>
                <td>
                  <div style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}>
                    <Avatar person={owner} size={22}/>
                    <span style={{ fontSize: 12, color: 'var(--ink-700)' }}>{owner?.name.split(' ')[0]}</span>
                  </div>
                </td>
                <td>
                  <span className="numeric" style={{ fontWeight: 600, color: 'var(--ink-700)', fontSize: isMeeting ? 16 : 14 }}>
                    {m.dir === '<=' ? '≤ ' : ''}{fmtNum(window.scorecardTarget(m), m)}
                  </span>
                </td>
                {weeksData.map((v, i) => {
                  const s = metricStatus(m, v);
                  const isNow = i === currentWeekIdx;
                  let cls = 'sc-cell';
                  if (s === 'good') cls += ' sc-cell--good';
                  else if (s === 'warn') cls += ' sc-cell--warn';
                  else if (s === 'bad') cls += ' sc-cell--bad';
                  return (
                    <td
                      key={i}
                      className={isNow ? cls + ' sc-now' : cls}
                      aria-current={isNow ? 'true' : undefined}
                    >
                      {fmtCell(v, m)}
                    </td>
                  );
                })}
                <td style={{ minWidth: 110 }}>
                  <Spark data={weeksData} width={isMeeting ? 110 : 96} height={isMeeting ? 32 : 26} target={window.scorecardTarget(m)} dir={m.dir} fill={false}/>
                </td>
              </tr>
            );
          })}
        </tbody>
      </table>
    </div>
  );
}

function ScorecardMobile({ metrics, currentWeekIdx }) {
  return (
    <div className="sc-stack">
      {metrics.map(m => (
        <ScorecardMobileCard key={m.id} metric={m} currentWeekIdx={currentWeekIdx}/>
      ))}
    </div>
  );
}

function ScorecardMobileCard({ metric, currentWeekIdx }) {
  const [open, setOpen] = React.useState(false);
  const rawData = HISTORY[metric.id] || [];
  const data = window.metricCadence(metric) === 'monthly' ? applyMonthlyMask(rawData) : rawData;
  const owner = PEOPLE.find(p => p.id === metric.ownerId);
  const streak = trailingGreenStreak(metric, data);

  // Show three-week window centered on the current week, clamped to the 13-week range.
  const windowStart = Math.max(0, Math.min(10, currentWeekIdx - 1));
  const indices = [windowStart, windowStart + 1, windowStart + 2];

  return (
    <div className="sc-stack-card">
      <div style={{ display: 'flex', alignItems: 'flex-start', gap: 10 }}>
        <Avatar person={owner} size={28}/>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
            <div style={{ fontSize: 14.5, fontWeight: 600, color: 'var(--ink-900)', lineHeight: 1.25 }}>{metric.label}</div>
            {streak >= 4 && <span className="streak-mark" title={streak + ' green weeks'}>▲</span>}
          </div>
          <div style={{ fontSize: 11.5, color: 'var(--ink-500)', marginTop: 2 }}>
            {owner?.name.split(' ')[0]} · {metric.fn} · {metric.dir === '<=' ? '≤ ' : ''}<span className="numeric">{fmtNum(window.scorecardTarget(metric), metric)}</span>/{window.metricCadence(metric) === 'monthly' ? 'mo' : 'wk'}
          </div>
        </div>
      </div>

      <div className="sc-strip" aria-label="Last three weeks">
        {indices.map(i => {
          const v = data[i];
          const s = metricStatus(metric, v);
          let stripClass = 'sc-strip-cell';
          if (s === 'good') stripClass += ' sc-strip--good';
          else if (s === 'warn') stripClass += ' sc-strip--warn';
          else if (s === 'bad') stripClass += ' sc-strip--bad';
          if (i === currentWeekIdx) stripClass += ' sc-strip--now';
          return (
            <div key={i} className={stripClass}>
              <div className="sc-strip-week">{i === currentWeekIdx ? 'NOW' : window.NORWILL_DATA.rollingWeekLabels()[i]}</div>
              <div className="sc-strip-val">{fmtCell(v, metric)}</div>
            </div>
          );
        })}
      </div>

      <button
        type="button"
        onClick={() => setOpen(o => !o)}
        className="btn btn-quiet btn-sm"
        style={{ marginTop: 10, padding: '6px 0', justifyContent: 'flex-start', gap: 6 }}
      >
        {open ? 'Hide full 13 weeks' : 'See full 13 weeks'}
        <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round" style={{ transform: open ? 'rotate(180deg)' : 'none', transition: 'transform 160ms var(--ease-out)' }}><polyline points="6 9 12 15 18 9"/></svg>
      </button>

      {open && (
        <div style={{ marginTop: 10 }}>
          <Spark data={data} width={300} height={36} target={window.scorecardTarget(metric)} dir={metric.dir}/>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(13, 1fr)', gap: 3, marginTop: 8 }}>
            {data.map((v, i) => {
              const s = metricStatus(metric, v);
              const bg = s === 'good' ? 'var(--summit-bg)'
                       : s === 'warn' ? 'var(--caution-bg)'
                       : s === 'bad' ? 'var(--slip-bg)'
                       : 'var(--ink-50)';
              const fg = s === 'good' ? 'var(--summit)'
                       : s === 'warn' ? 'var(--caution)'
                       : s === 'bad' ? 'var(--slip)'
                       : 'var(--ink-400)';
              return (
                <div key={i} style={{
                  background: bg, color: fg,
                  borderRadius: 6, fontSize: 10,
                  fontFamily: 'var(--font-mono)', fontVariantNumeric: 'tabular-nums',
                  padding: '6px 0', textAlign: 'center', fontWeight: 600,
                  outline: i === currentWeekIdx ? '1.5px solid var(--norwill-forest)' : 'none',
                }} title={'Week ending ' + window.NORWILL_DATA.rollingWeekLabels()[i] + ': ' + (v == null ? 'no data' : fmtNum(v, metric))}>
                  {fmtCell(v, metric)}
                </div>
              );
            })}
          </div>
        </div>
      )}
    </div>
  );
}

function Legend({ mode }) {
  return (
    <div style={{
      display: 'flex', flexWrap: 'wrap', gap: 14, marginTop: 16, alignItems: 'center',
      fontSize: 11.5, color: 'var(--ink-600)',
    }}>
      <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}>
        <span className="dot" style={{ background: 'var(--summit)' }}/>On target
      </span>
      <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}>
        <span className="dot" style={{ background: 'var(--caution)' }}/>Within 15%
      </span>
      <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}>
        <span className="dot" style={{ background: 'var(--slip)' }}/>Off pace
      </span>
      <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}>
        <span className="streak-mark" style={{ width: 16, height: 16 }}>▲</span>
        4+ weeks on target
      </span>
      <span style={{ flex: 1 }}/>
      <span style={{ color: 'var(--ink-400)' }}>
        {mode === 'meeting' ? 'Meeting mode · larger type, presenter-friendly' : 'Working mode · daily entry'}
      </span>
    </div>
  );
}

// ─── Issues / IDS ──────────────────────────────────────────────
const STAGES = [
  { id: 'identified', label: 'Identified', cls: 'iss-stage--identified' },
  { id: 'discussing', label: 'Discussing', cls: 'iss-stage--discussing' },
  { id: 'solved',     label: 'Solved',     cls: 'iss-stage--solved' },
];

function issueStageClass(stage) {
  return STAGES.find(s => s.id === stage)?.cls || 'iss-stage--identified';
}

// Map the data.js status field to our stage id.
function inferStage(rawStatus) {
  if (!rawStatus) return 'identified';
  const s = rawStatus.toLowerCase();
  if (s === 'open' || s === 'identified') return 'identified';
  if (s === 'ids' || s === 'discussing') return 'discussing';
  if (s === 'solved' || s === 'closed' || s === 'done') return 'solved';
  return 'identified';
}

function priorityRank(p) {
  if (p === 'High') return 0;
  if (p === 'Med') return 1;
  return 2;
}

function Issues({ persona, mode = 'working' }) {
  const isMobile = useMedia('(max-width: 760px)');
  const isMeeting = mode === 'meeting';
  const week = window.NORWILL_DATA.CURRENT_WEEK_IDX;

  // Auto-flagged off-pace metrics — surfaced as a banner above the manual list.
  const flagged = METRICS
    .map(m => ({ m, val: HISTORY[m.id]?.[week] }))
    .filter(({ m, val }) => metricStatus(m, val) === 'bad');

  // Local issue list, seeded from data.js. Sorts by priority then date.
  const [issues, setIssues] = React.useState(() => MANUAL_ISSUES.map(it => ({
    id: it.id,
    text: it.issue,
    raisedBy: it.raisedBy,
    date: it.date,
    priority: it.priority || 'Med',
    stage: inferStage(it.status),
    note: it.notes || '',
    open: false,
  })));
  const [draft, setDraft] = React.useState('');
  const [draftPriority, setDraftPriority] = React.useState('Med');

  const addIssue = () => {
    const text = draft.trim();
    if (!text) return;
    const next = {
      id: Date.now(),
      text,
      raisedBy: persona.id,
      date: new Date().toISOString().slice(0, 10),
      priority: draftPriority,
      stage: 'identified',
      note: '',
      open: false,
    };
    setIssues(curr => [next, ...curr]);
    setDraft('');
  };

  const cycleStage = (id) => {
    setIssues(curr => curr.map(it => {
      if (it.id !== id) return it;
      const idx = STAGES.findIndex(s => s.id === it.stage);
      const next = STAGES[(idx + 1) % STAGES.length].id;
      return { ...it, stage: next, open: next === 'solved' ? true : it.open };
    }));
  };

  const toggleOpen = (id) => setIssues(curr => curr.map(it => it.id === id ? { ...it, open: !it.open } : it));
  const setNote   = (id, v) => setIssues(curr => curr.map(it => it.id === id ? { ...it, note: v } : it));
  const setPriority = (id, v) => setIssues(curr => curr.map(it => it.id === id ? { ...it, priority: v } : it));

  const move = (id, delta) => {
    setIssues(curr => {
      const idx = curr.findIndex(x => x.id === id);
      const next = idx + delta;
      if (idx < 0 || next < 0 || next >= curr.length) return curr;
      const copy = curr.slice();
      const [item] = copy.splice(idx, 1);
      copy.splice(next, 0, item);
      return copy;
    });
  };

  const sorted = [...issues].sort((a, b) => priorityRank(a.priority) - priorityRank(b.priority));

  return (
    <div style={{ padding: isMobile ? '20px 16px 32px' : '28px 32px 40px' }}>
      <div className="view-header" style={{ flexWrap: 'wrap' }}>
        <div>
          <div className="eyebrow">Identify · Discuss · Solve</div>
          <h2 className="view-title">Issues</h2>
          <div className="view-sub">
            {isMeeting
              ? 'Meeting view. Drag to reorder, tap a stage to advance, expand to capture the solve.'
              : 'Working view. Capture an issue in one line. The team works it during L10.'}
          </div>
        </div>
        <span style={{ flex: 1 }}/>
        <CountStat label="Active" value={issues.filter(i => i.stage !== 'solved').length}/>
        <CountStat label="Off pace" value={flagged.length}/>
      </div>

      {flagged.length > 0 && (
        <FlaggedBanner flagged={flagged}/>
      )}

      {!isMeeting && (
        <form
          onSubmit={(e) => { e.preventDefault(); addIssue(); }}
          className="iss-capture"
          style={{ marginTop: flagged.length > 0 ? 14 : 0 }}
        >
          <Icon.plus/>
          <input
            className="input"
            type="text"
            value={draft}
            onChange={(e) => setDraft(e.target.value)}
            placeholder="Capture an issue. Press Enter to add."
            aria-label="New issue"
            style={{ flex: 1 }}
          />
          <select
            value={draftPriority}
            onChange={(e) => setDraftPriority(e.target.value)}
            aria-label="Priority"
            style={{
              padding: '6px 10px', border: '1px solid var(--hairline)',
              borderRadius: 8, fontSize: 12, background: 'var(--surface-card)',
              color: 'var(--ink-800)', fontWeight: 600,
            }}>
            <option value="High">High</option>
            <option value="Med">Med</option>
            <option value="Low">Low</option>
          </select>
          <button type="submit" className="btn btn-primary btn-sm" disabled={!draft.trim()}>Add</button>
        </form>
      )}

      {issues.length === 0 ? (
        <div className="card" style={{ padding: '32px 24px', textAlign: 'center', marginTop: 16 }}>
          <div style={{ fontFamily: 'var(--font-display)', fontWeight: 500, fontSize: 20 }}>No issues. Capture them here as they come up.</div>
          <div style={{ color: 'var(--ink-600)', marginTop: 6, fontSize: 13.5 }}>An empty list is a quiet week. Most teams capture 3 to 8 in a typical week.</div>
        </div>
      ) : (
        <div className="iss-list" style={{ marginTop: 16 }}>
          {sorted.map((it, idx) => (
            <IssueRow
              key={it.id}
              issue={it}
              isMeeting={isMeeting}
              isFirst={idx === 0}
              isLast={idx === sorted.length - 1}
              onCycleStage={() => cycleStage(it.id)}
              onToggle={() => toggleOpen(it.id)}
              onSetNote={(v) => setNote(it.id, v)}
              onSetPriority={(v) => setPriority(it.id, v)}
              onMoveUp={() => move(it.id, -1)}
              onMoveDown={() => move(it.id, +1)}
            />
          ))}
        </div>
      )}
    </div>
  );
}

function CountStat({ label, value }) {
  return (
    <div style={{
      display: 'flex', flexDirection: 'column', alignItems: 'flex-end',
      padding: '0 6px', minWidth: 64,
    }}>
      <span className="numeric" style={{ fontFamily: 'var(--font-mono)', fontWeight: 600, fontSize: 22, color: 'var(--ink-900)' }}>{value}</span>
      <span className="eyebrow" style={{ fontSize: 9.5 }}>{label}</span>
    </div>
  );
}

function FlaggedBanner({ flagged }) {
  return (
    <div style={{
      display: 'flex', flexWrap: 'wrap', gap: 10,
      padding: '12px 14px',
      background: 'var(--caution-bg)',
      borderRadius: 'var(--radius)',
      border: '1px solid rgba(181, 118, 23, 0.18)',
      alignItems: 'center',
    }}>
      <span className="chip warn" style={{ height: 22, flexShrink: 0 }}>
        <Icon.alert/>{flagged.length} off pace
      </span>
      <span style={{ fontSize: 12.5, color: 'var(--ink-700)', flex: 1, minWidth: 200 }}>
        {flagged.slice(0, 3).map(({ m }) => m.label).join(' · ')}
        {flagged.length > 3 && ' · +' + (flagged.length - 3) + ' more'}
      </span>
    </div>
  );
}

function IssueRow({ issue, isMeeting, isFirst, isLast, onCycleStage, onToggle, onSetNote, onSetPriority, onMoveUp, onMoveDown }) {
  const owner = PEOPLE.find(p => p.id === issue.raisedBy);
  const stageObj = STAGES.find(s => s.id === issue.stage) || STAGES[0];

  return (
    <div className={'iss-row' + (isMeeting ? ' iss-row--ids' : '') + (issue.open ? ' is-open' : '')}>
      {isMeeting && (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
          <button
            className="btn btn-quiet btn-sm"
            onClick={onMoveUp}
            disabled={isFirst}
            aria-label="Move up"
            style={{ padding: 4, minHeight: 22 }}
          >
            <Icon.up/>
          </button>
          <button
            className="btn btn-quiet btn-sm"
            onClick={onMoveDown}
            disabled={isLast}
            aria-label="Move down"
            style={{ padding: 4, minHeight: 22 }}
          >
            <Icon.down/>
          </button>
        </div>
      )}

      <div style={{ minWidth: 0 }}>
        <button
          type="button"
          className="iss-text"
          onClick={onToggle}
          style={{
            background: 'none', border: 'none', padding: 0,
            textAlign: 'left', cursor: 'pointer', color: 'inherit',
            fontFamily: 'inherit', fontSize: 'inherit', lineHeight: 'inherit',
          }}
        >
          {issue.text}
        </button>
        <div className="iss-meta">
          {owner && (
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5 }}>
              <Avatar person={owner} size={16}/>{owner.name.split(' ')[0]}
            </span>
          )}
          <span>·</span>
          <span>{issue.date}</span>
          <span>·</span>
          <select
            value={issue.priority}
            onChange={(e) => onSetPriority(e.target.value)}
            aria-label="Priority"
            style={{
              border: 'none', background: 'transparent', fontWeight: 600,
              color: issue.priority === 'High' ? 'var(--slip)'
                   : issue.priority === 'Med'  ? 'var(--caution)'
                   : 'var(--ink-500)',
              padding: 0, cursor: 'pointer', fontSize: 11.5,
            }}>
            <option value="High">High</option>
            <option value="Med">Med</option>
            <option value="Low">Low</option>
          </select>
        </div>
        {issue.open && (
          <div style={{ marginTop: 12, display: 'flex', flexDirection: 'column', gap: 8 }}>
            <label className="eyebrow" htmlFor={'note-' + issue.id}>
              {issue.stage === 'solved' ? 'Solve note' : 'Discussion note'}
            </label>
            <textarea
              id={'note-' + issue.id}
              className="input"
              value={issue.note}
              onChange={(e) => onSetNote(e.target.value)}
              rows={3}
              placeholder={issue.stage === 'solved'
                ? 'What did the team agree on? What changes next week?'
                : 'What do we need to dig into? Root cause? Owner?'}
              style={{ resize: 'vertical', minHeight: 64 }}
            />
          </div>
        )}
      </div>

      <button
        type="button"
        onClick={onCycleStage}
        className={'iss-stage ' + stageObj.cls}
        title="Tap to advance stage"
      >
        {stageObj.label}
        <Icon.arrow/>
      </button>
    </div>
  );
}

Object.assign(window, { Scorecard, Issues });
