/**
 * XML schema for FarmControl document template tags.
 * Mirrors custom elements / style attrs handled in farmcontrol-ws TemplateManager.
 */

const styleAttrs = [
  'padding',
  'width',
  'height',
  'maxWidth',
  'maxHeight',
  'gap',
  'justify',
  'align',
  'border',
  'borderRadius',
  'vertical',
  'grow',
  'shrink',
  'color',
  'background',
  'scale',
  'textAlign',
  'textSize',
  'wordWrap'
]

const justifyValues = [
  'flex-start',
  'flex-end',
  'center',
  'space-between',
  'space-around',
  'space-evenly'
]

const alignValues = [
  'flex-start',
  'flex-end',
  'center',
  'stretch',
  'baseline'
]

/** @type {import('@codemirror/lang-xml').AttrSpec[]} */
export const fcTemplateAttributes = [
  ...styleAttrs.map((name) => {
    const attr = { name, global: true }
    if (name === 'vertical') attr.values = ['true', 'false']
    if (name === 'justify') attr.values = justifyValues
    if (name === 'align') attr.values = alignValues
    if (name === 'textAlign') {
      attr.values = ['left', 'center', 'right', 'justify']
    }
    return attr
  }),
  {
    name: 'format',
    values: ['code128', 'code39', 'ean13', 'ean8', 'upc', 'qrcode']
  },
  { name: 'barcodeWidth' },
  {
    name: 'type',
    values: ['header', 'footer', 'body']
  }
]

const allTags = [
  'Flex',
  'Container',
  'Title1',
  'Title2',
  'Title3',
  'Title4',
  'Text',
  'Bold',
  'Divider',
  'ProgressBar',
  'Barcode',
  'DateTime',
  'Table',
  'Row',
  'Col'
]

/** @type {import('@codemirror/lang-xml').ElementSpec[]} */
export const fcTemplateElements = allTags.map((name) => {
  const el = { name, top: true, children: allTags }

  if (name === 'Barcode') {
    el.attributes = ['format', 'barcodeWidth', ...styleAttrs]
  } else if (name === 'Row') {
    el.attributes = ['type', ...styleAttrs]
  } else if (name === 'Divider') {
    el.children = []
  }

  return el
})

/** Runtime helpers available as `fc` inside templates. */
export const fcTemplateHelpers = {
  listObjects: async () => [],
  getObject: async () => ({}),
  formatDate: () => ''
}
