
import React, { useState, useMemo, useRef, useEffect } from 'react';
import ReactDOM from 'react-dom/client';
import { GoogleGenAI } from "@google/genai";

// --- Services ---
const ai = new GoogleGenAI({ apiKey: process.env.API_KEY || '' });

const getGeminiResponse = async (history: { role: string; content: string }[]) => {
  try {
    const response = await ai.models.generateContent({
      model: 'gemini-3-flash-preview',
      contents: history.map(h => ({
        role: h.role === 'user' ? 'user' : 'model',
        parts: [{ text: h.content }]
      })),
      config: {
        systemInstruction: `You are Sunvolts AI, representing SUNVOLTS LIFE TECHNOLOGIES, a Kerala-based lithium-ion battery manufacturer.
        You are an expert on the Defender Series inverters and LiFePO4 battery systems.
        Our systems offer 8000+ cycles, IP54 rating, and touch screen interfaces.
        Be professional, helpful, and concise. Use Kerala grid context where appropriate.`,
        temperature: 0.7,
      },
    });
    return response.text;
  } catch (error) {
    console.error(error);
    return "Support is currently busy. Please contact us via phone.";
  }
};

// --- Components ---

const Navbar = () => {
  const [isOpen, setIsOpen] = useState(false);
  return (
    <nav className="fixed top-0 left-0 right-0 z-[100] bg-white/90 backdrop-blur-md border-b border-slate-200 h-20">
      <div className="max-w-7xl mx-auto px-4 h-full flex items-center justify-between">
        <a href="#" className="flex items-center space-x-2">
          <div className="h-10 w-auto">
            <img src="logo.png" alt="SUNVOLTS" className="h-full object-contain" onError={(e) => {
              (e.target as HTMLImageElement).parentElement!.innerHTML = '<span class="text-2xl font-black italic text-slate-900">SUN<span class="text-amber-500">VOLTS</span></span>';
            }} />
          </div>
        </a>
        <div className="hidden md:flex space-x-8">
          {['Home', 'Products', 'Features', 'Calculator', 'Contact'].map(link => (
            <a key={link} href={`#${link.toLowerCase()}`} className="text-sm font-bold text-slate-600 hover:text-amber-500 transition-colors uppercase tracking-widest">{link}</a>
          ))}
        </div>
        <button className="md:hidden text-slate-900" onClick={() => setIsOpen(!isOpen)}>
          <i className={`fas ${isOpen ? 'fa-times' : 'fa-bars'} text-xl`}></i>
        </button>
      </div>
      {isOpen && (
        <div className="md:hidden bg-white border-b border-slate-200 p-4 space-y-4 animate-fade-in-up">
          {['Home', 'Products', 'Features', 'Calculator', 'Contact'].map(link => (
            <a key={link} href={`#${link.toLowerCase()}`} onClick={() => setIsOpen(false)} className="block text-slate-900 font-bold uppercase tracking-widest text-sm">{link}</a>
          ))}
        </div>
      )}
    </nav>
  );
};

const Hero = () => (
  <section id="home" className="pt-32 pb-20 bg-slate-950 text-white relative overflow-hidden">
    <div className="max-w-7xl mx-auto px-4 relative z-10 lg:flex items-center gap-12">
      <div className="lg:w-1/2 mb-12 lg:mb-0">
        <div className="inline-block px-4 py-1.5 bg-amber-500/10 border border-amber-500/20 rounded-full text-amber-500 text-[10px] font-black uppercase tracking-[0.3em] mb-6">
          Advanced Kerala Engineering
        </div>
        <h1 className="text-5xl lg:text-7xl font-black heading-font leading-[1.05] mb-6 tracking-tighter">
          Powering Your Life <br/><span className="text-amber-500 italic">Efficiently.</span>
        </h1>
        <p className="text-slate-400 text-lg mb-8 max-w-lg leading-relaxed">
          Kerala's leading manufacturer of high-density Lithium-Ion storage and Defender Series inverters. Sustainable energy, engineered for the future.
        </p>
        <div className="flex flex-col sm:flex-row gap-4">
          <a href="#products" className="bg-amber-500 text-slate-950 px-10 py-4 rounded-2xl font-black uppercase tracking-widest text-xs hover:bg-amber-400 transition-all text-center">Explore Products</a>
          <a href="#calculator" className="bg-white/5 border border-white/10 px-10 py-4 rounded-2xl font-black uppercase tracking-widest text-xs hover:bg-white/10 transition-all text-center">Load Calculator</a>
        </div>
      </div>
      <div className="lg:w-1/2 relative">
        <div className="aspect-square bg-gradient-to-tr from-amber-500/20 to-blue-500/20 rounded-[4rem] flex items-center justify-center p-8">
           <img src="https://images.unsplash.com/photo-1620714223084-8fcacc6dfd8d?auto=format&fit=crop&q=80&w=800" alt="Battery System" className="rounded-[3rem] shadow-2xl rotate-3 hover:rotate-0 transition-transform duration-700" />
        </div>
        <div className="absolute -bottom-6 -right-6 bg-white text-slate-900 p-6 rounded-3xl shadow-2xl animate-bounce hidden md:block">
           <p className="text-3xl font-black leading-none">8000+</p>
           <p className="text-[10px] uppercase font-bold tracking-widest text-slate-500">Cycles Life</p>
        </div>
      </div>
    </div>
    <div className="absolute top-0 right-0 w-[500px] h-[500px] bg-amber-500/5 rounded-full blur-[120px] -mr-64 -mt-64"></div>
  </section>
);

const Products = () => {
  const [selected, setSelected] = useState<any>(null);
  const items = [
    {
      id: 1,
      name: '51.2V 200Ah',
      type: 'Touch Screen Series',
      energy: '10.24kWh',
      img: 'https://images.unsplash.com/photo-1548611635-b6e78bb0d502?auto=format&fit=crop&q=80&w=800',
      specs: {
        'Product Model': '51.2V 200Ah',
        'Rated Voltage': '51.2V',
        'Rated Capacity': '200Ah',
        'Rated Energy': '10240Wh',
        'Cycle Life': '>8000 cycles',
        'Display': 'Touch Screen',
        'Dimensions': '720 * 525 * 255 mm',
        'Weight': '98 KG'
      }
    },
    {
      id: 2,
      name: '51.2V 300Ah',
      type: 'Elite Touch Series',
      energy: '15.36kWh',
      img: 'https://images.unsplash.com/photo-1592833159155-c62df1b65634?auto=format&fit=crop&q=80&w=800',
      specs: {
        'Product Model': '51.2V 300Ah',
        'Rated Voltage': '51.2V',
        'Rated Capacity': '300Ah',
        'Rated Energy': '15360Wh',
        'Cycle Life': '>8000 cycles',
        'Display': 'Touch Screen',
        'Dimensions': '850 * 525 * 255 mm',
        'Weight': '125 KG'
      }
    },
    {
      id: 3,
      name: '51.2V 300Ah (B)',
      type: 'Button Style Series',
      energy: '15.36kWh',
      img: 'https://images.unsplash.com/photo-1620714223084-8fcacc6dfd8d?auto=format&fit=crop&q=80&w=800',
      specs: {
        'Product Model': '51.2V 300Ah (Button)',
        'Rated Voltage': '51.2V',
        'Rated Capacity': '300Ah',
        'Rated Energy': '15360Wh',
        'Cycle Life': '>8000 cycles',
        'Dimensions': '919.5 * 525 * 255 mm',
        'Weight': '125 KG'
      }
    }
  ];

  return (
    <section id="products" className="py-24 bg-white">
      <div className="max-w-7xl mx-auto px-4 text-center mb-16">
        <h2 className="text-3xl lg:text-5xl font-black heading-font mb-4 italic">Product Catalog</h2>
        <div className="w-20 h-1.5 bg-amber-500 mx-auto rounded-full"></div>
      </div>
      <div className="max-w-7xl mx-auto px-4 grid md:grid-cols-3 gap-8">
        {items.map(p => (
          <div key={p.id} className="bg-slate-50 rounded-[2.5rem] border border-slate-100 overflow-hidden group hover:shadow-2xl transition-all">
            <div className="h-64 relative overflow-hidden">
              <img src={p.img} alt={p.name} className="w-full h-full object-cover group-hover:scale-110 transition-transform duration-700" />
              <div className="absolute top-4 right-4 bg-amber-500 text-slate-900 font-black px-4 py-1 rounded-full text-[10px] uppercase tracking-widest">{p.energy}</div>
            </div>
            <div className="p-8">
              <span className="text-amber-600 font-bold text-[10px] uppercase tracking-widest block mb-1">{p.type}</span>
              <h4 className="text-2xl font-black text-slate-900 heading-font mb-4 italic">{p.name}</h4>
              <button onClick={() => setSelected(p)} className="w-full py-4 bg-slate-900 text-white rounded-2xl font-bold uppercase tracking-widest text-[10px] hover:bg-slate-800 transition-colors">Technical Parameters</button>
            </div>
          </div>
        ))}
      </div>

      {selected && (
        <div className="fixed inset-0 z-[200] flex items-center justify-center p-4 bg-slate-950/90 backdrop-blur-md animate-fade-in-up">
          <div className="bg-white rounded-[2.5rem] w-full max-w-2xl max-h-[90vh] overflow-y-auto relative shadow-2xl">
            <div className="bg-amber-400 p-8 flex justify-between items-center sticky top-0 z-10">
              <h3 className="text-slate-950 font-black uppercase italic tracking-tighter text-2xl">Technical Parameters</h3>
              <button onClick={() => setSelected(null)} className="w-10 h-10 bg-slate-950 text-white rounded-full flex items-center justify-center"><i className="fas fa-times"></i></button>
            </div>
            <div className="p-8">
              <div className="border border-slate-200 rounded-2xl overflow-hidden">
                {Object.entries(selected.specs).map(([k, v], i) => (
                  <div key={k} className={`flex justify-between p-4 text-sm ${i % 2 === 0 ? 'bg-slate-50' : 'bg-white'}`}>
                    <span className="text-slate-500 font-bold uppercase tracking-tight">{k}</span>
                    <span className="text-slate-900 font-black">{v as string}</span>
                  </div>
                ))}
              </div>
            </div>
          </div>
        </div>
      )}
    </section>
  );
};

const Features = () => {
  const feats = [
    { icon: 'fa-hand-pointer', title: 'Easy Access', desc: 'LCD touch screen and remote web portal.' },
    { icon: 'fa-microchip', title: 'BMS Optimization', desc: 'Smart battery energy management.' },
    { icon: 'fa-mobile-screen', title: 'Remote Monitoring', desc: 'Control via smartphone or PC.' },
    { icon: 'fa-expand-arrows-alt', title: 'Expansion', desc: 'Greater output power support.' },
    { icon: 'fa-shield-halved', title: 'Superior Safety', desc: 'Sleep-class silence and multi-protection.' },
    { icon: 'fa-globe', title: '9 Languages', desc: 'Global compatibility for local needs.' }
  ];
  return (
    <section id="features" className="py-24 bg-slate-50">
      <div className="max-w-7xl mx-auto px-4 grid md:grid-cols-3 gap-8">
        {feats.map((f, i) => (
          <div key={i} className="bg-white p-10 rounded-[2.5rem] shadow-sm hover:shadow-xl transition-all border border-slate-100 group">
            <div className="w-16 h-16 bg-amber-500/10 rounded-2xl flex items-center justify-center mb-6 group-hover:scale-110 transition-transform">
              <i className={`fas ${f.icon} text-amber-500 text-2xl`}></i>
            </div>
            <h4 className="text-xl font-black heading-font text-slate-900 mb-2 italic">{f.title}</h4>
            <p className="text-slate-500 text-sm leading-relaxed">{f.desc}</p>
          </div>
        ))}
      </div>
    </section>
  );
};

const LoadCalculator = () => {
  const [load, setLoad] = useState(500);
  const [hours, setHours] = useState(4);
  const batteryAh = useMemo(() => Math.ceil(((load * hours) / 12) * 1.2), [load, hours]);

  return (
    <section id="calculator" className="py-24 bg-white">
      <div className="max-w-4xl mx-auto px-4">
        <div className="bg-slate-900 rounded-[3rem] p-10 lg:p-16 text-white shadow-2xl relative overflow-hidden">
          <h3 className="text-3xl lg:text-5xl font-black heading-font italic mb-12">Load Calculator</h3>
          <div className="space-y-12 relative z-10">
            <div>
              <div className="flex justify-between mb-4 uppercase tracking-widest font-black text-[10px]">
                <span>Total Expected Load (Watts)</span>
                <span className="text-amber-500">{load}W</span>
              </div>
              <input type="range" min="100" max="5000" step="50" value={load} onChange={e => setLoad(parseInt(e.target.value))} className="w-full h-2 bg-white/10 rounded-full accent-amber-500 appearance-none cursor-pointer" />
            </div>
            <div>
              <div className="flex justify-between mb-4 uppercase tracking-widest font-black text-[10px]">
                <span>Required Backup Time (Hours)</span>
                <span className="text-amber-500">{hours}h</span>
              </div>
              <input type="range" min="1" max="24" value={hours} onChange={e => setHours(parseInt(e.target.value))} className="w-full h-2 bg-white/10 rounded-full accent-amber-500 appearance-none cursor-pointer" />
            </div>
            <div className="pt-8 border-t border-white/10 grid sm:grid-cols-2 gap-8">
              <div className="bg-white/5 p-6 rounded-3xl border border-white/10">
                <p className="text-[10px] font-black uppercase tracking-[0.2em] text-slate-400 mb-1">Recommended Battery</p>
                <p className="text-3xl font-black text-amber-500">{batteryAh} <span className="text-xs text-white">Ah (Lithium)</span></p>
              </div>
              <div className="bg-white/5 p-6 rounded-3xl border border-white/10">
                <p className="text-[10px] font-black uppercase tracking-[0.2em] text-slate-400 mb-1">Recommended Inverter</p>
                <p className="text-3xl font-black text-white">{Math.ceil(load * 1.5 / 100) * 100 / 1000} <span className="text-xs text-amber-500">KVA</span></p>
              </div>
            </div>
          </div>
          <div className="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-[600px] h-[600px] bg-amber-500/5 rounded-full blur-[120px] pointer-events-none"></div>
        </div>
      </div>
    </section>
  );
};

const Footer = () => (
  <footer id="contact" className="bg-slate-950 text-white py-20 border-t border-white/5">
    <div className="max-w-7xl mx-auto px-4">
      <div className="grid md:grid-cols-3 gap-16 mb-20">
        <div className="col-span-1">
          <img src="logo.png" alt="SUNVOLTS" className="h-12 mb-8 brightness-125" onError={(e) => {
            (e.target as HTMLImageElement).parentElement!.innerHTML = '<span class="text-2xl font-black italic">SUN<span class="text-amber-500">VOLTS</span></span>';
          }} />
          <p className="text-slate-400 text-sm leading-relaxed mb-8">SUNVOLTS LIFE TECHNOLOGIES is a Kerala-based leader in sustainable power. We engineer premium Lithium-Ion systems for modern life.</p>
          <div className="flex space-x-4">
            {['facebook', 'instagram', 'twitter', 'linkedin'].map(s => (
              <a key={s} href="#" className="w-10 h-10 rounded-full bg-white/5 flex items-center justify-center hover:bg-amber-500 transition-colors"><i className={`fab fa-${s}`}></i></a>
            ))}
          </div>
        </div>
        <div>
          <h5 className="font-black heading-font uppercase tracking-widest text-xs mb-8">Contact Info</h5>
          <ul className="space-y-4 text-sm text-slate-400">
            <li className="flex items-center space-x-3"><i className="fas fa-location-dot text-amber-500"></i><span>Ernakulam Hub, Kerala, India</span></li>
            <li className="flex items-center space-x-3"><i className="fas fa-phone text-amber-500"></i><span>+91 98765 43210</span></li>
            <li className="flex items-center space-x-3"><i className="fas fa-envelope text-amber-500"></i><span>info@sunvoltslife.com</span></li>
          </ul>
        </div>
        <div>
          <h5 className="font-black heading-font uppercase tracking-widest text-xs mb-8">Company</h5>
          <ul className="space-y-4 text-sm text-slate-400">
            <li><a href="#" className="hover:text-amber-500">Terms & Conditions</a></li>
            <li><a href="#" className="hover:text-amber-500">Privacy Policy</a></li>
            <li><a href="#" className="hover:text-amber-500">Support Center</a></li>
          </ul>
        </div>
      </div>
      <div className="pt-8 border-t border-white/5 text-center text-[10px] font-black uppercase tracking-[0.3em] text-slate-600">
        &copy; {new Date().getFullYear()} SUNVOLTS LIFE TECHNOLOGIES. ENGINEERED IN KERALA.
      </div>
    </div>
  </footer>
);

const ChatAssistant = () => {
  const [isOpen, setIsOpen] = useState(false);
  const [messages, setMessages] = useState([{ role: 'assistant', content: "Hello! I'm Sunvolts AI. How can I help with your power solution today?" }]);
  const [input, setInput] = useState('');
  const [loading, setLoading] = useState(false);
  const scrollRef = useRef<HTMLDivElement>(null);

  useEffect(() => { scrollRef.current?.scrollTo(0, scrollRef.current.scrollHeight); }, [messages]);

  const send = async () => {
    if (!input.trim() || loading) return;
    const userMsg = { role: 'user', content: input };
    setMessages(p => [...p, userMsg]);
    setInput('');
    setLoading(true);
    const resp = await getGeminiResponse([...messages, userMsg]);
    setMessages(p => [...p, { role: 'assistant', content: resp || "Disconnected." }]);
    setLoading(false);
  };

  return (
    <div className="fixed bottom-6 right-6 z-[200]">
      {isOpen ? (
        <div className="bg-white rounded-[2.5rem] shadow-2xl w-[90vw] sm:w-[400px] h-[600px] flex flex-col border border-slate-100 overflow-hidden animate-fade-in-up">
          <div className="bg-slate-900 p-6 flex justify-between items-center">
            <div className="flex items-center space-x-3">
              <div className="w-10 h-10 bg-amber-500 rounded-xl flex items-center justify-center text-slate-900"><i className="fas fa-bolt"></i></div>
              <span className="text-white font-black heading-font italic">Sunvolts AI</span>
            </div>
            <button onClick={() => setIsOpen(false)} className="text-slate-400 hover:text-white"><i className="fas fa-times"></i></button>
          </div>
          <div ref={scrollRef} className="flex-1 overflow-y-auto p-6 space-y-4 bg-slate-50">
            {messages.map((m, i) => (
              <div key={i} className={`flex ${m.role === 'user' ? 'justify-end' : 'justify-start'}`}>
                <div className={`max-w-[85%] p-4 rounded-2xl text-sm ${m.role === 'user' ? 'bg-slate-900 text-white rounded-br-none' : 'bg-white text-slate-800 shadow-sm border border-slate-100 rounded-bl-none'}`}>{m.content}</div>
              </div>
            ))}
            {loading && <div className="text-[10px] font-black uppercase text-amber-600 animate-pulse italic">Sunvolts AI is thinking...</div>}
          </div>
          <div className="p-6 bg-white border-t border-slate-100 flex gap-2">
            <input value={input} onChange={e => setInput(e.target.value)} onKeyPress={e => e.key === 'Enter' && send()} placeholder="Ask anything..." className="flex-1 bg-slate-100 rounded-2xl px-5 text-sm outline-none focus:ring-2 focus:ring-amber-500" />
            <button onClick={send} className="w-12 h-12 bg-amber-500 rounded-2xl flex items-center justify-center text-slate-900 shadow-lg shadow-amber-500/20"><i className="fas fa-paper-plane"></i></button>
          </div>
        </div>
      ) : (
        <button onClick={() => setIsOpen(true)} className="w-20 h-20 bg-slate-900 rounded-full shadow-2xl flex items-center justify-center group border-4 border-white hover:scale-110 transition-transform">
          <i className="fas fa-bolt text-3xl text-amber-500 group-hover:rotate-12 transition-transform"></i>
        </button>
      )}
    </div>
  );
};

const App = () => (
  <div className="min-h-screen">
    <Navbar />
    <Hero />
    <Products />
    <Features />
    <LoadCalculator />
    <Footer />
    <ChatAssistant />
  </div>
);

// --- Mounting ---
const root = ReactDOM.createRoot(document.getElementById('root')!);
root.render(<App />);
