import { Component, createMemo } from 'solid-js';
import { ScreenplayElement, TemplateType } from '../../lib/screenplay/types';
import { getStyleForElement, elementTypeClass } from '../../lib/screenplay/format';

export interface PreviewPanelProps {
  elements: ScreenplayElement[];
  template: TemplateType;
}

export const PreviewPanel: Component<PreviewPanelProps> = (props) => {
  const renderedElements = createMemo(() => {
    return props.elements.map((el) => {
      const style = getStyleForElement(el.type, props.template);
      return { element: el, style };
    });
  });

  const getStyle = (el: ScreenplayElement): string => {
    const style = getStyleForElement(el.type, props.template);
    const parts: string[] = [];

    parts.push(`text-align: ${style.textAlign}`);
    parts.push(`padding-left: ${(style.indentStart * 12).toFixed(0)}px`);
    parts.push(`padding-right: ${(style.indentEnd * 12).toFixed(0)}px`);
    parts.push(`margin-bottom: ${(style.marginBottom * 12).toFixed(0)}px`);
    parts.push(`line-height: ${style.lineHeight}`);

    if (style.uppercase) {
      parts.push('text-transform: uppercase');
    }
    if (style.bold) {
      parts.push('font-weight: bold');
    }

    return parts.join('; ');
  };

  return (
    <div class="screenplay-preview">
      <div class="screenplay-page">
        {renderedElements().map(({ element: el, style }) => (
          <div
            class={elementTypeClass(el.type)}
            style={getStyle(el)}
          >
            {el.content.split('\n').map((line, i) => (
              <div class="preview-line" style={i === el.content.split('\n').length - 1 && line.trim() === '' ? 'display: none' : ''}>
                {line}
              </div>
            ))}
          </div>
        ))}
      </div>
    </div>
  );
};

export default PreviewPanel;
