import * as React from 'react';
import {Link} from 'gatsby';

function Breadcrumbs({location}) {
    const paths = location.split('/').filter((i) => i);
    const getBreadcrumbTitle = (name) =>
        name
            .replaceAll('-', ' ')
            .replaceAll(/(^\w{1})|(\s+\w{1})/g, (letter) => letter.toUpperCase());
    return (
        <nav className="breadcrumb" aria-label="Breadcrumb">
            <ol className="breadcrumb__list">
                <li className="breadcrumb__item">
                    <Link className="breadcrumb__link" to="/">
                        Home
                    </Link>
                    <span className="breadcrumb__separator" aria-hidden="true"/>
                </li>
                {paths.map((path, i) => (
                    <li key={i} className="breadcrumb__item">
                        {paths.length > i + 1 ? (
                            <>
                                <Link className="breadcrumb__link" to={`/${path}`}>
                                    {getBreadcrumbTitle(path)}
                                </Link>
                                <span className="breadcrumb__separator" aria-hidden="true"/>
                            </>
                        ) : (
                            <div className="breadcrumb__link">{getBreadcrumbTitle(path)}</div>
                        )}
                    </li>
                ))}
            </ol>
        </nav>
    );
}

export default Breadcrumbs;
