/**
 * Panel "Diagram type" — Icon-Buttons zur Auswahl des Layouts.
 *
 * Standard-Layouts kommen aus `LAYOUT_ORDER`. Add-on-Plugins koennen ueber
 * `window.__CE_PD_EDITOR_EXT__.registerLayoutOption(...)` weitere Layout-Buttons
 * registrieren; sie werden nach order-Wert eingemischt (Standard-Order-Indizes:
 * straight=1, stacked=3, pie=7).
 */
import { LAYOUT_ORDER } from '../constants.js';
import { layoutIconUrls } from '../editorData.js';
import { cePdEditorExt } from '../editorExt.js';

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

const BASE_LAYOUT_ORDER_INDEX = { straight: 1, stacked: 3, pie: 7, pieStairs: 10, wave: 4, pyramid: 12 };

/**
 * Kategorie-Zuordnung der Free-Layouts. Pro-Layouts liefern ihre Kategorie
 * selbst ueber `registerLayoutOption({ category })` mit.
 */
const BASE_LAYOUT_CATEGORY = { straight: 'bars', stacked: 'bars', pie: 'circular', pieStairs: 'circular', wave: 'trends', pyramid: 'infographic' };

/**
 * Anzeige-Reihenfolge der Kategorie-Zwischenueberschriften im Picker.
 * Unbekannte Kategorien (z. B. aus kuenftigen Add-ons) werden hinten angehaengt.
 */
const LAYOUT_CATEGORY_ORDER = ['bars', 'circular', 'trends', 'infographic'];

/**
 * Lesbare, uebersetzte Anzeigenamen der Free-Layouts. Pro-Layout-Namen kommen
 * ausschliesslich aus der Pro-Registrierung (`opt.label`), damit das Free-Plugin
 * keine Pro-Bezeichnungen enthaelt. Muss in der Funktion (nicht Top-Level)
 * aufgerufen werden, damit setLocaleData bereits gelaufen ist.
 */
function buildLayoutLabels() {
  return {
    straight: __('Column bars', 'pop3d-charts'),
    stacked: __('Stacked bars', 'pop3d-charts'),
    pie: __('Pie / Donut', 'pop3d-charts'),
    pieStairs: __('Stair donut', 'pop3d-charts'),
    wave: __('Line / Area', 'pop3d-charts'),
    pyramid: __('Pyramid', 'pop3d-charts'),
  };
}

/** Uebersetzte Kategorie-Ueberschriften. */
function buildCategoryLabels() {
  return {
    bars: __('Bars & columns', 'pop3d-charts'),
    circular: __('Circular & proportions', 'pop3d-charts'),
    trends: __('Trends & relationships', 'pop3d-charts'),
    infographic: __('Infographics', 'pop3d-charts'),
  };
}

function buildLayoutOptions() {
  const base = LAYOUT_ORDER.map((id) => ({
    id,
    iconUrl: layoutIconUrls[id] || '',
    order: BASE_LAYOUT_ORDER_INDEX[id] != null ? BASE_LAYOUT_ORDER_INDEX[id] : 99,
    category: BASE_LAYOUT_CATEGORY[id] || LAYOUT_CATEGORY_ORDER[0],
  }));
  const ext = (cePdEditorExt && typeof cePdEditorExt.getLayoutOptions === 'function')
    ? cePdEditorExt.getLayoutOptions()
    : [];
  const merged = [];
  const seen = new Set();
  base.concat(ext).forEach((opt) => {
    if (!opt || typeof opt.id !== 'string' || seen.has(opt.id)) return;
    seen.add(opt.id);
    merged.push({
      id: opt.id,
      iconUrl: opt.iconUrl || layoutIconUrls[opt.id] || '',
      order: typeof opt.order === 'number' ? opt.order : 99,
      label: typeof opt.label === 'string' ? opt.label : '',
      category: typeof opt.category === 'string' && opt.category !== '' ? opt.category : LAYOUT_CATEGORY_ORDER[0],
    });
  });
  merged.sort((a, b) => a.order - b.order);
  return merged;
}

export function DiagramTypePanel({ layout, attributes, setAttributes, openState }) {
  const visibleLayouts = buildLayoutOptions();
  const layoutLabels = buildLayoutLabels();
  const categoryLabels = buildCategoryLabels();

  /* Nach Kategorie gruppieren; Kategorie-Reihenfolge gemaess LAYOUT_CATEGORY_ORDER,
   * unbekannte Kategorien werden hinten angehaengt. */
  const byCategory = new Map();
  visibleLayouts.forEach((opt) => {
    if (!byCategory.has(opt.category)) byCategory.set(opt.category, []);
    byCategory.get(opt.category).push(opt);
  });
  const orderedCategories = [
    ...LAYOUT_CATEGORY_ORDER.filter((c) => byCategory.has(c)),
    ...[...byCategory.keys()].filter((c) => LAYOUT_CATEGORY_ORDER.indexOf(c) === -1),
  ];

  const renderButton = (opt) => {
    const { id, iconUrl } = opt;
    const layoutName = opt.label || layoutLabels[id] || id;
    return el('button', {
      key: id,
      type: 'button',
      'aria-label': layoutName,
      'aria-pressed': layout === id,
      title: layoutName,
      onClick: () => {
        const patch = { defaultLayout: id };
        /* Von anderem Typ auf Line/Area: Tabellenreihenfolge, nicht die vorherige Sortierung. */
        if (id === 'wave' && layout !== 'wave') {
          if ((attributes?.sortOrder || 'custom') !== 'custom') patch.sortOrder = 'custom';
          if (attributes?.viewerSortEnabled === true) patch.viewerSortEnabled = false;
        }
        setAttributes(patch);
      },
      className: 'ce-diagram-layout-btn' + (layout === id ? ' is-active' : ''),
    },
      iconUrl
        ? el('img', {
          className: 'ce-diagram-layout-icon-img',
          src: iconUrl,
          width: 80,
          height: 80,
          alt: '',
          decoding: 'async',
          draggable: false,
        })
        : null,
      el('span', { className: 'ce-diagram-layout-btn-label' }, layoutName)
    );
  };

  return el(PanelBody, { title: __('Diagram type', 'pop3d-charts'), ...(openState || { initialOpen: true }) },
    orderedCategories.map((cat) =>
      el('div', { key: cat, className: 'ce-diagram-layout-category' },
        el('span', { className: 'ce-diagram-layout-category-title' }, categoryLabels[cat] || cat),
        el('div', {
          className: 'ce-diagram-layout-icons',
          role: 'group',
          'aria-label': categoryLabels[cat] || cat,
        },
          byCategory.get(cat).map(renderButton)
        )
      )
    )
  );
}
