// From https://www.gatsbyjs.com/docs/reference/built-in-components/gatsby-link/

import React from "react"
import { graphql, useStaticQuery, Link as GatsbyLink } from "gatsby"

interface Props {
    children?: React.ReactNode
    to: string
    activeClassName?: string
    partiallyActive?: any
    onClick?: any
    className?: any
}

// Since DOM elements <a> cannot receive activeClassName
// and partiallyActive, destructure the prop here and
// pass it only to GatsbyLink
const Link = ({
    children,
    to,
    activeClassName,
    partiallyActive,
    onClick,
    className,
    ...other
}: Props) => {
    // Basé sur les données de l'API GraphQL = liste des pages
    const data = useStaticQuery(graphql`
        query appPages {
            allSitePage {
                nodes {
                    path
                }
            }
        }
    `)

    // /^https?:\/\//
    // Si "to" n'est pas dans la liste des pages, c'est un lien externe
    // ignore le "/" à la fin du 'path' et de 'to'
    const internal = data.allSitePage.nodes.find(
        ({ path }) => path.replace(/\/+$/, "") === to.replace(/\/+$/, "")
    )

    // Use Gatsby Link for internal links, and <a> for others
    if (internal) {
        // console.log("Internal", to)
        return (
            <GatsbyLink
                to={to}
                activeClassName={activeClassName}
                partiallyActive={partiallyActive}
                onClick={onClick}
                className={className}
                {...other}
            >
                {children}
            </GatsbyLink>
        )
    }

    // console.log("External", to)
    return (
        <a href={to} {...other} onClick={onClick} className={className}>
            {children}
        </a>
    )
}

export default Link