/**
 * Expandierbarer Editor fuer eine einzelne Bar-Row (Wert, Label, Beschreibung ...).
 * Wird im Chart-Data-Panel fuer jede Zeile in `bars` angezeigt.
 *
 * Add-on-Plugins koennen ueber `window.__CE_PD_EDITOR_EXT__.barItem` Layouts
 * mit zusaetzlichen Feldern und Labels erweitern:
 *  - rowLabel(layout)          → String
 *  - colorLabel(layout)        → String
 *  - labelPlaceholder(layout)  → String
 *  - showGroupKey(layout)      → boolean (zeigt das X-group-Feld)
 *  - groupKeyHelp(layout)      → String (Help-Text dafuer)
 *  - fieldsBefore(layout, bar, onChange, ctx) → array<ReactElement> (vor groupKey)
 *  - fieldsAfter(layout, bar, onChange, ctx)  → array<ReactElement> (nach Source)
 *
 * `ctx` enthaelt `{ el, __, Button, TextControl, TextareaControl }`, damit
 * Add-ons keine internen Helfer importieren muessen.
 */
import { ColorSwatchPicker } from './ColorSwatchPicker.js';

const { createElement: el, Fragment, useState } = wp.element;
const { __ } = wp.i18n;
const { Button, TextControl, TextareaControl, ToggleControl } = wp.components;

function _editorExt() {
  return (typeof window !== 'undefined' && window.__CE_PD_EDITOR_EXT__ && window.__CE_PD_EDITOR_EXT__.barItem) || null;
}

export function BarItemEditor({ bar, displayIndex, originalIndex, onChange, onRemove, onMoveUp, onMoveDown, onDuplicate, total, layout }) {
  const [expanded, setExpanded] = useState(false);
  const ext = _editorExt();
  const extCtx = { el, __, Button, TextControl, TextareaControl };

  const rowLabel = (ext && typeof ext.rowLabel === 'function' && ext.rowLabel(layout)) || __('Bar', 'pop3d-charts');
  const colorLabel = (ext && typeof ext.colorLabel === 'function' && ext.colorLabel(layout)) || __('Bar color', 'pop3d-charts');
  const labelPlaceholder = (ext && typeof ext.labelPlaceholder === 'function' && ext.labelPlaceholder(layout))
    || ((layout === 'stacked') ? __('Series name (tooltip)', 'pop3d-charts') : __('Category name for tooltip', 'pop3d-charts'));
  /* Das stacked-Layout zeigt das X-group-Feld immer; Add-ons koennen weitere
   * Layouts via `showGroupKey` ergaenzen. */
  const showGroupKey = layout === 'stacked' || layout === 'wave'
    || (ext && typeof ext.showGroupKey === 'function' && ext.showGroupKey(layout) === true);
  const groupKeyHelp = (ext && typeof ext.groupKeyHelp === 'function' && ext.groupKeyHelp(layout))
    || __('Rows with the same value share one cluster on the X axis. Leave empty for a single-bar cluster.', 'pop3d-charts');
  const extFieldsBefore = (ext && typeof ext.fieldsBefore === 'function' && ext.fieldsBefore(layout, bar, onChange, extCtx)) || [];
  const extFieldsAfter = (ext && typeof ext.fieldsAfter === 'function' && ext.fieldsAfter(layout, bar, onChange, extCtx)) || [];

  const titleStr = rowLabel + ' ' + (displayIndex + 1);
  const toggle = () => setExpanded((o) => !o);

  /* Eingeklappt: kurze Vorschau (Bezeichnung + Wert) im Header, damit lange
   * Listen ohne Aufklappen scannbar bleiben. */
  const valuePreview = (bar.value != null && bar.value !== '')
    ? String(bar.value) + (bar.unit ? ' ' + String(bar.unit).trim() : '')
    : '';
  const summary = [bar.headline, valuePreview].filter(Boolean).join('  \u00B7  ');

  return el('div', { className: 'ce-diagram-bar-item' },
    el('div', { className: 'ce-diagram-bar-item-header', style: { display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: '8px', flexWrap: 'wrap' } },
      el(Button, {
        variant: 'tertiary',
        isSmall: true,
        onClick: toggle,
        'aria-expanded': expanded,
        style: { flex: '1 1 auto', minWidth: 0, justifyContent: 'flex-start' },
      },
        el('span', { style: { fontWeight: 600, flex: '0 0 auto' } }, (expanded ? '\u25BC ' : '\u25B6 ') + titleStr),
        (!expanded && summary) ? el('span', {
          style: { marginLeft: '6px', fontWeight: 400, color: '#757575', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', minWidth: 0 },
        }, summary) : null
      ),
      el('div', { style: { display: 'flex', gap: '4px', flexWrap: 'wrap' } },
        displayIndex > 0 ? el(Button, { key: 'up', isSmall: true, variant: 'secondary', onClick: onMoveUp, label: __('Move up', 'pop3d-charts') }, '\u2191') : null,
        displayIndex < total - 1 ? el(Button, { key: 'down', isSmall: true, variant: 'secondary', onClick: onMoveDown, label: __('Move down', 'pop3d-charts') }, '\u2193') : null,
        el(Button, { key: 'dup', isSmall: true, variant: 'secondary', onClick: onDuplicate }, __('Duplicate', 'pop3d-charts')),
        el(Button, { key: 'rm', isDestructive: true, isSmall: true, onClick: onRemove }, __('Remove', 'pop3d-charts'))
      )
    ),
    expanded ? el(Fragment, { key: 'fields' },
      el(TextControl, { label: __('Value', 'pop3d-charts'), type: 'number', value: String(bar.value ?? 0), onChange: (v) => { const n = parseFloat(v); if (!isNaN(n) && n >= -1e8 && n <= 1e8) onChange({ ...bar, value: n }); }, help: __('-100,000,000 to 100,000,000', 'pop3d-charts'), __nextHasNoMarginBottom: true, __next40pxDefaultSize: true }),
      el(TextControl, { label: __('Value unit (tooltip)', 'pop3d-charts'), value: bar.unit != null ? String(bar.unit) : '', onChange: (v) => onChange({ ...bar, unit: v }), placeholder: __('e.g. " Punkte" or " M" — leave empty for Y-axis format', 'pop3d-charts'), help: __('Optional. Appended after the number in the tooltip and data table. Empty = use the Y-axis unit prefix/suffix.', 'pop3d-charts'), __nextHasNoMarginBottom: true, __next40pxDefaultSize: true }),
      ...extFieldsBefore,
      showGroupKey ? el(TextControl, { label: __('X group (category)', 'pop3d-charts'), value: bar.groupKey || '', onChange: (v) => onChange({ ...bar, groupKey: v }), help: groupKeyHelp, placeholder: __('e.g. 2020, Q1', 'pop3d-charts'), __nextHasNoMarginBottom: true, __next40pxDefaultSize: true }) : null,
      el(TextControl, { label: __('Label', 'pop3d-charts'), value: bar.headline || '', onChange: (v) => onChange({ ...bar, headline: v }), placeholder: labelPlaceholder, __nextHasNoMarginBottom: true, __next40pxDefaultSize: true }),
      el(TextareaControl, { label: __('Description', 'pop3d-charts'), value: bar.paragraph || '', onChange: (v) => onChange({ ...bar, paragraph: v }), placeholder: __('Description text', 'pop3d-charts'), rows: 2, __nextHasNoMarginBottom: true }),
      el(TextControl, { label: __('Source', 'pop3d-charts'), value: bar.smallPrint || '', onChange: (v) => onChange({ ...bar, smallPrint: v }), placeholder: __('Source / citation', 'pop3d-charts'), __nextHasNoMarginBottom: true, __next40pxDefaultSize: true }),
      el(TextControl, { label: __('Link URL', 'pop3d-charts'), type: 'url', value: bar.link || '', onChange: (v) => onChange({ ...bar, link: v }), placeholder: 'https://example.com', help: __('Optional. Clicking or tapping this bar opens the link on the website.', 'pop3d-charts'), __nextHasNoMarginBottom: true, __next40pxDefaultSize: true }),
      el(ToggleControl, { label: __('Open in new tab', 'pop3d-charts'), checked: bar.linkNewTab === true, onChange: (v) => onChange({ ...bar, linkNewTab: v }), __nextHasNoMarginBottom: true }),
      ...extFieldsAfter,
      el(ColorSwatchPicker, {
        label: colorLabel,
        id: 'ce-diagram-bar-color-' + originalIndex,
        help: __('Leave empty to use the chart default (uniform color or color scheme).', 'pop3d-charts'),
        color: bar.color, isEmpty: !bar.color,
        onChange: (hex) => onChange({ ...bar, color: hex || undefined }),
        defaultButton: bar.color ? el(Button, { isSmall: true, variant: 'secondary', onClick: () => onChange({ ...bar, color: undefined }) }, __('Use default', 'pop3d-charts')) : null,
      })
    ) : null
  );
}
