import React from 'react';
import { Breadcrumbs as MantineBreadcrumbs, Anchor } from '@mantine/core';
import { useLocation, useNavigate } from 'react-router-dom';

const Breadcrumbs: React.FC = () => {
  const location = useLocation();
  const navigate = useNavigate();

  const pathSegments = location.pathname.split('/').filter(Boolean);
  
  const breadcrumbItems = [
    { label: 'Home', path: '/' },
    ...pathSegments.map((segment, index) => {
      const path = '/' + pathSegments.slice(0, index + 1).join('/');
      let label = segment;
      
      // Convert common path segments to readable labels
      if (segment === 'app') {
        label = 'Applications';
      } else if (segment === 'demo') {
        label = 'Demo App';
      } else if (segment === 'analytics') {
        label = 'Analytics';
      } else {
        // Capitalize first letter and replace hyphens/underscores with spaces
        label = segment.charAt(0).toUpperCase() + segment.slice(1).replace(/[-_]/g, ' ');
      }
      
      return { label, path };
    }),
  ];

  // Remove duplicates and empty segments
  const uniqueBreadcrumbs = breadcrumbItems.filter((item, index, arr) => 
    item.path !== '/' || index === 0
  );

  if (uniqueBreadcrumbs.length <= 1) {
    return null;
  }

  return (
    <MantineBreadcrumbs separator=">" separatorMargin="md" mt="xs">
      {uniqueBreadcrumbs.map((item, index) => (
        <Anchor
          key={item.path}
          onClick={() => navigate(item.path)}
          c={index === uniqueBreadcrumbs.length - 1 ? 'dimmed' : 'blue'}
          style={{
            cursor: index === uniqueBreadcrumbs.length - 1 ? 'default' : 'pointer',
            textDecoration: 'none',
          }}
        >
          {item.label}
        </Anchor>
      ))}
    </MantineBreadcrumbs>
  );
};

export default Breadcrumbs;