import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
import { LanguageProvider } from './context/LanguageContext';
import Navbar from './components/Navbar';
import Footer from './components/Footer';
import ScrollToTop from './components/ScrollToTop';
import Home from './pages/Home';
import Pricing from './pages/Pricing';
import Login from './pages/Login';
import Register from './pages/Register';
import VerifyEmail from './pages/VerifyEmail';
import RegistrationSuccess from './pages/RegistrationSuccess';
import Payment from './pages/Payment';
import PaymentSuccess from './pages/PaymentSuccess';
import PaymentCancel from './pages/PaymentCancel';
import About from './pages/About';
import AiTrends from './pages/AiTrends';
import ImageGeneration from './pages/ImageGeneration';
import Analytics from './pages/Analytics';
import BrandGrowth from './pages/BrandGrowth';
import Contact from './pages/Contact';
import Terms from './pages/Terms';
import Privacy from './pages/Privacy';
import { useState, useEffect } from 'react';
import { API_HOST } from './config';

function App() {
  const [pricingData, setPricingData] = useState(null);
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    const fetchPricingData = async () => {
      try {
        const response = await fetch(`${API_HOST}/api/v1/onboard/products`);
        if (!response.ok) throw new Error('Failed to fetch products');
        const data = await response.json();
        
        // Transform API data to match UI requirements
        const transformedProducts = data.map(product => ({
          name: product.name,
          prices: {
            monthly: product.prices.monthly,
            yearly: product.prices.yearly,
            monthlyPriceId: product.prices.monthly_price_id,
            yearlyPriceId: product.prices.yearly_price_id
          },
          features: product.features,
          description: product.description,
          popular: product.metadata?.is_popular === "true",
          maxUsers: product.max_users,
          storageLimit: product.storage_limit,
          apiRateLimit: product.api_rate_limit,
          supportTier: product.support_tier,
          customDomain: product.custom_domain
        }));
        
        setPricingData(transformedProducts);
      } catch (error) {
        console.error('Error fetching products:', error);
        // Set fallback pricing data
        setPricingData([
          {
            name: 'Starter',
            prices: { monthly: 29, yearly: 290 },
            features: [
              'Basic AI trend analysis',
              '25 AI image generations/month',
              'Basic analytics dashboard',
              'Content calendar',
              'Email support',
              'Single user'
            ],
          },
          // ... other fallback plans
        ]);
      } finally {
        setIsLoading(false);
      }
    };

    fetchPricingData();
  }, []);

  return (
    <LanguageProvider>
      <Router>
        <ScrollToTop />
        <div className="min-h-screen bg-white">
          <Navbar />
          <Routes>
            <Route path="/" element={<Home />} />
            <Route path="/pricing" element={<Pricing pricingData={pricingData} isLoading={isLoading} />} />
            <Route path="/login" element={<Login />} />
            <Route path="/register" element={<Register pricingData={pricingData} />} />
            <Route path="/verify-email" element={<VerifyEmail />} />
            <Route path="/registration-success" element={<RegistrationSuccess />} />
            <Route path="/payment" element={<Payment pricingData={pricingData} />} />
            <Route path="/payment/success" element={<PaymentSuccess />} />
            <Route path="/payment/cancel" element={<PaymentCancel />} />
            <Route path="/about" element={<About />} />
            <Route path="/ai-trends" element={<AiTrends />} />
            <Route path="/image-generation" element={<ImageGeneration />} />
            <Route path="/analytics" element={<Analytics />} />
            <Route path="/brand-growth" element={<BrandGrowth />} />
            <Route path="/contact" element={<Contact />} />
            <Route path="/terms" element={<Terms />} />
            <Route path="/privacy" element={<Privacy />} />
          </Routes>
        </div>
      </Router>
    </LanguageProvider>
  );
}

export default App;
