// ===== Stock Data Monitoring Page =====
// Shows NIFTY 50 daily candle crawl status, per-symbol health grid,
// and detailed candle data drill-down with interactive candlestick chart.

// ── Candlestick Chart Component (TradingView Lightweight Charts) ──
function StockCandleChart({ candles, symbol }) {
  const containerRef = React.useRef(null);
  const chartRef = React.useRef(null);
  const [chartType, setChartType] = React.useState('candle'); // 'candle' | 'line'

  React.useEffect(() => {
    if (!containerRef.current || !candles || candles.length === 0) return;
    if (typeof LightweightCharts === 'undefined') return;

    // Clean up previous chart
    if (chartRef.current) {
      chartRef.current.remove();
      chartRef.current = null;
    }

    const isDark = document.documentElement.getAttribute('data-theme') === 'dark';

    const chart = LightweightCharts.createChart(containerRef.current, {
      height: 420,
      layout: {
        background: { type: 'solid', color: isDark ? '#1a1a2e' : '#ffffff' },
        textColor: isDark ? '#d1d5db' : '#374151',
        fontFamily: "'Inter', system-ui, -apple-system, sans-serif",
        fontSize: 12,
      },
      grid: {
        vertLines: { color: isDark ? '#2d2d44' : '#f0f0f0' },
        horzLines: { color: isDark ? '#2d2d44' : '#f0f0f0' },
      },
      crosshair: {
        mode: LightweightCharts.CrosshairMode.Normal,
        vertLine: { labelBackgroundColor: isDark ? '#3b82f6' : '#1e40af' },
        horzLine: { labelBackgroundColor: isDark ? '#3b82f6' : '#1e40af' },
      },
      rightPriceScale: {
        borderColor: isDark ? '#2d2d44' : '#e5e7eb',
        scaleMargins: { top: 0.05, bottom: 0.25 },
      },
      timeScale: {
        borderColor: isDark ? '#2d2d44' : '#e5e7eb',
        timeVisible: false,
        fixLeftEdge: true,
        fixRightEdge: true,
      },
      handleScroll: { mouseWheel: true, pressedMouseMove: true },
      handleScale: { axisPressedMouseMove: true, mouseWheel: true, pinch: true },
    });

    // Sort candles ascending by date for the chart
    const sorted = [...candles].sort((a, b) => a.tradeDate.localeCompare(b.tradeDate));

    if (chartType === 'candle') {
      const candleSeries = chart.addCandlestickSeries({
        upColor: '#22c55e',
        downColor: '#ef4444',
        borderDownColor: '#dc2626',
        borderUpColor: '#16a34a',
        wickDownColor: '#dc2626',
        wickUpColor: '#16a34a',
      });
      candleSeries.setData(sorted.map(c => ({
        time: c.tradeDate,
        open: c.open,
        high: c.high,
        low: c.low,
        close: c.close,
      })));
    } else {
      const lineSeries = chart.addLineSeries({
        color: '#3b82f6',
        lineWidth: 2,
        crosshairMarkerVisible: true,
        crosshairMarkerRadius: 4,
      });
      lineSeries.setData(sorted.map(c => ({
        time: c.tradeDate,
        value: c.close,
      })));
    }

    // Volume histogram on secondary price scale
    const volumeSeries = chart.addHistogramSeries({
      priceFormat: { type: 'volume' },
      priceScaleId: 'volume',
    });
    chart.priceScale('volume').applyOptions({
      scaleMargins: { top: 0.8, bottom: 0 },
    });
    volumeSeries.setData(sorted.map((c, i) => {
      const prev = i > 0 ? sorted[i - 1] : null;
      const isUp = prev ? c.close >= prev.close : c.close >= c.open;
      return {
        time: c.tradeDate,
        value: c.volume,
        color: isUp
          ? (isDark ? 'rgba(34,197,94,0.35)' : 'rgba(34,197,94,0.4)')
          : (isDark ? 'rgba(239,68,68,0.35)' : 'rgba(239,68,68,0.4)'),
      };
    }));

    chart.timeScale().fitContent();
    chartRef.current = chart;

    // Resize observer
    const ro = new ResizeObserver(() => {
      if (containerRef.current && chartRef.current) {
        chartRef.current.applyOptions({ width: containerRef.current.clientWidth });
      }
    });
    ro.observe(containerRef.current);

    return () => {
      ro.disconnect();
      if (chartRef.current) { chartRef.current.remove(); chartRef.current = null; }
    };
  }, [candles, symbol, chartType]);

  if (!candles || candles.length === 0) return null;

  // Compute summary stats
  const sorted = [...candles].sort((a, b) => a.tradeDate.localeCompare(b.tradeDate));
  const latest = sorted[sorted.length - 1];
  const first = sorted[0];
  const periodReturn = first.close > 0 ? ((latest.close - first.close) / first.close * 100) : 0;
  const high52 = Math.max(...sorted.map(c => c.high));
  const low52 = Math.min(...sorted.map(c => c.low));
  const avgVol = sorted.reduce((a, c) => a + c.volume, 0) / sorted.length;
  const prev = sorted.length >= 2 ? sorted[sorted.length - 2] : null;
  const dayChange = prev ? latest.close - prev.close : 0;
  const dayChangePct = prev && prev.close > 0 ? (dayChange / prev.close * 100) : 0;

  return React.createElement('div', null,
    // Header stats bar
    React.createElement('div', {
      style: {
        display: 'flex', alignItems: 'center', gap: '20px', padding: '14px 16px',
        background: 'var(--bg-surface-alt, #f8fafc)', borderBottom: '1px solid var(--border, #e2e8f0)',
        flexWrap: 'wrap', fontSize: '13px',
      }
    },
      // Current price + day change
      React.createElement('div', { style: { display: 'flex', alignItems: 'baseline', gap: '8px' } },
        React.createElement('span', { style: { fontSize: '22px', fontWeight: 700, fontFamily: 'monospace' } },
          '\u20B9' + latest.close.toLocaleString('en-IN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })),
        prev && React.createElement('span', {
          style: { fontWeight: 600, fontSize: '14px', color: dayChange >= 0 ? '#16a34a' : '#dc2626' }
        }, `${dayChange >= 0 ? '+' : ''}${dayChange.toFixed(2)} (${dayChangePct >= 0 ? '+' : ''}${dayChangePct.toFixed(2)}%)`)
      ),
      React.createElement('div', { style: { width: '1px', height: '24px', background: 'var(--border, #e2e8f0)' } }),
      // Key stats
      React.createElement('span', null, React.createElement('b', null, 'High: '), '\u20B9' + high52.toLocaleString('en-IN')),
      React.createElement('span', null, React.createElement('b', null, 'Low: '), '\u20B9' + low52.toLocaleString('en-IN')),
      React.createElement('span', null, React.createElement('b', null, 'Avg Vol: '), formatLargeNumber(avgVol)),
      React.createElement('span', {
        style: { fontWeight: 600, color: periodReturn >= 0 ? '#16a34a' : '#dc2626' }
      }, React.createElement('b', { style: { color: 'var(--text-secondary)' } }, 'Period: '),
        `${periodReturn >= 0 ? '+' : ''}${periodReturn.toFixed(2)}%`),
      // Chart type toggle (right side)
      React.createElement('div', { style: { marginLeft: 'auto', display: 'flex', gap: '4px' } },
        React.createElement('button', {
          onClick: () => setChartType('candle'),
          style: {
            padding: '4px 10px', fontSize: '11px', fontWeight: 600, borderRadius: '4px', cursor: 'pointer',
            border: '1px solid ' + (chartType === 'candle' ? '#3b82f6' : 'var(--border, #d1d5db)'),
            background: chartType === 'candle' ? '#3b82f6' : 'transparent',
            color: chartType === 'candle' ? '#fff' : 'var(--text-secondary)',
          }
        }, '\uD83D\uDD6F Candle'),
        React.createElement('button', {
          onClick: () => setChartType('line'),
          style: {
            padding: '4px 10px', fontSize: '11px', fontWeight: 600, borderRadius: '4px', cursor: 'pointer',
            border: '1px solid ' + (chartType === 'line' ? '#3b82f6' : 'var(--border, #d1d5db)'),
            background: chartType === 'line' ? '#3b82f6' : 'transparent',
            color: chartType === 'line' ? '#fff' : 'var(--text-secondary)',
          }
        }, '\uD83D\uDCC8 Line')
      )
    ),
    // Chart container
    React.createElement('div', {
      ref: containerRef,
      style: { width: '100%', minHeight: '420px' }
    })
  );
}

function StockDataPage() {
  const toast = useToast();
  const [status, setStatus] = React.useState(null);
  const [loading, setLoading] = React.useState(true);
  const [selectedSymbol, setSelectedSymbol] = React.useState(null);
  const [candles, setCandles] = React.useState([]);
  const [candleDays, setCandleDays] = React.useState(30);
  const [candleLoading, setCandleLoading] = React.useState(false);
  const [searchTerm, setSearchTerm] = React.useState('');
  const [sortField, setSortField] = React.useState('symbol');
  const [sortAsc, setSortAsc] = React.useState(true);
  const [triggerPending, setTriggerPending] = React.useState(false);
  const [controlStatus, setControlStatus] = React.useState(null);

  React.useEffect(() => { loadStatus(); loadControlStatus(); }, []);

  React.useEffect(() => {
    if (selectedSymbol) loadCandles(selectedSymbol);
  }, [selectedSymbol, candleDays]);

  async function loadStatus() {
    setLoading(true);
    try {
      const result = await API.get('/api/stock-candles/status');
      setStatus(result);
    } catch (err) {
      toast(err.message || 'Failed to load stock data status', 'error');
    } finally {
      setLoading(false);
    }
  }

  async function loadCandles(symbol) {
    setCandleLoading(true);
    try {
      const result = await API.get(`/api/stock-candles/${encodeURIComponent(symbol)}?days=${candleDays}`);
      setCandles(result.candles || []);
    } catch (err) {
      toast(err.message || `Failed to load candles for ${symbol}`, 'error');
      setCandles([]);
    } finally {
      setCandleLoading(false);
    }
  }

  async function loadControlStatus() {
    try {
      const result = await API.get('/api/stock-candles/control');
      setControlStatus(result);
    } catch (err) {
      // Silently ignore — table may not exist yet
    }
  }

  async function triggerCrawl() {
    setTriggerPending(true);
    try {
      const result = await API.post('/api/stock-candles/trigger');
      toast(result.message || 'Crawl triggered!', result.triggered ? 'success' : 'info');
      await loadControlStatus();
    } catch (err) {
      toast(err.message || 'Failed to trigger crawl', 'error');
    } finally {
      setTriggerPending(false);
    }
  }

  function handleSort(field) {
    if (sortField === field) { setSortAsc(!sortAsc); }
    else { setSortField(field); setSortAsc(true); }
  }

  function getSortedSymbols() {
    if (!status || !status.symbols) return [];
    let list = status.symbols;
    if (searchTerm) {
      const term = searchTerm.toUpperCase();
      list = list.filter(s => s.symbol.includes(term));
    }
    list = [...list].sort((a, b) => {
      let av, bv;
      if (sortField === 'symbol') { av = a.symbol; bv = b.symbol; }
      else if (sortField === 'totalCandles') { av = a.totalCandles; bv = b.totalCandles; }
      else if (sortField === 'latestDate') { av = a.latestDate; bv = b.latestDate; }
      else if (sortField === 'firstDate') { av = a.firstDate; bv = b.firstDate; }
      else { av = a.symbol; bv = b.symbol; }
      if (av < bv) return sortAsc ? -1 : 1;
      if (av > bv) return sortAsc ? 1 : -1;
      return 0;
    });
    return list;
  }

  const sortIcon = (field) => sortField === field ? (sortAsc ? ' \u25B2' : ' \u25BC') : '';

  return React.createElement('div', { className: 'page-content' },
    React.createElement('div', { className: 'page-header' },
      React.createElement('h1', { className: 'page-title' }, '\uD83D\uDCC8 Stock Data Monitor'),
      React.createElement('p', { className: 'page-subtitle' }, 'NIFTY 50 daily candle crawl status \u2014 verify data freshness & completeness')
    ),

    // Refresh + Trigger buttons
    React.createElement('div', { className: 'filters-bar' },
      React.createElement('button', { className: 'btn btn-outline btn-sm', onClick: () => { loadStatus(); loadControlStatus(); }, disabled: loading }, '\u21BB Refresh'),
      React.createElement('button', {
        className: 'btn btn-sm',
        onClick: triggerCrawl,
        disabled: triggerPending || (controlStatus && controlStatus.hasPendingTrigger),
        style: {
          marginLeft: '8px',
          background: (controlStatus && controlStatus.hasPendingTrigger) ? '#f59e0b' : '#3b82f6',
          color: '#fff', border: 'none', borderRadius: '6px', padding: '6px 14px', fontWeight: 600, cursor: 'pointer'
        }
      }, triggerPending ? '\u23F3 Triggering\u2026'
        : (controlStatus && controlStatus.hasPendingTrigger) ? '\u23F3 Trigger Pending'
        : '\uD83D\uDE80 Trigger Crawl Now'),
      controlStatus && controlStatus.lastCompletedUtc && React.createElement('span', {
        className: 'text-sm text-muted', style: { marginLeft: '12px' }
      }, `Last completed: ${controlStatus.lastCompletedUtc}`),
      controlStatus && controlStatus.hasPendingTrigger && React.createElement('span', {
        className: 'text-sm', style: { marginLeft: '12px', color: '#f59e0b', fontWeight: 600 }
      }, `\u26A1 Pending since ${controlStatus.pendingTriggerUtc} — Worker polls every ~5 min`),
      React.createElement('div', { style: { flex: 1 } }),
      status && status.summary && React.createElement('span', { className: 'text-sm text-muted' },
        `Last crawl: ${status.summary.lastCrawlUtc}`)
    ),

    loading ? React.createElement(Loading, { text: 'Loading stock data status\u2026' }) :
    !status || !status.symbols || status.symbols.length === 0 ?
      React.createElement(EmptyState, {
        icon: '\uD83D\uDCCA',
        title: 'No Stock Data Yet',
        text: 'The stock candle backfill service has not crawled any data yet. Check Worker logs for [StockBackfill] entries.'
      }) :
    React.createElement(React.Fragment, null,

      // Summary Cards
      status.summary && React.createElement('div', { className: 'stats-grid' },
        React.createElement(StatCard, { label: 'Stocks Tracked', value: status.summary.totalSymbols }),
        React.createElement(StatCard, { label: 'Total Candles', value: status.summary.totalCandles.toLocaleString() }),
        React.createElement(StatCard, { label: 'Date Range', value: `${status.summary.earliestDate} \u2014 ${status.summary.latestDate}` }),
        React.createElement(StatCard, {
          label: 'Latest Data',
          value: status.summary.latestDate,
          type: isDateStale(status.summary.latestDate) ? 'negative' : 'positive',
          sub: isDateStale(status.summary.latestDate) ? '\u26A0 Stale' : '\u2705 Fresh'
        })
      ),

      // Crawl Health Grid
      React.createElement('div', { className: 'card mb-4' },
        React.createElement('div', { className: 'card-header' },
          React.createElement('span', null, '\uD83D\uDFE2 Crawl Health Grid'),
          React.createElement('span', { className: 'text-sm text-muted' },
            `${status.symbols.length} symbols \u2022 ${status.symbols.filter(s => !s.isStale).length} fresh`)
        ),
        React.createElement('div', { className: 'card-body', style: { padding: '12px' } },
          React.createElement('div', {
            style: {
              display: 'grid',
              gridTemplateColumns: 'repeat(auto-fill, minmax(105px, 1fr))',
              gap: '8px'
            }
          },
            status.symbols.map(s =>
              React.createElement('div', {
                key: s.symbol,
                onClick: () => setSelectedSymbol(s.symbol),
                style: {
                  padding: '10px 8px',
                  borderRadius: '8px',
                  border: `2px solid ${selectedSymbol === s.symbol ? '#3b82f6' : s.isStale ? '#fecaca' : '#bbf7d0'}`,
                  background: s.isStale
                    ? 'linear-gradient(135deg, #fef2f2, #fee2e2)'
                    : 'linear-gradient(135deg, #f0fdf4, #dcfce7)',
                  cursor: 'pointer',
                  textAlign: 'center',
                  transition: 'all 0.15s ease',
                  transform: selectedSymbol === s.symbol ? 'scale(1.05)' : 'scale(1)',
                  boxShadow: selectedSymbol === s.symbol ? '0 2px 8px rgba(59,130,246,0.3)' : 'none',
                }
              },
                React.createElement('div', {
                  style: { fontWeight: 700, fontSize: '12px', letterSpacing: '0.5px', marginBottom: '2px' }
                }, s.symbol),
                React.createElement('div', {
                  style: { fontSize: '10px', color: 'var(--text-secondary)' }
                }, s.latestDate),
                React.createElement('div', {
                  style: { fontSize: '10px', color: 'var(--text-secondary)', marginTop: '2px' }
                }, `${s.totalCandles} candles`)
              )
            )
          )
        )
      ),

      // Per-Symbol Details Table
      React.createElement('div', { className: 'card mb-4' },
        React.createElement('div', { className: 'card-header' },
          React.createElement('span', null, '\uD83D\uDCCB Symbol Details'),
          React.createElement('input', {
            type: 'text',
            placeholder: 'Search symbol\u2026',
            value: searchTerm,
            onChange: (e) => setSearchTerm(e.target.value),
            className: 'form-input',
            style: { width: '180px', padding: '4px 10px', fontSize: '12px' }
          })
        ),
        React.createElement('div', { className: 'card-body', style: { padding: 0 } },
          React.createElement('div', { style: { overflowX: 'auto' } },
            React.createElement('table', { className: 'data-table' },
              React.createElement('thead', null,
                React.createElement('tr', null,
                  React.createElement('th', {
                    style: { cursor: 'pointer' }, onClick: () => handleSort('symbol')
                  }, 'Symbol' + sortIcon('symbol')),
                  React.createElement('th', {
                    style: { cursor: 'pointer' }, onClick: () => handleSort('totalCandles')
                  }, 'Candles' + sortIcon('totalCandles')),
                  React.createElement('th', {
                    style: { cursor: 'pointer' }, onClick: () => handleSort('firstDate')
                  }, 'First Date' + sortIcon('firstDate')),
                  React.createElement('th', {
                    style: { cursor: 'pointer' }, onClick: () => handleSort('latestDate')
                  }, 'Latest Date' + sortIcon('latestDate')),
                  React.createElement('th', null, 'Last Crawled'),
                  React.createElement('th', null, 'Status')
                )
              ),
              React.createElement('tbody', null,
                getSortedSymbols().map(s =>
                  React.createElement('tr', {
                    key: s.symbol,
                    onClick: () => setSelectedSymbol(s.symbol),
                    style: {
                      cursor: 'pointer',
                      background: selectedSymbol === s.symbol ? 'var(--bg-selected, #eff6ff)' : 'transparent'
                    }
                  },
                    React.createElement('td', null,
                      React.createElement('span', { style: { fontWeight: 600 } }, s.symbol)),
                    React.createElement('td', null, s.totalCandles),
                    React.createElement('td', null, s.firstDate),
                    React.createElement('td', null, s.latestDate),
                    React.createElement('td', { className: 'text-sm text-muted' }, s.lastCrawledUtc),
                    React.createElement('td', null,
                      React.createElement(Badge, { type: s.isStale ? 'danger' : 'success' },
                        s.isStale ? 'Stale' : 'Fresh'))
                  )
                )
              )
            )
          )
        )
      ),

      // Candle Detail Panel (when symbol selected)
      selectedSymbol && React.createElement('div', { className: 'card mb-4' },
        React.createElement('div', { className: 'card-header' },
          React.createElement('div', { className: 'flex items-center gap-2' },
            React.createElement('span', { style: { fontSize: '18px' } }, '\uD83D\uDD6F'),
            React.createElement('span', { style: { fontWeight: 700, fontSize: '16px' } }, `${selectedSymbol}`),
            React.createElement('button', {
              className: 'btn btn-ghost btn-xs',
              onClick: () => setSelectedSymbol(null),
              style: { marginLeft: '8px' }
            }, '\u2715 Close')
          ),
          React.createElement('div', { className: 'flex gap-2' },
            [7, 30, 90, 180, 365, 1825].map(d =>
              React.createElement('button', {
                key: d,
                className: `filter-chip ${candleDays === d ? 'active' : ''}`,
                onClick: () => setCandleDays(d)
              }, d <= 30 ? `${d}D` : d < 365 ? `${Math.round(d / 30)}M` : d === 365 ? '1Y' : '5Y')
            )
          )
        ),
        React.createElement('div', { className: 'card-body', style: { padding: 0 } },
          candleLoading ? React.createElement(Loading, { text: 'Loading candles\u2026' }) :
          candles.length === 0 ?
            React.createElement(EmptyState, { icon: '\uD83D\uDCC9', title: 'No candles', text: `No data for ${selectedSymbol} in the selected range` }) :
          React.createElement(React.Fragment, null,
            // Candlestick Chart
            React.createElement(StockCandleChart, { candles: candles, symbol: selectedSymbol }),
            // Data Table (collapsible)
            React.createElement('details', { style: { borderTop: '1px solid var(--border, #e2e8f0)' } },
              React.createElement('summary', {
                style: {
                  padding: '10px 16px', cursor: 'pointer', fontSize: '13px',
                  fontWeight: 600, color: 'var(--text-secondary)',
                  userSelect: 'none',
                }
              }, '\uD83D\uDCCB Raw Data Table (' + candles.length + ' candles)'),
              React.createElement('div', { style: { overflowX: 'auto', maxHeight: '400px', overflowY: 'auto' } },
              React.createElement('table', { className: 'data-table' },
                React.createElement('thead', { style: { position: 'sticky', top: 0, background: 'var(--bg-surface, #fff)', zIndex: 1 } },
                  React.createElement('tr', null,
                    React.createElement('th', null, 'Date'),
                    React.createElement('th', { style: { textAlign: 'right' } }, 'Open'),
                    React.createElement('th', { style: { textAlign: 'right' } }, 'High'),
                    React.createElement('th', { style: { textAlign: 'right' } }, 'Low'),
                    React.createElement('th', { style: { textAlign: 'right' } }, 'Close'),
                    React.createElement('th', { style: { textAlign: 'right' } }, 'Change'),
                    React.createElement('th', { style: { textAlign: 'right' } }, 'Volume')
                  )
                ),
                React.createElement('tbody', null,
                  candles.map((c, i) => {
                    const prev = candles[i + 1]; // sorted DESC so i+1 is previous day
                    const chg = prev ? c.close - prev.close : 0;
                    const chgPct = prev && prev.close > 0 ? (chg / prev.close * 100) : 0;
                    const isUp = chg >= 0;
                    return React.createElement('tr', { key: c.tradeDate },
                      React.createElement('td', { style: { fontWeight: 500, whiteSpace: 'nowrap' } }, c.tradeDate),
                      React.createElement('td', { style: { textAlign: 'right', fontFamily: 'monospace' } }, c.open.toFixed(2)),
                      React.createElement('td', { style: { textAlign: 'right', fontFamily: 'monospace' } }, c.high.toFixed(2)),
                      React.createElement('td', { style: { textAlign: 'right', fontFamily: 'monospace' } }, c.low.toFixed(2)),
                      React.createElement('td', { style: { textAlign: 'right', fontWeight: 600, fontFamily: 'monospace' } }, c.close.toFixed(2)),
                      React.createElement('td', {
                        style: {
                          textAlign: 'right', fontFamily: 'monospace', fontWeight: 500,
                          color: prev ? (isUp ? '#16a34a' : '#dc2626') : 'var(--text-secondary)'
                        }
                      }, prev ? `${isUp ? '+' : ''}${chgPct.toFixed(2)}%` : '\u2014'),
                      React.createElement('td', {
                        style: { textAlign: 'right', fontFamily: 'monospace', color: 'var(--text-secondary)' }
                      }, formatLargeNumber(c.volume))
                    );
                  })
                )
              )
            )
          )
        )
      )
    )
    )
  );
}

// Helpers
function isDateStale(dateStr) {
  if (!dateStr || dateStr === '-') return true;
  const d = new Date(dateStr);
  const now = new Date();
  const ist = new Date(now.getTime() + (now.getTimezoneOffset() * 60000) + (5.5 * 60 * 60 * 1000));
  const diffDays = Math.floor((ist - d) / (1000 * 60 * 60 * 24));
  // Stale if more than 2 days old (accounts for weekends)
  return diffDays > 2;
}

function formatLargeNumber(n) {
  if (n == null || isNaN(n)) return '\u2014';
  n = Math.round(n);
  if (n >= 10000000) return (n / 10000000).toFixed(2) + ' Cr';
  if (n >= 100000) return (n / 100000).toFixed(2) + ' L';
  if (n >= 1000) return (n / 1000).toFixed(1) + ' K';
  return n.toString();
}
