/**
 * Panel "Legend" — Sichtbarkeit, Position und Textfarbe der Legende.
 */
import { ColorSwatchPicker } from '../ColorSwatchPicker.js';

const { createElement: el } = wp.element;
const { __ } = wp.i18n;
const { PanelBody, ToggleControl, SelectControl, Button } = wp.components;

export function LegendPanel({ attributes, setAttributes, openState }) {
  const legendEnabled = attributes.legendEnabled !== false;
  const legendCustomColor = typeof attributes.legendTextColor === 'string' && attributes.legendTextColor.trim() !== '';

  return el(PanelBody, { title: __('Legend', 'pop3d-charts'), ...(openState || {}) },
    el(ToggleControl, {
      label: __('Chart legend', 'pop3d-charts'),
      help: __('Color key and titles next to the chart. Visitors can hide or show it with the Legend control.', 'pop3d-charts'),
      checked: legendEnabled,
      onChange: (v) => setAttributes({ legendEnabled: v }),
      __nextHasNoMarginBottom: true,
    }),
    legendEnabled ? el(SelectControl, {
      label: __('Legend position', 'pop3d-charts'),
      value: attributes.legendPosition || 'left',
      options: [
        { label: __('Left', 'pop3d-charts'), value: 'left' },
        { label: __('Bottom', 'pop3d-charts'), value: 'bottom' },
        { label: __('Hidden', 'pop3d-charts'), value: 'hidden' },
      ],
      onChange: (v) => setAttributes({ legendPosition: v }),
      __nextHasNoMarginBottom: true,
    }) : null,
    legendEnabled && attributes.legendPosition === 'bottom' ? el(ToggleControl, {
      label: __('Legend outside chart', 'pop3d-charts'),
      help: __('Keeps the chart at full width. The legend appears below the chart and the block grows taller.', 'pop3d-charts'),
      checked: attributes.legendOutsideChart === true,
      onChange: (v) => setAttributes({ legendOutsideChart: v }),
      __nextHasNoMarginBottom: true,
    }) : null,
    legendEnabled && attributes.legendPosition !== 'hidden' ? el(ToggleControl, {
      label: __('Legend visible by default', 'pop3d-charts'),
      checked: attributes.legendVisibleDefault !== false,
      onChange: (v) => setAttributes({ legendVisibleDefault: v }),
      __nextHasNoMarginBottom: true,
    }) : null,
    legendEnabled && attributes.legendPosition !== 'hidden' ? el(ColorSwatchPicker, {
      label: __('Legend text color', 'pop3d-charts'),
      id: 'ce-diagram-legend-text-color',
      help: __('Text color for legend labels and footnotes.', 'pop3d-charts'),
      color: legendCustomColor ? attributes.legendTextColor.trim() : '#000000',
      isEmpty: !legendCustomColor,
      onChange: (hex) => setAttributes({ legendTextColor: hex || '' }),
      defaultButton: legendCustomColor
        ? el(Button, { isSmall: true, variant: 'secondary', onClick: () => setAttributes({ legendTextColor: '' }) }, __('Reset to default', 'pop3d-charts'))
        : null,
    }) : null
  );
}
