const { useState, useEffect, useRef, useMemo } = React;

/**
 * Recipe Renderer for the AI Chat section - Text-only version
 */
const AiRecipeRenderer = ({ recipe, onAdd }) => {
  return (
    <div className="ai-card-v2 pill-container">
      <div className="ai-card-content">
        <div className="ai-card-header">
          <div className="ai-card-badge pill">{recipe.cuisine}</div>
          <h4>{recipe.name}</h4>
          <div className="meta-row">
            <span><i className="far fa-clock"></i> {recipe.time}</span>
            <span><i className="fas fa-bolt"></i> {recipe.difficulty}</span>
          </div>
        </div>
        <div className="ai-card-actions">
          <button className="pill primary-btn sm" onClick={() => onAdd({ ...recipe })}>
            <i className="fas fa-plus"></i> Add to Collection
          </button>
        </div>
      </div>
    </div>
  );
};

const CentralAIChat = ({ onNewRecipe }) => {
  const [messages, setMessages] = useState([
    { role: 'assistant', content: "I'm QTCook AI. Tell me what you're craving and I'll generate a recipe with ingredients and cooking instructions!", id: 'init' }
  ]);
  const [input, setInput] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const chatEndRef = useRef(null);
  
  const aiClient = useRef(new QTwareAI({
    systemPrompt: `You are QTCook AI. When providing recipes, ALWAYS include a JSON block at the end. \n    JSON SCHEMA: { \n      "type": "recipe", \n      "name": "Name", \n      "cuisine": "Cuisine", \n      "time": "Time", \n      "difficulty": "Difficulty", \n      "ingredients": ["item 1"], \n      "instructions": ["step 1", "step 2"]\n    }.\n    Do NOT provide any text outside the JSON block.`,
    model: 'gpt-4o'
  }));

  useEffect(() => {
    chatEndRef.current?.scrollIntoView({ behavior: "smooth" });
  }, [messages]);

  const handleSend = async (e) => {
    e.preventDefault();
    if (!input.trim() || isLoading) return;

    const userMsg = input;
    setMessages(prev => [...prev, { role: 'user', content: userMsg, id: Date.now() }]);
    setInput('');
    setIsLoading(true);

    try {
      const response = await aiClient.current.chat(userMsg);
      setMessages(prev => [...prev, { role: 'assistant', content: response, id: Date.now() + 1 }]);
    } catch (error) {
      setMessages(prev => [...prev, { role: 'assistant', content: "The kitchen is a bit busy. Please try again!", id: Date.now() + 2 }]);
    } finally {
      setIsLoading(false);
    }
  };

  const parseResponse = (content, msgId) => {
    const jsonRegex = /```json([\\s\\S]*?)```|\\{([\\s\\S]*?)"type":\\s*"recipe"([\\s\\S]*?)\\}/;
    const match = content.match(jsonRegex);
    if (match) {
      try {
        let jsonStr = match[0];
        if (jsonStr.startsWith('```json')) {
          jsonStr = match[1];
        }
        const data = JSON.parse(jsonStr.trim());
        return { text: '', data };
      } catch (e) { 
        return { text: content, data: null }; 
      }
    }
    return { text: content, data: null };
  };

  return (
    <div className="central-hub">
      <div className="hub-header">
        <div className="hub-badge pill">AI CULINARY HUB</div>
        <h2>QTCook Intelligence</h2>
      </div>
      
      <div className="hub-chat-area">
        {messages.map((msg) => {
          const parsed = parseResponse(msg.content, msg.id);
          return (
            <div key={msg.id} className={`hub-msg ${msg.role}`}>
              {parsed.text && <div className="msg-bubble">{parsed.text}</div>}
              {parsed.data && parsed.data.type === 'recipe' && (
                <AiRecipeRenderer recipe={parsed.data} onAdd={onNewRecipe} />
              )}
            </div>
          );
        })}
        {isLoading && <div className="typing-status"><i className="fas fa-utensils fa-spin"></i> Cooking up a recipe...</div>}
        <div ref={chatEndRef} />
      </div>

      <form className="hub-input" onSubmit={handleSend}>
        <input 
          className="pill" 
          type="text" 
          placeholder="What would you like to cook?"
          value={input}
          onChange={(e) => setInput(e.target.value)}
        />
        <button className="pill active-btn" type="submit" disabled={isLoading}>
          <i className="fas fa-paper-plane"></i>
        </button>
      </form>
    </div>
  );
};

const App = () => {
  const [recipes, setRecipes] = useState([]);
  const [filter, setFilter] = useState("All");
  const [selectedRecipe, setSelectedRecipe] = useState(null);

  const cuisines = ["All", "Turkish", "Italian", "Japanese", "Mexican", "French"];

  const addNewRecipe = (recipe) => {
    const newRecipe = { ...recipe, id: Date.now() };
    setRecipes(prev => [newRecipe, ...prev]);
  };

  const filtered = recipes.filter(r => filter === "All" || r.cuisine === filter);

  return (
    <div className="app-root">
      <nav className="top-nav">
        <div className="logo">
          <i className="fas fa-fire-alt"></i>
          <span>QTCook</span>
        </div>
        <div className="user-stats pill">
          <i className="fas fa-hat-chef"></i> {recipes.length} Discovered
        </div>
      </nav>

      <main className="content-wrapper">
        <CentralAIChat onNewRecipe={addNewRecipe} />

        <section className="collection">
          <div className="collection-head">
            <h3>Culinary Collection</h3>
            <div className="filters">
              {cuisines.map(c => (
                <button 
                  key={c} 
                  className={`pill filter-chip ${filter === c ? 'active' : ''}`}
                  onClick={() => setFilter(c)}
                >
                  {c}
                </button>
              ))}
            </div>
          </div>

          <div className="grid">
            {filtered.length === 0 && (
              <div className="empty-state">
                <i className="fas fa-concierge-bell"></i>
                <p>No recipes yet. Ask the AI to create one!</p>
              </div>
            )}
            {filtered.map(r => (
              <div key={r.id} className="card pill-container" onClick={() => setSelectedRecipe(r)}>
                <div className="card-body">
                  <div className="card-header-row">
                    <span className="tag-inline pill">{r.cuisine}</span>
                    <h4>{r.name}</h4>
                  </div>
                  <div className="card-meta">
                    <span><i className="far fa-clock"></i> {r.time}</span>
                    <span><i className="fas fa-signal"></i> {r.difficulty}</span>
                  </div>
                </div>
              </div>
            ))}
          </div>
        </section>
      </main>

      {selectedRecipe && (
        <div className="modal" onClick={() => setSelectedRecipe(null)}>
          <div className="modal-inner-compact" onClick={e => e.stopPropagation()}>
            <button className="close-btn pill" onClick={() => setSelectedRecipe(null)}>
              <i className="fas fa-times"></i>
            </button>

            <div className="modal-content-compact">
              <div className="modal-title-bar">
                <h2>{selectedRecipe.name}</h2>
                <div className="pill-meta-group">
                  <span className="pill tag-pill">{selectedRecipe.cuisine}</span>
                  <span className="pill tag-pill"><i className="far fa-clock"></i> {selectedRecipe.time}</span>
                  <span className="pill tag-pill"><i className="fas fa-signal"></i> {selectedRecipe.difficulty}</span>
                </div>
              </div>

              <div className="ingredients-section">
                <div className="section-header-compact">
                  <i className="fas fa-mortar-pestle"></i>
                  <h5>Ingredients</h5>
                </div>
                <div className="ing-grid">
                  {selectedRecipe.ingredients && selectedRecipe.ingredients.map((ing, i) => (
                    <div key={i} className="ing-item pill">{ing}</div>
                  ))}
                </div>
              </div>

              {selectedRecipe.instructions && (
                <div className="instructions-section">
                  <div className="section-header-compact">
                    <i className="fas fa-list-check"></i>
                    <h5>How to Cook</h5>
                  </div>
                  <div className="instructions-list">
                    {selectedRecipe.instructions.map((step, i) => (
                      <div key={i} className="step-item">
                        <span className="step-num pill">{i + 1}</span>
                        <p>{step}</p>
                      </div>
                    ))}
                  </div>
                </div>
              )}
            </div>
          </div>
        </div>
      )}

      <footer>
        <p>© 2026 QTware | Powered by QTware Database 2026</p>
      </footer>
    </div>
  );
};

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