import { useState, useEffect } from "react";
import { EVSpec, cars } from "./data";
import Header from "./components/Header";
import Hero from "./components/Hero";
import BrowsePage from "./components/BrowsePage";
import ComparePage from "./components/ComparePage";
import AdminApp from "./admin/AdminApp";
import { Zap, Heart } from "lucide-react";

type View = "home" | "browse" | "compare" | "admin";

function App() {
  const [currentView, setCurrentView] = useState<View>("home");
  const [compareList, setCompareList] = useState<EVSpec[]>([]);

  // Check for admin route
  useEffect(() => {
    const checkAdminRoute = () => {
      if (window.location.hash === '#admin' || window.location.pathname === '/admin') {
        setCurrentView('admin');
      }
    };
    checkAdminRoute();
    window.addEventListener('hashchange', checkAdminRoute);
    return () => window.removeEventListener('hashchange', checkAdminRoute);
  }, []);

  const addToCompare = (ev: EVSpec) => {
    if (compareList.find((c) => c.id === ev.id)) {
      // Remove if already in list
      setCompareList((prev) => prev.filter((c) => c.id !== ev.id));
    } else if (compareList.length < 4) {
      setCompareList((prev) => [...prev, ev]);
    }
  };

  const removeFromCompare = (id: string) => {
    setCompareList((prev) => prev.filter((c) => c.id !== id));
  };

  const navigateToCompare = () => {
    if (compareList.length === 0) {
      // Add first two popular cars as defaults
      setCompareList([cars[0], cars[6]]);
    }
    setCurrentView("compare");
  };

  return (
    <div className="min-h-screen bg-gray-50 flex flex-col">
      {/* Skip to main content for accessibility */}
      <a href="#main-content" className="skip-link">
        Skip to main content
      </a>
      <Header currentView={currentView} onNavigate={setCurrentView} />

      {/* Floating compare bar */}
      {compareList.length > 0 && currentView !== "compare" && (
        <div className="fixed bottom-6 left-1/2 -translate-x-1/2 z-50 bg-white border border-gray-200 rounded-2xl shadow-2xl px-5 py-3 flex items-center gap-4">
          <div className="flex -space-x-2">
            {compareList.map((ev) => (
              <div
                key={ev.id}
                className="w-9 h-9 rounded-full border-2 border-white overflow-hidden bg-gray-100"
              >
                <img
                  src={ev.image}
                  alt={`${ev.brand} ${ev.name}`}
                  width={36}
                  height={36}
                  loading="lazy"
                  decoding="async"
                  className="w-full h-full object-cover"
                  onError={(e) => {
                    (e.target as HTMLImageElement).src = `https://placehold.co/100x100/e2e8f0/64748b?text=${ev.brand[0]}`;
                  }}
                />
              </div>
            ))}
          </div>
          <span className="text-sm text-gray-600">
            <span className="font-semibold text-gray-900">{compareList.length}</span> vehicle{compareList.length > 1 ? "s" : ""} selected
          </span>
          <button
            onClick={navigateToCompare}
            aria-label={`Compare ${compareList.length} selected vehicles side by side`}
            className="bg-gradient-to-r from-emerald-500 to-teal-600 text-white px-4 py-2 rounded-xl text-sm font-semibold hover:shadow-lg transition-shadow"
          >
            Compare Now
          </button>
          <button
            onClick={() => setCompareList([])}
            aria-label="Clear all vehicles from comparison"
            className="text-gray-400 hover:text-red-500 text-xs transition-colors"
          >
            Clear
          </button>
        </div>
      )}

      <main id="main-content" className="flex-1">
        {currentView === "home" && (
          <>
            <Hero
              onStartCompare={navigateToCompare}
              onBrowse={() => setCurrentView("browse")}
            />
            {/* Popular comparisons section */}
            <section className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-20">
              <div className="text-center mb-12">
                <h2 className="text-3xl font-bold text-gray-900 mb-3">Popular Comparisons</h2>
                <p className="text-gray-600">See how the most popular EVs stack up against each other</p>
              </div>
              <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                {[
                  [cars[0], cars[6]], // Model 3 vs Ioniq 5
                  [cars[1], cars[9]], // Model Y vs Mach-E
                  [cars[5], cars[15]], // Taycan vs Polestar 2
                  [cars[7], cars[8]], // Ioniq 6 vs EV6
                  [cars[3], cars[13]], // BMW iX vs Audi Q8
                  [cars[11], cars[2]], // EQS vs Model S
                ].map(([a, b], idx) => (
                  <button
                    key={idx}
                    onClick={() => {
                      setCompareList([a, b]);
                      setCurrentView("compare");
                    }}
                    className="group bg-white border border-gray-100 rounded-2xl p-4 flex items-center gap-3 hover:shadow-lg hover:border-gray-200 transition-all text-left"
                  >
                    <div className="flex -space-x-3 flex-shrink-0">
                      <div className="w-14 h-14 rounded-xl overflow-hidden border-2 border-white bg-gray-100">
                        <img
                          src={a.image}
                          alt={`${a.brand} ${a.name}`}
                          width={56}
                          height={56}
                          loading="lazy"
                          decoding="async"
                          className="w-full h-full object-cover"
                          onError={(e) => {
                            (e.target as HTMLImageElement).src = `https://placehold.co/200x200/e2e8f0/64748b?text=${a.brand[0]}`;
                          }}
                        />
                      </div>
                      <div className="w-14 h-14 rounded-xl overflow-hidden border-2 border-white bg-gray-100">
                        <img
                          src={b.image}
                          alt={`${b.brand} ${b.name}`}
                          width={56}
                          height={56}
                          loading="lazy"
                          decoding="async"
                          className="w-full h-full object-cover"
                          onError={(e) => {
                            (e.target as HTMLImageElement).src = `https://placehold.co/200x200/e2e8f0/64748b?text=${b.brand[0]}`;
                          }}
                        />
                      </div>
                    </div>
                    <div className="flex-1 min-w-0">
                      <p className="text-sm font-semibold text-gray-900 truncate">
                        {a.brand} {a.name}
                      </p>
                      <p className="text-xs text-gray-400 my-0.5">vs</p>
                      <p className="text-sm font-semibold text-gray-900 truncate">
                        {b.brand} {b.name}
                      </p>
                    </div>
                    <div className="text-emerald-500 opacity-0 group-hover:opacity-100 transition-opacity">
                      →
                    </div>
                  </button>
                ))}
              </div>
            </section>

            {/* Stats section */}
            <section className="bg-gradient-to-br from-emerald-500 to-teal-600 py-16">
              <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
                <div className="grid grid-cols-2 md:grid-cols-4 gap-8 text-center">
                  <div>
                    <p className="text-4xl font-bold text-white">{cars.length}</p>
                    <p className="text-emerald-100 text-sm mt-1">Electric Vehicles</p>
                  </div>
                  <div>
                    <p className="text-4xl font-bold text-white">
                      {new Set(cars.map((e) => e.brand)).size}
                    </p>
                    <p className="text-emerald-100 text-sm mt-1">Brands</p>
                  </div>
                  <div>
                    <p className="text-4xl font-bold text-white">
                      {Math.max(...cars.map((e) => e.range))}
                    </p>
                    <p className="text-emerald-100 text-sm mt-1">Max Range (km)</p>
                  </div>
                  <div>
                    <p className="text-4xl font-bold text-white">
                      {Math.max(...cars.map((e) => e.chargingDC))}
                    </p>
                    <p className="text-emerald-100 text-sm mt-1">Max DC Charge (kW)</p>
                  </div>
                </div>
              </div>
            </section>

            {/* CTA section */}
            <section className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-20 text-center">
              <h2 className="text-3xl font-bold text-gray-900 mb-4">
                Ready to find your perfect EV?
              </h2>
              <p className="text-gray-600 max-w-xl mx-auto mb-8">
                Use our comparison tool to see detailed specs, performance data, and charging 
                information for every electric vehicle in our database.
              </p>
              <div className="flex flex-col sm:flex-row items-center justify-center gap-4">
                <button
                  onClick={() => setCurrentView("browse")}
                  className="bg-gradient-to-r from-emerald-500 to-teal-600 text-white px-8 py-4 rounded-2xl font-semibold shadow-lg shadow-emerald-200 hover:shadow-xl hover:shadow-emerald-300 transition-all hover:-translate-y-0.5"
                >
                  Browse All EVs
                </button>
                <button
                  onClick={navigateToCompare}
                  className="bg-white text-gray-700 px-8 py-4 rounded-2xl font-semibold border border-gray-200 hover:border-gray-300 hover:shadow-md transition-all"
                >
                  Start Comparing
                </button>
              </div>
            </section>
          </>
        )}

        {currentView === "browse" && (
          <BrowsePage
            compareList={compareList}
            onAddToCompare={addToCompare}
            onRemoveFromCompare={removeFromCompare}
          />
        )}

        {currentView === "compare" && (
          <ComparePage
            compareList={compareList}
            onAddToCompare={addToCompare}
            onRemoveFromCompare={removeFromCompare}
          />
        )}

        {currentView === "admin" && (
          <div className="fixed inset-0 z-50 bg-gray-50 overflow-auto">
            <AdminApp />
          </div>
        )}
      </main>

      {/* Footer */}
      <footer className="bg-white border-t border-gray-100 py-8 mt-auto">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="flex flex-col md:flex-row items-center justify-between gap-4">
            <div className="flex items-center gap-2">
              <div className="w-7 h-7 bg-gradient-to-br from-emerald-400 to-teal-600 rounded-lg flex items-center justify-center">
                <Zap className="w-4 h-4 text-white" fill="white" />
              </div>
              <span className="font-bold text-gray-900">E-cars Compare</span>
            </div>
            <p className="text-sm text-gray-500">
              Dedicated to helping you find the perfect electric vehicle.
            </p>
            <p className="text-sm text-gray-400">
              Built with <Heart className="w-3.5 h-3.5 inline text-red-400" fill="currentColor" /> for EV enthusiasts
            </p>
          </div>
        </div>
      </footer>
    </div>
  );
}

export default App;
