
import React, { useState } from 'react';
import ReactDOM from 'react-dom/client';
import { 
  Car, 
  Phone, 
  ShieldCheck, 
  ArrowRight, 
  Menu, 
  X,
  Facebook,
  Twitter,
  Instagram,
  Clock,
  MapPin,
  IndianRupee,
  Shield,
  Play,
  Loader2,
  AlertCircle,
  Sparkles
} from 'lucide-react';
import { GoogleGenAI } from "@google/genai";

// --- TYPES ---

interface CarModel {
  name: string;
  category: 'Hatchback' | 'Sedan' | 'SUV' | 'Luxury';
  image: string;
}

interface Feature {
  title: string;
  description: string;
  icon: React.ReactNode;
}

enum VideoStatus {
  IDLE = 'IDLE',
  CHECKING_KEY = 'CHECKING_KEY',
  GENERATING = 'GENERATING',
  COMPLETED = 'COMPLETED',
  ERROR = 'ERROR'
}

// Accessing window properties through type casting for browser-side Babel compatibility
const aistudio = (window as any).aistudio;

// --- CONSTANTS ---

const BOOKING_NUMBER = "7530009998";

const CAR_MODELS: CarModel[] = [
  { name: 'Swift', category: 'Hatchback', image: 'https://images.unsplash.com/photo-1590362891991-f776e747a588?auto=format&fit=crop&q=80&w=400' },
  { name: 'Etios', category: 'Sedan', image: 'https://images.unsplash.com/photo-1549317661-bd32c8ce0db2?auto=format&fit=crop&q=80&w=400' },
  { name: 'Innova', category: 'SUV', image: 'https://images.unsplash.com/photo-1533473359331-0135ef1b58bf?auto=format&fit=crop&q=80&w=400' },
  { name: 'Xylo', category: 'SUV', image: 'https://images.unsplash.com/photo-1552519507-da3b142c6e3d?auto=format&fit=crop&q=80&w=400' },
  { name: 'Desire', category: 'Sedan', image: 'https://images.unsplash.com/photo-1583121274602-3e2820bc49dd?auto=format&fit=crop&q=80&w=400' },
  { name: 'Tavera', category: 'SUV', image: 'https://images.unsplash.com/photo-1541899481282-d53bffe3c35d?auto=format&fit=crop&q=80&w=400' },
];

const FEATURES: Feature[] = [
  {
    title: 'One-Way Fares',
    description: 'Only pay for the distance you travel. No return charges. Save up to 40% on every trip.',
    icon: <IndianRupee className="w-6 h-6 text-yellow-500" />
  },
  {
    title: '24/7 Availability',
    description: 'Need a ride at 3 AM? We are always ready to serve you across all major routes.',
    icon: <Clock className="w-6 h-6 text-yellow-500" />
  },
  {
    title: 'Wide Network',
    description: 'Covering inter-city routes across the country with reliable GPS-enabled tracking.',
    icon: <MapPin className="w-6 h-6 text-yellow-500" />
  },
  {
    title: 'Safe & Comfortable',
    description: 'Luxurious, well-maintained vehicles driven by professional and verified chauffeurs.',
    icon: <Shield className="w-6 h-6 text-yellow-500" />
  }
];

const COMPANY_STORY = `One Way Cab Taxi is an Indian company providing call taxi service with oneway fare. We identified that market taxis charge two ways, usually citing the reason of returning empty. We changed that by charging only one way, saving customers up to 40%. From Indica to Innova, our fleet is luxurious and available 24x7. Established in 2016, we pride ourselves on transparency and comfort.`;

// --- COMPONENTS ---

const VideoGenerator: React.FC = () => {
  const [status, setStatus] = useState<VideoStatus>(VideoStatus.IDLE);
  const [videoUrl, setVideoUrl] = useState<string | null>(null);
  const [error, setError] = useState<string | null>(null);

  const generateVideo = async () => {
    try {
      setStatus(VideoStatus.CHECKING_KEY);
      
      const hasKey = aistudio ? await aistudio.hasSelectedApiKey() : false;
      
      if (!hasKey && aistudio) {
        await aistudio.openSelectKey();
      }

      setStatus(VideoStatus.GENERATING);
      // Fix: Follow guidelines to use process.env.API_KEY directly in constructor
      const ai = new GoogleGenAI({ apiKey: process.env.API_KEY });
      
      const prompt = `A cinematic high-quality promotional video for an Indian taxi service called "One Way Cab Taxi". Show a sleek yellow and white taxi driving through scenic Indian roads, bridges, and city streets. The text "SAVE 40% ON ONE WAY TRIPS" appears gracefully. The atmosphere is professional, reliable, and modern. 1080p, smooth motion.`;

      let operation = await ai.models.generateVideos({
        model: 'veo-3.1-fast-generate-preview',
        prompt,
        config: {
          numberOfVideos: 1,
          resolution: '1080p',
          aspectRatio: '16:9'
        }
      });

      while (!operation.done) {
        await new Promise(resolve => setTimeout(resolve, 5000));
        // Fix: Follow guidelines to create a new instance right before making an API call to ensure current key is used
        const aiPolling = new GoogleGenAI({ apiKey: process.env.API_KEY });
        operation = await aiPolling.operations.getVideosOperation({ operation: operation });
      }

      const downloadLink = operation.response?.generatedVideos?.[0]?.video?.uri;
      if (downloadLink) {
        // Fix: Use process.env.API_KEY directly when fetching video data
        const response = await fetch(`${downloadLink}&key=${process.env.API_KEY}`);
        const blob = await response.blob();
        setVideoUrl(URL.createObjectURL(blob));
        setStatus(VideoStatus.COMPLETED);
      } else {
        throw new Error("Failed to retrieve video link");
      }
    } catch (err: any) {
      console.error(err);
      if (err.message?.includes("Requested entity was not found") && aistudio) {
        setError("API Key error. Please re-select your key.");
        aistudio.openSelectKey();
      } else {
        setError("Generation failed. Please try again later.");
      }
      setStatus(VideoStatus.ERROR);
    }
  };

  return (
    <div className="bg-white rounded-[48px] shadow-2xl overflow-hidden border border-gray-100 p-10 lg:p-14 max-w-5xl mx-auto my-16">
      <div className="flex flex-col lg:flex-row items-center gap-12">
        <div className="flex-1 text-center lg:text-left space-y-8">
          <div className="inline-flex items-center gap-2 px-4 py-2 rounded-full bg-yellow-100 text-yellow-800 text-sm font-black uppercase tracking-widest border border-yellow-200">
            <Sparkles size={16} />
            <span>AI Brand Visualizer</span>
          </div>
          <h2 className="text-4xl font-black tracking-tight text-gray-900">Experience Our Journey</h2>
          <p className="text-gray-500 text-lg leading-relaxed font-medium">
            Create a professional cinematic promo for One Way Cab Taxi using our proprietary AI. See how we're changing travel across India.
          </p>
          
          <div className="space-y-4">
            {status === VideoStatus.IDLE && (
              <button
                onClick={generateVideo}
                className="flex items-center justify-center gap-3 bg-black text-white px-10 py-6 rounded-3xl font-black text-lg hover:bg-gray-800 transition-all w-full lg:w-auto shadow-2xl shadow-black/20"
              >
                <Play size={24} fill="currentColor" />
                Generate Promo
              </button>
            )}

            {(status === VideoStatus.GENERATING || status === VideoStatus.CHECKING_KEY) && (
              <div className="flex flex-col items-center lg:items-start gap-4 p-6 bg-gray-50 rounded-3xl border border-gray-100">
                <div className="flex items-center gap-3 text-yellow-600 font-black animate-pulse uppercase tracking-widest">
                  <Loader2 size={24} className="animate-spin" />
                  <span>Cinematic processing...</span>
                </div>
                <p className="text-sm text-gray-400 font-bold">
                  Usually takes 1-2 minutes. Your vision is being rendered.
                </p>
              </div>
            )}

            {status === VideoStatus.ERROR && (
              <div className="flex items-center gap-4 text-red-500 bg-red-50 p-6 rounded-3xl border border-red-100">
                <AlertCircle size={24} />
                <div className="flex-1">
                  <span className="text-sm font-black block uppercase tracking-widest">System Error</span>
                  <span className="text-sm font-medium opacity-80">{error}</span>
                </div>
                <button 
                  onClick={() => setStatus(VideoStatus.IDLE)} 
                  className="bg-red-500 text-white px-4 py-2 rounded-xl text-xs font-black uppercase tracking-widest hover:bg-red-600 transition-all"
                >
                  Retry
                </button>
              </div>
            )}
          </div>
        </div>

        <div className="flex-1 w-full aspect-video rounded-[40px] bg-gray-900 overflow-hidden relative flex items-center justify-center border-8 border-gray-50 shadow-inner">
          {videoUrl ? (
            <video 
              src={videoUrl} 
              controls 
              className="w-full h-full object-cover"
              autoPlay
              loop
            />
          ) : (
            <div className="text-center p-10">
              {status === VideoStatus.GENERATING ? (
                <div className="space-y-6">
                   <div className="flex justify-center">
                    <div className="w-20 h-20 border-8 border-yellow-400 border-t-transparent rounded-full animate-spin"></div>
                   </div>
                   <p className="text-white font-black uppercase tracking-[0.2em] text-xs">Visualizing...</p>
                </div>
              ) : (
                <div className="text-gray-700 space-y-4">
                  <div className="w-20 h-20 bg-white/5 rounded-full flex items-center justify-center mx-auto border border-white/5">
                    <Play size={32} className="opacity-20" />
                  </div>
                  <p className="text-xs font-black uppercase tracking-widest opacity-40">Ready to Visualize</p>
                </div>
              )}
            </div>
          )}
        </div>
      </div>
    </div>
  );
};

// --- MAIN APP ---

const App: React.FC = () => {
  const [isMenuOpen, setIsMenuOpen] = useState(false);

  return (
    <div className="min-h-screen flex flex-col">
      {/* Navigation */}
      <nav className="sticky top-0 z-50 bg-white/80 backdrop-blur-md border-b border-gray-100">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="flex justify-between items-center h-20">
            <div className="flex items-center gap-2">
              <div className="bg-yellow-400 p-2 rounded-lg">
                <Car className="text-black" size={24} />
              </div>
              <span className="text-xl font-bold tracking-tight uppercase">ONEWAY<span className="text-yellow-500">CABTAXI</span></span>
            </div>
            
            <div className="hidden md:flex items-center gap-8">
              <a href="#services" className="text-sm font-medium hover:text-yellow-500 transition-colors">Services</a>
              <a href="#fleet" className="text-sm font-medium hover:text-yellow-500 transition-colors">Fleet</a>
              <a href="#about" className="text-sm font-medium hover:text-yellow-500 transition-colors">About</a>
              <a 
                href={`tel:${BOOKING_NUMBER}`}
                className="bg-black text-white px-6 py-2.5 rounded-full text-sm font-semibold hover:bg-gray-800 transition-all flex items-center gap-2 shadow-lg shadow-black/10"
              >
                <Phone size={16} />
                {BOOKING_NUMBER}
              </a>
            </div>

            <div className="md:hidden">
              <button 
                onClick={() => setIsMenuOpen(!isMenuOpen)}
                className="p-2 text-gray-600"
              >
                {isMenuOpen ? <X /> : <Menu />}
              </button>
            </div>
          </div>
        </div>

        {/* Mobile Menu */}
        {isMenuOpen && (
          <div className="md:hidden bg-white border-b border-gray-100 px-4 py-6 space-y-4 shadow-xl">
            <a href="#services" onClick={() => setIsMenuOpen(false)} className="block text-lg font-medium px-4">Services</a>
            <a href="#fleet" onClick={() => setIsMenuOpen(false)} className="block text-lg font-medium px-4">Fleet</a>
            <a href="#about" onClick={() => setIsMenuOpen(false)} className="block text-lg font-medium px-4">About</a>
            <a 
              href={`tel:${BOOKING_NUMBER}`}
              className="w-full bg-black text-white px-6 py-4 rounded-xl font-bold flex items-center justify-center gap-2"
            >
              <Phone size={18} />
              Call {BOOKING_NUMBER}
            </a>
          </div>
        )}
      </nav>

      <main>
        {/* Hero Section */}
        <section className="relative pt-12 pb-24 lg:pt-20 lg:pb-32 overflow-hidden">
          <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 flex flex-col lg:flex-row items-center gap-16">
            <div className="flex-1 space-y-10 text-center lg:text-left">
              <div className="inline-flex items-center gap-2 px-4 py-2 bg-yellow-50 text-yellow-700 rounded-full text-sm font-bold tracking-wide border border-yellow-100">
                <span className="flex h-2 w-2 rounded-full bg-yellow-500 animate-pulse"></span>
                PREMIUM ONE-WAY CAB SERVICE
              </div>
              <h1 className="text-5xl lg:text-7xl font-extrabold leading-tight text-gray-900 tracking-tight">
                Premium Drop Trips, <br />
                <span className="text-yellow-500">One-Way Fares.</span>
              </h1>
              <p className="text-xl text-gray-600 max-w-2xl mx-auto lg:mx-0 leading-relaxed font-medium">
                Why pay for the return when you only go one way? Save up to 40% on inter-city travels with India's most trusted cab taxi service.
              </p>
              <div className="flex flex-col sm:flex-row items-center justify-center lg:justify-start gap-4">
                <a 
                  href={`tel:${BOOKING_NUMBER}`}
                  className="w-full sm:w-auto bg-black text-white px-10 py-5 rounded-2xl text-lg font-bold hover:scale-105 transition-all shadow-2xl shadow-black/20 flex items-center justify-center gap-2"
                >
                  Book Now: {BOOKING_NUMBER} <ArrowRight size={20} />
                </a>
              </div>
            </div>
            <div className="flex-1 relative">
              <div className="absolute -top-12 -right-12 w-72 h-72 bg-yellow-400/20 rounded-full blur-[100px]"></div>
              <div className="relative bg-white p-5 rounded-[48px] shadow-2xl border border-gray-100">
                <img 
                  src="https://images.unsplash.com/photo-1554672408-730436b60dde?auto=format&fit=crop&q=80&w=1000" 
                  alt="One Way Cab Taxi Service" 
                  className="rounded-[36px] w-full h-[550px] object-cover shadow-inner"
                />
              </div>
            </div>
          </div>
        </section>

        {/* AI Video Promo Section */}
        <section className="bg-gray-50 py-24 border-y border-gray-100">
          <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
             <div className="text-center mb-16 space-y-4">
               <h2 className="text-4xl lg:text-5xl font-black tracking-tight">Experience the Brand</h2>
               <p className="text-gray-500 max-w-2xl mx-auto text-lg leading-relaxed">
                 We believe in transparency and innovation. Use our AI tool below to generate a cinematic view of our journey across India.
               </p>
             </div>
             <VideoGenerator />
          </div>
        </section>

        {/* Features Grid */}
        <section id="services" className="py-32 bg-white">
          <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-10">
              {FEATURES.map((feature, idx) => (
                <div key={idx} className="p-10 rounded-[40px] border border-gray-50 bg-gray-50/30 hover:bg-white hover:border-yellow-200 hover:shadow-2xl hover:shadow-yellow-100/50 transition-all duration-500 group cursor-default">
                  <div className="mb-8 p-5 rounded-2xl bg-white group-hover:bg-yellow-400 group-hover:text-black shadow-sm group-hover:shadow-lg transition-all w-fit">
                    {React.cloneElement(feature.icon as React.ReactElement<any>, { className: "w-7 h-7" })}
                  </div>
                  <h3 className="text-2xl font-extrabold mb-4 group-hover:text-gray-900 transition-colors">{feature.title}</h3>
                  <p className="text-gray-500 leading-relaxed text-base">{feature.description}</p>
                </div>
              ))}
            </div>
          </div>
        </section>

        {/* Fleet Section */}
        <section id="fleet" className="py-32 bg-gray-900 text-white overflow-hidden">
          <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 text-center relative">
            <div className="absolute top-0 left-1/2 -translate-x-1/2 w-[800px] h-[400px] bg-yellow-400/10 rounded-full blur-[120px] -z-0"></div>
            <h2 className="text-4xl lg:text-5xl font-black mb-6 relative z-10 tracking-tight">Our Luxurious Fleet</h2>
            <p className="text-gray-400 mb-20 max-w-2xl mx-auto text-lg leading-relaxed relative z-10">
              Well-maintained vehicles for every travel requirement. From business sedans to luxury multi-seaters.
            </p>
            <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-10 relative z-10">
              {CAR_MODELS.map((car, idx) => (
                <div key={idx} className="bg-white/5 backdrop-blur-sm rounded-[40px] overflow-hidden hover:bg-white/10 transition-all duration-500 border border-white/10 group">
                  <div className="h-64 overflow-hidden relative">
                    <img 
                      src={car.image} 
                      alt={car.name} 
                      className="w-full h-full object-cover group-hover:scale-110 transition-transform duration-700 opacity-80 group-hover:opacity-100"
                    />
                    <div className="absolute top-6 left-6 bg-yellow-400 text-black px-4 py-1.5 rounded-full text-xs font-black uppercase tracking-widest">
                      {car.category}
                    </div>
                  </div>
                  <div className="p-8 text-left flex items-center justify-between">
                    <div>
                      <h4 className="text-2xl font-bold text-white">{car.name}</h4>
                      <p className="text-sm text-gray-400 font-medium">Standard Class</p>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          </div>
        </section>

        {/* About Section */}
        <section id="about" className="py-32 bg-white">
          <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
            <div className="flex flex-col lg:flex-row items-center gap-24">
              <div className="flex-1 space-y-8">
                <h2 className="text-4xl lg:text-5xl font-black mb-8 leading-tight tracking-tight">
                  Disrupting the Two-Way <br /> Fare Industry
                </h2>
                <div className="space-y-6 text-xl text-gray-500 leading-relaxed font-medium">
                  <p>{COMPANY_STORY}</p>
                </div>
                <div className="pt-8 grid grid-cols-2 gap-12">
                  <div className="space-y-2">
                    <div className="text-5xl font-black text-yellow-500">24/7</div>
                    <div className="text-sm text-gray-400 font-bold uppercase tracking-widest">Always Available</div>
                  </div>
                  <div className="space-y-2">
                    <div className="text-5xl font-black text-yellow-500">40%</div>
                    <div className="text-sm text-gray-400 font-bold uppercase tracking-widest">Avg. Savings</div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </section>
      </main>

      {/* Footer */}
      <footer className="bg-gray-950 text-gray-400 py-24">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="grid grid-cols-1 md:grid-cols-3 gap-20">
            <div className="space-y-8">
              <div className="flex items-center gap-2">
                <div className="bg-yellow-400 p-2 rounded-lg">
                  <Car className="text-black" size={24} />
                </div>
                <span className="text-2xl font-black tracking-tight text-white uppercase">ONEWAY<span className="text-yellow-500">CABTAXI</span></span>
              </div>
              <p className="text-lg leading-relaxed font-medium">
                The most reliable inter-city one-way cab service in India.
              </p>
            </div>
            <div>
              <h4 className="text-white font-black text-lg mb-8 uppercase tracking-widest">Contact</h4>
              <ul className="space-y-6">
                <li className="flex items-start gap-4">
                  <Phone size={20} className="text-yellow-500" />
                  <div>
                    <div className="text-xs font-black text-white/40 uppercase tracking-widest mb-1">Booking Number</div>
                    <a href={`tel:${BOOKING_NUMBER}`} className="text-xl font-black text-white hover:text-yellow-500 transition-colors leading-none">{BOOKING_NUMBER}</a>
                  </div>
                </li>
              </ul>
            </div>
          </div>
          <div className="mt-24 pt-10 border-t border-white/5 text-center text-sm font-bold">
            <p>© 2024 One Way Cab Taxi. All rights reserved.</p>
          </div>
        </div>
      </footer>
    </div>
  );
};

// --- ROOT RENDER ---

const rootElement = document.getElementById('root');
if (rootElement) {
  const root = ReactDOM.createRoot(rootElement);
  root.render(
    <React.StrictMode>
      <App />
    </React.StrictMode>
  );
}
