/* Noctua Ledger — Sheet grid, agent cursor, inline proposal float */
(function () {
  const { useRef } = React;
  const STATUS = window.LEDGER.STATUS;
  const colLetter = (i) => String.fromCharCode(65 + i);

  const Badge = window.CircleBackDesignSystem_66b292.Badge;

  /* ---- one data cell ---- */
  function Cell({ col, text, agent, kind, phase, dark, h }) {
    let bg = 'transparent', fg = dark ? 'var(--ink-200)' : 'var(--ink-700)', bl = 'transparent', weight = 500;
    if (agent) {
      weight = 600;
      if (kind === 'flag') {
        bg = phase === 'committed' ? 'var(--warning-bg)' : 'rgba(176,122,18,0.12)';
        fg = 'var(--warning)'; bl = 'var(--warning)';
      } else {
        bg = phase === 'committed' ? 'var(--green-100)' : 'var(--green-50)';
        fg = 'var(--green-700)'; bl = 'var(--brand-bright)';
      }
    }
    return React.createElement('td', {
      'data-cell': null,
      style: {
        width: col.w, minWidth: col.w, maxWidth: col.w, height: h, padding: '0 10px',
        borderRight: dark ? '1px solid rgba(255,255,255,.07)' : '1px solid var(--ink-100)',
        borderBottom: dark ? '1px solid rgba(255,255,255,.07)' : '1px solid var(--ink-100)',
        background: bg, color: fg, textAlign: col.align || 'left',
        fontFamily: col.mono ? 'var(--font-mono)' : 'var(--font-body)',
        fontSize: col.mono ? '12.5px' : '13px', fontWeight: weight,
        boxShadow: agent ? `inset 3px 0 0 ${bl}` : 'none',
        whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
        transition: 'background .35s var(--ease-out), color .35s var(--ease-out)', position: 'relative',
      },
    },
      agent && phase !== 'committed' && React.createElement('span', {
        style: { display: 'inline-block', width: 6, height: 6, borderRadius: '50%', marginRight: 7,
          background: kind === 'flag' ? 'var(--warning)' : 'var(--brand-bright)', verticalAlign: 'middle',
          animation: 'cb-pulse 1.1s var(--ease-out) infinite' },
      }),
      text);
  }

  /* ---- status cell ---- */
  function StatusCell({ row, dark, h }) {
    const meta = STATUS[row.status] || STATUS.open;
    let content;
    if (row.active && !row.prog) {
      content = React.createElement('span', {
        style: { display: 'inline-flex', alignItems: 'center', gap: 7, fontFamily: 'var(--font-mono)',
          fontSize: '11.5px', letterSpacing: '.04em', textTransform: 'uppercase', color: 'var(--green-600)', fontWeight: 600 },
      },
        React.createElement('span', { style: { width: 6, height: 6, borderRadius: '50%', background: 'var(--brand-bright)',
          animation: 'cb-pulse 1s var(--ease-out) infinite' } }), 'Reading…');
    } else if (row.status === 'open') {
      content = React.createElement('span', { style: { fontFamily: 'var(--font-mono)', fontSize: '11.5px',
        color: dark ? 'var(--ink-500)' : 'var(--ink-400)', textTransform: 'uppercase', letterSpacing: '.04em' } }, 'Open');
    } else {
      content = React.createElement(Badge, { tone: meta.tone, dot: true }, meta.label);
    }
    return React.createElement('td', {
      style: { width: 150, minWidth: 150, height: h, padding: '0 10px',
        borderBottom: dark ? '1px solid rgba(255,255,255,.07)' : '1px solid var(--ink-100)',
        background: 'transparent', transition: 'background .35s var(--ease-out)' },
    }, content);
  }

  /* ---- the sheet ---- */
  const Sheet = React.forwardRef(function Sheet({ lane, viewRows, density, dark }, ref) {
    const h = density === 'compact' ? 32 : density === 'comfy' ? 46 : 38;
    const cols = lane.columns;
    const headBg = dark ? 'var(--ink-800)' : 'var(--surface-2)';
    const headFg = dark ? 'var(--ink-200)' : 'var(--ink-700)';
    const rnBg = dark ? 'var(--ink-800)' : 'var(--surface-2)';
    const line = dark ? '1px solid rgba(255,255,255,.07)' : '1px solid var(--ink-100)';
    const lineStrong = dark ? '1px solid rgba(255,255,255,.14)' : '1px solid var(--ink-200)';

    return React.createElement('div', {
      ref, className: dark ? 'on-ink' : '',
      style: { position: 'relative', flex: 1, overflow: 'auto',
        background: dark ? 'var(--ink-900)' : 'var(--surface)' },
    },
      React.createElement('table', { style: { borderCollapse: 'collapse', tableLayout: 'fixed', width: 'max-content' } },
        React.createElement('colgroup', null,
          React.createElement('col', { style: { width: 42 } }),
          cols.map((c) => React.createElement('col', { key: c.id, style: { width: c.w } }))),
        React.createElement('thead', null,
          /* spreadsheet letter row */
          React.createElement('tr', null,
            React.createElement('th', { style: { width: 42, height: 22, background: rnBg, borderRight: lineStrong, borderBottom: line, position: 'sticky', top: 0, zIndex: 3 } }),
            cols.map((c, i) => React.createElement('th', {
              key: c.id, style: { height: 22, background: headBg, borderRight: line, borderBottom: line,
                color: dark ? 'var(--ink-500)' : 'var(--ink-400)', fontFamily: 'var(--font-mono)', fontSize: '10px',
                fontWeight: 500, position: 'sticky', top: 0, zIndex: 2 } }, colLetter(i)))),
          /* named header row */
          React.createElement('tr', null,
            React.createElement('th', { style: { width: 42, height: 30, background: rnBg, borderRight: lineStrong, borderBottom: lineStrong, position: 'sticky', top: 22, zIndex: 3 } }),
            cols.map((c) => React.createElement('th', {
              key: c.id, style: { height: 30, padding: '0 10px', textAlign: c.align || 'left', background: headBg,
                borderRight: line, borderBottom: lineStrong, color: headFg, fontFamily: 'var(--font-mono)',
                fontSize: '10.5px', fontWeight: 600, letterSpacing: '.06em', position: 'sticky', top: 22, zIndex: 2 } }, c.name)))),
        React.createElement('tbody', null,
          viewRows.map((row, ri) => {
            const activeBg = row.active ? (dark ? 'rgba(52,168,120,.10)' : 'var(--green-50)') : 'transparent';
            return React.createElement('tr', { key: row.id, 'data-row': row.id, style: { background: activeBg, transition: 'background .3s var(--ease-out)' } },
              React.createElement('td', { style: { width: 42, height: h, textAlign: 'center', background: rnBg,
                borderRight: lineStrong, borderBottom: line, color: dark ? 'var(--ink-500)' : 'var(--ink-400)',
                fontFamily: 'var(--font-mono)', fontSize: '11px', fontWeight: 500 } }, ri + 1),
              cols.map((c) => {
                if (c.id === 'status') return React.createElement(StatusCellWrap, { key: c.id, row, dark, h });
                const isAgent = row.agentCols && row.agentCols.indexOf(c.id) !== -1;
                return React.createElement('td', {
                  key: c.id, 'data-cell': row.id + ':' + c.id,
                  style: cellStyle(c, isAgent, row.kind, row.phase, dark, h),
                },
                  isAgent && row.phase !== 'committed' && React.createElement('span', {
                    style: { display: 'inline-block', width: 6, height: 6, borderRadius: '50%', marginRight: 7,
                      background: row.kind === 'flag' ? 'var(--warning)' : 'var(--brand-bright)', verticalAlign: 'middle',
                      animation: 'cb-pulse 1.1s var(--ease-out) infinite' } }),
                  row.values[c.id]);
              }));
          }))));
  });

  function cellStyle(col, agent, kind, phase, dark, h) {
    let bg = 'transparent', fg = dark ? 'var(--ink-200)' : 'var(--ink-700)', bl = null;
    if (agent) {
      if (kind === 'flag') { bg = phase === 'committed' ? 'var(--warning-bg)' : 'rgba(176,122,18,0.13)'; fg = 'var(--warning)'; bl = 'var(--warning)'; }
      else { bg = phase === 'committed' ? 'var(--green-100)' : 'var(--green-50)'; fg = 'var(--green-700)'; bl = 'var(--brand-bright)'; }
    }
    return { height: h, padding: '0 10px', borderRight: dark ? '1px solid rgba(255,255,255,.07)' : '1px solid var(--ink-100)',
      borderBottom: dark ? '1px solid rgba(255,255,255,.07)' : '1px solid var(--ink-100)', background: bg, color: fg,
      textAlign: col.align || 'left', fontFamily: col.mono ? 'var(--font-mono)' : 'var(--font-body)',
      fontSize: col.mono ? '12.5px' : '13px', fontWeight: agent ? 600 : 500,
      boxShadow: bl ? `inset 3px 0 0 ${bl}` : 'none', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
      transition: 'background .35s var(--ease-out), color .35s var(--ease-out)' };
  }

  function StatusCellWrap({ row, dark, h }) { return StatusCell({ row, dark, h }); }

  /* ---- agent cursor (human-like pointer) ---- */
  function AgentCursor({ pos, name, label, hidden }) {
    return React.createElement('div', {
      style: { position: 'absolute', left: 0, top: 0, transform: `translate(${pos.x}px, ${pos.y}px)`,
        transition: 'transform .62s cubic-bezier(.5,.05,.2,1)', pointerEvents: 'none', zIndex: 20,
        opacity: hidden ? 0 : 1, willChange: 'transform' },
    },
      React.createElement('svg', { width: 22, height: 22, viewBox: '0 0 22 22', style: { filter: 'drop-shadow(0 2px 3px rgba(22,20,15,.28))' } },
        React.createElement('path', { d: 'M3 2 L3 17 L7.2 13.2 L10.3 20 L13 18.8 L9.9 12.2 L15.5 12 Z',
          fill: 'var(--green-600)', stroke: '#fff', strokeWidth: 1.3, strokeLinejoin: 'round' })),
      React.createElement('div', {
        style: { position: 'absolute', left: 17, top: 15, background: 'var(--green-600)', color: '#fff',
          fontFamily: 'var(--font-mono)', fontSize: '10.5px', fontWeight: 600, letterSpacing: '.03em',
          padding: '3px 9px', borderRadius: 'var(--radius-pill)', whiteSpace: 'nowrap', boxShadow: 'var(--shadow-sm)' },
      },
        name, label && React.createElement('span', { style: { opacity: .8, marginLeft: 6 } }, label)));
  }

  /* ---- inline proposal float anchored to the active row ---- */
  function ProposalFloat({ pos, step, persona, onApprove, onSkip, kind }) {
    if (!step) return null;
    const accent = kind === 'flag' ? 'var(--warning)' : 'var(--green-600)';
    return React.createElement('div', {
      className: 'cb-fade',
      style: { position: 'absolute', left: 0, top: 0, transform: `translate(${pos.x}px, ${pos.y}px)`,
        transition: 'transform .5s var(--ease-out)', zIndex: 18, width: 268,
        background: 'var(--surface)', border: `1.5px solid ${accent}`, borderRadius: 'var(--radius-md)',
        boxShadow: 'var(--shadow-lg)', padding: '12px 13px' },
    },
      React.createElement('div', { style: { display: 'flex', alignItems: 'center', gap: 8, marginBottom: 7 } },
        React.createElement('span', { style: { width: 7, height: 7, borderRadius: '50%', background: accent } }),
        React.createElement('span', { style: { fontFamily: 'var(--font-mono)', fontSize: '10.5px', fontWeight: 600,
          letterSpacing: '.06em', textTransform: 'uppercase', color: accent } }, kind === 'flag' ? 'Exception · proposing' : 'Proposing edit'),
        React.createElement('span', { style: { marginLeft: 'auto', fontFamily: 'var(--font-mono)', fontSize: '10px', color: 'var(--ink-400)' } }, persona)),
      React.createElement('div', { style: { fontFamily: 'var(--font-mono)', fontSize: '11px', color: 'var(--ink-500)', marginBottom: 4 } }, step.proposal.sub),
      React.createElement('div', { style: { display: 'flex', alignItems: 'center', gap: 8, fontFamily: 'var(--font-mono)', fontSize: '12.5px', marginBottom: 8 } },
        React.createElement('span', { style: { color: 'var(--ink-400)', textDecoration: 'line-through' } }, step.proposal.from),
        React.createElement('span', { style: { color: 'var(--ink-400)' } }, '→'),
        React.createElement('span', { style: { color: accent, fontWeight: 600 } }, step.proposal.to)),
      React.createElement('div', { style: { fontSize: '12px', color: 'var(--ink-600)', lineHeight: 1.45, marginBottom: onApprove ? 11 : 0 } }, step.proposal.note),
      onApprove && React.createElement('div', { style: { display: 'flex', gap: 7 } },
        React.createElement('button', { onClick: onApprove, style: btn(accent, true) }, 'Approve'),
        React.createElement('button', { onClick: onSkip, style: btn('var(--ink-300)', false) }, 'Skip')),
      !onApprove && React.createElement('div', { style: { fontFamily: 'var(--font-mono)', fontSize: '10px', color: 'var(--ink-400)',
        letterSpacing: '.04em', borderTop: '1px solid var(--ink-100)', paddingTop: 8, marginTop: 9 } }, 'Staged → review in the panel →'));
  }
  function btn(color, filled) {
    return { flex: 1, height: 32, borderRadius: 'var(--radius-sm)', cursor: 'pointer',
      fontFamily: 'var(--font-body)', fontSize: '12.5px', fontWeight: 600,
      background: filled ? color : 'transparent', color: filled ? '#fff' : 'var(--ink-700)',
      border: filled ? '1px solid transparent' : '1px solid var(--ink-200)', transition: 'all .15s var(--ease-out)' };
  }

  window.LedgerSheet = { Sheet, AgentCursor, ProposalFloat };
})();
