import React, { useState, useEffect, useCallback, useMemo } from 'react';
import { initializeApp } from 'firebase/app';
import { getAuth, signInWithCustomToken, signInAnonymously, onAuthStateChanged } from 'firebase/auth';
import { getFirestore, doc, setDoc, collection, onSnapshot, updateDoc, deleteDoc, query, orderBy } from 'firebase/firestore';
import { Camera, Zap, AlertTriangle, Leaf, X, Clock, Sun, Droplet, Users, Trash2, Loader2, Feather } from 'lucide-react';

// --- Variáveis Globais do Ambiente (NÃO REMOVER) ---
const appId = typeof __app_id !== 'undefined' ? __app_id : 'succulent-guardian-default';
const firebaseConfig = typeof __firebase_config !== 'undefined' ? JSON.parse(__firebase_config) : {};
const initialAuthToken = typeof __initial_auth_token !== 'undefined' ? __initial_auth_token : null;
// --- FIM Variáveis Globais do Ambiente ---

// Inicializa Firebase (Configurações necessárias para o Immersive Canvas)
const app = initializeApp(firebaseConfig);
const db = getFirestore(app);
const auth = getAuth(app);

/**
 * Utilitário para converter ArrayBuffer para Base64 (necessário para APIs de Imagem)
 * @param {ArrayBuffer} buffer
 * @returns {string}
 */
const arrayBufferToBase64 = (buffer) => {
    let binary = '';
    const bytes = new Uint8Array(buffer);
    const len = bytes.byteLength;
    for (let i = 0; i < len; i++) {
        binary += String.fromCharCode(bytes[i]);
    }
    return btoa(binary);
};

/**
 * Função utilitária para chamar a API Gemini com retry e backoff exponencial.
 * @param {Array<object>} contents Conteúdo da requisição (texto e/ou imagem).
 * @param {string} systemInstruction Instrução para guiar a resposta da IA.
 * @returns {Promise<string>} O texto gerado pela IA.
 */
const callGeminiApi = async (contents, systemInstruction) => {
    const apiKey = ""; 
    const apiUrl = `https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-preview-05-20:generateContent?key=${apiKey}`;
    const MAX_RETRIES = 5;

    const payload = {
        contents: contents,
        systemInstruction: { parts: [{ text: systemInstruction }] },
    };

    for (let i = 0; i < MAX_RETRIES; i++) {
        try {
            const response = await fetch(apiUrl, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(payload)
            });

            if (!response.ok) {
                if (response.status === 429 && i < MAX_RETRIES - 1) {
                    const delay = Math.pow(2, i) * 1000 + Math.random() * 1000;
                    await new Promise(resolve => setTimeout(resolve, delay));
                    continue; 
                }
                throw new Error(`Erro de API: ${response.status} - ${await response.text()}`);
            }

            const result = await response.json();
            const text = result.candidates?.[0]?.content?.parts?.[0]?.text;

            if (!text) {
                throw new Error("Resposta da API Gemini vazia ou inválida.");
            }

            return text;

        } catch (error) {
            console.error(`Tentativa ${i + 1} falhou:`, error);
            if (i === MAX_RETRIES - 1) {
                throw new Error(`Falha ao conectar ou processar a resposta da IA após ${MAX_RETRIES} tentativas.`);
            }
        }
    }
};


// --- Componentes de UI Básicos ---

const Card = ({ children, className = '' }) => (
    <div className={`p-5 bg-zinc-800 rounded-xl shadow-2xl ${className}`}>
        {children}
    </div>
);

const Button = ({ children, onClick, className = '', disabled = false, icon: Icon = null }) => (
    <button
        onClick={onClick}
        disabled={disabled}
        className={`flex items-center justify-center space-x-2 px-4 py-2 text-sm font-semibold rounded-lg transition duration-200 ease-in-out 
                   ${disabled 
                       ? 'bg-zinc-700 text-zinc-500 cursor-not-allowed' 
                       : 'bg-emerald-500 hover:bg-emerald-600 text-white shadow-emerald-700/50 hover:shadow-emerald-700/70 shadow-lg'}
                   ${className}`}
    >
        {Icon && <Icon size={18} className={disabled ? 'opacity-50' : ''} />}
        <span>{children}</span>
    </button>
);

const StatusIndicator = ({ lastWatered, wateringFrequencyDays }) => {
    if (!lastWatered) return <span className="text-zinc-500 flex items-center"><AlertTriangle size={14} className="mr-1" /> Sem Rega Registrada</span>;

    const lastWateredDate = new Date(lastWatered.seconds * 1000);
    const nextWateringTime = lastWateredDate.getTime() + (wateringFrequencyDays * 24 * 60 * 60 * 1000);
    const timeDifference = nextWateringTime - new Date().getTime();
    const daysUntilNext = Math.ceil(timeDifference / (1000 * 60 * 60 * 24));

    if (daysUntilNext <= 0) {
        return <span className="text-red-400 font-bold flex items-center"><Droplet size={14} className="mr-1 animate-pulse" /> REGAR AGORA!</span>;
    } else if (daysUntilNext <= 3) {
        return <span className="text-yellow-400 flex items-center"><Clock size={14} className="mr-1" /> Regar em {daysUntilNext} dias</span>;
    } else {
        return <span className="text-emerald-400 flex items-center"><Leaf size={14} className="mr-1" /> OK ({daysUntilNext} dias)</span>;
    }
};

// --- Funções de Componentes Modais ---

const Modal = ({ title, isOpen, onClose, children }) => {
    if (!isOpen) return null;
    return (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black bg-opacity-80 backdrop-blur-sm p-4" onClick={onClose}>
            <div className="w-full max-w-lg bg-zinc-900 rounded-2xl shadow-2xl border border-zinc-700/50" onClick={e => e.stopPropagation()}>
                <div className="p-6 border-b border-zinc-800 flex justify-between items-center">
                    <h2 className="text-xl font-bold text-white">{title}</h2>
                    <button onClick={onClose} className="text-zinc-400 hover:text-white transition"><X size={24} /></button>
                </div>
                <div className="p-6">
                    {children}
                </div>
            </div>
        </div>
    );
};

const PlantItem = ({ plant, userId, db }) => {
    const [isDeleting, setIsDeleting] = useState(false);
    
    // Função para atualizar a data da última rega
    const handleWatering = async () => {
        const plantRef = doc(db, `artifacts/${appId}/users/${userId}/suculentas`, plant.id);
        try {
            await updateDoc(plantRef, {
                lastWatered: new Date(),
            });
            console.log("Rega atualizada com sucesso!");
        } catch (error) {
            console.error("Erro ao atualizar a rega:", error);
        }
    };

    // Função para deletar a planta
    const handleDelete = async () => {
        // NOTE: Use um modal customizado em produção, mas aqui usamos confirm() para simplicidade de um arquivo único.
        if (!confirm(`Tem certeza que deseja remover ${plant.name}?`)) return;
        setIsDeleting(true);
        try {
            await deleteDoc(doc(db, `artifacts/${appId}/users/${userId}/suculentas`, plant.id));
        } catch (error) {
            console.error("Erro ao deletar planta:", error);
        } finally {
            setIsDeleting(false);
        }
    };

    return (
        <Card className="flex flex-col md:flex-row justify-between items-start md:items-center space-y-3 md:space-y-0 text-white hover:border-l-4 hover:border-emerald-500 transition-all duration-300">
            <div className="flex-1 min-w-0">
                <h3 className="text-lg font-semibold truncate text-emerald-400">{plant.name} ({plant.species || 'Espécie Desconhecida'})</h3>
                <div className="mt-1 space-y-1 text-sm text-zinc-400">
                    <p className="flex items-center"><Sun size={14} className="mr-2 text-yellow-300" />Luz: {plant.light || 'N/A'}</p>
                    <p className="flex items-center"><Droplet size={14} className="mr-2 text-blue-300" />Rega: A cada {plant.wateringFrequencyDays || 'N/A'} dias</p>
                    <p>Última Rega: {plant.lastWatered ? new Date(plant.lastWatered.seconds * 1000).toLocaleDateString() : 'Nunca'}</p>
                </div>
            </div>
            <div className="flex flex-col items-start md:items-end space-y-2 md:space-x-3 md:flex-row md:justify-end">
                <StatusIndicator 
                    lastWatered={plant.lastWatered} 
                    wateringFrequencyDays={plant.wateringFrequencyDays || 7} 
                />
                <Button 
                    onClick={handleWatering} 
                    icon={Droplet} 
                    className="w-full md:w-auto bg-blue-500 hover:bg-blue-600 shadow-blue-700/50"
                >
                    Regar Hoje
                </Button>
                <Button 
                    onClick={handleDelete} 
                    icon={isDeleting ? Loader2 : Trash2} 
                    disabled={isDeleting}
                    className="w-full md:w-auto bg-red-500 hover:bg-red-600 shadow-red-700/50"
                >
                    {isDeleting ? 'Removendo...' : 'Remover'}
                </Button>
            </div>
        </Card>
    );
};

// Componente para adicionar/identificar planta via IA
const AddPlantModal = ({ isOpen, onClose, userId, db }) => {
    const [image, setImage] = useState(null);
    const [imageData, setImageData] = useState(null);
    const [plantName, setPlantName] = useState('');
    const [aiResult, setAiResult] = useState(null); // { species, light, wateringFrequencyDays, soil }
    const [customFrequency, setCustomFrequency] = useState(7);
    const [isLoading, setIsLoading] = useState(false);
    const [error, setError] = useState('');
    const [step, setStep] = useState(1); // 1: Upload, 2: Identify, 3: Confirm/Save

    const handleImageChange = (e) => {
        const file = e.target.files[0];
        if (file) {
            setImage(URL.createObjectURL(file));
            const reader = new FileReader();
            reader.onload = (event) => {
                setImageData({
                    mimeType: file.type,
                    data: arrayBufferToBase64(event.target.result),
                });
            };
            reader.readAsArrayBuffer(file);
            setAiResult(null);
            setError('');
            setStep(2); // Vai para o passo de identificação
        }
    };

    const identifyPlant = useCallback(async () => {
        if (!imageData) return; 

        setIsLoading(true);
        setError('');
        try {
            const identificationPrompt = "Analise esta imagem. IDENTIFIQUE o nome popular e científico desta suculenta/cacto e gere um JSON conciso com as seguintes chaves: 'species' (o nome popular/científico), 'light' (ex: Sol Pleno, Sombra, Meia Sombra), 'wateringFrequencyDays' (Apenas o número de dias, ex: 7, 10, 14), e 'soil' (ex: Drenante, Rico em Matéria Orgânica). Foque apenas em suculentas ou cactos. O JSON deve ser a ÚNICA saída.";

            const contents = [
                { text: "Identifique esta planta e crie uma ficha de cuidados resumida." },
                { inlineData: imageData }
            ];

            const resultText = await callGeminiApi(contents, identificationPrompt);
            
            // Tenta parsear o JSON retornado pela IA
            const jsonStart = resultText.indexOf('{');
            const jsonEnd = resultText.lastIndexOf('}') + 1;
            const jsonString = resultText.substring(jsonStart, jsonEnd);

            const resultJson = JSON.parse(jsonString);
            
            setAiResult({
                species: resultJson.species || 'Espécie Desconhecida',
                light: resultJson.light || 'Não Informado',
                wateringFrequencyDays: parseInt(resultJson.wateringFrequencyDays, 10) || 7,
                soil: resultJson.soil || 'Não Informado',
            });
            setCustomFrequency(parseInt(resultJson.wateringFrequencyDays, 10) || 7);
            setStep(3); // Vai para o passo de confirmação
            
        } catch (e) {
            console.error("Erro na identificação da IA:", e);
            setError("Falha na identificação da IA. Tente uma imagem mais clara ou insira os dados manualmente.");
            setAiResult({
                species: 'Falha na Identificação',
                light: 'N/A',
                wateringFrequencyDays: 7,
                soil: 'N/A',
            });
            setStep(3); // Permite ao usuário salvar manualmente, mesmo com erro
        } finally {
            setIsLoading(false);
        }
    }, [imageData]);


    const handleSave = async () => {
        if (!plantName || !aiResult || !aiResult.species) {
            return setError("Nome da planta e espécie são obrigatórios.");
        }

        setIsLoading(true);
        setError('');
        try {
            const newPlantRef = doc(collection(db, `artifacts/${appId}/users/${userId}/suculentas`));
            await setDoc(newPlantRef, {
                id: newPlantRef.id,
                name: plantName,
                species: aiResult.species,
                light: aiResult.light, // Usando a luz do AI result
                soil: aiResult.soil, // Usando o solo do AI result
                wateringFrequencyDays: customFrequency, // Usando a frequência (customizada ou AI)
                lastWatered: new Date(), 
                createdAt: new Date(),
                ownerId: userId,
            });
            onClose();
        } catch (e) {
            console.error("Erro ao salvar planta:", e);
            setError("Erro ao salvar a planta no banco de dados. Tente novamente.");
        } finally {
            setIsLoading(false);
        }
    };

    const handleClose = () => {
        setImage(null);
        setImageData(null);
        setPlantName('');
        setAiResult(null);
        setCustomFrequency(7);
        setIsLoading(false);
        setError('');
        setStep(1);
        onClose();
    };

    // Componente de indicador de passo
    const StepIndicator = ({ number, title, active }) => (
        <div className="flex items-center space-x-2">
            <div className={`w-6 h-6 flex items-center justify-center rounded-full font-bold text-xs ${active ? 'bg-emerald-500 text-white' : 'bg-zinc-700 text-zinc-400'}`}>
                {number}
            </div>
            <span className={`text-sm font-semibold ${active ? 'text-white' : 'text-zinc-400'}`}>{title}</span>
        </div>
    );
    
    // Conteúdo Principal do Modal
    const renderContent = () => {
        if (step === 1) {
            return (
                <>
                    <p className="text-zinc-400 mb-4">Selecione uma imagem para começar a identificação automática.</p>
                    <input
                        type="file"
                        accept="image/*"
                        onChange={handleImageChange}
                        className="w-full text-sm text-zinc-300 file:mr-4 file:py-2 file:px-4 file:rounded-lg file:border-0 file:text-sm file:font-semibold file:bg-emerald-700 file:text-white hover:file:bg-emerald-600 cursor-pointer"
                    />
                </>
            );
        }
        
        return (
            <div className="space-y-4">
                {/* Imagem de Pré-visualização */}
                {image && (
                    <div className="relative h-40 bg-zinc-800 rounded-lg overflow-hidden border border-zinc-700">
                        <img src={image} alt="Pré-visualização da planta" className="w-full h-full object-cover" />
                    </div>
                )}
                
                {/* Passo 2: Identificar */}
                {step === 2 && (
                    <Button onClick={identifyPlant} disabled={isLoading} icon={isLoading ? Loader2 : Camera} className="w-full">
                        {isLoading ? '2. Identificando com IA...' : '2. Iniciar Identificação da IA'}
                    </Button>
                )}

                {/* Resultado da IA e Confirmação */}
                {step === 3 && (
                    <>
                        <h4 className="text-lg font-semibold text-emerald-400 flex items-center"><Feather size={18} className="mr-2" /> 3. Confirme os Detalhes do Guardião</h4>

                        <input
                            type="text"
                            placeholder="Nome amigável (ex: Rosinha, Zé Cacto)"
                            value={plantName}
                            onChange={(e) => setPlantName(e.target.value)}
                            className="w-full p-3 bg-zinc-700 border border-zinc-600 rounded-lg text-white placeholder-zinc-400 focus:outline-none focus:ring-2 focus:ring-emerald-500"
                            disabled={isLoading}
                        />

                        {aiResult && (
                            <Card className="bg-zinc-700 border border-zinc-600 p-4 space-y-2">
                                <p className="text-sm font-bold text-zinc-300">Resultado da IA (Edite se necessário):</p>
                                <p className="text-base text-white">Espécie: <span className="text-emerald-300 font-medium">{aiResult.species}</span></p>
                                <p className="text-base text-white flex items-center"><Sun size={14} className="mr-2 text-yellow-300" /> Luz: {aiResult.light}</p>
                                <p className="text-base text-white flex items-center"><Feather size={14} className="mr-2 text-blue-300" /> Solo: {aiResult.soil}</p>

                                <div className="flex items-center space-x-4 pt-2 border-t border-zinc-600">
                                    <label className="text-zinc-300 whitespace-nowrap text-sm">Rega a cada (dias):</label>
                                    <input
                                        type="number"
                                        value={customFrequency}
                                        onChange={(e) => setCustomFrequency(Math.max(1, parseInt(e.target.value) || 1))}
                                        className="w-full p-2 bg-zinc-800 border border-zinc-600 rounded-lg text-white text-sm focus:outline-none focus:ring-2 focus:ring-emerald-500"
                                        disabled={isLoading}
                                    />
                                </div>
                            </Card>
                        )}
                        
                        <Button onClick={handleSave} disabled={isLoading || !plantName || !aiResult || !aiResult.species} className="w-full mt-4">
                            {isLoading ? 'Salvando...' : 'Salvar Guardião e Iniciar Monitoramento'}
                        </Button>
                    </>
                )}

                {error && <p className="text-red-400 text-sm mt-4">{error}</p>}
                
            </div>
        );
    }


    return (
        <Modal title="Adicionar Novo Guardião" isOpen={isOpen} onClose={handleClose}>
            <div className="flex justify-between items-center mb-4 border-b border-zinc-800 pb-4">
                <StepIndicator number={1} title="Upload" active={step >= 1} />
                <div className={`flex-1 h-0.5 mx-2 ${step > 1 ? 'bg-emerald-500' : 'bg-zinc-700'}`}></div>
                <StepIndicator number={2} title="Identificar IA" active={step >= 2} />
                <div className={`flex-1 h-0.5 mx-2 ${step > 2 ? 'bg-emerald-500' : 'bg-zinc-700'}`}></div>
                <StepIndicator number={3} title="Confirmar" active={step >= 3} />
            </div>
            {renderContent()}
        </Modal>
    );
};

// Componente para verificação de pragas via IA (Feature Killer #2)
const PestCheckModal = ({ isOpen, onClose }) => {
    const [image, setImage] = useState(null);
    const [imageData, setImageData] = useState(null);
    const [result, setResult] = useState('');
    const [isLoading, setIsLoading] = useState(false);
    const [error, setError] = useState('');

    const handleImageChange = (e) => {
        const file = e.target.files[0];
        if (file) {
            setImage(URL.createObjectURL(file));
            const reader = new FileReader();
            reader.onload = (event) => {
                setImageData({
                    mimeType: file.type,
                    data: arrayBufferToBase64(event.target.result),
                });
            };
            reader.readAsArrayBuffer(file);
            setResult('');
            setError('');
        }
    };

    const analyzePest = useCallback(async () => {
        if (!imageData) return setError("Por favor, selecione uma imagem da planta doente.");

        setIsLoading(true);
        setError('');
        setResult('');
        try {
            const pestPrompt = "Analise esta imagem focando em pragas ou doenças de suculentas ou cactos. Identifique a PRAGA ou DOENÇA e sugira um TRATAMENTO NATURAL e minimalista (ex: com álcool isopropílico, água e sabão de coco, óleo de neem ou canela em pó). Responda de forma concisa em Português, focando na identificação e na solução.";

            const contents = [
                { text: "Analise esta planta em busca de pragas ou doenças." },
                { inlineData: imageData }
            ];

            const resultText = await callGeminiApi(contents, pestPrompt);
            setResult(resultText);

        } catch (e) {
            console.error("Erro na análise de pragas da IA:", e);
            setError("Falha ao analisar. Certifique-se de que a imagem mostra claramente a área afetada.");
        } finally {
            setIsLoading(false);
        }
    }, [imageData]);

    const handleClose = () => {
        setImage(null);
        setImageData(null);
        setResult('');
        setIsLoading(false);
        setError('');
        onClose();
    };

    return (
        <Modal title="Diagnóstico Rápido de Pragas" isOpen={isOpen} onClose={handleClose}>
            <div className="space-y-4">
                <p className="text-zinc-400 text-sm">Tire uma foto da folha/caule afetado para um diagnóstico rápido.</p>
                <input
                    type="file"
                    accept="image/*"
                    onChange={handleImageChange}
                    className="w-full text-sm text-zinc-300 file:mr-4 file:py-2 file:px-4 file:rounded-lg file:border-0 file:text-sm file:font-semibold file:bg-zinc-700 file:text-red-400 hover:file:bg-zinc-600 cursor-pointer"
                />

                {image && (
                    <div className="relative h-40 bg-zinc-800 rounded-lg overflow-hidden border border-zinc-700">
                        <img src={image} alt="Pré-visualização da área afetada" className="w-full h-full object-cover" />
                    </div>
                )}
                
                <Button onClick={analyzePest} disabled={!imageData || isLoading} icon={Zap} className="w-full bg-red-600 hover:bg-red-700 shadow-red-700/50">
                    {isLoading ? 'Analisando o Problema...' : 'Iniciar Diagnóstico'}
                </Button>

                {error && <p className="text-red-400 text-sm">{error}</p>}
                
                {result && (
                    <Card className="mt-4 border border-zinc-700/50">
                        <h4 className="text-lg font-bold text-red-400 flex items-center mb-2"><AlertTriangle size={20} className="mr-2" />Resultado do Diagnóstico</h4>
                        <p className="text-zinc-300 whitespace-pre-wrap">{result}</p>
                    </Card>
                )}
            </div>
        </Modal>
    );
};


// --- Componente Principal ---

export default function App() {
    const [userId, setUserId] = useState(null);
    const [plants, setPlants] = useState([]);
    const [isAuthReady, setIsAuthReady] = useState(false);
    const [showAddModal, setShowAddModal] = useState(false);
    const [showPestModal, setShowPestModal] = useState(false);

    // 1. Autenticação e Configuração do Usuário
    useEffect(() => {
        const handleAuth = async () => {
            try {
                if (initialAuthToken) {
                    await signInWithCustomToken(auth, initialAuthToken);
                } else {
                    await signInAnonymously(auth);
                }
            } catch (e) {
                console.error("Erro na autenticação:", e);
                await signInAnonymously(auth);
            }
        };

        const unsubscribe = onAuthStateChanged(auth, (user) => {
            if (user) {
                setUserId(user.uid);
            } else {
                handleAuth();
            }
            setIsAuthReady(true);
        });

        return () => unsubscribe();
    }, []);

    // 2. Carregamento e Listeners do Firestore
    useEffect(() => {
        if (!userId || !isAuthReady) return;

        console.log(`Firestore: Ouvindo coleção de suculentas para o usuário: ${userId}`);
        const plantsCollectionRef = collection(db, `artifacts/${appId}/users/${userId}/suculentas`);

        const q = query(plantsCollectionRef, orderBy("createdAt", "desc"));
        
        const unsubscribe = onSnapshot(q, (snapshot) => {
            const newPlants = snapshot.docs.map(doc => ({
                id: doc.id,
                ...doc.data(),
            }));
            setPlants(newPlants);
        }, (error) => {
            console.error("Erro ao carregar plantas do Firestore:", error);
        });

        return () => unsubscribe();
    }, [userId, isAuthReady]);
    
    // Calcula as plantas que precisam de rega
    const plantsNeedingWater = useMemo(() => {
        return plants.filter(plant => {
            if (!plant.lastWatered) return true; 

            const lastWateredDate = new Date(plant.lastWatered.seconds * 1000);
            const nextWateringTime = lastWateredDate.getTime() + (plant.wateringFrequencyDays * 24 * 60 * 60 * 1000);
            return new Date().getTime() >= nextWateringTime;
        }).length;
    }, [plants]);


    if (!isAuthReady) {
        return (
            <div className="flex items-center justify-center min-h-screen bg-zinc-900 text-emerald-400">
                <Loader2 className="animate-spin mr-2" size={24} />
                Carregando Guardião...
            </div>
        );
    }

    return (
        <div className="min-h-screen bg-gradient-to-br from-zinc-900 via-zinc-900 to-zinc-800 text-white font-sans p-4 md:p-8">
            {/* Header/Dashboard Resumo */}
            <div className="flex justify-between items-center mb-8 border-b border-zinc-800 pb-4">
                <h1 className="text-3xl font-extrabold text-emerald-400 flex items-center space-x-2">
                    <Leaf size={32} />
                    <span>Guardião de Suculentas</span>
                </h1>
                <div className="flex items-center space-x-3 text-sm text-zinc-400 hidden sm:flex">
                    <Users size={16} />
                    <span>ID: {userId}</span>
                </div>
            </div>

            <div className="grid grid-cols-1 md:grid-cols-3 gap-6 mb-8">
                {/* Card de Rega Urgente */}
                <Card className="border border-red-500/50 bg-gradient-to-r from-zinc-800 to-zinc-800/80">
                    <h2 className="text-2xl font-bold mb-2 text-red-400 flex items-center">
                        <Droplet size={24} className="mr-2 animate-pulse" />
                        Atenção!
                    </h2>
                    <p className="text-zinc-300">
                        {plantsNeedingWater} {plantsNeedingWater === 1 ? 'planta' : 'plantas'} precisam de rega urgente.
                    </p>
                </Card>
                
                {/* Card de Adicionar Planta */}
                <Card className="flex flex-col justify-center items-center bg-zinc-700/50 hover:bg-zinc-700 transition cursor-pointer border border-emerald-500/50 hover:shadow-emerald-900/50" onClick={() => setShowAddModal(true)}>
                    <Camera size={30} className="text-emerald-400 mb-2" />
                    <p className="text-sm font-semibold text-emerald-300">Novo Guardião (Identificar)</p>
                </Card>

                {/* Card de Checar Praga */}
                <Card className="flex flex-col justify-center items-center bg-zinc-700/50 hover:bg-zinc-700 transition cursor-pointer border border-yellow-500/50 hover:shadow-yellow-900/50" onClick={() => setShowPestModal(true)}>
                    <Zap size={30} className="text-yellow-400 mb-2" />
                    <p className="text-sm font-semibold text-yellow-300">Diagnóstico de Pragas (IA)</p>
                </Card>
            </div>

            {/* Lista de Plantas (Prontuário) */}
            <h2 className="text-2xl font-bold mb-4 text-white">Meu Prontuário de Plantas ({plants.length})</h2>
            <div className="space-y-4">
                {plants.length === 0 ? (
                    <Card className="text-center text-zinc-400 border border-dashed border-zinc-700">
                        <p>Você ainda não adicionou nenhum Guardião. Use o botão "Novo Guardião" acima para começar!</p>
                    </Card>
                ) : (
                    plants.map(plant => (
                        <PlantItem 
                            key={plant.id} 
                            plant={plant} 
                            userId={userId} 
                            db={db} 
                        />
                    ))
                )}
            </div>
            
            {/* Modais */}
            {userId && (
                <>
                    <AddPlantModal 
                        isOpen={showAddModal} 
                        onClose={() => setShowAddModal(false)} 
                        userId={userId} 
                        db={db} 
                    />
                    <PestCheckModal 
                        isOpen={showPestModal} 
                        onClose={() => setShowPestModal(false)} 
                    />
                </>
            )}
        </div>
    );
}