/**
 * Panel "Axis configuration" — Y-min/max, Prefix/Suffix, X- und Y-Titel
 * für die Layouts straight, stacked und pie. Add-ons koennen ueber
 * `editorExt.registerPanelSection('axis', ...)` weitere Axis-Felder
 * (z. B. zusaetzliche Achsen fuer Layout-Erweiterungen) registrieren.
 */
import { cePdEditorExt } from '../editorExt.js';
import { isPieLayout } from '../constants.js';

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

const isBarChart = (layout) => layout === 'straight' || layout === 'stacked';

/** Rundet auf eine "schoene" Obergrenze (1/2/2.5/5/10 × Zehnerpotenz). */
function niceCeil(v) {
  if (!(v > 0)) return 0;
  const exp = Math.floor(Math.log10(v));
  const base = Math.pow(10, exp);
  const f = v / base;
  let nice;
  if (f <= 1) nice = 1;
  else if (f <= 2) nice = 2;
  else if (f <= 2.5) nice = 2.5;
  else if (f <= 5) nice = 5;
  else nice = 10;
  return nice * base;
}
/* Free deckt straight/stacked über `isBarChart()` ab; Pro-Layouts mit
 * Serien-X-Beschriftung (arc/grouped/horizontal/wave) bzw. vertikalem
 * Y-Achsentitel (arc/grouped/wave) melden sich über die Capability-Hooks. */
const hasXAxisLabelField = (layout) => isBarChart(layout) || cePdEditorExt.layoutHasSeriesAxisXLabelField(layout);
const hasYAxisLabelField = (layout) => isBarChart(layout) || cePdEditorExt.layoutHasYAxisLabelField(layout);

function setAxisYField(attributes, setAttributes, field, value) {
  const n = parseFloat(value);
  if (!isNaN(n) && n >= -1e8 && n <= 1e8) {
    setAttributes({ axisY: { ...(attributes.axisY || {}), [field]: n } });
  }
}

export function AxisPanel({ attributes, setAttributes, layout, bars, openState }) {
  /* Layouts ganz ohne Achsen (z. B. BubblePack): Panel komplett ausblenden. */
  if (cePdEditorExt.layoutHidesAxisPanel(layout)) return null;

  const extSections = cePdEditorExt.renderPanelSections('axis', { attributes, setAttributes, layout });
  /* Layouts mit Wert-Achse (Y = Hoehe): Bar-Layouts; Add-ons koennen weitere
   * Layouts via `layoutHasValueAxisMinMax` als wert-achsig registrieren. */
  const hasValueAxisMinMax = isBarChart(layout) || cePdEditorExt.layoutHasValueAxisMinMax(layout);
  /* Echte raeumliche Achse vorhanden? Bar-Layouts, Ruler-Layouts oder Layouts mit
   * Serien-X-/Y-Achsentitel. Pie/Donut und radiale Ringe haben keine — dort
   * heisst das Panel "Values & units" statt "Axis configuration". */
  const hasSpatialAxis = isBarChart(layout)
    || cePdEditorExt.layoutHasRuler(layout)
    || cePdEditorExt.layoutHasSeriesAxisXLabelField(layout)
    || cePdEditorExt.layoutHasYAxisLabelField(layout);
  const panelTitle = (isPieLayout(layout) || !hasSpatialAxis)
    ? __('Values & units', 'pop3d-charts')
    : __('Axis configuration', 'pop3d-charts');
  /* Pie/Donut nutzt fuer die Geometrie pieAngleBasis (Summe/100%), nicht min/max —
   * "Fit axis to data" haette dort keinen sichtbaren Effekt und bleibt ausgeblendet. */
  const showFitToData = hasValueAxisMinMax;

  /** Leitet min/max der Werteskala aus den aktuellen Zeilenwerten ab. */
  const fitAxisToData = () => {
    const vals = (bars || [])
      .map((b) => Number(b.value))
      .filter((n) => Number.isFinite(n));
    if (vals.length === 0) return;
    const maxV = Math.max(...vals);
    const minV = Math.min(...vals);
    const newMax = maxV > 0 ? niceCeil(maxV) : (maxV === 0 ? 1 : 0);
    const newMin = minV < 0 ? -niceCeil(-minV) : 0;
    setAttributes({ axisY: { ...(attributes.axisY || {}), min: newMin, max: newMax } });
  };

  return el(PanelBody, { title: panelTitle, ...(openState || {}) },
    isPieLayout(layout) ? el(Notice, { status: 'info', isDismissible: false },
      __('Pie: slice sizes use row values. The unit fields below set how values appear in slice labels, tooltips and the data table.', 'pop3d-charts')) : null,

    hasValueAxisMinMax ? el(TextControl, {
      label: __('Y-axis min', 'pop3d-charts'),
      type: 'number',
      value: String((attributes.axisY?.min) ?? 0),
      onChange: (v) => setAxisYField(attributes, setAttributes, 'min', v),
      __nextHasNoMarginBottom: true,
      __next40pxDefaultSize: true,
    }) : null,
    hasValueAxisMinMax ? el(TextControl, {
      label: __('Y-axis max', 'pop3d-charts'),
      type: 'number',
      value: String((attributes.axisY?.max) ?? 100),
      onChange: (v) => setAxisYField(attributes, setAttributes, 'max', v),
      __nextHasNoMarginBottom: true,
      __next40pxDefaultSize: true,
    }) : null,

    showFitToData ? el(Button, {
      variant: 'secondary',
      onClick: fitAxisToData,
      __next40pxDefaultSize: true,
    }, __('Fit axis to data', 'pop3d-charts')) : null,
    showFitToData ? el('p', { style: { marginTop: '4px', marginBottom: '12px', fontSize: '12px', color: '#666' } },
      __('Sets the Y-axis min and max from the current data values.', 'pop3d-charts')) : null,

    el(TextControl, {
      label: __('Unit prefix', 'pop3d-charts'),
      value: (attributes.axisY?.unitPrefix) ?? '',
      onChange: (v) => setAttributes({ axisY: { ...(attributes.axisY || {}), unitPrefix: v } }),
      placeholder: __('e.g. $, £, €', 'pop3d-charts'),
      help: __('Shown before the value.', 'pop3d-charts'),
      __nextHasNoMarginBottom: true,
      __next40pxDefaultSize: true,
    }),
    el(TextControl, {
      label: __('Unit suffix', 'pop3d-charts'),
      value: (attributes.axisY?.unitSuffix) ?? '%',
      onChange: (v) => setAttributes({ axisY: { ...(attributes.axisY || {}), unitSuffix: v } }),
      placeholder: __('e.g. %, pts, k, Mio.', 'pop3d-charts'),
      help: __('Shown after the value.', 'pop3d-charts'),
      __nextHasNoMarginBottom: true,
      __next40pxDefaultSize: true,
    }),

    hasXAxisLabelField(layout) ? el(TextControl, {
      label: __('Series axis label (short)', 'pop3d-charts'),
      help: __('Rendered in the 3D scene at the end of the baseline.', 'pop3d-charts'),
      value: attributes.axisXLabel || '',
      onChange: (v) => setAttributes({ axisXLabel: String(v || '').slice(0, 48) }),
      placeholder: __('e.g. Time, Region, Products', 'pop3d-charts'),
      __nextHasNoMarginBottom: true,
      __next40pxDefaultSize: true,
    }) : null,

    hasYAxisLabelField(layout) ? el(TextControl, {
      label: __('Y-axis title (vertical)', 'pop3d-charts'),
      help: __('Optional. Shown upright beside the value ticks (left of ticks on Straight and Stacked) in 2D and 3D.', 'pop3d-charts'),
      value: attributes.axisYLabel || '',
      onChange: (v) => setAttributes({ axisYLabel: String(v || '').slice(0, 48) }),
      placeholder: __('e.g. Revenue, Share', 'pop3d-charts'),
      __nextHasNoMarginBottom: true,
      __next40pxDefaultSize: true,
    }) : null,

    /* Add-on-Sektionen werden hier eingehaengt, statt in einen eigenen Reiter. */
    ...extSections
  );
}
