/**
 * Panel "Import/Export" — Daten importieren (Modal) und als JSON/CSV exportieren.
 */

import { useImportDataModal } from '../import/useImportDataModal.js';
import { exportBarsAsCsv, downloadTextFile } from '../dataIO.js';

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

export function ImportExportPanel({ bars, setAttributes, openState }) {
  const { importModalElement, openImportModal } = useImportDataModal({ setAttributes });

  const exportBarsJson = () => downloadTextFile('ce-diagram-data.json', JSON.stringify(bars, null, 2), 'application/json;charset=utf-8');
  const exportBarsCsv = () => downloadTextFile('ce-diagram-data.csv', exportBarsAsCsv(bars), 'text/csv;charset=utf-8');

  return el(PanelBody, { title: __('Import / Export', 'pop3d-charts'), ...(openState || {}) },
    el('p', { style: { marginBottom: '0.75rem', color: '#666', fontSize: '12px' } },
      __('Import rows from Excel, Google Sheets, CSV, or JSON. Paste or upload a file in the dialog — column headers are detected automatically.', 'pop3d-charts')),
    el('div', { style: { display: 'flex', gap: '8px', marginBottom: '1rem', flexWrap: 'wrap' } },
      el(Button, { variant: 'primary', onClick: openImportModal }, __('Import data', 'pop3d-charts'))
    ),
    el('p', { style: { marginBottom: '0.5rem', marginTop: '0.5rem', color: '#666', fontSize: '12px' } },
      __('Download current rows for backup or editing in a spreadsheet.', 'pop3d-charts')),
    el('div', { style: { display: 'flex', gap: '8px', flexWrap: 'wrap' } },
      el(Button, { variant: 'secondary', isSmall: true, onClick: exportBarsJson }, __('Export JSON', 'pop3d-charts')),
      el(Button, { variant: 'secondary', isSmall: true, onClick: exportBarsCsv }, __('Export CSV', 'pop3d-charts'))
    ),
    importModalElement
  );
}
