/*
📁 Project Structure:

- /src
  ├── App.tsx
  ├── main.tsx
  ├── firebase.ts
  ├── api/
  │   └── chat.ts
  ├── components/
  │   ├── Chat.tsx
  │   ├── LanguageSelector.tsx
  │   └── VoiceControls.tsx
  ├── agents/
  │   └── systemPrompts.ts
  └── styles/
      └── index.css
*/

// src/main.tsx
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import './styles/index.css';

ReactDOM.createRoot(document.getElementById('root')!).render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);

// src/App.tsx
import Chat from './components/Chat';
import LanguageSelector from './components/LanguageSelector';
import VoiceControls from './components/VoiceControls';
import { useState } from 'react';

export default function App() {
  const [language, setLanguage] = useState('en-US');
  return (
    <div className="min-h-screen bg-gray-900 text-white p-4">
      <h1 className="text-2xl font-bold mb-4">Multilingual AI Chatbot</h1>
      <LanguageSelector language={language} setLanguage={setLanguage} />
      <Chat language={language} />
      <VoiceControls language={language} />
    </div>
  );
}

// src/firebase.ts
import { initializeApp } from 'firebase/app';
import { getAuth } from 'firebase/auth';

const firebaseConfig = {
  apiKey: import.meta.env.VITE_FIREBASE_API_KEY,
  authDomain: import.meta.env.VITE_FIREBASE_AUTH_DOMAIN,
  projectId: import.meta.env.VITE_FIREBASE_PROJECT_ID,
};

const app = initializeApp(firebaseConfig);
export const auth = getAuth(app);

// src/api/chat.ts
const fetchAIResponse = async (messages: any[]) => {
  const response = await fetch('https://openrouter.ai/api/v1/chat/completions', {
    method: 'POST',
    headers: {
      Authorization: `Bearer ${import.meta.env.VITE_OPENROUTER_API_KEY}`,
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      model: 'openai/gpt-3.5-turbo',
      messages,
    }),
  });
  const data = await response.json();
  return data.choices[0].message.content;
};

export default fetchAIResponse;

// src/agents/systemPrompts.ts
export const getSystemPrompt = (agent: string) => {
  switch (agent) {
    case 'code-generator':
      return 'You are a code generator. Generate valid HTML/CSS/JS code.';
    case 'translator':
      return 'You are a translator. Translate the user message.';
    case 'summarizer':
      return 'You are a summarizer. Return a short summary of the user message.';
    default:
      return 'You are a helpful AI assistant.';
  }
};

// src/components/LanguageSelector.tsx
export default function LanguageSelector({ language, setLanguage }: any) {
  return (
    <select
      value={language}
      onChange={(e) => setLanguage(e.target.value)}
      className="mb-4 p-2 text-black"
    >
      <option value="en-US">English</option>
      <option value="hi-IN">Hindi</option>
      <option value="ta-IN">Tamil</option>
      <option value="te-IN">Telugu</option>
      <option value="fr-FR">French</option>
    </select>
  );
}

// src/components/VoiceControls.tsx
export default function VoiceControls({ language }: any) {
  const speakText = (text: string) => {
    const utterance = new SpeechSynthesisUtterance(text);
    utterance.lang = language;
    window.speechSynthesis.speak(utterance);
  };

  const handleMic = () => {
    const SpeechRecognition = window.SpeechRecognition || (window as any).webkitSpeechRecognition;
    if (!SpeechRecognition) {
      alert('Speech Recognition not supported in this browser.');
      return;
    }
    const recognition = new SpeechRecognition();
    recognition.lang = language;
    recognition.onresult = (e: any) => {
      const result = e.results[0][0].transcript;
      alert('Voice Input: ' + result);
    };
    recognition.start();
  };

  return (
    <div className="mt-4 flex gap-4">
      <button onClick={handleMic} className="bg-blue-500 px-4 py-2 rounded">🎤 Speak</button>
      <button onClick={() => speakText('This is a sample AI response.')} className="bg-green-500 px-4 py-2 rounded">🔊 Read</button>
    </div>
  );
}

// src/components/Chat.tsx
import { useState } from 'react';
import fetchAIResponse from '../api/chat';

export default function Chat({ language }: any) {
  const [messages, setMessages] = useState<any[]>([]);
  const [input, setInput] = useState('');

  const handleSend = async () => {
    const userMsg = { role: 'user', content: input };
    const newMsgs = [...messages, userMsg];
    setMessages(newMsgs);
    setInput('');
    try {
      const reply = await fetchAIResponse(newMsgs);
      setMessages([...newMsgs, { role: 'assistant', content: reply }]);
    } catch (error) {
      setMessages([...newMsgs, { role: 'assistant', content: 'Error fetching response.' }]);
    }
  };

  return (
    <div>
      <div className="bg-gray-800 p-4 h-96 overflow-y-scroll rounded mb-4">
        {messages.map((msg, idx) => (
          <div key={idx} className={`my-2 ${msg.role === 'user' ? 'text-right' : 'text-left'}`}>
            <span className="block p-2 rounded bg-gray-700 inline-block">{msg.content}</span>
          </div>
        ))}
      </div>
      <div className="flex gap-2">
        <input
          value={input}
          onChange={(e) => setInput(e.target.value)}
          placeholder="Type your message..."
          className="flex-grow p-2 text-black rounded"
        />
        <button onClick={handleSend} className="bg-purple-600 px-4 py-2 rounded">Send</button>
      </div>
    </div>
  );
}

// src/styles/index.css
@tailwind base;
@tailwind components;
@tailwind utilities;

/* Custom scrollbar for chat */
::-webkit-scrollbar {
  width: 8px;
}
::-webkit-scrollbar-thumb {
  background: #555;
  border-radius: 4px;
}
::-webkit-scrollbar-thumb:hover {
  background: #888;
}