import { css, customElement, GenesisElement, html, observable } from '@genesislcap/web-core';
import DOMPurify from 'dompurify';
import { marked } from 'marked';

const styles = css`
  :host {
    display: block;
    font-size: var(--type-ramp-base-font-size);
    line-height: var(--type-ramp-base-line-height);
  }

  p {
    margin: 0 0 calc(var(--design-unit, 4) * 2px);
  }

  p:last-child {
    margin-bottom: 0;
  }

  ul,
  ol {
    margin: 0 0 calc(var(--design-unit, 4) * 2px);
    padding-left: calc(var(--design-unit, 4) * 5px);
  }

  code {
    background-color: var(--neutral-fill-rest);
    padding: 2px 4px;
    border-radius: calc(var(--design-unit, 4) * 0.5px);
    font-family: monospace;
  }

  pre {
    background-color: var(--neutral-fill-rest);
    padding: calc(var(--design-unit, 4) * 2px);
    border-radius: calc(var(--design-unit, 4) * 1px);
    overflow-x: auto;
    border: 1px solid var(--neutral-stroke-rest);
    margin: calc(var(--design-unit, 4) * 2px) 0;
  }

  pre code {
    background-color: transparent;
    padding: 0;
    border-radius: 0;
    border: none;
    font-family: inherit;
    color: inherit;
  }

  table {
    display: block;
    overflow-x: auto;
    border-collapse: collapse;
    max-width: 100%;
    margin: calc(var(--design-unit, 4) * 2px) 0;
  }

  th,
  td {
    border: 1px solid var(--neutral-stroke-rest);
    padding: calc(var(--design-unit, 4) * 1px) calc(var(--design-unit, 4) * 2.5px);
    white-space: nowrap;
  }

  th {
    background-color: var(--neutral-fill-stealth-rest);
    font-weight: 600;
  }
`;

@customElement({
  name: 'ai-chat-markdown',
  template: html<AiChatMarkdown>`
    <div :innerHTML="${(x) => x.renderMarkdown()}"></div>
  `,
  styles,
})
export class AiChatMarkdown extends GenesisElement {
  /** The markdown string to render. */
  @observable content: string = '';

  /** @internal */
  renderMarkdown() {
    if (!this.content) return '';
    const rawHtml = marked.parse(this.content) as string;
    return DOMPurify.sanitize(rawHtml);
  }
}
