/* RC-SEC-001 — KPI scorecards grid (flat ordered, no legacy groupings).
   Consistent primary-value typography across cards.
   RC-PAGE-021 — drag-to-reorder (onReorder callback). */

const ScorecardsGrid = ({ metricIds, comparison, changeMode = 'pct', currency = 'USD', onReorder, disabled }) => {
  const [dragIdx, setDragIdx] = React.useState(null);
  const [hoverIdx, setHoverIdx] = React.useState(null);

  const handleDrop = (to) => {
    if (!onReorder || dragIdx == null || dragIdx === to) { setDragIdx(null); setHoverIdx(null); return; }
    const next = [...metricIds];
    const [moved] = next.splice(dragIdx, 1);
    next.splice(to, 0, moved);
    onReorder(next);
    setDragIdx(null); setHoverIdx(null);
  };

  return (
    <div style={{
      display: 'grid',
      gridTemplateColumns: `repeat(${Math.min(metricIds.length, 11)}, minmax(0, 1fr))`,
      background: 'var(--rc-card)',
      border: '1px solid var(--rc-border)',
      borderRadius: 12,
      overflow: 'hidden',
    }}>
      {metricIds.map((id, i) => {
        const isDragging = dragIdx === i;
        const isTarget = hoverIdx === i && dragIdx != null && dragIdx !== i;
        const insertBefore = isTarget && dragIdx > i;
        const insertAfter = isTarget && dragIdx < i;
        return (
          <div key={id}
            draggable={!disabled && !!onReorder}
            onDragStart={(e) => {
              if (disabled || !onReorder) return;
              setDragIdx(i);
              e.dataTransfer.effectAllowed = 'move';
              // Custom drag-image with reduced opacity for better visual feedback
              try {
                const rect = e.currentTarget.getBoundingClientRect();
                const ghost = e.currentTarget.cloneNode(true);
                ghost.style.opacity = '0.7';
                ghost.style.position = 'absolute';
                ghost.style.top = '-1000px';
                ghost.style.width = rect.width + 'px';
                ghost.style.transform = 'rotate(-1deg) scale(0.98)';
                ghost.style.boxShadow = '0 10px 32px -8px rgba(15,23,42,0.35)';
                document.body.appendChild(ghost);
                e.dataTransfer.setDragImage(ghost, rect.width / 2, rect.height / 2);
                setTimeout(() => ghost.remove(), 0);
              } catch (err) {}
            }}
            onDragOver={(e) => { if (dragIdx == null) return; e.preventDefault(); setHoverIdx(i); }}
            onDragLeave={() => { if (hoverIdx === i) setHoverIdx(null); }}
            onDrop={(e) => { e.preventDefault(); handleDrop(i); }}
            onDragEnd={() => { setDragIdx(null); setHoverIdx(null); }}
            style={{
              position: 'relative',
              opacity: isDragging ? 0.35 : 1,
              transform: isDragging ? 'scale(0.98)' : 'scale(1)',
              cursor: (!disabled && onReorder) ? (isDragging ? 'grabbing' : 'grab') : 'default',
              background: isTarget ? 'color-mix(in srgb, var(--rc-chart-1) 5%, transparent)' : 'transparent',
              transition: 'background 0.12s, opacity 0.12s, transform 0.12s',
            }}>
            {/* Insertion line — left edge if dragging right-to-left, right edge if left-to-right */}
            {insertBefore && (
              <div style={{
                position: 'absolute', left: -1, top: 6, bottom: 6, width: 3,
                background: 'var(--rc-chart-1)', borderRadius: 2, zIndex: 2,
                boxShadow: '0 0 0 4px color-mix(in srgb, var(--rc-chart-1) 18%, transparent)',
              }} />
            )}
            {insertAfter && (
              <div style={{
                position: 'absolute', right: -1, top: 6, bottom: 6, width: 3,
                background: 'var(--rc-chart-1)', borderRadius: 2, zIndex: 2,
                boxShadow: '0 0 0 4px color-mix(in srgb, var(--rc-chart-1) 18%, transparent)',
              }} />
            )}
            <Scorecard metricId={id} first={i === 0} comparison={comparison} changeMode={changeMode} currency={currency} />
          </div>
        );
      })}
    </div>
  );
};

const Scorecard = ({ metricId, first, comparison, changeMode, currency }) => {
  const label = METRIC_LABELS[metricId] || metricId;
  const values = window.series(metricId, 30);
  const priors = window.priorPeriodSeries(metricId, 30);
  const current = values.reduce((a, b) => a + b, 0) / values.length;
  const prior = priors.reduce((a, b) => a + b, 0) / priors.length;
  const val = BASELINES[metricId] ?? current;

  const change = comparison === 'none' ? null : formatChange(metricId, current, prior, changeMode);
  const delta = current - prior;
  const dir = comparison === 'none' ? 'flat' : changeDirection(metricId, delta);

  return (
    <div style={{
      padding: '14px 14px 12px',
      borderLeft: first ? 'none' : '1px solid var(--rc-border-soft)',
      display: 'flex', flexDirection: 'column', gap: 4,
      minWidth: 0,
    }}>
      <div style={{
        fontSize: 11, color: 'var(--rc-text-sub)', fontWeight: 500,
        textTransform: 'none', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
      }}>{label}</div>
      <div style={{
        fontSize: 19, fontWeight: 700, color: 'var(--rc-text)',
        fontFamily: 'Poppins', letterSpacing: '-0.02em', lineHeight: 1.15,
        fontVariantNumeric: 'tabular-nums',
      }}>{formatValue(metricId, val, { currency })}</div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 6, minHeight: 16 }}>
        {change && <Delta value={change} direction={dir} size={11} />}
        <Sparkline values={values} height={16} width={50}
          color={dir === 'bad' ? 'var(--rc-negative-soft)' : 'var(--rc-chart-1)'}
          direction={dir} />
      </div>
    </div>
  );
};

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