/**
 * Editor-Preview: Markup-Wrapper, das auf das gleiche DOM setzt wie die
 * Frontend-Version und von view.js wiederverwendet wird (`__cePdInitDiagramWrappers`).
 * Seed-Daten für neue Blöcke; Layout-Icons kommen als externe SVG-URLs aus `editorData.js`.
 */
import {
  contrastTextColor,
  resolveHeaderTextColorAttr,
  resolvePieCalloutLineLength,
  resolvePieCalloutFontScale,
  resolvePieAngleBasis,
  resolveWaveLabelAtNodes,
  resolveWaveLabelAlongFloor,
  resolvePyramidSegmentGap,
  resolvePyramidInverted,
  resolvePyramidSliceLabelMode,
  resolvePyramidLabelAutoContrast,
  resolvePyramidAnnotation,
  resolvePyramidAnnotationLineLength,
  resolvePyramidAnnotationFontScale,
} from '../shared/config.js';
import { editorIcons, themePalette } from './editorData.js';
import { ENABLE_DIAGRAM_MAX_HEIGHT, isPieLayout } from './constants.js';
import {
  mergeDiagramMaxHByBp,
  getStraightBarLabelSlots,
  getStackedBarSumAbove,
  getPieSliceLabel,
  getDiagramRegionAriaLabel,
} from './attributeHelpers.js';
import { cePdEditorExt } from './editorExt.js';
import { normalizeRulerStyle } from '../scene/ruler.js';

const { createElement: el } = wp.element;
const { __ } = wp.i18n;

export const defaultBars = () => [
  { value: 43, unit: '', headline: 'Social Media', paragraph: 'Organic reach across platforms.', smallPrint: 'Q4 Report' },
  { value: 80, unit: '', headline: 'SEO Traffic', paragraph: 'Search engine driven visits.', smallPrint: 'Analytics' },
  { value: 95, unit: '', headline: 'Direct Sales', paragraph: 'Revenue from direct channels.', smallPrint: 'CRM Data' },
];
export const defaultBar = () => ({ value: 80, unit: '', headline: 'New Category', paragraph: '', smallPrint: '', groupKey: '', scatterX: 0, scatterY: 0 });
export const emptyDatasetBar = () => ({ value: 0, unit: '', headline: '', paragraph: '', smallPrint: '', groupKey: '' });

/**
 * Baut das Preview-Markup, das danach per Three.js (view.js) hydriert wird.
 * Identisches Layout wie das Frontend-HTML aus render.php.
 */
export function buildPreviewWrapper(attributes, bars, clientId) {
  const legendIconUrl = editorIcons.legendToggle || '';
  const dataTableIconUrl = editorIcons.dataTable || '';
  const fullscreenEnterIconUrl = editorIcons.fullscreenEnter || '';
  const fullscreenExitIconUrl = editorIcons.fullscreenExit || '';
  const pngDownloadIconUrl = editorIcons.pngDownload || '';
  const projectionTo2dIconUrl = editorIcons.projectionTo2d || '';
  const projectionTo3dIconUrl = editorIcons.projectionTo3d || '';
  const interactionHintIconUrl = editorIcons.interactionHint || '';
  const viewerSortGlyphUrl = editorIcons.viewerSort || '';
  const gridEnabled = attributes.gridEnabled !== false;
  const bgTransparent = attributes.backgroundTransparent === true;
  const wrapperStyle = { ...(!bgTransparent && attributes.backgroundColor ? { '--ce-diagram-loader-bg': attributes.backgroundColor } : {}) };
  const layout = attributes.defaultLayout || 'straight';
  /* Stairs-Donut ist ein reines 3D-Layout (liegende Treppenform): Projektion fix
   * auf 3D, kein 2D/3D-Umschalter. Spiegelt render.php (kein Ortho, kein Toggle). */
  const isStairsLayout = layout === 'pieStairs';
  const isPyramidLayout = layout === 'pyramid';
  const effectiveProjection = isStairsLayout ? '3d' : (attributes.defaultProjection || '3d');
  const projectionToggleEnabled = attributes.viewerProjectionToggleEnabled !== false;
  /* Layouts ohne Ortho-Support blenden den 2D/3D-Button immer aus,
   * unabhaengig vom Attribut — passt zum gleichen Verhalten im Frontend-Renderer
   * via PHP-Filter `ce_pd_layout_projection_toggleable`. */
  const projectionToggleable = projectionToggleEnabled && !isStairsLayout && cePdEditorExt.layoutSupportsOrthographic(layout);
  const initialIs2d = effectiveProjection === '2d';

  const axisY = attributes.axisY || { mode: 'numeric', min: 0, max: 100, unit: '%' };
  const axisXTrim = typeof attributes.axisXLabel === 'string' ? attributes.axisXLabel.trim().slice(0, 48) : '';

  let config = {
    bars,
    sortOrder: attributes.sortOrder || 'custom',
    gridEnabled,
    gridLineColor: attributes.gridLineColor || '#dcdcdc',
    backgroundType: attributes.backgroundType || 'grid',
    backgroundTransparent: bgTransparent,
    backgroundColor: attributes.backgroundColor || '#f8f9fa',
    gradientFloorColor: attributes.gradientFloorColor || '#c0c1c2',
    defaultLayout: layout,
    defaultProjection: effectiveProjection,
    cameraPreset: typeof attributes.cameraPreset === 'string' ? attributes.cameraPreset.trim() : 'default',
    startZoom: (typeof attributes.startZoom === 'number' && isFinite(attributes.startZoom) && attributes.startZoom > 0)
      ? Math.max(0.5, Math.min(2, attributes.startZoom))
      : 1,
    headerAlign: attributes.headerAlign || 'left',
    alwaysColorful: attributes.alwaysColorful === true,
    colorScheme: attributes.colorScheme || 'vivid',
    themePalette,
    ignoreBarColors: attributes.ignoreBarColors === true,
    defaultDataColor: typeof attributes.defaultDataColor === 'string' ? attributes.defaultDataColor.trim() : '',
    rulerEnabled: attributes.rulerEnabled !== false,
    rulerColor: attributes.rulerColor || '#858585',
    rulerColorAttr: typeof attributes.rulerColor === 'string' ? attributes.rulerColor.trim() : '',
    rulerStyle: normalizeRulerStyle(attributes.rulerStyle),
    barLabelColor: (typeof attributes.barLabelColor === 'string' && attributes.barLabelColor.trim() !== '') ? attributes.barLabelColor.trim() : (attributes.rulerColor || '#858585'),
    groupLabelColor: (typeof attributes.groupLabelColor === 'string' && attributes.groupLabelColor.trim() !== '') ? attributes.groupLabelColor.trim() : (attributes.rulerColor || '#858585'),

    interactionEnabled: attributes.interactionEnabled !== false,
    axisY,
    axisXLabel: axisXTrim,
    axisYLabel: typeof attributes.axisYLabel === 'string' ? attributes.axisYLabel.trim().slice(0, 48) : '',
    diagramMaxHeightByBreakpoint: ENABLE_DIAGRAM_MAX_HEIGHT ? mergeDiagramMaxHByBp(attributes.diagramMaxHeightByBreakpoint) : null,
    labelsUnderBars: (() => {
      if (layout === 'straight') return getStraightBarLabelSlots(attributes).below === 'headline';
      if (layout === 'wave') return resolveWaveLabelAlongFloor(attributes) === 'headline';
      return attributes.labelsUnderBars === true;
    })(),
    straightBarLabelAbove: layout === 'straight' ? getStraightBarLabelSlots(attributes).above : '',
    straightBarLabelBelow: layout === 'straight' ? getStraightBarLabelSlots(attributes).below : '',
    stackedBarSumAbove: layout === 'stacked' ? getStackedBarSumAbove(attributes) : false,
    barThicknessScale: typeof attributes.barThicknessScale === 'number' ? attributes.barThicknessScale : 1,
    barOpacity: typeof attributes.barOpacity === 'number' ? attributes.barOpacity : 1,
    barCornerRadius: typeof attributes.barCornerRadius === 'number' ? attributes.barCornerRadius : 1,
    barGradientEnabled: attributes.barGradientEnabled === true,
    sceneYScale: typeof attributes.sceneYScale === 'number' ? attributes.sceneYScale : 1,
    dataLabelFontScale: typeof attributes.dataLabelFontScale === 'number' ? attributes.dataLabelFontScale : 1,
    pieSliceLabel: isPieLayout(layout) ? getPieSliceLabel(attributes) : 'off',
    pieInnerRadius: isPieLayout(layout) ? (typeof attributes.pieInnerRadius === 'number' ? attributes.pieInnerRadius : 0.5) : 0.5,
    pieThickness: isPieLayout(layout) ? (typeof attributes.pieThickness === 'number' ? attributes.pieThickness : 1) : 1,
    pieAngleBasis: isPieLayout(layout) ? resolvePieAngleBasis(attributes) : 'sum',
    pieCalloutLineLength: isPieLayout(layout) ? resolvePieCalloutLineLength({ pieCalloutLineLength: attributes.pieCalloutLineLength }) : 0.25,
    pieCalloutFontScale: isPieLayout(layout) ? resolvePieCalloutFontScale({ pieCalloutFontScale: attributes.pieCalloutFontScale }) : 1,
    pieCalloutColor: isPieLayout(layout) && typeof attributes.pieCalloutColor === 'string' ? attributes.pieCalloutColor.trim() : '',
    circleLabelStyle: 'simple',
    pieLabelAutoContrast: isPieLayout(layout) && attributes.pieLabelAutoContrast !== false,
    stairStepHeight: layout === 'pieStairs' ? (typeof attributes.stairStepHeight === 'number' ? attributes.stairStepHeight : 0.18) : 0.18,
    pyramidSegmentGap: isPyramidLayout ? resolvePyramidSegmentGap(attributes) : 0,
    pyramidSegmentOpacity: 1,
    pyramidInverted: isPyramidLayout ? resolvePyramidInverted(attributes) : false,
    pyramidSliceLabel: isPyramidLayout ? resolvePyramidSliceLabelMode(attributes) : 'off',
    pyramidLabelAutoContrast: isPyramidLayout && attributes.pyramidLabelAutoContrast !== false,
    pyramidAnnotation: isPyramidLayout && resolvePyramidAnnotation(attributes),
    pyramidAnnotationLineLength: isPyramidLayout ? resolvePyramidAnnotationLineLength(attributes) : 0.25,
    pyramidAnnotationFontScale: isPyramidLayout ? resolvePyramidAnnotationFontScale(attributes) : 1,
    waveStyle: layout === 'wave' ? (attributes.waveStyle === 'line' ? 'line' : 'ribbon') : 'ribbon',
    waveRibbonDepth: layout === 'wave' && Number.isFinite(attributes.waveRibbonDepth) ? attributes.waveRibbonDepth : 0.08,
    waveRibbonOpacity: layout === 'wave' && Number.isFinite(attributes.waveRibbonOpacity) ? attributes.waveRibbonOpacity : 1,
    waveAreaFill: layout === 'wave' ? attributes.waveAreaFill !== false : false,
    waveAreaFillOpacity: layout === 'wave' && Number.isFinite(attributes.waveAreaFillOpacity) ? attributes.waveAreaFillOpacity : 0.35,
    waveBaselineValue: layout === 'wave' && Number.isFinite(attributes.waveBaselineValue) ? attributes.waveBaselineValue : 0,
    waveGradientDirection: layout === 'wave' && typeof attributes.waveGradientDirection === 'string' ? attributes.waveGradientDirection : 'vertical',
    waveLineThickness: layout === 'wave' && Number.isFinite(attributes.waveLineThickness) ? attributes.waveLineThickness : 1,
    waveSmoothness: layout === 'wave' && Number.isFinite(attributes.waveSmoothness) ? attributes.waveSmoothness : 0.5,
    waveShowPoints: layout === 'wave' ? attributes.waveShowPoints !== false : true,
    wavePointSize: layout === 'wave' && Number.isFinite(attributes.wavePointSize) ? attributes.wavePointSize : 1,
    waveMultiSeries: layout === 'wave' ? attributes.waveMultiSeries !== false : true,
    waveLabelAtNodes: layout === 'wave' ? resolveWaveLabelAtNodes(attributes) : 'off',
    waveLabelAlongFloor: layout === 'wave' ? resolveWaveLabelAlongFloor(attributes) : 'off',
    waveAnnotationLineLength: layout === 'wave' && Number.isFinite(attributes.waveAnnotationLineLength) ? attributes.waveAnnotationLineLength : 0.25,
    waveAnnotationFontScale: layout === 'wave' && Number.isFinite(attributes.waveAnnotationFontScale) ? attributes.waveAnnotationFontScale : 1,
    i18nSource: __('Source:', 'pop3d-charts'),
    i18nLoadError: __('Diagram could not be loaded.', 'pop3d-charts'),
    i18nContextLost: __('WebGL context was lost.', 'pop3d-charts'),
    i18nFullscreenEnter: __('Enter fullscreen', 'pop3d-charts'),
    i18nFullscreenExit: __('Exit fullscreen', 'pop3d-charts'),
    i18nDataTableShow: __('Show data table', 'pop3d-charts'),
    i18nDataTableClose: __('Close', 'pop3d-charts'),
    i18nDataTableCaption: __('Diagram data', 'pop3d-charts'),
    i18nDataTableColValue: __('Value', 'pop3d-charts'),
    i18nDataTableColTitle: __('Title', 'pop3d-charts'),
    i18nDataTableColDescription: __('Description', 'pop3d-charts'),
    i18nDataTableColSmallPrint: __('Note', 'pop3d-charts'),
    i18nDataTableColColor: __('Color', 'pop3d-charts'),
    i18nDataTableColGroup: __('X group', 'pop3d-charts'),
    legendEnabled: attributes.legendEnabled !== false,
    legendVisibleDefault: attributes.legendVisibleDefault !== false,
    legendPosition: (attributes.legendPosition === 'bottom' || attributes.legendPosition === 'hidden') ? attributes.legendPosition : 'left',
    legendOutsideChart: attributes.legendOutsideChart === true && attributes.legendPosition === 'bottom',
    legendTextColor: (typeof attributes.legendTextColor === 'string' && attributes.legendTextColor.trim() !== '') ? attributes.legendTextColor.trim() : '',
    i18nLegendShow: __('Show legend', 'pop3d-charts'),
    i18nLegendHide: __('Hide legend', 'pop3d-charts'),
    viewerSortEnabled: attributes.viewerSortEnabled === true,
    viewerSortGlyphUrl,
    i18nViewerSortLabel: __('Sort order', 'pop3d-charts'),
    i18nViewerSortAria: __('Sort chart rows', 'pop3d-charts'),
    i18nSortCustom: __('Custom (manual)', 'pop3d-charts'),
    i18nSortValueAsc: __('Value ascending', 'pop3d-charts'),
    i18nSortValueDesc: __('Value descending', 'pop3d-charts'),
    i18nSortHeadlineAsc: __('Label A–Z', 'pop3d-charts'),
    viewerPngDownloadEnabled: attributes.viewerPngDownloadEnabled === true,
    i18nPngDownload: __('PNG Download', 'pop3d-charts'),
    headerTextColor: (typeof attributes.headerTextColor === 'string' && attributes.headerTextColor.trim() !== '') ? attributes.headerTextColor.trim() : '',
    numberLocale: (typeof document !== 'undefined' && document.documentElement.lang && document.documentElement.lang.trim())
      ? document.documentElement.lang.trim().replace(/_/g, '-')
      : ((typeof navigator !== 'undefined' && navigator.language) ? navigator.language : 'en-US'),
  };

  if (cePdEditorExt && typeof cePdEditorExt.applyConfig === 'function') {
    config = cePdEditorExt.applyConfig(config, attributes, layout) || config;
  }

  const headerFooterVarStyle = () => {
    const s = {};
    const user = resolveHeaderTextColorAttr(attributes.headerTextColor);
    if (user) s['--ce-header-color'] = user;
    else if (!bgTransparent) { const c = contrastTextColor(attributes.backgroundColor || '#f8f9fa'); if (c) s['--ce-header-color'] = c; }
    if (attributes.headerAlign === 'center' || attributes.headerAlign === 'right') s['--ce-header-align'] = attributes.headerAlign;
    return s;
  };

  const blockId = 'ce-diagram-' + (clientId || 'preview');
  return el('div', {
    id: blockId,
    className: 'ce-diagram-wrapper ce-diagram-editor-preview' + (bgTransparent ? ' ce-diagram-wrapper--transparent-bg' : '') + (attributes.legendPosition === 'bottom' ? ' ce-diagram-wrapper--legend-bottom' : '') + (attributes.legendOutsideChart === true && attributes.legendPosition === 'bottom' ? ' ce-diagram-wrapper--legend-external' : ''),
    style: wrapperStyle,
    'data-config': JSON.stringify(config),
    'data-ruler-color': config.rulerColor,
    'data-bar-label-color': config.barLabelColor,
    'data-group-label-color': config.groupLabelColor,
    role: 'region',
    'aria-label': getDiagramRegionAriaLabel(layout, effectiveProjection),
  },
    (attributes.chartTitle || attributes.chartSubtitle)
      ? el('div', { className: 'ce-diagram-header', style: (() => {
          const s = headerFooterVarStyle();
          return Object.keys(s).length ? s : undefined;
        })() },
        attributes.chartTitle ? el('div', { className: 'ce-diagram-chart-title' }, attributes.chartTitle) : null,
        attributes.chartSubtitle ? el('div', { className: 'ce-diagram-chart-subtitle' }, attributes.chartSubtitle) : null)
      : null,
    el('div', { className: 'ce-diagram-loader', 'aria-live': 'polite', 'aria-busy': 'true' },
      el('div', { className: 'ce-diagram-loader-bar' })
    ),
    el('div', { className: 'ce-diagram-inner' },
      attributes.legendEnabled !== false && attributes.legendPosition !== 'hidden' && !(attributes.legendOutsideChart === true && attributes.legendPosition === 'bottom')
        ? el('aside', {
          className: 'ce-diagram-legend',
          'data-ce-legend-aside': '1',
          'aria-label': __('Legend', 'pop3d-charts'),
          hidden: attributes.legendVisibleDefault === false,
          'aria-hidden': attributes.legendVisibleDefault === false ? 'true' : 'false',
          style: (() => {
            let c = (typeof attributes.legendTextColor === 'string' && attributes.legendTextColor.trim()) ? attributes.legendTextColor.trim() : '';
            if (!c && !attributes.backgroundTransparent) c = contrastTextColor(attributes.backgroundColor || '#f8f9fa');
            return c ? { '--ce-legend-color': c } : undefined;
          })(),
        })
        : null,
      el('div', { className: 'pop3d-charts', 'aria-hidden': true }),
      el('div', { className: 'ce-diagram-icon-wrapper', role: 'group', 'aria-label': __('Controls', 'pop3d-charts') },
        el('div', { className: 'ce-diagram-icon-tooltip', role: 'tooltip' },
          el('p', null, el('strong', null, __('Scroll / pinch gesture', 'pop3d-charts')), ' ', el('span', { className: 'ce-diagram-icon-tooltip-hint' }, __('Zoom in and out', 'pop3d-charts'))),
          el('p', null, el('strong', null, __('Left mouse click drag', 'pop3d-charts')), ' ', el('span', { className: 'ce-diagram-icon-tooltip-hint' }, __('Rotate the diagram', 'pop3d-charts'))),
          el('p', null, el('strong', null, __('Right mouse click drag', 'pop3d-charts')), ' ', el('span', { className: 'ce-diagram-icon-tooltip-hint' }, __('Pan camera position', 'pop3d-charts'))),
          el('p', null, el('strong', null, __('Click / tap', 'pop3d-charts')), ' ', el('span', { className: 'ce-diagram-icon-tooltip-hint' }, __('Show details on elements', 'pop3d-charts')))
        ),
        interactionHintIconUrl
          ? el('img', {
            className: 'ce-diagram-icon',
            src: interactionHintIconUrl,
            width: 58,
            height: 17,
            alt: __('Scroll and drag with mouse or tap with finger', 'pop3d-charts'),
            decoding: 'async',
            draggable: false,
          })
          : null
      )
    ),
    attributes.legendEnabled !== false && attributes.legendOutsideChart === true && attributes.legendPosition === 'bottom'
      ? el('aside', {
        className: 'ce-diagram-legend',
        'data-ce-legend-aside': '1',
        'aria-label': __('Legend', 'pop3d-charts'),
        hidden: attributes.legendVisibleDefault === false,
        'aria-hidden': attributes.legendVisibleDefault === false ? 'true' : 'false',
        style: (() => {
          let c = (typeof attributes.legendTextColor === 'string' && attributes.legendTextColor.trim()) ? attributes.legendTextColor.trim() : '';
          if (!c && !attributes.backgroundTransparent) c = contrastTextColor(attributes.backgroundColor || '#f8f9fa');
          return c ? { '--ce-legend-color': c } : undefined;
        })(),
      })
      : null,
    el('div', { className: 'ce-diagram-top-actions' },
      el('button', {
        type: 'button',
        className: 'ce-diagram-expand-btn ce-diagram-fullscreen-btn',
        'aria-pressed': 'false',
        'aria-label': __('Enter fullscreen', 'pop3d-charts'),
        title: __('Enter fullscreen', 'pop3d-charts'),
      },
        el('span', { className: 'ce-diagram-expand-btn__label', 'aria-hidden': 'true' }, __('Enter fullscreen', 'pop3d-charts')),
        el('span', { className: 'ce-diagram-expand-btn__icon', 'aria-hidden': 'true' },
          fullscreenEnterIconUrl
            ? el('img', { className: 'ce-diagram-fullscreen-icon ce-diagram-fullscreen-icon--enter', src: fullscreenEnterIconUrl, width: 24, height: 24, alt: '', decoding: 'async', draggable: false })
            : null,
          fullscreenExitIconUrl
            ? el('img', { className: 'ce-diagram-fullscreen-icon ce-diagram-fullscreen-icon--exit', src: fullscreenExitIconUrl, width: 24, height: 24, alt: '', decoding: 'async', draggable: false })
            : null
        )
      ),
      attributes.legendEnabled !== false && attributes.legendPosition !== 'hidden'
        ? el('button', {
          type: 'button',
          className: 'ce-diagram-expand-btn ce-diagram-legend-toggle-btn',
          'aria-pressed': attributes.legendVisibleDefault !== false ? 'true' : 'false',
          'aria-label': attributes.legendVisibleDefault !== false ? __('Hide legend', 'pop3d-charts') : __('Show legend', 'pop3d-charts'),
          title: attributes.legendVisibleDefault !== false ? __('Hide legend', 'pop3d-charts') : __('Show legend', 'pop3d-charts'),
        },
        el('span', { className: 'ce-diagram-expand-btn__label', 'aria-hidden': 'true' }, __('Legend', 'pop3d-charts')),
        el('span', { className: 'ce-diagram-expand-btn__icon', 'aria-hidden': 'true' },
          legendIconUrl
            ? el('img', { className: 'ce-diagram-legend-icon', src: legendIconUrl, width: 24, height: 24, alt: '', decoding: 'async', draggable: false })
            : null
        )
        )
        : null,
      el('button', { type: 'button', className: 'ce-diagram-expand-btn ce-diagram-data-table-btn' },
        el('span', { className: 'ce-diagram-expand-btn__label', 'aria-hidden': 'true' }, __('Show data table', 'pop3d-charts')),
        el('span', { className: 'ce-diagram-expand-btn__icon', 'aria-hidden': 'true' },
          dataTableIconUrl
            ? el('img', { className: 'ce-diagram-data-table-icon', src: dataTableIconUrl, width: 24, height: 24, alt: '', decoding: 'async', draggable: false })
            : null
        )
      ),
      attributes.viewerPngDownloadEnabled === true
        ? el('button', {
          type: 'button',
          className: 'ce-diagram-expand-btn ce-diagram-png-download-btn',
          'aria-label': __('PNG Download', 'pop3d-charts'),
          title: __('PNG Download', 'pop3d-charts'),
        },
        el('span', { className: 'ce-diagram-expand-btn__label', 'aria-hidden': 'true' }, __('PNG Download', 'pop3d-charts')),
        el('span', { className: 'ce-diagram-expand-btn__icon', 'aria-hidden': 'true' },
          pngDownloadIconUrl
            ? el('img', { className: 'ce-diagram-png-download-icon', src: pngDownloadIconUrl, width: 24, height: 24, alt: '', decoding: 'async', draggable: false })
            : null
        )
        )
        : null,
      /* 2D/3D-Toggle: identisches Markup wie render.php (gleiche Klassen/data-i18n-*),
       * damit view.js → createProjectionToggle den Button im Editor-Preview per
       * wrapper.querySelector('.ce-diagram-projection-btn') findet. */
      projectionToggleable
        ? el('button', {
          type: 'button',
          className: 'ce-diagram-expand-btn ce-diagram-projection-btn',
          'aria-pressed': initialIs2d ? 'true' : 'false',
          'aria-label': initialIs2d ? __('Switch to 3D view', 'pop3d-charts') : __('Switch to 2D view', 'pop3d-charts'),
          title: initialIs2d ? __('Switch to 3D view', 'pop3d-charts') : __('Switch to 2D view', 'pop3d-charts'),
          'data-i18n-to-2d': __('Switch to 2D view', 'pop3d-charts'),
          'data-i18n-to-3d': __('Switch to 3D view', 'pop3d-charts'),
          'data-i18n-flat-view': __('Flat view', 'pop3d-charts'),
          'data-i18n-perspective': __('Perspective', 'pop3d-charts'),
        },
        el('span', { className: 'ce-diagram-expand-btn__label', 'aria-hidden': 'true' }, initialIs2d ? __('Perspective', 'pop3d-charts') : __('Flat view', 'pop3d-charts')),
        el('span', { className: 'ce-diagram-expand-btn__icon', 'aria-hidden': 'true' },
          projectionTo2dIconUrl
            ? el('img', { className: 'ce-diagram-projection-icon ce-diagram-projection-icon--to-2d', src: projectionTo2dIconUrl, width: 24, height: 24, alt: '', decoding: 'async', draggable: false })
            : null,
          projectionTo3dIconUrl
            ? el('img', { className: 'ce-diagram-projection-icon ce-diagram-projection-icon--to-3d', src: projectionTo3dIconUrl, width: 24, height: 24, alt: '', decoding: 'async', draggable: false })
            : null
        )
        )
        : null
    ),
    el('div', { className: 'ce-diagram-tooltip', role: 'status', 'aria-live': 'polite', 'aria-atomic': 'true' }),
    attributes.chartFootnote ? el('footer', { className: 'ce-diagram-footnote', style: (() => {
      const s = headerFooterVarStyle();
      return Object.keys(s).length ? s : undefined;
    })() }, attributes.chartFootnote) : null
  );
}
