import { pug } from 'startupjs'
import { Sandbox } from '@startupjs/docs'
import { Div, Button, Span, TextInput } from '@startupjs/ui'
import { Recaptcha } from '@startupjs/recaptcha'
import { useState, useRef } from 'react'
import axios from 'axios'
import './index.styl'

# @startupjs/recaptcha

library for displaying and interacting with [Google ReCaptcha](https://www.google.com/recaptcha/about/)

## Install the module

`yarn add @startupjs/recaptcha`

## Init module on server

Add the following lines to `server/index.js`:
```js
  import { initRecaptcha } from '@startupjs/recaptcha/server'
```
Add to the `startupjsServer` function:
```js
  initRecaptcha(ee, options)
```
The `options` argument accepts an object with a `type` field, that specify which [reCAPTCHA type](https://www.google.com/recaptcha/about) you want to use (possible types: `enterprise` or `v3`)

In the `getHead` function, add a call to the `getRecaptchaHead` function:

```js
  import { getRecaptchaHead } from '@startupjs/recaptcha/server'

  function getHead (req) {
    return `
      // ...
      ${getRecaptchaHead(req)}
      // ...
    `
}
```

## Configuring config.json

In `config.json` file of your project, you need to add for **reCAPTCHA Enterprise**:

```js
  {
    "RECAPTCHA_SECRET_KEY": "YOUR_SECRET_KEY",
    "RECAPTCHA_ENTERPRISE_NORMAL_SITE_KEY": "YOUR_SITE_KEY",
    "RECAPTCHA_ENTERPRISE_INVISIBLE_SITE_KEY": "YOUR_SITE_KEY",
    "GOOGLE_CLOUD_PROJECT_ID": "ID_YOUR_CLOUD_PROJECT"
  }
```
`RECAPTCHA_SECRET_KEY` created here https://console.cloud.google.com/apis/credentials
`RECAPTCHA_ENTERPRISE_NORMAL_SITE_KEY` и `RECAPTCHA_ENTERPRISE_INVISIBLE_SITE_KEY` - https://cloud.google.com/recaptcha-enterprise/docs/create-key

For **reCAPTCHA v3**, it will be enough:
```js
  {
    "RECAPTCHA_SECRET_KEY": "YOUR_SECRET_KEY",
    "RECAPTCHA_SITE_KEY": "YOUR_SITE_KEY"
  }
```
These keys are created in the [Google Admin Console](https://www.google.com/recaptcha/admin/).

## Usage

### Client

```jsx
  import { Recaptcha } from '@startupjs/recaptcha'
```

```jsx example
  const [recaptchaVerified, setRecaptchaVerified] = useState(false)
  const [email, setEmail] = useState('')

  const ref = useRef()

  const openRecaptcha = () => {
    if (!email) return

    ref.current.open()
  }

  const onVerify = async recaptcha => {
    try {
      const res = await axios.post('/api/subscribe-to-mailing', {
        recaptcha,
        email
      })
      console.log('Response: ', res.data)
      setRecaptchaVerified(res.data)
    } catch (err) {
      console.error(err.response.data)
    }
  }

  return pug`
    Div.root
      TextInput.emailInput(
        label='Your email'
        value=email
        onChangeText=setEmail
      )
      Recaptcha(
        ref=ref
        onVerify=onVerify
        onLoad=() => console.log('onLoad')
        onExpire=() => console.log('onExpire')
        onError=error => console.log('onError', error)
        onClose=() => console.log('onClose')
      )
      if recaptchaVerified
        Span.label Thank you for subscribing
      Button(
        onPress=openRecaptcha
        disabled=recaptchaVerified
      ) Subscribe
  `
```

### Server
```js
import { checkRecaptcha } from '@startupjs/recaptcha/server'

export default function initRoutes (router) {
  router.post('/api/subscribe-to-mailing', async function (req, res) {
    const { recaptcha, email } = req.body

    const isVerified = await checkRecaptcha(recaptcha)

    if (!isVerified) {
      return res.status(403).send(isVerified)
    }

    // Do something with email subscription...
  })
}
```

## Recaptcha component props

The `Recaptcha` component takes parameters from [official Google reCAPTCHA documentation](https://developers.google.com/recaptcha/docs/invisible#config)

 - `variant` [String] - The variant of the widget (`invisible`, `normal` or `compact`). Default: `invisible`
 - `theme` [String] - The color theme of the widget (`dark` or `light`). Default: `light`
 - `baseUrl` [String] - The URL (domain) configured in the reCAPTCHA setup. (ex. `http://my.domain.com`). Default: your `BASE_URL` from `@env`
 - `lang` [String] - [Language code](https://developers.google.com/recaptcha/docs/language). Default: `en`
 - `onLoad` [Function] - A callback function, executed when the reCAPTCHA is ready to use
 - `onVerify` [Function(token)] - A callback function, executed when the user submits a successful response. The recaptcha response token is passed to your callback
 - `onExpire` [Function] - A callback function, executed when the reCAPTCHA response expires and the user needs to re-verify
 - `onError` [Function(error)] - A callback function, executed when reCAPTCHA encounters an error (usually network connectivity) and cannot continue until connectivity is restored. If you specify a function here, you are responsible for informing the user that they should retry
 - `onClose` [Function] - (Experimental) A callback function, executed when the Modal is closed

## Advanced use

```js
  import { checkDataRecaptcha } from '@startupjs/recaptcha/server'
```

`checkDataRecaptcha(recaptcha)` is an advanced variant of `checkRecaptcha(recaptcha)` function that returns an object with the original Google API response. Different reCAPTCHA types return different data structures in the response.
