import { useState, useEffect } from 'react';
import { Link } from 'react-router-dom';
import { Helmet } from 'react-helmet-async';
import { Header } from '@/components/Header';
import { SearchBar } from '@/components/SearchBar';
import { CategoryFilter } from '@/components/CategoryFilter';
import { EmojiGrid } from '@/components/EmojiGrid';
import { LazyImageEditor } from '@/components/LazyImageEditor';
import { Footer } from '@/components/Footer';
import { Navigation } from '@/components/Navigation';
import { LazyCookieConsent } from '@/components/LazyCookieConsent';
import { submitHomepage } from '@/utils/indexnow';
import { useEmojiData } from '@/hooks/useEmojiData';
import { useFilteredEmojis } from '@/hooks/useFilteredEmojis';

const Index = () => {
  const [searchQuery, setSearchQuery] = useState('');
  const [selectedCategory, setSelectedCategory] = useState<string | null>(null);
  
  // Load emoji data asynchronously to avoid blocking main thread
  const { emojis, loading: emojiLoading } = useEmojiData();
  
  // Use optimized filtering hook
  const filteredEmojis = useFilteredEmojis(emojis, searchQuery, selectedCategory);

  // Handle immediate search transfer from loading state
  useEffect(() => {
    const handleImmediateSearch = (event: CustomEvent) => {
      if (event.detail?.query) {
        setSearchQuery(event.detail.query);
      }
    };

    window.addEventListener('immediateSearchTransfer', handleImmediateSearch as EventListener);
    return () => {
      window.removeEventListener('immediateSearchTransfer', handleImmediateSearch as EventListener);
    };
  }, []);

  // Submit homepage to IndexNow (already deferred in utility function)
  useEffect(() => {
    submitHomepage();
  }, []);

  return (
    <div className="min-h-screen bg-background">
      <Helmet>
        <title>Emojis Xpress 2026 – Free Emoji Copy & Paste Tool</title>
        <meta name="description" content="Copy & paste 3000+ free emojis instantly. Updated for 2026 with the latest Unicode emojis, meanings, and Gen-Z slang guide." />
        <meta name="robots" content="index, follow, max-image-preview:large" />
        <meta name="googlebot" content="index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1" />
        <link rel="canonical" href="https://emojisxpress.com/" />
        
        <meta property="og:type" content="website" />
        <meta property="og:title" content="Emojis Xpress 2026 – Free Emoji Copy & Paste Tool" />
        <meta property="og:description" content="Copy & paste 3000+ free emojis instantly. Updated for 2026 with the latest Unicode emojis, meanings, and Gen-Z slang guide." />
        <meta property="og:url" content="https://emojisxpress.com/" />
        <meta property="og:image" content="https://emojisxpress.com/og-image-400.webp" />
        <meta property="og:image:width" content="400" />
        <meta property="og:image:height" content="400" />
        <meta property="og:site_name" content="Emojis Xpress" />
        <meta property="og:locale" content="en_US" />
        
        <meta name="twitter:card" content="summary_large_image" />
        <meta name="twitter:site" content="@EmojisXpress" />
        <meta name="twitter:creator" content="@EmojisXpress" />
        <meta name="twitter:title" content="Emojis Xpress – Free Emoji Copy & Paste Tool" />
        <meta name="twitter:description" content="Copy and paste 3000+ free emojis instantly. Unicode emoji library with smart search." />
        <meta property="twitter:domain" content="emojisxpress.com" />
        <meta property="twitter:url" content="https://emojisxpress.com/" />
        <meta property="twitter:image" content="https://emojisxpress.com/og-image-400.webp" />
        <meta name="twitter:image:alt" content="Emojis Xpress - Free Emoji Copy Paste Platform" />
        
        {/* Structured Data - Organization */}
        <script type="application/ld+json">
          {JSON.stringify({
            "@context": "https://schema.org",
            "@type": "Organization",
            "name": "Emojis Xpress",
            "url": "https://emojisxpress.com",
            "logo": "https://emojisxpress.com/logo-48.webp",
            "description": "Free emoji copy paste tool with 3000+ Unicode symbols organized by categories",
            "contactPoint": {
              "@type": "ContactPoint",
              "contactType": "Customer Support",
              "email": "support@emojis-xpress.com",
              "url": "https://emojisxpress.com/contact"
            },
            "sameAs": [
              "https://twitter.com/EmojisXpress"
            ]
          })}
        </script>
        
        {/* Structured Data - Website */}
        <script type="application/ld+json">
          {JSON.stringify({
            "@context": "https://schema.org",
            "@type": "WebSite",
            "name": "Emojis Xpress",
            "url": "https://emojisxpress.com",
            "description": "Free emoji copy paste tool with 3000+ Unicode symbols",
            "potentialAction": {
              "@type": "SearchAction",
              "target": {
                "@type": "EntryPoint",
                "urlTemplate": "https://emojisxpress.com/?search={search_term_string}"
              },
              "query-input": "required name=search_term_string"
            },
            "mainEntity": {
              "@type": "SoftwareApplication",
              "name": "Emoji Copy Paste Tool",
              "applicationCategory": "Utility",
              "operatingSystem": "Web Browser",
              "offers": {
                "@type": "Offer",
                "price": "0",
                "priceCurrency": "USD"
              }
            }
          })}
        </script>

        {/* Structured Data - FAQPage (AEO / generative-engine answers) */}
        <script type="application/ld+json">
          {JSON.stringify({
            "@context": "https://schema.org",
            "@type": "FAQPage",
            "mainEntity": [
              {
                "@type": "Question",
                "name": "How do I copy and paste an emoji?",
                "acceptedAnswer": {
                  "@type": "Answer",
                  "text": "Open Emojis Xpress, search or browse for the emoji you want, and click it once — it's copied to your clipboard. Paste anywhere with Ctrl+V (Windows) or Cmd+V (Mac). Emojis work in chats, social posts, emails, docs, and code editors."
                }
              },
              {
                "@type": "Question",
                "name": "Are the emojis free to use?",
                "acceptedAnswer": {
                  "@type": "Answer",
                  "text": "Yes. Every emoji on Emojis Xpress is a standard Unicode character and is free to copy, paste, and download. No account, login, or payment is required."
                }
              },
              {
                "@type": "Question",
                "name": "Do these emojis work on iPhone, Android, Windows, and Mac?",
                "acceptedAnswer": {
                  "@type": "Answer",
                  "text": "Yes. Because the emojis are Unicode characters, they render natively on iOS, Android, Windows, macOS, Linux, and all modern web browsers — each platform draws them in its own style."
                }
              },
              {
                "@type": "Question",
                "name": "How do I download an emoji as a PNG image?",
                "acceptedAnswer": {
                  "@type": "Answer",
                  "text": "Open any emoji's download page, choose a size and background (transparent or solid), then click Download. The PNG works in slides, video thumbnails, design tools, and anywhere you need a high-resolution emoji image."
                }
              },
              {
                "@type": "Question",
                "name": "What does the blue heart emoji 💙 mean?",
                "acceptedAnswer": {
                  "@type": "Answer",
                  "text": "The blue heart 💙 signals trust, loyalty, and calm devotion. It's also widely used for autism awareness and team spirit. See the full color-by-color guide on the Emoji Meanings page."
                }
              },
              {
                "@type": "Question",
                "name": "How many emojis does Emojis Xpress have?",
                "acceptedAnswer": {
                  "@type": "Answer",
                  "text": "Over 3,000 Unicode emojis organized into eight categories: Smileys & People, Animals & Nature, Food & Drink, Travel & Places, Activities, Objects, Symbols, and Flags."
                }
              }
            ]
          })}
        </script>

        {/* Structured Data - HowTo */}
        <script type="application/ld+json">
          {JSON.stringify({
            "@context": "https://schema.org",
            "@type": "HowTo",
            "name": "How to copy and paste an emoji",
            "description": "Find, copy, and paste any emoji in seconds using Emojis Xpress.",
            "totalTime": "PT10S",
            "step": [
              { "@type": "HowToStep", "position": 1, "name": "Search or browse", "text": "Type a keyword in the search bar or pick a category to find the emoji you want." },
              { "@type": "HowToStep", "position": 2, "name": "Click to copy", "text": "Click the emoji once — Emojis Xpress copies it to your clipboard automatically." },
              { "@type": "HowToStep", "position": 3, "name": "Paste anywhere", "text": "Paste with Ctrl+V (Windows) or Cmd+V (Mac) into any app: chats, social posts, docs, or code." }
            ]
          })}
        </script>

      </Helmet>
      <Navigation />
      <Header />
      
      <main className="container mx-auto px-4 space-y-8">
        {/* Hidden H1 for SEO */}
        <h1 className="sr-only">Emojis Xpress - Free Emoji Copy and Paste Tool with 3000+ Unicode Symbols</h1>
        
        <SearchBar onSearch={setSearchQuery} />
        
        <CategoryFilter
          onCategoryChange={setSelectedCategory}
          selectedCategory={selectedCategory}
        />
        
        {/* Defer ImageEditor to not block critical path */}
        {!emojiLoading && <LazyImageEditor />}
        
        <EmojiGrid emojis={filteredEmojis} loading={emojiLoading} />
        
        {/* Enhanced SEO Content Section */}
        <section className="max-w-4xl mx-auto py-16 space-y-8">
          <h2 className="text-2xl font-bold text-foreground">Master Digital Expression with Professional Emoji Tools</h2>
          <p className="text-muted-foreground">
            Emojis Xpress revolutionizes digital communication through advanced emoji discovery technology and comprehensive unicode symbol organization. 
            Our platform provides instant access to meticulously categorized emoji collections. Discover our <Link to="/about" className="inline-link">comprehensive platform features</Link> or
            explore <Link to="/category/smileys" className="inline-link mx-1">Smileys & People</Link> for emotional expression,
            <Link to="/category/animals" className="inline-link mx-1">Animals & Nature</Link> for environmental themes,
            <Link to="/category/food" className="inline-link mx-1">Food & Drink</Link> for culinary content,
            <Link to="/category/travel" className="inline-link mx-1">Travel & Places</Link> for geographic references,
            <Link to="/category/activities" className="inline-link mx-1">Activities</Link> for sports and entertainment,
            <Link to="/category/objects" className="inline-link mx-1">Objects</Link> for technology and tools,
            <Link to="/category/symbols" className="inline-link mx-1">Symbols</Link> for mathematical and directional indicators, and
            <Link to="/category/flags" className="inline-link mx-1">Flags</Link> for international representation.
          </p>
          
          <h3 className="text-xl font-semibold text-foreground">Professional Features and Advanced Capabilities</h3>
          <p className="text-muted-foreground">
            Experience next-generation emoji discovery with intelligent search algorithms, real-time filtering, and cross-platform compatibility. 
            Our emoji copy paste technology ensures seamless integration across all devices, operating systems, and applications. Professional users 
            benefit from bulk copying capabilities, trending emoji analytics, and enterprise-grade reliability. Whether you're creating social media 
            content, developing user interfaces, or enhancing digital communications, <Link to="/" className="inline-link">Emojis Xpress</Link> provides the tools and emoji library you need 
            for impactful visual storytelling. <Link to="/contact" className="inline-link">Contact our team</Link> for enterprise solutions.
          </p>
          
          <nav aria-label="Sitemap Navigation" className="bg-gradient-card p-6 rounded-lg border border-border">
            <h3 className="text-lg font-semibold text-foreground mb-4">Explore Our Platform</h3>
            <div className="grid md:grid-cols-2 gap-4 text-sm">
              <div>
                <h4 className="font-medium text-foreground mb-2">Main Pages</h4>
                <ul className="space-y-1 text-muted-foreground">
                  <li><Link to="/" className="hover:text-primary transition-colors">Home - Emoji Collection</Link></li>
                  <li><Link to="/about" className="hover:text-primary transition-colors">About Emojis Xpress</Link></li>
                  <li><Link to="/contact" className="hover:text-primary transition-colors">Contact Support</Link></li>
                  <li><Link to="/download/face-with-tears-of-joy-%F0%9F%98%82" className="hover:text-primary transition-colors">Emoji Download Tool</Link></li>
                </ul>
              </div>
              <div>
                <h4 className="font-medium text-foreground mb-2">Emoji Categories</h4>
                <ul className="space-y-1 text-muted-foreground">
                  <li><Link to="/category/smileys" className="hover:text-primary transition-colors">😀 Smileys & People</Link></li>
                  <li><Link to="/category/animals" className="hover:text-primary transition-colors">🐶 Animals & Nature</Link></li>
                  <li><Link to="/category/food" className="hover:text-primary transition-colors">🍕 Food & Drink</Link></li>
                  <li><Link to="/category/travel" className="hover:text-primary transition-colors">✈️ Travel & Places</Link></li>
                  <li><Link to="/category/activities" className="hover:text-primary transition-colors">⚽ Activities & Sports</Link></li>
                  <li><Link to="/category/objects" className="hover:text-primary transition-colors">💻 Objects & Tech</Link></li>
                </ul>
              </div>
            </div>
          </nav>
          
          <p className="text-muted-foreground">
            Learn more <Link to="/about" className="inline-link">about our mission and technology</Link>, 
            review our <Link to="/privacy-policy" className="inline-link">privacy policy</Link> and 
            <Link to="/terms-of-service" className="inline-link">terms of service</Link>, or 
            <Link to="/contact" className="inline-link">contact our team</Link> for enterprise solutions and technical support.
            Explore our main <Link to="/" className="inline-link">emoji collection</Link> and discover all available 
            <Link to="/category/smileys" className="inline-link">categories</Link> for enhanced digital communication.
          </p>

          {/* Visible FAQ — quoted directly by AI Overviews, Perplexity, ChatGPT */}
          <section aria-labelledby="faq-heading" className="space-y-4 pt-6 border-t border-border">
            <h2 id="faq-heading" className="text-2xl font-bold text-foreground">Frequently Asked Questions</h2>
            <div>
              <h3 className="text-lg font-semibold text-foreground">How do I copy and paste an emoji?</h3>
              <p className="text-muted-foreground">Search or browse for the emoji you want, then click it once — Emojis Xpress copies it to your clipboard. Paste anywhere with Ctrl+V on Windows or Cmd+V on Mac.</p>
            </div>
            <div>
              <h3 className="text-lg font-semibold text-foreground">Are the emojis free to use?</h3>
              <p className="text-muted-foreground">Yes. Every emoji is a standard Unicode character — free to copy, paste, and download with no account or payment required.</p>
            </div>
            <div>
              <h3 className="text-lg font-semibold text-foreground">Do these emojis work on iPhone, Android, Windows, and Mac?</h3>
              <p className="text-muted-foreground">Yes. Unicode emojis render natively on every modern platform, so the same emoji works in iMessage, WhatsApp, Instagram, Slack, Gmail, Word, and anywhere else.</p>
            </div>
            <div>
              <h3 className="text-lg font-semibold text-foreground">How do I download an emoji as a PNG?</h3>
              <p className="text-muted-foreground">Open the emoji's download page, choose a size and background (transparent or solid), and click Download. The PNG is perfect for thumbnails, slides, and design work.</p>
            </div>
            <div>
              <h3 className="text-lg font-semibold text-foreground">What do the different heart colors mean?</h3>
              <p className="text-muted-foreground">Red ❤️ is romantic love, orange 🧡 is friendship, yellow 💛 is joy, green 💚 is nature, blue 💙 is loyalty, purple 💜 is K-pop and admiration, black 🖤 is edgy or grieving, white 🤍 is pure or minimalist, brown 🤎 is warmth and identity. Full breakdown on the <Link to="/meanings" className="inline-link">Emoji Meanings</Link> page.</p>
            </div>
            <div>
              <h3 className="text-lg font-semibold text-foreground">How many emojis are on Emojis Xpress?</h3>
              <p className="text-muted-foreground">Over 3,000 Unicode emojis across eight categories — Smileys & People, Animals & Nature, Food & Drink, Travel & Places, Activities, Objects, Symbols, and Flags.</p>
            </div>
          </section>
        </section>
      </main>
      
      <Footer />
      <LazyCookieConsent />
    </div>
  );
};

export default Index;