<script>
// @flow
/** @jsx h */
import { isObject } from 'utils';

export default {
  name: 'TaoServiceCard',
  functional: true,
  props: {
    icon: {
      type: String,
      default: '',
    },
    title: {
      type: String,
      default: '',
    },
    subtitle: {
      type: String,
      default: '',
    },
    to: {
      type: [String, Object],
      default: '',
    },
    disabled: {
      type: Boolean,
      default: false,
    },
    isRouter: {
      type: Boolean,
      default: () => null,
    },
  },
  render(h: Function, { props, data }: Functional) {
    let HTTP_START = false;
    let WWW_START = false;

    if (!isObject(props.to)) {
      HTTP_START = props.to.startsWith('http://') || props.to.startsWith('https://');
      WWW_START = props.to.startsWith('www.');
    }

    const hostnameRegex = new RegExp(window.location.hostname);
    const linkIsntHostname = !hostnameRegex.test(props.to);
    const isExternalLink = props.isRouter !== null
      ? !props.isRouter
      : (WWW_START || HTTP_START) && linkIsntHostname;


    const renderData = {
      class: {
        'bg-white rounded shadow-large border-thin-default': true, // UI
        'inline-block cursor-pointer user-select-none relative text-center': true, // UTILS
        'px-2 py-3': true, // PADDING
        'tao__service-card': true,
      },
      attrs: {
        disabled: props.disabled,
        draggable: false,
      },
    };

    const iconClass = 'text-brand-darker opacity-high-max';
    const titleClass = 'service-card__title text-brand-darker my-1 font-medium';
    const subtitleClass = 'service-card__subtitle text-02 font-medium overflow-hidden';

    if ((props.isRouter || !isExternalLink) && props.to) {
      return (
        <router-link
          {...data}
          {...renderData}
          to={ props.to }
          append>
          <tao-large-icon
            class={ iconClass }
            size={ 5 }
            name={ props.icon }
          />
          <h2
            class={ titleClass }>
            { props.title }
          </h2>
          <p
            class={ subtitleClass }>
            { props.subtitle }
          </p>
        </router-link>
      );
    }
    return (
      <a
        {...data}
        {...renderData}
        href={ props.to || '#' }>
        <tao-large-icon
          class={ iconClass }
          size={ 5 }
          name={ props.icon }
        />
        <h2
          class={ titleClass }>
          { props.title }
        </h2>
        <p
          class={ subtitleClass }>
          { props.subtitle }
        </p>
      </a>
    );
  },
};
</script>
