import * as React from 'react';

export type SectionProps = Readonly<React.ComponentPropsWithoutRef<'table'>>;

export const Section = React.forwardRef<HTMLTableElement, SectionProps>(
  ({ children, style = {}, ...props }, ref) => {
    // Split padding styles to improve compatibility with Klaviyo and Outlook,
    // while preserving user-provided style property order without allocating
    // entry arrays on each render.
    const tdStyle: React.CSSProperties = {};
    const tableStyle: React.CSSProperties = {};

    const styleRecord = style as Record<string, unknown>;

    for (const key in styleRecord) {
      if (!Object.hasOwn(styleRecord, key)) {
        continue;
      }

      const value = styleRecord[key];

      if (
        key === 'padding' ||
        key === 'paddingTop' ||
        key === 'paddingRight' ||
        key === 'paddingBottom' ||
        key === 'paddingLeft'
      ) {
        (tdStyle as Record<string, unknown>)[key] = value;
      } else {
        (tableStyle as Record<string, unknown>)[key] = value;
      }
    }

    return (
      <table
        align="center"
        width="100%"
        border={0}
        cellPadding="0"
        cellSpacing="0"
        role="presentation"
        {...props}
        ref={ref}
        style={tableStyle}
      >
        <tbody>
          <tr>
            <td style={tdStyle}>{children}</td>
          </tr>
        </tbody>
      </table>
    );
  },
);

Section.displayName = 'Section';
