import { component$, useStylesScoped$ } from '@builder.io/qwik';

import styles from './styles.css?inline';
import type { DataCellProps, DataCellPropsRenderInit } from './types';

export const DataCell = component$<DataCellProps>(
  ({ as, class: cls, init, render$, ...props }) => {
    useStylesScoped$(styles);

    const { label, value } = init.col;
    const Comp = as === 'td' || as === 'th' ? as : 'td';
    const init2: DataCellPropsRenderInit<typeof Comp> = {
      col: init.col,
      defaultCellProps: {
        class: 'cell',
        ...init?.defaultCellProps,
      },
      defaultProps: {
        ...props,
        'aria-label': label || undefined,
        key: props.key || value,
        title: label || undefined,
        ...init?.defaultProps,
      },
    };

    return render$ ? (
      <>{render$(init2)}</>
    ) : (
      <Comp {...init2.defaultProps} class={[init2.defaultProps?.class, cls]}>
        {value && <div {...init2.defaultCellProps}>{value}</div>}
      </Comp>
    );
  }
);
