import React, { useState, useEffect, useMemo } from 'react';

import { Heart, Users, Smile, Edit3, Home, Sun, Sparkles, Quote, Send } from 'lucide-react';

import { initializeApp } from 'firebase/app';

import { getAuth, signInAnonymously, signInWithCustomToken, onAuthStateChanged } from 'firebase/auth';

import { getFirestore, collection, onSnapshot, addDoc, serverTimestamp, query } from 'firebase/firestore';


// --- Firebase Initialization ---

// We use the environment-provided configuration for the live database.

const firebaseConfig = typeof __firebase_config !== 'undefined' ? JSON.parse(__firebase_config) : {};

const app = Object.keys(firebaseConfig).length > 0 ? initializeApp(firebaseConfig) : null;

const auth = app ? getAuth(app) : null;

const db = app ? getFirestore(app) : null;

const appId = typeof __app_id !== 'undefined' ? __app_id : 'lovely-connection-demo';


export default function LovelyConnectionApp() {

  const [activeTab, setActiveTab] = useState('home');

  const [user, setUser] = useState(null);

  const [posts, setPosts] = useState([]);

  const [isSubmitting, setIsSubmitting] = useState(false);

  const [filter, setFilter] = useState('All');


  // New Post State

  const [newPost, setNewPost] = useState({

    title: '',

    message: '',

    category: 'Everyone',

    author: 'Admin'

  });


  // --- Authentication (Required before database access) ---

  useEffect(() => {

    if (!auth) return;

    const initAuth = async () => {

      try {

        if (typeof __initial_auth_token !== 'undefined' && __initial_auth_token) {

          await signInWithCustomToken(auth, __initial_auth_token);

        } else {

          await signInAnonymously(auth);

        }

      } catch (error) {

        console.error("Auth Error:", error);

      }

    };

    initAuth();

    

    const unsubscribe = onAuthStateChanged(auth, (currentUser) => {

      setUser(currentUser);

    });

    return () => unsubscribe();

  }, []);


  // --- Real-time Database Fetching ---

  useEffect(() => {

    if (!user || !db) return;


    // We use a public data path so the wall can be shared and viewed by anyone

    const postsRef = collection(db, 'artifacts', appId, 'public', 'data', 'lovely_posts');

    const q = query(postsRef);

    

    const unsubscribe = onSnapshot(q, (snapshot) => {

      const loadedPosts = snapshot.docs.map(doc => ({

        id: doc.id,

        ...doc.data()

      }));

      

      // Sort in memory to avoid needing complex Firestore indexes

      loadedPosts.sort((a, b) => {

        const timeA = a.createdAt?.toMillis() || 0;

        const timeB = b.createdAt?.toMillis() || 0;

        return timeB - timeA;

      });

      

      setPosts(loadedPosts);

    }, (error) => {

      console.error("Database Error:", error);

    });


    return () => unsubscribe();

  }, [user]);


  // --- Handle Posting Content ---

  const handlePostSubmit = async (e) => {

    e.preventDefault();

    if (!user || !db || !newPost.title || !newPost.message) return;

    

    setIsSubmitting(true);

    try {

      const postsRef = collection(db, 'artifacts', appId, 'public', 'data', 'lovely_posts');

      await addDoc(postsRef, {

        ...newPost,

        createdAt: serverTimestamp(),

        userId: user.uid

      });

      

      // Reset form and go to wall

      setNewPost({ title: '', message: '', category: 'Everyone', author: 'Admin' });

      setActiveTab('wall');

      setFilter('All');

    } catch (error) {

      console.error("Error adding post:", error);

    } finally {

      setIsSubmitting(false);

    }

  };


  // --- Creative Element: Random Quotes ---

  const quotes = [

    "Connection is the energy that exists between people when they feel seen, heard, and valued.",

    "Family and friends are hidden treasures, seek them and enjoy their riches.",

    "The most beautiful discovery true friends make is that they can grow separately without growing apart.",

    "Children remind us of the magic in the world. Men and women remind us of the strength to protect it."

  ];

  const [dailyQuote, setDailyQuote] = useState(quotes[0]);

  

  const generateNewQuote = () => {

    const random = quotes[Math.floor(Math.random() * quotes.length)];

    setDailyQuote(random);

  };


  // --- UI Helpers ---

  const getCategoryColor = (category) => {

    switch(category) {

      case 'Women': return 'bg-pink-100 text-pink-800 border-pink-200';

      case 'Men': return 'bg-blue-100 text-blue-800 border-blue-200';

      case 'Kids': return 'bg-yellow-100 text-yellow-800 border-yellow-200';

      default: return 'bg-purple-100 text-purple-800 border-purple-200';

    }

  };


  const filteredPosts = useMemo(() => {

    if (filter === 'All') return posts;

    return posts.filter(p => p.category === filter);

  }, [posts, filter]);


  return (

    <div className="min-h-screen bg-rose-50 font-sans text-slate-800 selection:bg-rose-200">

      

      {/* Header */}

      <header className="bg-white shadow-sm sticky top-0 z-10">

        <div className="max-w-5xl mx-auto px-4 py-4 flex flex-col sm:flex-row justify-between items-center gap-4">

          <div className="flex items-center gap-2">

            <Heart className="w-8 h-8 text-rose-500 fill-rose-500" />

            <div>

              <h1 className="text-2xl font-bold text-slate-900 tracking-tight">LovelyConnection<span className="text-rose-500">.org</span></h1>

              <p className="text-xs text-slate-500 uppercase tracking-wider font-semibold">Celebrating The People In Our Lives</p>

            </div>

          </div>

          

          <nav className="flex gap-2 bg-slate-100 p-1 rounded-full">

            <button 

              onClick={() => setActiveTab('home')}

              className={`flex items-center gap-2 px-4 py-2 rounded-full text-sm font-medium transition-colors ${activeTab === 'home' ? 'bg-white shadow text-rose-600' : 'text-slate-600 hover:text-slate-900'}`}

            >

              <Home className="w-4 h-4" /> Home

            </button>

            <button 

              onClick={() => setActiveTab('wall')}

              className={`flex items-center gap-2 px-4 py-2 rounded-full text-sm font-medium transition-colors ${activeTab === 'wall' ? 'bg-white shadow text-rose-600' : 'text-slate-600 hover:text-slate-900'}`}

            >

              <Users className="w-4 h-4" /> The Wall

            </button>

            <button 

              onClick={() => setActiveTab('post')}

              className={`flex items-center gap-2 px-4 py-2 rounded-full text-sm font-medium transition-colors ${activeTab === 'post' ? 'bg-white shadow text-rose-600' : 'text-slate-600 hover:text-slate-900'}`}

            >

              <Edit3 className="w-4 h-4" /> Post Content

            </button>

          </nav>

        </div>

      </header>


      {/* Main Content Area */}

      <main className="max-w-5xl mx-auto px-4 py-8">

        

        {/* --- HOME TAB --- */}

        {activeTab === 'home' && (

          <div className="space-y-8 animate-in fade-in slide-in-from-bottom-4 duration-500">

            {/* Hero Section */}

            <div className="bg-gradient-to-br from-rose-400 to-purple-500 rounded-3xl p-8 sm:p-12 text-white shadow-xl text-center relative overflow-hidden">

              <Sparkles className="absolute top-4 right-4 w-8 h-8 opacity-20" />

              <Sun className="absolute bottom-4 left-4 w-12 h-12 opacity-20" />

              <h2 className="text-3xl sm:text-5xl font-extrabold mb-4">A Space for Gratitude</h2>

              <p className="text-lg sm:text-xl text-rose-50 max-w-2xl mx-auto leading-relaxed">

                Dedicated to the incredible men, the inspiring women, and the joyful children who shape our world and fill our lives with meaning.

              </p>

            </div>


            {/* Interactive Quote Section */}

            <div className="bg-white rounded-2xl p-8 shadow-sm border border-slate-100 flex flex-col items-center text-center">

              <Quote className="w-10 h-10 text-rose-300 mb-4" />

              <p className="text-xl sm:text-2xl text-slate-700 font-medium italic max-w-3xl mb-6">

                "{dailyQuote}"

              </p>

              <button 

                onClick={generateNewQuote}

                className="px-6 py-2 bg-rose-50 text-rose-600 rounded-full text-sm font-semibold hover:bg-rose-100 transition-colors flex items-center gap-2"

              >

                <Sparkles className="w-4 h-4" /> Spark Joy

              </button>

            </div>


            {/* Categories Preview */}

            <div className="grid grid-cols-1 md:grid-cols-3 gap-6">

              <div className="bg-blue-50 rounded-2xl p-6 border border-blue-100 hover:shadow-md transition-shadow cursor-pointer" onClick={() => { setActiveTab('wall'); setFilter('Men'); }}>

                <div className="w-12 h-12 bg-blue-200 rounded-full flex items-center justify-center mb-4 text-blue-700">

                  <Users className="w-6 h-6" />

                </div>

                <h3 className="text-xl font-bold text-blue-900 mb-2">For the Men</h3>

                <p className="text-blue-800/80 text-sm">Honoring strength, guidance, and the steadfast presence of the men in our lives.</p>

              </div>

              <div className="bg-pink-50 rounded-2xl p-6 border border-pink-100 hover:shadow-md transition-shadow cursor-pointer" onClick={() => { setActiveTab('wall'); setFilter('Women'); }}>

                <div className="w-12 h-12 bg-pink-200 rounded-full flex items-center justify-center mb-4 text-pink-700">

                  <Heart className="w-6 h-6" />

                </div>

                <h3 className="text-xl font-bold text-pink-900 mb-2">For the Women</h3>

                <p className="text-pink-800/80 text-sm">Celebrating the nurturing, resilience, and boundless love of the women we cherish.</p>

              </div>

              <div className="bg-yellow-50 rounded-2xl p-6 border border-yellow-100 hover:shadow-md transition-shadow cursor-pointer" onClick={() => { setActiveTab('wall'); setFilter('Kids'); }}>

                <div className="w-12 h-12 bg-yellow-200 rounded-full flex items-center justify-center mb-4 text-yellow-700">

                  <Smile className="w-6 h-6" />

                </div>

                <h3 className="text-xl font-bold text-yellow-900 mb-2">For the Kids</h3>

                <p className="text-yellow-800/80 text-sm">Embracing the laughter, curiosity, and bright futures of the children around us.</p>

              </div>

            </div>

          </div>

        )}


        {/* --- THE WALL TAB --- */}

        {activeTab === 'wall' && (

          <div className="space-y-6 animate-in fade-in duration-500">

            <div className="flex flex-col sm:flex-row justify-between items-center mb-8 gap-4">

              <h2 className="text-3xl font-bold text-slate-800">The Appreciation Wall</h2>

              

              {/* Filters */}

              <div className="flex flex-wrap gap-2">

                {['All', 'Women', 'Men', 'Kids', 'Everyone'].map(cat => (

                  <button

                    key={cat}

                    onClick={() => setFilter(cat)}

                    className={`px-4 py-1.5 rounded-full text-sm font-medium transition-all ${

                      filter === cat 

                        ? 'bg-slate-800 text-white shadow-md' 

                        : 'bg-white text-slate-600 border border-slate-200 hover:bg-slate-50'

                    }`}

                  >

                    {cat}

                  </button>

                ))}

              </div>

            </div>


            {filteredPosts.length === 0 ? (

              <div className="text-center py-20 bg-white rounded-2xl border border-dashed border-slate-300">

                <Heart className="w-12 h-12 text-slate-300 mx-auto mb-4" />

                <h3 className="text-lg font-medium text-slate-600">No appreciations found for this category yet.</h3>

                <p className="text-slate-500 mb-4">Be the first to share some love!</p>

                <button 

                  onClick={() => setActiveTab('post')}

                  className="px-6 py-2 bg-rose-500 text-white rounded-full font-medium hover:bg-rose-600 transition-colors"

                >

                  Write a Post

                </button>

              </div>

            ) : (

              <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">

                {filteredPosts.map(post => (

                  <div key={post.id} className="bg-white rounded-2xl p-6 shadow-sm border border-slate-100 hover:shadow-md transition-shadow flex flex-col h-full">

                    <div className="flex justify-between items-start mb-4">

                      <span className={`px-3 py-1 rounded-full text-xs font-bold border ${getCategoryColor(post.category)}`}>

                        {post.category}

                      </span>

                      {post.createdAt && (

                        <span className="text-xs text-slate-400">

                          {new Date(post.createdAt.toMillis()).toLocaleDateString()}

                        </span>

                      )}

                    </div>

                    <h3 className="text-xl font-bold text-slate-800 mb-2">{post.title}</h3>

                    <p className="text-slate-600 mb-6 flex-grow whitespace-pre-wrap">{post.message}</p>

                    <div className="pt-4 border-t border-slate-50 flex items-center gap-2 mt-auto">

                      <div className="w-8 h-8 rounded-full bg-slate-100 flex items-center justify-center text-slate-500 font-bold text-sm">

                        {post.author ? post.author.charAt(0).toUpperCase() : 'A'}

                      </div>

                      <span className="text-sm font-medium text-slate-700">{post.author || 'Anonymous'}</span>

                    </div>

                  </div>

                ))}

              </div>

            )}

          </div>

        )}


        {/* --- POST CONTENT TAB (Admin/Creator Area) --- */}

        {activeTab === 'post' && (

          <div className="max-w-2xl mx-auto animate-in fade-in slide-in-from-bottom-4 duration-500">

            <div className="bg-white rounded-3xl shadow-xl overflow-hidden border border-slate-100">

              <div className="bg-gradient-to-r from-rose-500 to-rose-400 p-8 text-white">

                <h2 className="text-3xl font-bold mb-2">Share Your Appreciation</h2>

                <p className="text-rose-100">Add a new message, memory, or shoutout directly to the lovelyconnection.org wall.</p>

              </div>

              

              <form onSubmit={handlePostSubmit} className="p-8 space-y-6">

                <div>

                  <label className="block text-sm font-semibold text-slate-700 mb-2">Dedicated To (Category)</label>

                  <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">

                    {['Women', 'Men', 'Kids', 'Everyone'].map(cat => (

                      <button

                        type="button"

                        key={cat}

                        onClick={() => setNewPost({...newPost, category: cat})}

                        className={`py-2 rounded-xl text-sm font-medium border transition-all ${

                          newPost.category === cat 

                            ? getCategoryColor(cat) + ' ring-2 ring-offset-1 ring-slate-200'

                            : 'bg-white text-slate-600 border-slate-200 hover:bg-slate-50'

                        }`}

                      >

                        {cat}

                      </button>

                    ))}

                  </div>

                </div>


                <div>

                  <label htmlFor="title" className="block text-sm font-semibold text-slate-700 mb-2">Title / Headline</label>

                  <input

                    id="title"

                    type="text"

                    required

                    value={newPost.title}

                    onChange={(e) => setNewPost({...newPost, title: e.target.value})}

                    placeholder="e.g., Thank you to my amazing sister"

                    className="w-full px-4 py-3 rounded-xl border border-slate-200 focus:ring-2 focus:ring-rose-500 focus:border-rose-500 outline-none transition-all"

                  />

                </div>


                <div>

                  <label htmlFor="message" className="block text-sm font-semibold text-slate-700 mb-2">Your Message</label>

                  <textarea

                    id="message"

                    required

                    rows="5"

                    value={newPost.message}

                    onChange={(e) => setNewPost({...newPost, message: e.target.value})}

                    placeholder="Write your words of appreciation here..."

                    className="w-full px-4 py-3 rounded-xl border border-slate-200 focus:ring-2 focus:ring-rose-500 focus:border-rose-500 outline-none transition-all resize-y"

                  ></textarea>

                </div>


                <div>

                  <label htmlFor="author" className="block text-sm font-semibold text-slate-700 mb-2">Signed By</label>

                  <input

                    id="author"

                    type="text"

                    value={newPost.author}

                    onChange={(e) => setNewPost({...newPost, author: e.target.value})}

                    placeholder="Your Name"

                    className="w-full px-4 py-3 rounded-xl border border-slate-200 focus:ring-2 focus:ring-rose-500 focus:border-rose-500 outline-none transition-all"

                  />

                </div>


                <button

                  type="submit"

                  disabled={isSubmitting || !newPost.title || !newPost.message}

                  className="w-full py-4 bg-slate-900 text-white rounded-xl font-bold text-lg hover:bg-slate-800 transition-colors flex justify-center items-center gap-2 disabled:opacity-50 disabled:cursor-not-allowed shadow-lg shadow-slate-200"

                >

                  {isSubmitting ? 'Posting...' : (

                    <>

                      Post to Wall <Send className="w-5 h-5" />

                    </>

                  )}

                </button>

              </form>

            </div>

          </div>

        )}

      </main>

      

      {/* Footer */}

      <footer className="max-w-5xl mx-auto px-4 py-8 text-center text-slate-500 text-sm border-t border-slate-200 mt-12">

        <p>© {new Date().getFullYear()} LovelyConnection.org. Created with love, React, and Firebase.</p>

      </footer>

    </div>

  );

}