import type { ReactNode } from 'react'
import styles from './DomainGuard.module.css'

export interface DomainGuardConfig {
  isAllowedHost: (hostname?: string) => boolean
  getExpectedHost: () => string
  dashboardLabel: string
}

export function createDomainGuard(config: DomainGuardConfig) {
  const { isAllowedHost, getExpectedHost, dashboardLabel } = config

  return function DomainGuard({ children }: { children: ReactNode }) {
    if (isAllowedHost()) {
      return children
    }

    const expectedHost = getExpectedHost()

    return (
      <div className={styles.page}>
        <div className={styles.card}>
          <h1 className={styles.title}>Wrong domain</h1>
          <p className={styles.text}>
            This {dashboardLabel} is only available at <strong>{expectedHost}</strong>.
          </p>
          <p className={styles.hint}>
            Add <code>127.0.0.1 {expectedHost}</code> to your hosts file, then open{' '}
            <code>
              http://{expectedHost}
              {typeof window !== 'undefined' && window.location.port
                ? `:${window.location.port}`
                : ''}
            </code>
            .
          </p>
        </div>
      </div>
    )
  }
}
