/**
 * CodeMirror 6 extension for zebra-striped editor lines.
 *
 * Previously also contained inline result widgets, but results
 * are now rendered in a separate ResultsPanel component.
 */

import { Decoration, EditorView, ViewPlugin } from '@codemirror/view'
import type { DecorationSet, ViewUpdate } from '@codemirror/view'
import type { Extension } from '@codemirror/state'

/**
 * ViewPlugin that applies alternating background colors (zebra striping)
 * to even-numbered editor lines, helping users visually connect
 * expressions on the left to their inline results on the right.
 */
export const stripedLines = ViewPlugin.fromClass(
  class {
    decorations: DecorationSet

    constructor(view: EditorView) {
      this.decorations = buildStripeDecorations(view)
    }

    update(update: ViewUpdate) {
      if (update.docChanged || update.viewportChanged) {
        this.decorations = buildStripeDecorations(update.view)
      }
    }
  },
  {
    decorations: (v) => v.decorations,
  },
)

const stripeDeco = Decoration.line({ class: 'cm-stripe' })

function buildStripeDecorations(view: EditorView): DecorationSet {
  const decorations: Array<ReturnType<typeof stripeDeco.range>> = []
  for (let i = 1; i <= view.state.doc.lines; i++) {
    if (i % 2 === 0) {
      const line = view.state.doc.line(i)
      decorations.push(stripeDeco.range(line.from))
    }
  }
  return Decoration.set(decorations)
}

/**
 * Creates the striped-lines extension for the editor.
 */
export function stripedLinesExtension(): Extension {
  return [stripedLines]
}
