// React Router Configuration for Subdirectory Deployment
// This file provides the necessary configuration for React Router to work in a subdirectory

import { createBrowserRouter, createHashRouter } from 'react-router-dom';

// Configuration constants
export const SUBDIRECTORY_PATH = '/music'; // Change this to your subdirectory
export const API_BASE_URL = `${SUBDIRECTORY_PATH}/api`;
export const PUBLIC_URL = SUBDIRECTORY_PATH;

// Router configuration for subdirectory deployment
export const createSubdirectoryRouter = (routes, options = {}) => {
  const {
    useHashRouter = false, // Set to true if you prefer hash routing
    basename = SUBDIRECTORY_PATH
  } = options;

  if (useHashRouter) {
    // Hash router - works without server configuration
    // URLs will be like: domain.com/music/#/page
    return createHashRouter(routes);
  } else {
    // Browser router - requires server configuration (recommended)
    // URLs will be like: domain.com/music/page
    return createBrowserRouter(routes, {
      basename: basename
    });
  }
};

// Utility function to build URLs with subdirectory prefix
export const buildUrl = (path = '') => {
  // Remove leading slash if present
  const cleanPath = path.startsWith('/') ? path.slice(1) : path;
  
  // Build full URL with subdirectory
  if (cleanPath) {
    return `${SUBDIRECTORY_PATH}/${cleanPath}`;
  }
  return SUBDIRECTORY_PATH;
};

// Utility function to build API URLs
export const buildApiUrl = (endpoint = '') => {
  // Remove leading slash if present
  const cleanEndpoint = endpoint.startsWith('/') ? endpoint.slice(1) : endpoint;
  
  // Build full API URL
  if (cleanEndpoint) {
    return `${API_BASE_URL}/${cleanEndpoint}`;
  }
  return API_BASE_URL;
};

// Navigation helper for programmatic navigation
export const navigateToSubdirectory = (navigate, path = '') => {
  const fullPath = buildUrl(path);
  navigate(fullPath);
};

// Link component wrapper for subdirectory links
export const SubdirectoryLink = ({ to, children, ...props }) => {
  const fullPath = buildUrl(to);
  return (
    <Link to={fullPath} {...props}>
      {children}
    </Link>
  );
};

// Example route configuration for subdirectory deployment
export const createAppRoutes = () => [
  {
    path: '/',
    element: <Layout />,
    children: [
      {
        index: true,
        element: <HomePage />
      },
      {
        path: 'create',
        element: <CreatePage />
      },
      {
        path: 'dashboard',
        element: <DashboardPage />
      },
      {
        path: 'pricing',
        element: <PricingPage />
      },
      {
        path: 'auth/login',
        element: <LoginPage />
      },
      {
        path: 'auth/register',
        element: <RegisterPage />
      },
      {
        path: '*',
        element: <NotFoundPage />
      }
    ]
  }
];

// Environment detection
export const getEnvironmentConfig = () => {
  const isProduction = import.meta.env.PROD;
  const isDevelopment = import.meta.env.DEV;
  
  return {
    isProduction,
    isDevelopment,
    apiBaseUrl: isProduction ? API_BASE_URL : 'http://localhost:3001/api',
    publicUrl: isProduction ? PUBLIC_URL : '',
    subdirectoryPath: isProduction ? SUBDIRECTORY_PATH : ''
  };
};

// Asset URL helper for subdirectory deployment
export const getAssetUrl = (assetPath) => {
  const env = getEnvironmentConfig();
  
  if (env.isDevelopment) {
    return assetPath;
  }
  
  // In production, prepend the subdirectory path
  const cleanPath = assetPath.startsWith('/') ? assetPath.slice(1) : assetPath;
  return `${SUBDIRECTORY_PATH}/${cleanPath}`;
};

// Example App.jsx configuration for subdirectory deployment
export const AppConfigExample = `
import React from 'react';
import { RouterProvider } from 'react-router-dom';
import { createSubdirectoryRouter, createAppRoutes } from './config/router-config';

// Import your components
import Layout from './components/Layout';
import HomePage from './pages/HomePage';
import CreatePage from './pages/CreatePage';
// ... other imports

const router = createSubdirectoryRouter(createAppRoutes(), {
  useHashRouter: false, // Set to true if you prefer hash routing
  basename: '/music' // Your subdirectory path
});

function App() {
  return (
    <div className="App">
      <RouterProvider router={router} />
    </div>
  );
}

export default App;
`;

// Example service configuration for API calls
export const ServiceConfigExample = `
import axios from 'axios';
import { buildApiUrl, getEnvironmentConfig } from './config/router-config';

const env = getEnvironmentConfig();

// Create axios instance with subdirectory-aware base URL
const api = axios.create({
  baseURL: env.apiBaseUrl,
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  }
});

// Example service methods
export const musicService = {
  // Create song from vision board
  createSong: async (visionBoardData) => {
    const response = await api.post('/songs/create', visionBoardData);
    return response.data;
  },
  
  // Get song status
  getSongStatus: async (songId) => {
    const response = await api.get(\`/songs/\${songId}/status\`);
    return response.data;
  },
  
  // Upload vision board images
  uploadVisionBoard: async (files) => {
    const formData = new FormData();
    files.forEach((file, index) => {
      formData.append(\`image\${index}\`, file);
    });
    
    const response = await api.post('/upload/vision-board', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    });
    return response.data;
  }
};
`;

// Example component with subdirectory-aware navigation
export const ComponentExample = `
import React from 'react';
import { useNavigate, Link } from 'react-router-dom';
import { navigateToSubdirectory, buildUrl } from './config/router-config';

const Navigation = () => {
  const navigate = useNavigate();
  
  const handleNavigation = (path) => {
    navigateToSubdirectory(navigate, path);
  };
  
  return (
    <nav>
      <Link to={buildUrl('/')}>Home</Link>
      <Link to={buildUrl('/create')}>Create</Link>
      <Link to={buildUrl('/dashboard')}>Dashboard</Link>
      <button onClick={() => handleNavigation('/pricing')}>
        Pricing
      </button>
    </nav>
  );
};

export default Navigation;
`;

export default {
  SUBDIRECTORY_PATH,
  API_BASE_URL,
  PUBLIC_URL,
  createSubdirectoryRouter,
  buildUrl,
  buildApiUrl,
  navigateToSubdirectory,
  getEnvironmentConfig,
  getAssetUrl,
  createAppRoutes
};

