import React, { useState, useEffect } from 'react';
import { BrowserRouter, Routes, Route, Link, useNavigate, useLocation, useParams, useSearchParams } from 'react-router-dom';
import { Helmet, HelmetProvider } from 'react-helmet-async';
import { 
  Search, ShoppingCart, Menu, X, ChevronRight, ChevronLeft, 
  Phone, Settings, Mail, MapPin, CheckCircle, Zap, Trash2, 
  ArrowLeft, Image as ImageIcon, ShieldCheck, FileText, Upload, 
  Database, Lock, Play, Globe, Cpu, BarChart, Server, RefreshCw, Send, Plane, Plus
} from 'lucide-react';

// ==================================================================================
// --- DECLARAÇÕES GLOBAIS (PRERENDER.IO) ---
// ==================================================================================
declare global {
  interface Window {
    prerenderReady: boolean;
  }
}

// ==================================================================================
// --- ASSETS CONFIGURATION ---
// ==================================================================================

import localHero from './assets/fundo.png';
import localLogo from './assets/logo.png';
import localEng from './assets/img1.png';
import localAvionics from './assets/img2.png';
import localLogistics from './assets/img3.png';

const HERO_IMAGE = localHero;
const LOGO_URL = localLogo;
const VIDEO_URL = "/video.mp4"; 

const GALLERY = {
  engineering: localEng,
  avionics: localAvionics,
  logistics: localLogistics,
};

const API_BASE_URL = 'https://api.globalpartstechnology.com';
const SOURCING_API_URL = 'https://sourcing.globalpartstechnology.com';

// --- TYPES ---
interface Product {
  id: number;
  pn: string;
  oem: string;
  name: string;
  condition: 'NE' | 'OH' | 'SV' | 'AR';
  price: number;
  stock: number;
  category: string;
}

interface CartItem extends Product {
  quantity: number;
}

interface NeighborData {
    id: number;
    pn: string;
}

interface Neighbors {
    prev: NeighborData | null;
    next: NeighborData | null;
}

interface FetchResult {
    items: Product[];
    total: number;
    totalPages: number;
}

interface Supplier {
    id: number;
    company_name: string;
    domain: string;
    email: string;
    tier: string;
    country?: string;
    capabilities: string[];
}

// --- API SERVICES ---

const fetchProductsFromApi = async (query: string, page: number = 1, exactMatch: boolean = false, specificId: string | null = null): Promise<FetchResult> => {
    try {
        let url = `${API_BASE_URL}/products.php?`;
        if (specificId) { url += `id=${specificId}`; } 
        else {
            url += `page=${page}`;
            if (query) { url += `&q=${encodeURIComponent(query)}`; if (exactMatch) url += `&exact=true`; }
        }
        url += `&_t=${new Date().getTime()}`; 
        const response = await fetch(url);
        if (!response.ok) throw new Error(`HTTP Error: ${response.status}`);
        const rawData = await response.json();
        let items: Product[] = []; let total = 0; let pages = 1;
        if (rawData.data && Array.isArray(rawData.data)) { items = rawData.data; if (rawData.meta) { total = rawData.meta.total_items || 0; pages = rawData.meta.total_pages || 1; } } 
        else if (Array.isArray(rawData)) { items = rawData; total = items.length; }
        return { items, total, totalPages: pages };
    } catch (error) { console.error("API Failure:", error); return { items: [], total: 0, totalPages: 0 }; }
};

const fetchNeighbors = async (id: number): Promise<Neighbors> => {
    try { const res = await fetch(`${API_BASE_URL}/products.php?neighbor_of=${id}`); if (!res.ok) return { prev: null, next: null }; return await res.json(); } catch (e) { return { prev: null, next: null }; }
};

const Badge = ({ children, color }: { children: React.ReactNode, color: string }) => (
  <span className={`px-1.5 py-0.5 rounded text-[10px] font-bold tracking-wider ${color} shadow-sm backdrop-blur-md bg-opacity-80`}>{children}</span>
);

const formatPrice = (price: number) => {
    const numPrice = Number(price);
    if (isNaN(numPrice) || numPrice <= 0) return 'RFQ';
    return new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(numPrice);
};

// ==================================================================================
// --- PAGES ---
// ==================================================================================

const Home = () => {
  const navigate = useNavigate();
  const [search, setSearch] = useState('');

  useEffect(() => {
    localStorage.removeItem('last_catalog_search');
    window.prerenderReady = true;
  }, []);

  return (
    <>
      <Helmet>
        <title>Global Parts-Technology | Aviation Parts Distributor</title>
        <meta name="description" content="Global leader in aviation supply chain. Search our SQL database for commercial and civil aircraft parts. AOG Support 24/7." />
        <link rel="canonical" href="https://globalpartstechnology.com/" />
      </Helmet>

      {/* HERO SECTION */}
      <div className="relative min-h-[90vh] flex items-center justify-center overflow-hidden py-20">
        <div className="relative z-10 text-center px-4 max-w-5xl mx-auto">
          <h1 className="text-5xl md:text-7xl font-bold text-transparent bg-clip-text bg-gradient-to-b from-white to-slate-200 mb-6 tracking-tight drop-shadow-[0_2px_10px_rgba(0,0,0,0.8)]">
            Global Parts-Technology keeping the World <br/><span className="text-cyan-400 drop-shadow-[0_0_20px_rgba(34,211,238,0.6)]">Flying Safe</span>
          </h1>
          
          <p className="text-lg md:text-xl text-slate-100 mb-10 font-light tracking-wide max-w-3xl mx-auto drop-shadow-md">
            Your certified partner for <strong className="text-white font-semibold"> Quality</strong>, <strong className="text-white font-semibold">Traceable Components</strong>, and <strong className="text-white font-semibold">24/7 AOG Support</strong>.
          </p>

          <div className="max-w-3xl mx-auto relative group mt-10">
            <div className="relative flex items-center bg-black/30 backdrop-blur-md border border-white/20 rounded-lg shadow-2xl overflow-hidden transition-all hover:bg-black/40">
              <Search className="w-6 h-6 ml-4 text-cyan-400" />
              <input 
                type="text" 
                placeholder="Search by Part Number..."
                className="w-full bg-transparent border-none text-white px-4 py-4 focus:ring-0 text-lg placeholder-slate-300 font-medium outline-none"
                value={search}
                onChange={(e) => setSearch(e.target.value)}
                onKeyDown={(e) => e.key === 'Enter' && navigate(`/catalog?q=${encodeURIComponent(search)}`)}
              />
              <button onClick={() => navigate(`/catalog?q=${encodeURIComponent(search)}`)} className="bg-cyan-600/80 hover:bg-cyan-500/90 text-white font-bold px-8 py-4 transition-all tracking-widest border-l border-white/10 backdrop-blur-md cursor-pointer">SEARCH</button>
            </div>
            
            <p className="text-lg md:text-xl text-slate-200 mb-10 font-light tracking-wide max-w-3xl mx-auto mt-6 drop-shadow-sm">
              <span className="flex items-center gap-2 justify-center"><ShieldCheck className="w-3 h-3"/>  <span className="hidden md:inline mx-2">security |</span> <FileText className="w-3 h-3 hidden md:inline"/>  <span className="hidden md:inline">Traceability Guaranteed</span></span>
            </p>

            <div className="mt-8 bg-black/20 backdrop-blur-sm border border-white/10 rounded-xl p-6 text-slate-100 text-sm md:text-base leading-relaxed shadow-lg max-w-3xl mx-auto">
                <p className="mb-4">
                  Global Parts-Technology is your trusted partner for high-tech electronic components for commercial aviation, civil, and other sectors. We connect supply and demand, specializing in hard-to-find parts with a focus on safety and original quality.
                </p>
                <p className="mb-4">
                  Backed by strict adherence to industry standards and a dedicated team of experts, we ensure your operations remain efficient and compliant.
                </p>
                <p className="font-bold text-cyan-400">
                  Explore over 12 Million aerospace and electronic components today.
                </p>
            </div>

            <div className="mt-12 w-full">
                <div className="relative rounded-2xl p-[1px] bg-gradient-to-b from-slate-700 to-transparent shadow-[0_0_40px_rgba(6,182,212,0.15)]">
                    <div className="bg-black/60 backdrop-blur-xl rounded-2xl overflow-hidden">
                        <div className="h-9 bg-white/5 border-b border-white/10 flex items-center px-4 gap-2">
                            <div className="w-3 h-3 rounded-full bg-red-500/80 shadow-sm"></div>
                            <div className="w-3 h-3 rounded-full bg-yellow-500/80 shadow-sm"></div>
                            <div className="w-3 h-3 rounded-full bg-green-500/80 shadow-sm"></div>
                            <div className="ml-auto flex items-center gap-2 text-[10px] tracking-widest text-slate-400 font-mono uppercase">
                                <Play className="w-3 h-3 text-cyan-500" />
                                Corporate_Presentation.mp4
                            </div>
                        </div>
                        <div className="relative aspect-video bg-black">
                            <video className="w-full h-full object-cover" controls src={VIDEO_URL} poster={LOGO_URL} >
                                Your browser does not support the video tag.
                            </video>
                        </div>
                    </div>
                </div>
            </div>

          </div>
        </div>
      </div>

      <section className="py-20 bg-black/20 relative border-t border-white/10 backdrop-blur-sm">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="text-center mb-16">
            <h2 className="text-3xl font-bold text-gray-100 mb-4 tracking-wide">Why Choose Global Parts</h2>
            <div className="h-1 w-24 bg-gradient-to-r from-transparent via-cyan-600 to-transparent mx-auto"></div>
          </div>
          <div className="grid grid-cols-1 md:grid-cols-3 gap-8">
            {[
              { icon: Zap, title: "AOG Support", desc: "24/7 Aircraft On Ground expedited shipping services worldwide." },
              { icon: CheckCircle, title: "Traceability", desc: "Full documentation and OEM certification with every part." },
              { icon: Settings, title: "Technical Expertise", desc: "Access our database of technical manuals and cross-reference checks." }
            ].map((feature, i) => (
              <div key={i} className="bg-slate-900/20 p-8 rounded-2xl border border-white/10 hover:border-cyan-500/50 transition-all duration-500 group backdrop-blur-md hover:bg-slate-900/40 hover:shadow-lg">
                <feature.icon className="w-12 h-12 text-slate-300 mb-6 group-hover:text-cyan-400 group-hover:scale-110 transition-all duration-300" />
                <h3 className="text-xl font-bold text-white mb-3">{feature.title}</h3>
                <p className="text-slate-200 leading-relaxed">{feature.desc}</p>
              </div>
            ))}
          </div>
        </div>
      </section>

      <section className="bg-black/30 py-20 border-t border-slate-800/50 backdrop-blur-md">
        <div className="max-w-7xl mx-auto px-4">
          <h2 className="text-3xl font-bold text-gray-100 mb-12 text-center flex items-center justify-center gap-3">
            <ImageIcon className="w-8 h-8 text-cyan-500"/> Operational Excellence
          </h2>
          <div className="grid grid-cols-1 md:grid-cols-3 gap-6 h-96">
             <div className="group relative rounded-2xl overflow-hidden border border-slate-800/50 shadow-xl h-full bg-slate-900/20 backdrop-blur-sm">
              <div className="absolute inset-0 bg-cover bg-center transition-transform duration-700 group-hover:scale-110 opacity-80 group-hover:opacity-100" style={{backgroundImage: `url("${GALLERY.engineering}")`}}></div>
              <div className="absolute inset-0 bg-gradient-to-t from-black via-black/40 to-transparent"></div>
              <div className="absolute bottom-0 left-0 p-6">
                <h3 className="text-xl font-bold text-white mb-1">Precision Engineering</h3>
                <p className="text-cyan-400 text-sm">Certified Components</p>
              </div>
            </div>
            <div className="group relative rounded-2xl overflow-hidden border border-slate-800/50 shadow-xl h-full md:-mt-8 md:mb-8 bg-slate-900/20 backdrop-blur-sm">
              <div className="absolute inset-0 bg-cover bg-center transition-transform duration-700 group-hover:scale-110 opacity-80 group-hover:opacity-100" style={{backgroundImage: `url("${GALLERY.avionics}")`}}></div>
              <div className="absolute inset-0 bg-gradient-to-t from-black via-black/40 to-transparent"></div>
              <div className="absolute bottom-0 left-0 p-6">
                <h3 className="text-xl font-bold text-white mb-1">Avionics Systems</h3>
                <p className="text-cyan-400 text-sm">Advanced Technology</p>
              </div>
            </div>
            <div className="group relative rounded-2xl overflow-hidden border border-slate-800/50 shadow-xl h-full bg-slate-900/20 backdrop-blur-sm">
              <div className="absolute inset-0 bg-cover bg-center transition-transform duration-700 group-hover:scale-110 opacity-80 group-hover:opacity-100" style={{backgroundImage: `url("${GALLERY.logistics}")`}}></div>
              <div className="absolute inset-0 bg-gradient-to-t from-black via-black/40 to-transparent"></div>
              <div className="absolute bottom-0 left-0 p-6">
                <h3 className="text-xl font-bold text-white mb-1">Global Logistics</h3>
                <p className="text-cyan-400 text-sm">24/7 Dispatch</p>
              </div>
            </div>
          </div>
        </div>
      </section>
    </>
  );
};

// 2. CATALOG PAGE
const Catalog = ({ addToCart }: { addToCart: (p: Product) => void }) => {
  const [products, setProducts] = useState<Product[]>([]);
  const [totalResults, setTotalResults] = useState(0);
  const [totalPages, setTotalPages] = useState(1);
  const [loading, setLoading] = useState(false);
  const [jumpPage, setJumpPage] = useState('');
  const [searchParams, setSearchParams] = useSearchParams();
  const location = useLocation();
  const query = searchParams.get('q') || '';
  const pageParam = parseInt(searchParams.get('page') || '1');
  const [currentPage, setCurrentPage] = useState(pageParam);
  const [inputValue, setInputValue] = useState(query);

  useEffect(() => {
    localStorage.setItem('last_catalog_search', location.search);
  }, [location.search]);

  useEffect(() => {
    setInputValue(query);
    setCurrentPage(pageParam > 0 ? pageParam : 1);
  }, [query, pageParam]);

  useEffect(() => {
    let isMounted = true;
    window.prerenderReady = false; 

    const fetchIt = async () => {
      setLoading(true);
      const { items, total, totalPages: serverPages } = await fetchProductsFromApi(query, currentPage, false);      
      
      if (isMounted) {
        setProducts(items);
        setTotalResults(total);
        setTotalPages(serverPages);
        setLoading(false);
        window.prerenderReady = true; 
      }
    };
    
    const timer = setTimeout(() => fetchIt(), query ? 300 : 0);
    return () => { clearTimeout(timer); isMounted = false; };
  }, [query, currentPage]);

  const updateUrl = (newQuery: string, newPage: number) => {
    setSearchParams({ q: newQuery, page: newPage.toString() });
  };

  const handleSearchChange = (val: string) => {
    setInputValue(val);
    updateUrl(val, 1);
  };

  const handlePageChange = (newPage: number) => {
    setCurrentPage(newPage);
    updateUrl(query, newPage);
    window.scrollTo({ top: 0, behavior: 'smooth' });
  };

  const handleJumpToPage = (e: React.FormEvent) => {
      e.preventDefault();
      const p = parseInt(jumpPage);
      if (!isNaN(p) && p >= 1 && p <= totalPages) {
          handlePageChange(p);
          setJumpPage('');
      } else {
          alert(`Please enter a page between 1 and ${totalPages}`);
      }
  };

  const safePage = Math.min(Math.max(1, currentPage), Math.max(1, totalPages));

  return (
    <>
      <Helmet>
        <title>Inventory Search | Global Parts</title>
        <meta name="description" content={`Browse our extensive aviation parts inventory. Currently showing results.`} />
        <link rel="canonical" href="https://globalpartstechnology.com/catalog" />
      </Helmet>

      <div className="max-w-7xl mx-auto px-4 py-12">
        <div className="flex flex-col md:flex-row justify-between items-end mb-8 gap-4">
          <div>
            <h2 className="text-3xl font-bold text-white tracking-wide drop-shadow-md">Parts Inventory</h2>
            <p className="text-cyan-400 font-mono mt-1 text-sm flex items-center gap-2">
              <span className="w-2 h-2 rounded-full bg-cyan-500 animate-pulse shadow-[0_0_10px_#06b6d4]"></span>
              Live Database
            </p>
            {!loading && (
                 <p className="text-slate-200 text-xs mt-2 font-mono drop-shadow-sm">
                    Found <span className="text-white font-bold">{totalResults}</span> items. Page {safePage} of {totalPages}.
                </p>
            )}
          </div>
          <div className="w-full md:w-1/5 relative">
            <Search className="absolute left-3 top-3 h-5 w-5 text-slate-300" />
            <input 
              type="text" value={inputValue} onChange={(e) => handleSearchChange(e.target.value)}
              placeholder="Filter by PN..."
              className="w-full bg-black/20 backdrop-blur-xl border border-white/20 rounded-lg pl-10 pr-4 py-2.5 text-white focus:border-cyan-500/50 focus:ring-1 focus:ring-cyan-500/50 transition-all placeholder-slate-400 outline-none"
            />
          </div>
        </div>

{loading ? (
  <div className="text-center py-20 text-cyan-400 animate-pulse font-mono text-lg font-bold drop-shadow-lg">LOADING DATA...</div>
) : (
  <div className="grid grid-cols-2 md:grid-cols-4 lg:grid-cols-5 gap-4">
    {products.length === 0 ? (
        <div className="md:col-span-5 text-center py-10 text-slate-300 bg-black/20 rounded-lg backdrop-blur-sm border border-white/10">
            {inputValue ? `No results found for "${inputValue}". Check your spelling.` : "No items loaded from database. Please try searching."}
        </div>
    ) : (
        products.map((product) => (
          <article key={product.id} className="bg-slate-900/20 backdrop-blur-md rounded-lg border border-white/10 hover:border-cyan-500/40 p-3 flex flex-col justify-between h-full group transition-all duration-300 hover:bg-slate-900/40 hover:shadow-xl hover:-translate-y-1">
            
            <Link 
                to={`/part/${product.pn.trim().replace(/\s+/g, '-')}/${product.id}`} 
                className="block cursor-pointer"
            >
              {/* IMAGEM DINÂMICA NO CATÁLOGO */}
              <div className="relative w-full h-32 mb-3 bg-black/40 rounded flex items-center justify-center overflow-hidden border border-slate-700/30">
                 <img 
                    src={`${API_BASE_URL}/generate_image.php?pn=${encodeURIComponent(product.pn)}`}
                    alt={product.pn} 
                    className="max-h-full max-w-full object-contain opacity-70 group-hover:opacity-100 transition-opacity" 
                    onError={(e) => { e.currentTarget.src = '/peca.png'; }}
                 />
                 <div className="absolute top-2 right-2">
                    <Badge color="bg-cyan-900/80 text-cyan-200 border border-cyan-500/30">{product.condition}</Badge>
                 </div>
              </div>
              
              <h3 className="text-xs font-semibold text-white mb-2 line-clamp-2 min-h-[2.5em] group-hover:text-cyan-300 transition-colors drop-shadow-sm">{product.name}</h3>
              <div className="space-y-1 mb-3 text-xs">
                <div className="flex justify-between items-end mt-2">
                  <div className="flex flex-col">
                    <span className="text-slate-400 text-[9px] uppercase font-bold">Part Number</span>
                    <span className="text-cyan-400 font-mono font-bold text-sm drop-shadow-[0_0_5px_rgba(34,211,238,0.2)]">{product.pn}</span>
                  </div>
                  <div className="flex flex-col items-end">
                    <span className="text-slate-400 text-[9px] uppercase font-bold">Price</span>
                    <span className={`font-mono font-bold text-sm ${Number(product.price) > 0 ? 'text-green-400' : 'text-slate-300'}`}>
                      {formatPrice(product.price)}
                    </span>
                  </div>
                </div>
              </div>
            </Link>

            <button onClick={() => addToCart(product)} className="w-full relative z-10 bg-white/5 hover:bg-gradient-to-r hover:from-cyan-600 hover:to-cyan-500 text-gray-200 hover:text-white py-1.5 rounded border border-white/10 hover:border-transparent text-[10px] font-bold flex items-center justify-center gap-1 shadow-lg transition-all cursor-pointer backdrop-blur-sm mt-2">
              <ShoppingCart className="w-3 h-3" /> ADD
            </button>
          </article>
        ))
    )}
  </div>
)}

        {totalResults > 0 && (
           <div className="mt-12 bg-black/30 backdrop-blur-md p-4 rounded-xl border border-slate-700/50 flex flex-wrap justify-center items-center gap-6 shadow-xl max-w-3xl mx-auto">
             
             <div className="flex flex-wrap items-center justify-center gap-2">
                 <Link 
                     to={`/catalog?q=${encodeURIComponent(query)}&page=${safePage - 1}`} 
                     className={`text-white p-2 rounded hover:bg-white/10 transition ${safePage === 1 ? 'opacity-30 pointer-events-none' : 'hover:text-cyan-400'}`}
                 >
                     <ChevronLeft /> Prev
                 </Link>

                 <div className="hidden md:flex gap-2 mx-4 items-center">
                     <Link to={`/catalog?q=${encodeURIComponent(query)}&page=1`} className="text-xs font-mono text-slate-400 hover:text-cyan-400 p-1">1</Link>
                     {safePage > 3 && <span className="text-slate-600">...</span>}
                     
                     <span className="text-white text-sm font-bold font-mono bg-cyan-900/50 px-3 py-1 rounded border border-cyan-500/30">
                         Page {safePage} of {totalPages}
                     </span>
                     
                     {safePage < totalPages - 2 && <span className="text-slate-600">...</span>}
                     
                     {totalPages > 10 && safePage < totalPages / 2 && (
                         <Link to={`/catalog?q=${encodeURIComponent(query)}&page=${Math.floor(totalPages / 2)}`} className="text-xs font-mono text-slate-400 hover:text-cyan-400 p-1">
                             {Math.floor(totalPages / 2)}
                         </Link>
                     )}
                     <Link to={`/catalog?q=${encodeURIComponent(query)}&page=${totalPages}`} className="text-xs font-mono text-slate-400 hover:text-cyan-400 p-1">
                         {totalPages}
                     </Link>
                 </div>

                 <Link 
                     to={`/catalog?q=${encodeURIComponent(query)}&page=${safePage + 1}`} 
                     className={`text-white p-2 rounded hover:bg-white/10 transition ${safePage >= totalPages ? 'opacity-30 pointer-events-none' : 'hover:text-cyan-400'}`}
                 >
                     Next <ChevronRight />
                 </Link>
             </div>

             <div className="h-8 w-px bg-white/20 hidden md:block"></div>

             <form onSubmit={handleJumpToPage} className="flex items-center gap-2">
                 <label className="text-xs text-slate-300 uppercase font-bold hidden sm:block">Go to Page:</label>
                 <input 
                    type="number" 
                    min="1" 
                    max={totalPages}
                    placeholder="#"
                    className="w-20 bg-black/20 border border-slate-600 rounded px-2 py-1.5 text-white text-sm focus:border-cyan-500 outline-none text-center"
                    value={jumpPage}
                    onChange={(e) => setJumpPage(e.target.value)}
                 />
                 <button type="submit" className="bg-cyan-700 hover:bg-cyan-600 text-white text-xs font-bold px-3 py-2 rounded transition shadow-lg cursor-pointer">
                    GO
                 </button>
             </form>

           </div>
        )}
      </div>
    </>
  );
};

// ==========================================================
// COMPONENTE SEO: TEIA DE ARANHA (DADOS REAIS DO BANCO)
// ==========================================================
const RelatedParts = ({ realRelatedParts }: { realRelatedParts: Product[] }) => {
  if (!realRelatedParts || realRelatedParts.length === 0) {
    return null; 
  }

  return (
    <div className="mt-8 pt-8 border-t border-slate-700/50">
      <h3 className="text-xl font-bold text-white mb-2 flex items-center gap-2">
        <Search className="w-5 h-5 text-cyan-500" />
        Frequently Searched Alternatives
      </h3>
      
      <p className="text-sm text-slate-400 mb-6">
        Check the availability and specifications of these <strong className="text-cyan-400">real components</strong> from our inventory:
      </p>

      <div className="grid grid-cols-2 md:grid-cols-3 gap-3">
        {realRelatedParts.map((part, index) => (
          <Link 
            key={index} 
            to={`/part/${encodeURIComponent(encodeURIComponent(part.pn))}/${part.id}`} 
            className="bg-slate-900/50 border border-slate-700 hover:border-cyan-500/50 text-slate-300 hover:text-cyan-400 text-sm font-mono p-3 rounded flex flex-col items-center justify-center gap-3 transition-all shadow-sm hover:bg-slate-800 relative group overflow-hidden"
          >
             {/* IMAGEM DINÂMICA NAS PEÇAS RELACIONADAS */}
             <div className="w-full h-24 bg-black/40 flex items-center justify-center rounded border border-slate-700/30 overflow-hidden">
                <img 
                    src={`${API_BASE_URL}/generate_image.php?pn=${encodeURIComponent(part.pn)}`}
                    alt={part.pn} 
                    className="h-full w-full object-contain opacity-60 group-hover:opacity-100 transition-opacity transform group-hover:scale-105 duration-500" 
                    onError={(e) => { e.currentTarget.src = '/peca.png'; }}
                />
             </div>
             <span className="font-bold">{part.pn}</span>
          </Link>
        ))}
      </div>
    </div>
  );
}

// 3. PRODUCT DETAIL
const ProductDetail = ({ addToCart }: { addToCart: (p: Product) => void }) => {
  const { id, pn } = useParams();
  const [product, setProduct] = useState<Product | null>(() => {
    return (window as any).__INITIAL_DATA__ || null;
  });
  const [neighbors, setNeighbors] = useState<Neighbors>({ prev: null, next: null });
  const [relatedParts, setRelatedParts] = useState<Product[]>([]); 
  const [loading, setLoading] = useState(true);
  const navigate = useNavigate();

  const handleBackToResults = () => {
    const lastSearch = localStorage.getItem('last_catalog_search');
    if (lastSearch) {
        navigate(`/catalog${lastSearch}`);
    } else {
        navigate('/catalog');
    }
  };

  useEffect(() => {
    const loadData = async () => {
      window.prerenderReady = false; 
      setLoading(true);
      
      try {
        let found: Product | undefined;

        if (pn) {
             const decodedPn = decodeURIComponent(decodeURIComponent(pn));
             const result = await fetchProductsFromApi(decodedPn, 1, true);
             
             if (result.items.length > 0) {
                 if (id) {
                     found = result.items.find(p => String(p.id) === String(id));
                 }
                 if (!found) found = result.items[0];
             }
        }

        if (!found && id) {
            const result = await fetchProductsFromApi('', 1, false, id);
            if (result.items.length > 0) {
                found = result.items[0];
            }
        }

        setProduct(found || null);

        if (found) {
            const neighData = await fetchNeighbors(found.id);
            setNeighbors(neighData);
            
            const randomParts = await fetchProductsFromApi('', 1, false);
            if (randomParts.items && randomParts.items.length > 0) {
                const filtered = randomParts.items.filter(p => p.id !== found.id).slice(0, 5);
                setRelatedParts(filtered);
            }
        }

      } catch (error) {
        setProduct(null);
      } finally { 
        setLoading(false); 
        window.prerenderReady = true; 
      }
    };
    
    loadData();
    window.scrollTo(0, 0);
  }, [id, pn]);

  if (loading && !product) return <div className="text-center py-20 animate-pulse text-cyan-500">Accessing Database...</div>;
  
  if (!product) return (
    <div className="text-center py-20 font-mono">
        <h2 className="text-red-500 text-xl font-bold mb-4">PART NOT FOUND</h2>
        <div className="bg-black/30 p-6 rounded max-w-lg mx-auto text-left text-sm space-y-2 border border-slate-700/50 backdrop-blur-md">
            <p className="text-white">The requested Part Number is not available or the ID is invalid.</p>
        </div>
        <button onClick={handleBackToResults} className="mt-6 text-cyan-400 border border-cyan-400 px-4 py-2 rounded hover:bg-cyan-400 hover:text-black transition">Return to Catalog</button>
    </div>
  );

  const resolveSmartCategory = (dbCategory: string, partNum: string) => {
    if (dbCategory && dbCategory.trim() !== '' && dbCategory.toLowerCase() !== 'avionics - aviation') return dbCategory;
    
    const prefix = partNum.substring(0, 2).toUpperCase();
    if (prefix === 'AN' || prefix === 'MS' || prefix === 'NA' || prefix === 'NAS') return 'Airframe Fasteners & Hardware';
    if (prefix === 'CR' || prefix === 'RC' || prefix === 'M8' || prefix === 'CW') return 'Electrical & Avionics Components';
    if (partNum.includes('-')) return 'Structural & Rotable Components';
    
    return 'Aerospace Consumables & Systems';
  };

  const displayOEM = product.oem || 'Various OEM'; 
  const displayCategory = resolveSmartCategory(product.category, product.pn);

  const generateUniqueDescription = (pn: string, oem: string, condition: string, category: string, pId: number) => {
    const condSafe = condition || 'various';
    const safeId = pId || 0;

    const intros = [
        `Looking for the ${pn}?`,
        `Source the high-quality ${pn} today.`,
        `We offer the ${pn} for immediate dispatch.`,
        `Request a quote for the ${pn}.`,
        `Find competitive pricing for the ${pn} aerospace part.`,
        `Secure the ${pn} for your maintenance needs.`,
        `The ${pn} is available in our extensive inventory.`,
        `Global Parts-Technology presents the ${pn}.`
    ];

    const details = [
        `Manufactured by ${oem}, this component meets strict aerospace standards.`,
        `This ${category} component by ${oem} ensures your fleet remains airborne.`,
        `As a critical ${category} part, this ${oem} product is highly reliable.`,
        `Supplied by ${oem}, this item is fully traceable and certified.`,
        `Engineered by ${oem}, it delivers exceptional performance in ${category} applications.`,
        `This ${oem} unit is a staple in modern ${category} systems.`
    ];

    const conditions = [
        `Currently available in ${condSafe} condition.`,
        `Held in stock in ${condSafe} status.`,
        `Offered in verified ${condSafe} condition.`,
        `Ready to ship globally in ${condSafe} state.`,
        `Provided in guaranteed ${condSafe} condition.`
    ];

    const ctas = [
        `Benefit from our 24/7 AOG support and fast global shipping.`,
        `Global Parts-Technology is your trusted supply chain partner.`,
        `Ensure operational excellence with our certified inventory.`,
        `Contact our sales team today for expedited delivery options.`,
        `Rely on us for uncompromised quality and aerospace traceability.`
    ];

    const introIdx = safeId % intros.length;
    const detailIdx = (safeId * 3) % details.length;
    const condIdx = (safeId * 7) % conditions.length;
    const ctaIdx = (safeId * 11) % ctas.length;

    return `${intros[introIdx]} ${details[detailIdx]} ${conditions[condIdx]} ${ctas[ctaIdx]} Catalog Ref: ${safeId}.`;
  };

  const displayName = (product.name?.trim() === 'PRODUCT' || !product.name) 
    ? `Aviation Component ${product.pn}` 
    : product.name;

  const dynamicDescription = generateUniqueDescription(product.pn, displayOEM, product.condition, displayCategory, product.id);

  const seoTitle = `${product.pn} - ${displayName} | Global Parts-Technology`;
  const seoDesc = dynamicDescription; 
  const canonicalUrl = `https://globalpartstechnology.com/part/${product.pn.trim().replace(/\s+/g, '-')}/${product.id}`;
  
  const prefix = product.pn.substring(0, 3);

  return (
    <div className="max-w-4xl mx-auto px-4 py-12 relative">
       <Helmet>
        <title>{seoTitle}</title>
        <meta name="description" content={seoDesc} />
        <link rel="canonical" href={canonicalUrl} />
        <meta name="fragment" content="!" />
      </Helmet>

      {/* NAVEGAÇÃO DE TRILHA HÍBRIDA (SEO + React UX) */}
      <nav className="flex flex-wrap items-center text-slate-400 text-xs font-mono mb-6 gap-2 bg-black/20 p-3 rounded-lg border border-white/5 shadow-sm">
        <Link to="/" className="hover:text-cyan-400 transition-colors">Home</Link>
        <span className="text-slate-600">/</span>
        
        <a 
            href="/directory.php" 
            onClick={(e) => { e.preventDefault(); navigate('/catalog'); }}
            className="hover:text-cyan-400 transition-colors cursor-pointer"
        >
            Directory
        </a>
        <span className="text-slate-600">/</span>
        
        <a 
            href={`/directory.php?prefix=${prefix}`} 
            onClick={(e) => { e.preventDefault(); navigate(`/catalog?q=${prefix}`); }}
            className="hover:text-cyan-400 transition-colors cursor-pointer"
        >
            Prefix {prefix}
        </a>
        
        <span className="text-slate-600">/</span>
        <span className="text-cyan-400 font-bold">{product.pn}</span>
      </nav>

       <div className="flex justify-between items-center mb-6">
           <button onClick={handleBackToResults} className="text-slate-300 hover:text-cyan-400 flex items-center gap-2 text-sm font-bold tracking-wide transition-colors">
               <ArrowLeft className="w-4 h-4" /> BACK TO RESULTS
           </button>

           <div className="flex gap-2">
               {neighbors.next ? (
                   <Link to={`/part/${encodeURIComponent(encodeURIComponent(neighbors.next.pn))}/${neighbors.next.id}`} className="bg-black/30 hover:bg-white/10 text-slate-300 px-3 py-1.5 rounded border border-slate-700/50 flex items-center gap-1 text-xs backdrop-blur-sm">
                       <ChevronLeft className="w-3 h-3"/> Prev
                   </Link>
               ) : (
                   <span className="opacity-50 px-3 py-1.5 text-xs text-slate-500 flex items-center gap-1 border border-transparent cursor-not-allowed">
                      <ChevronLeft className="w-3 h-3"/> First
                   </span>
               )}

               {neighbors.prev ? (
                   <Link to={`/part/${encodeURIComponent(encodeURIComponent(neighbors.prev.pn))}/${neighbors.prev.id}`} className="bg-black/30 hover:bg-white/10 text-slate-300 px-3 py-1.5 rounded border border-slate-700/50 flex items-center gap-1 text-xs backdrop-blur-sm">
                       Next <ChevronRight className="w-3 h-3"/>
                   </Link>
               ) : (
                   <span className="opacity-50 px-3 py-1.5 text-xs text-slate-500 flex items-center gap-1 border border-transparent cursor-not-allowed">
                      Last <ChevronRight className="w-3 h-3"/>
                   </span>
               )}
           </div>
       </div>

       <div className="bg-black/30 border border-slate-700/50 rounded-2xl overflow-hidden shadow-2xl p-8 backdrop-blur-xl relative">
            <div className="flex flex-col md:flex-row gap-8 mb-8">
                <div className="w-fit h-auto flex justify-center items-center bg-slate-900/50 border border-slate-700/50 rounded-xl p-4 shadow-inner overflow-hidden">
                    <img 
                      src={`${API_BASE_URL}/generate_image.php?pn=${encodeURIComponent(product.pn)}`}
                      alt={displayName} 
                      className="max-w-full h-auto object-contain opacity-80 hover:opacity-100 transition-opacity min-w-[200px]" 
                      onError={(e) => { e.currentTarget.src = '/peca.png'; }}
                    />
                </div>

                <div className="w-full md:w-2/3 flex flex-col justify-center">
                    <h1 className="text-3xl md:text-4xl font-bold text-white mb-2 drop-shadow-md">{displayName}</h1>
                    
                    <div className="flex gap-4 mb-6">
                        <span className="text-2xl text-cyan-400 font-mono drop-shadow-sm">{product.pn}</span>
                        <span className="bg-white/10 text-white px-2 py-1 rounded text-sm border border-white/10">{product.condition}</span>
                    </div>

                    <div className="bg-slate-900/50 border border-slate-800 rounded-lg p-4 my-6">
                      <p className="text-slate-300 text-sm md:text-base leading-relaxed">
                        {seoDesc}
                      </p>
                    </div>
                    
                    <div className="grid sm:grid-cols-2 gap-6">
                        <div>
                            <p className="text-slate-400 text-xs uppercase tracking-wider mb-1">Manufacturer</p>
                            <p className="text-xl text-white font-medium">{displayOEM}</p>
                        </div>
                        
                        <div>
                            <p className="text-slate-400 text-xs uppercase tracking-wider mb-1">Price / Availability</p>
                            <p className={`text-xl font-bold flex items-center gap-2 ${Number(product.price) > 0 ? 'text-green-400' : 'text-cyan-400'}`}>
                                {Number(product.price) > 0 ? formatPrice(product.price) : 'Request a Quote'}
                            </p>
                        </div>
                        
                        <div className="sm:col-span-2">
                            <p className="text-slate-400 text-xs uppercase tracking-wider mb-1">Category</p>
                            <p className="text-lg text-slate-200">{displayCategory}</p>
                        </div>
                    </div>
                </div>
            </div>

            <div className="pt-6 border-t border-slate-700/50">
                 <button onClick={() => addToCart(product)} className="w-full bg-cyan-600 hover:bg-cyan-500 text-white font-bold py-4 rounded shadow-lg flex justify-center items-center gap-2 transition-all cursor-pointer">
                    <ShoppingCart className="w-5 h-5"/> ADD TO QUOTE
                 </button>
            </div>

            <RelatedParts realRelatedParts={relatedParts} />
       </div>
    </div>
  );
};

// ==========================================================
// COMPONENTE: GLOBAL SOURCING (BIG DATA + MASS RFQ + SELECTION)
// ==========================================================
const GlobalSourcing = () => {
    const [search, setSearch] = useState('');
    const [activeTab, setActiveTab] = useState<'radar' | 'search' | 'bot'>('radar');
    const [mockResults, setMockResults] = useState<Supplier[]>([]);
    const [botLogs, setBotLogs] = useState<any[]>([]); 
    
    const [manualKeyword, setManualKeyword] = useState('');

    const [isAddModalOpen, setIsAddModalOpen] = useState(false);
    const [newSupplier, setNewSupplier] = useState({ 
        company_name: '', 
        domain: '', 
        main_email: '', 
        tier: 'Distributor', 
        country: 'USA' 
    });

    const [viewSupplier, setViewSupplier] = useState<Supplier | null>(null);

    const [selectedIds, setSelectedIds] = useState<number[]>([]);

    const [recipientEmail, setRecipientEmail] = useState('');
    const [isSendingReport, setIsSendingReport] = useState(false);
    
    const [isBulkModalOpen, setIsBulkModalOpen] = useState(false);
    const [bulkSubject, setBulkSubject] = useState('');
    const [bulkMessage, setBulkMessage] = useState('We are looking for price and lead time for PN: [INSERT PN HERE]. Please advise availability.');
    const [isBulkSending, setIsBulkSending] = useState(false);

    useEffect(() => {
      window.prerenderReady = true;
    }, []);

    const handleSearch = async () => {
        try {
            const res = await fetch(`${API_BASE_URL}/sourcing_api.php?action=search&q=${encodeURIComponent(search)}`);
            const data = await res.json();
            if (Array.isArray(data)) {
                setMockResults(data);
                setSelectedIds([]); 
            }
        } catch (error) {
            console.error(error);
            setMockResults([]);
        }
    };

    useEffect(() => {
        if (activeTab === 'search') {
            handleSearch(); 
        }
    }, [activeTab]);

    const fetchBotLogs = async () => {
        try {
            const res = await fetch(`${API_BASE_URL}/sourcing_api.php?action=logs`);
            const data = await res.json();
            if (Array.isArray(data)) setBotLogs(data);
        } catch (e) { console.error(e); }
    };

    useEffect(() => {
        if (activeTab === 'bot') {
            fetchBotLogs();
            const interval = setInterval(fetchBotLogs, 5000); 
            return () => clearInterval(interval);
        }
    }, [activeTab]);

    const handleManualTrigger = async () => {
        if (!manualKeyword) return;
        try {
            const res = await fetch(`${API_BASE_URL}/sourcing_api.php?action=trigger&q=${encodeURIComponent(manualKeyword)}&_t=${new Date().getTime()}`);
            const data = await res.json();
            
            if (data.success) {
                alert('Mining job started! Check the logs.');
                setManualKeyword(''); 
                fetchBotLogs(); 
            } else {
                alert('Error starting job: ' + data.message);
            }
        } catch (error) {
            console.error(error);
            alert('Network Error');
        }
    };

    const handleSaveSupplier = async () => {
        if (!newSupplier.company_name) {
            alert("Company Name is required");
            return;
        }
        try {
            const res = await fetch(`${API_BASE_URL}/sourcing_api.php?action=add_supplier`, {
                method: 'POST',
                body: JSON.stringify(newSupplier)
            });
            const data = await res.json();
            
            if (data.success) {
                alert('Supplier added successfully!');
                setIsAddModalOpen(false);
                setNewSupplier({ company_name: '', domain: '', main_email: '', tier: 'Distributor', country: 'USA' });
                if (activeTab === 'search') handleSearch();
            } else {
                alert('Error: ' + data.message);
            }
        } catch (e) {
            alert('Network Error');
        }
    };

    const toggleSelectAll = (e: React.ChangeEvent<HTMLInputElement>) => {
        if (e.target.checked) {
            setSelectedIds(mockResults.map(s => s.id));
        } else {
            setSelectedIds([]);
        }
    };

    const toggleSelectOne = (id: number) => {
        if (selectedIds.includes(id)) {
            setSelectedIds(selectedIds.filter(sid => sid !== id));
        } else {
            setSelectedIds([...selectedIds, id]);
        }
    };

    const handleSendReport = async () => {
        if (!recipientEmail) { alert('Please enter a recipient email.'); return; }
        
        const itemsToSend = selectedIds.length > 0 
            ? mockResults.filter(s => selectedIds.includes(s.id))
            : mockResults;

        setIsSendingReport(true);
        try {
            const res = await fetch(`${API_BASE_URL}/send_email.php`, {
                method: 'POST',
                body: JSON.stringify({ type: 'sourcing_report', email: recipientEmail, search_term: search || 'All Suppliers', items: itemsToSend })
            });
            const result = await res.json();
            if (result.success) { alert('Report sent successfully!'); setRecipientEmail(''); } 
            else { alert('Error: ' + result.message); }
        } catch (error) { alert('Network error.'); } finally { setIsSendingReport(false); }
    };
    
    const handleBulkSend = async () => {
        if (!bulkSubject || !bulkMessage) { alert('Please fill in Subject and Message.'); return; }
        
        const targets = mockResults.filter(s => selectedIds.includes(s.id));
        const targetEmails = targets.map(s => s.email).filter(e => e);
        
        if (targetEmails.length === 0) { alert("No suppliers selected or invalid emails."); return; }

        setIsBulkSending(true);
        try {
            const res = await fetch(`${API_BASE_URL}/send_email.php`, {
                method: 'POST',
                body: JSON.stringify({
                    type: 'bulk_rfq',
                    recipients: targetEmails,
                    subject: bulkSubject,
                    message: bulkMessage
                })
            });
            const result = await res.json();
            if (result.success) {
                alert(`SUCCESS! RFQ sent to ${targetEmails.length} suppliers.`);
                setIsBulkModalOpen(false);
                setSelectedIds([]); 
            } else {
                alert('Error: ' + result.message);
            }
        } catch (error) {
            alert('Network error.');
        } finally {
            setIsBulkSending(false);
        }
    };

    return (
        <div className="max-w-7xl mx-auto px-4 py-12 relative">
            <Helmet>
                <title>Global Sourcing Intelligence | Admin</title>
            </Helmet>

            <div className="mb-8">
                <h1 className="text-3xl font-bold text-white flex items-center gap-3">
                    <Globe className="text-cyan-500 w-8 h-8" /> Global Sourcing Intelligence
                </h1>
                <p className="text-slate-400 mt-2">Big Data Supplier Management & Mining System</p>
            </div>

            {/* TABS */}
            <div className="flex gap-4 mb-8 border-b border-slate-700 pb-1">
                <button onClick={() => setActiveTab('radar')} className={`px-4 py-2 text-sm font-bold transition-colors ${activeTab === 'radar' ? 'text-cyan-400 border-b-2 border-cyan-400' : 'text-slate-400 hover:text-white'}`}>
                    <BarChart className="w-4 h-4 inline mr-2"/> Supplier Radar
                </button>
                <button onClick={() => setActiveTab('search')} className={`px-4 py-2 text-sm font-bold transition-colors ${activeTab === 'search' ? 'text-cyan-400 border-b-2 border-cyan-400' : 'text-slate-400 hover:text-white'}`}>
                    <Search className="w-4 h-4 inline mr-2"/> Advanced Search
                </button>
                <button onClick={() => setActiveTab('bot')} className={`px-4 py-2 text-sm font-bold transition-colors ${activeTab === 'bot' ? 'text-cyan-400 border-b-2 border-cyan-400' : 'text-slate-400 hover:text-white'}`}>
                    <Cpu className="w-4 h-4 inline mr-2"/> Mining Bot
                </button>
            </div>

            {/* CONTENT */}
            <div className="bg-black/30 border border-slate-700 rounded-xl p-6 backdrop-blur-xl">
                {activeTab === 'radar' && (
                    <div className="grid md:grid-cols-3 gap-6">
                        <div className="bg-slate-900/50 p-6 rounded-lg border border-slate-600/50">
                            <h3 className="text-slate-400 text-xs uppercase font-bold mb-2">Total Suppliers</h3>
                            <div className="text-4xl font-bold text-white flex items-end gap-2">
                                15,420 <span className="text-sm text-green-400 mb-1 flex items-center"><ArrowLeft className="w-3 h-3 rotate-45"/> +12%</span>
                            </div>
                        </div>
                        <div className="bg-slate-900/50 p-6 rounded-lg border border-slate-600/50">
                            <h3 className="text-slate-400 text-xs uppercase font-bold mb-2">Active Agents</h3>
                            <div className="text-4xl font-bold text-white flex items-end gap-2">
                                8 <span className="text-sm text-cyan-400 mb-1">Running</span>
                            </div>
                        </div>
                        <div className="bg-slate-900/50 p-6 rounded-lg border border-slate-600/50">
                            <h3 className="text-slate-400 text-xs uppercase font-bold mb-2">Harvested Contacts</h3>
                            <div className="text-4xl font-bold text-white">45,102</div>
                        </div>
                        <div className="md:col-span-3 mt-4 h-64 flex items-center justify-center bg-slate-900/20 rounded border border-slate-700 border-dashed text-slate-500">
                            [Interactive Global Map Visualization Placeholder]
                        </div>
                    </div>
                )}

                {activeTab === 'search' && (
                    <div>
                        <div className="flex gap-4 mb-6">
                            <div className="relative flex-1">
                                <Search className="absolute left-3 top-3 h-5 w-5 text-slate-400" />
                                <input 
                                    type="text" 
                                    placeholder="Search by PN, Capability or Company..." 
                                    className="w-full bg-black/40 border border-slate-600 rounded pl-10 pr-4 py-2.5 text-white focus:border-cyan-500 outline-none"
                                    value={search}
                                    onChange={(e) => setSearch(e.target.value)}
                                    onKeyDown={(e) => e.key === 'Enter' && handleSearch()}
                                />
                            </div>
                            <button onClick={handleSearch} className="bg-cyan-600 hover:bg-cyan-500 text-white font-bold px-6 rounded">SEARCH</button>
                            <button onClick={() => setIsAddModalOpen(true)} className="bg-green-700 hover:bg-green-600 text-white font-bold px-4 rounded flex items-center gap-2">
                                <Plus className="w-4 h-4"/> ADD
                            </button>
                        </div>

                        {/* TOOLBAR: REPORT & MASS QUOTE */}
                        {mockResults.length > 0 && (
                            <div className="flex flex-wrap items-center justify-between mb-4 bg-slate-800/50 p-3 rounded border border-slate-600 gap-4">
                                <span className="text-sm text-slate-300">
                                    <strong>{selectedIds.length}</strong> selected of <strong>{mockResults.length}</strong> found.
                                </span>
                                
                                <div className="flex items-center gap-2">
                                    {/* MASS QUOTE BUTTON */}
                                    <button 
                                        onClick={() => { 
                                            if(selectedIds.length === 0) {
                                                alert("Please select at least one supplier.");
                                                return;
                                            }
                                            setBulkSubject(`RFQ: ${search}`); 
                                            setIsBulkModalOpen(true); 
                                        }}
                                        className={`font-bold px-4 py-1.5 rounded text-sm flex items-center gap-2 shadow-lg transition-all ${selectedIds.length > 0 ? 'bg-purple-600 hover:bg-purple-500 text-white' : 'bg-slate-700 text-slate-500 cursor-not-allowed'}`}
                                    >
                                        <Plane className="w-4 h-4" /> MASS QUOTE ({selectedIds.length})
                                    </button>

                                    <div className="h-6 w-px bg-slate-600 mx-2"></div>

                                    {/* SEND REPORT */}
                                    <input 
                                        type="email" 
                                        placeholder="Partner Email" 
                                        className="bg-black/50 border border-slate-500 rounded px-3 py-1.5 text-white text-sm focus:border-cyan-500 outline-none w-48"
                                        value={recipientEmail}
                                        onChange={(e) => setRecipientEmail(e.target.value)}
                                    />
                                    <button 
                                        onClick={handleSendReport} 
                                        disabled={isSendingReport}
                                        className="bg-green-700 hover:bg-green-600 text-white font-bold px-4 py-1.5 rounded text-sm flex items-center gap-2 disabled:opacity-50"
                                    >
                                        <Send className="w-3 h-3" /> Report
                                    </button>
                                </div>
                            </div>
                        )}

                        <div className="overflow-x-auto">
                            <table className="w-full text-left border-collapse">
                                <thead>
                                    <tr className="border-b border-slate-700 text-slate-400 text-xs uppercase">
                                        <th className="p-3 w-10">
                                            <input 
                                                type="checkbox" 
                                                className="cursor-pointer"
                                                onChange={toggleSelectAll}
                                                checked={mockResults.length > 0 && selectedIds.length === mockResults.length}
                                            />
                                        </th>
                                        <th className="p-3">Company</th>
                                        <th className="p-3">Email</th>
                                        <th className="p-3">Tier</th>
                                        <th className="p-3">Capabilities</th>
                                        <th className="p-3">Actions</th>
                                    </tr>
                                </thead>
                                <tbody className="text-sm text-slate-300">
                                    {mockResults.length > 0 ? mockResults.map(s => (
                                        <tr key={s.id} className={`border-b border-slate-800 transition-colors ${selectedIds.includes(s.id) ? 'bg-purple-900/20' : 'hover:bg-white/5'}`}>
                                            <td className="p-3">
                                                <input 
                                                    type="checkbox" 
                                                    className="cursor-pointer"
                                                    checked={selectedIds.includes(s.id)}
                                                    onChange={() => toggleSelectOne(s.id)}
                                                />
                                            </td>
                                            <td className="p-3 font-bold text-white">{s.company_name}<br/><span className="text-xs text-slate-500 font-normal">{s.domain}</span></td>
                                            <td className="p-3 text-cyan-400">{s.email}</td>
                                            <td className="p-3"><span className={`px-2 py-1 rounded text-xs ${s.tier === 'Tier 1' ? 'bg-green-900 text-green-300' : 'bg-blue-900 text-blue-300'}`}>{s.tier}</span></td>
                                            <td className="p-3">{s.capabilities.join(", ")}</td>
                                            <td className="p-3">
                                                <button 
                                                    onClick={() => setViewSupplier(s)}
                                                    className="text-cyan-400 hover:text-white text-xs underline"
                                                >
                                                    Details
                                                </button>
                                            </td>
                                        </tr>
                                    )) : (
                                        <tr><td colSpan={6} className="p-8 text-center text-slate-500">Start searching or use Manual Add.</td></tr>
                                    )}
                                </tbody>
                            </table>
                        </div>
                    </div>
                )}

                {activeTab === 'bot' && (
                    <div className="space-y-6">
                        <div className="bg-yellow-900/20 border border-yellow-700/50 p-4 rounded flex items-start gap-3">
                            <Server className="w-6 h-6 text-yellow-500 flex-shrink-0" />
                            <div>
                                <h4 className="text-yellow-500 font-bold">Node.js Miner Node Status</h4>
                                <p className="text-sm text-yellow-200/70">Connected to <span className="font-mono bg-black/30 px-1 rounded">{SOURCING_API_URL}</span>. Puppeteer instance is IDLE.</p>
                            </div>
                        </div>

                        <div className="grid md:grid-cols-2 gap-6">
                            <div className="bg-slate-900/40 p-6 rounded border border-slate-700">
                                <h3 className="text-white font-bold mb-4 flex items-center gap-2"><RefreshCw className="w-4 h-4"/> Manual Trigger</h3>
                                <input 
                                    placeholder="Target Keyword (e.g., 'Avionics Repair Miami')" 
                                    className="w-full bg-black/40 border border-slate-600 rounded p-2 mb-4 text-white text-sm"
                                    value={manualKeyword}
                                    onChange={(e) => setManualKeyword(e.target.value)}
                                />
                                <button 
                                    onClick={handleManualTrigger}
                                    className="w-full bg-cyan-700 hover:bg-cyan-600 text-white font-bold py-2 rounded shadow-lg transition-transform active:scale-95"
                                >
                                    START MINING JOB
                                </button>
                            </div>
                            <div className="bg-slate-900/40 p-6 rounded border border-slate-700">
                                <h3 className="text-white font-bold mb-4 flex items-center gap-2"><Upload className="w-4 h-4"/> Bulk Import (CSV)</h3>
                                <input 
                                    type="file" 
                                    accept=".csv" 
                                    className="block w-full text-sm text-slate-500 file:mr-4 file:py-2 file:px-4 file:rounded-full file:border-0 file:text-sm file:font-semibold file:bg-cyan-50 file:text-cyan-700 hover:file:bg-cyan-100"
                                    onChange={(e) => {
                                        if (e.target.files && e.target.files[0]) {
                                            alert("File selected: " + e.target.files[0].name + " (Future feature: upload to queue)");
                                        }
                                    }}
                                />
                            </div>
                        </div>

                        {/* LIVE LOGS MONITOR */}
                        <div className="bg-black/40 p-6 rounded border border-slate-700 h-64 overflow-y-auto">
                            <h3 className="text-white font-bold mb-4 flex items-center justify-between">
                                <span className="flex items-center gap-2"><FileText className="w-4 h-4"/> Live Activity Log</span>
                                <span className="text-xs text-green-400 animate-pulse">● Live</span>
                            </h3>
                            
                            <div className="space-y-3">
                                {botLogs.length > 0 ? botLogs.map((log) => (
                                    <div key={log.id} className="border-b border-slate-800 pb-2">
                                        <div className="flex justify-between items-center mb-1">
                                            <span className={`text-xs font-bold px-2 py-0.5 rounded ${
                                                log.status === 'Completed' ? 'bg-green-900 text-green-300' : 
                                                log.status === 'Running' ? 'bg-yellow-900 text-yellow-300' : 
                                                log.status === 'Pending' ? 'bg-blue-900 text-blue-300' : 'bg-red-900 text-red-300'
                                            }`}>
                                                {log.status}
                                            </span>
                                            <span className="text-[10px] text-slate-500">{log.time_ago}</span>
                                        </div>
                                        <p className="text-sm text-slate-300">
                                            Search: <span className="text-cyan-400">"{log.keyword}"</span>
                                        </p>
                                        {log.found_count > 0 && (
                                            <p className="text-xs text-slate-400">Found: {log.found_count} new suppliers.</p>
                                        )}
                                    </div>
                                )) : (
                                    <p className="text-slate-500 text-sm text-center mt-10">No recent activity logged.</p>
                                )}
                            </div>
                        </div>
                    </div>
                )}
            </div>

            {/* --- MODAL ADICIONAR FORNECEDOR --- */}
            {isAddModalOpen && (
                <div className="fixed inset-0 z-[100] flex items-center justify-center bg-black/80 backdrop-blur-sm p-4">
                    <div className="bg-slate-900 border border-cyan-600 rounded-xl w-full max-w-md shadow-2xl p-6 relative">
                        <button onClick={() => setIsAddModalOpen(false)} className="absolute top-4 right-4 text-slate-400 hover:text-white"><X /></button>
                        
                        <h2 className="text-xl font-bold text-white mb-4 flex items-center gap-2">
                            <Plus className="text-cyan-500"/> Add Manual Supplier
                        </h2>

                        <div className="space-y-3">
                            <input 
                                className="w-full bg-black/50 border border-slate-600 rounded p-2 text-white" 
                                placeholder="Company Name *" 
                                value={newSupplier.company_name}
                                onChange={e => setNewSupplier({...newSupplier, company_name: e.target.value})}
                            />
                            <input 
                                className="w-full bg-black/50 border border-slate-600 rounded p-2 text-white" 
                                placeholder="Domain (e.g. site.com)" 
                                value={newSupplier.domain}
                                onChange={e => setNewSupplier({...newSupplier, domain: e.target.value})}
                            />
                            <input 
                                className="w-full bg-black/50 border border-slate-600 rounded p-2 text-white" 
                                placeholder="Email (e.g. sales@site.com)" 
                                value={newSupplier.main_email}
                                onChange={e => setNewSupplier({...newSupplier, main_email: e.target.value})}
                            />
                            <div className="flex gap-2">
                                <select 
                                    className="bg-black/50 border border-slate-600 rounded p-2 text-white flex-1"
                                    value={newSupplier.tier}
                                    onChange={e => setNewSupplier({...newSupplier, tier: e.target.value})}
                                >
                                    <option value="Distributor">Distributor</option>
                                    <option value="Tier 1">Tier 1</option>
                                    <option value="Broker">Broker</option>
                                    <option value="MRO">MRO</option>
                                </select>
                                <input 
                                    className="bg-black/50 border border-slate-600 rounded p-2 text-white flex-1" 
                                    placeholder="Country" 
                                    value={newSupplier.country}
                                    onChange={e => setNewSupplier({...newSupplier, country: e.target.value})}
                                />
                            </div>
                        </div>

                        <button 
                            onClick={handleSaveSupplier}
                            className="w-full bg-cyan-700 hover:bg-cyan-600 text-white font-bold py-2 rounded mt-6 shadow-lg"
                        >
                            SAVE SUPPLIER
                        </button>
                    </div>
                </div>
            )}

            {/* --- MODAL DETALHES DO FORNECEDOR --- */}
            {viewSupplier && (
                <div className="fixed inset-0 z-[100] flex items-center justify-center bg-black/80 backdrop-blur-sm p-4">
                    <div className="bg-slate-900 border border-slate-500 rounded-xl w-full max-w-2xl shadow-2xl p-8 relative">
                        <button onClick={() => setViewSupplier(null)} className="absolute top-4 right-4 text-slate-400 hover:text-white"><X /></button>
                        
                        <div className="flex items-start gap-4 mb-6">
                            <div className="bg-cyan-900/30 p-3 rounded-lg border border-cyan-500/30">
                                <Globe className="w-8 h-8 text-cyan-400" />
                            </div>
                            <div>
                                <h2 className="text-2xl font-bold text-white">{viewSupplier.company_name}</h2>
                                <a href={`https://${viewSupplier.domain}`} target="_blank" rel="noreferrer" className="text-cyan-400 hover:underline text-sm">{viewSupplier.domain}</a>
                            </div>
                        </div>

                        <div className="grid grid-cols-2 gap-6 mb-6">
                            <div className="bg-black/30 p-4 rounded border border-slate-700">
                                <p className="text-xs text-slate-400 uppercase font-bold mb-1">Contact Email</p>
                                <p className="text-white">{viewSupplier.email || 'N/A'}</p>
                            </div>
                            <div className="bg-black/30 p-4 rounded border border-slate-700">
                                <p className="text-xs text-slate-400 uppercase font-bold mb-1">Business Tier</p>
                                <span className={`px-2 py-0.5 rounded text-xs ${viewSupplier.tier === 'Tier 1' ? 'bg-green-900 text-green-300' : 'bg-blue-900 text-blue-300'}`}>
                                    {viewSupplier.tier}
                                </span>
                            </div>
                            <div className="bg-black/30 p-4 rounded border border-slate-700">
                                <p className="text-xs text-slate-400 uppercase font-bold mb-1">Location</p>
                                <p className="text-white">{viewSupplier.country || 'Unknown'}</p>
                            </div>
                            <div className="bg-black/30 p-4 rounded border border-slate-700">
                                <p className="text-xs text-slate-400 uppercase font-bold mb-1">System ID</p>
                                <p className="text-slate-500 font-mono">#{viewSupplier.id}</p>
                            </div>
                        </div>

                        <div className="mb-6">
                            <h3 className="text-white font-bold mb-2 flex items-center gap-2"><Settings className="w-4 h-4"/> Capabilities / Keywords</h3>
                            <div className="flex flex-wrap gap-2">
                                {viewSupplier.capabilities && viewSupplier.capabilities.length > 0 ? (
                                    viewSupplier.capabilities.map((cap, i) => (
                                        <span key={i} className="bg-slate-800 text-slate-300 px-2 py-1 rounded text-xs border border-slate-600">
                                            {cap}
                                        </span>
                                    ))
                                ) : (
                                    <p className="text-slate-500 text-sm">No specific capabilities listed.</p>
                                )}
                            </div>
                        </div>

                        <div className="flex justify-end pt-4 border-t border-slate-700">
                            <button onClick={() => setViewSupplier(null)} className="px-6 py-2 bg-slate-700 hover:bg-slate-600 text-white rounded font-bold">Close</button>
                        </div>
                    </div>
                </div>
            )}

            {/* MASS QUOTE MODAL */}
            {isBulkModalOpen && (
                <div className="fixed inset-0 z-[100] flex items-center justify-center bg-black/80 backdrop-blur-sm p-4">
                    <div className="bg-slate-900 border border-purple-500/50 rounded-xl w-full max-w-2xl shadow-2xl p-6 relative">
                        <button onClick={() => setIsBulkModalOpen(false)} className="absolute top-4 right-4 text-slate-400 hover:text-white"><X /></button>
                        
                        <h2 className="text-2xl font-bold text-white mb-2 flex items-center gap-2">
                            <Plane className="text-purple-500" /> Mass RFQ Blaster
                        </h2>
                        <p className="text-slate-400 text-sm mb-6">
                            You are about to send a quote request to <strong className="text-white">{selectedIds.length} SELECTED suppliers</strong>.
                        </p>

                        <div className="space-y-4">
                            <div>
                                <label className="block text-xs font-bold text-slate-500 uppercase mb-1">Subject</label>
                                <input 
                                    className="w-full bg-black/50 border border-slate-600 rounded p-3 text-white focus:border-purple-500 outline-none" 
                                    value={bulkSubject}
                                    onChange={e => setBulkSubject(e.target.value)}
                                />
                            </div>
                            <div>
                                <label className="block text-xs font-bold text-slate-500 uppercase mb-1">Message</label>
                                <textarea 
                                    rows={6}
                                    className="w-full bg-black/50 border border-slate-600 rounded p-3 text-white focus:border-purple-500 outline-none" 
                                    value={bulkMessage}
                                    onChange={e => setBulkMessage(e.target.value)}
                                />
                            </div>
                        </div>

                        <div className="mt-8 flex justify-end gap-4">
                            <button onClick={() => setIsBulkModalOpen(false)} className="px-4 py-2 text-slate-400 hover:text-white">Cancel</button>
                            <button 
                                onClick={handleBulkSend} 
                                disabled={isBulkSending}
                                className="bg-purple-600 hover:bg-purple-500 text-white font-bold px-6 py-2 rounded shadow-lg flex items-center gap-2 disabled:opacity-50"
                            >
                                {isBulkSending ? 'SENDING...' : 'LAUNCH RFQ'}
                            </button>
                        </div>
                    </div>
                </div>
            )}
        </div>
    );
};

// 4. ADMIN PANEL
const AdminPanel = () => {
  const [file, setFile] = useState<File | null>(null);
  const [status, setStatus] = useState('');
  const [loading, setLoading] = useState(false);
  const [pass, setPass] = useState('');
  const [isAuth, setIsAuth] = useState(false);
  const navigate = useNavigate();

  useEffect(() => {
    window.prerenderReady = true;
  }, []);

  const handleLogin = (e: React.FormEvent) => {
      e.preventDefault();
      if(pass === 'admin2024') setIsAuth(true); 
      else alert('Invalid Password');
  };

  const handleUpload = async (e: React.FormEvent) => {
      e.preventDefault();
      if (!file) return;
      setLoading(true);
      setStatus('Uploading and Processing...');

      const formData = new FormData();
      formData.append('csv_file', file);

      try {
          const res = await fetch(`${API_BASE_URL}/import.php`, {
              method: 'POST',
              body: formData
          });

          const rawText = await res.text();
          
          try {
              const data = JSON.parse(rawText);
              setStatus(data.message || 'Done.');
          } catch (jsonError) {
              setStatus(`Server Error (Raw): ${rawText.substring(0, 200)}...`);
          }

      } catch (err) {
          setStatus('Network Error. Check console.');
      } finally {
          setLoading(false);
      }
  };

  if(!isAuth) return (
      <div className="min-h-screen flex items-center justify-center">
          <form onSubmit={handleLogin} className="bg-black/30 p-10 rounded-xl border border-slate-700/50 backdrop-blur-xl shadow-2xl">
              <h2 className="text-white text-xl mb-4 font-bold flex gap-2"><Lock className="text-cyan-500"/> Admin Access</h2>
              <input type="password" placeholder="Password" className="w-full bg-black/40 border border-slate-600 rounded p-2 text-white mb-4 placeholder-slate-400" value={pass} onChange={e=>setPass(e.target.value)}/>
              <button className="w-full bg-cyan-600 text-white font-bold py-2 rounded cursor-pointer">LOGIN</button>
          </form>
      </div>
  );

  return (
      <div className="max-w-4xl mx-auto px-4 py-20">
          <div className="grid md:grid-cols-2 gap-8">
              <div className="bg-black/30 p-8 rounded-xl border border-slate-700/50 backdrop-blur-xl shadow-2xl">
                  <h1 className="text-2xl text-white font-bold mb-2 flex items-center gap-2"><Database className="text-cyan-500"/> Inventory Database</h1>
                  <p className="text-xs text-slate-400 mb-6">Manage local stock via CSV.</p>
                  
                  <form onSubmit={handleUpload} className="space-y-6">
                      <div>
                          <label className="block mb-2 text-sm font-medium text-gray-300">Select CSV File</label>
                          <input 
                            type="file" 
                            accept=".csv" 
                            onChange={e => setFile(e.target.files ? e.target.files[0] : null)} 
                            className="block w-full text-sm text-slate-500
                                file:mr-4 file:py-2 file:px-4
                                file:rounded-full file:border-0
                                file:text-sm file:font-semibold
                                file:bg-cyan-50 file:text-cyan-700
                                hover:file:bg-cyan-100"
                          />
                      </div>

                      <button disabled={loading || !file} className="w-full bg-gradient-to-r from-cyan-700 to-cyan-600 text-white font-bold py-3 rounded shadow-lg disabled:opacity-50 cursor-pointer text-sm">
                          {loading ? 'PROCESSING...' : 'START IMPORT'}
                      </button>
                  </form>
                  {status && (
                      <div className={`mt-4 p-2 rounded border text-xs ${status.includes('Error') ? 'bg-red-900/20 border-red-500 text-red-200' : 'bg-green-900/20 border-green-500 text-green-200'} break-all`}>
                          <strong>Status:</strong> {status}
                      </div>
                  )}
              </div>

              <div className="bg-gradient-to-br from-slate-900 to-black p-8 rounded-xl border border-cyan-900/50 shadow-2xl flex flex-col justify-center items-center text-center relative overflow-hidden group">
                  <div className="absolute inset-0 bg-cyan-500/10 blur-3xl opacity-20 group-hover:opacity-30 transition-opacity"></div>
                  <Globe className="w-16 h-16 text-cyan-400 mb-4 animate-pulse" />
                  <h2 className="text-2xl text-white font-bold mb-2">Global Sourcing</h2>
                  <p className="text-sm text-slate-400 mb-6">Access Supplier Intelligence, Big Data Mining & Radar.</p>
                  <button onClick={() => navigate('/admin/sourcing')} className="px-8 py-3 bg-cyan-500 hover:bg-cyan-400 text-black font-bold rounded shadow-[0_0_20px_rgba(6,182,212,0.3)] transition-all transform hover:scale-105">
                      OPEN DASHBOARD
                  </button>
              </div>
          </div>
      </div>
  );
};

// 5. CONTACT PAGE
const Contact = () => {
  const [form, setForm] = useState({ name: '', email: '', message: '' });
  const [status, setStatus] = useState('');

  useEffect(() => {
    window.prerenderReady = true;
  }, []);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setStatus('Sending...');
    
    try {
        const res = await fetch(`${API_BASE_URL}/send_email.php`, {
            method: 'POST',
            body: JSON.stringify({
                type: 'contact',
                name: form.name,
                email: form.email,
                message: form.message
            })
        });
        const result = await res.json();
        if(result.success) {
            setStatus('Message Sent Successfully!');
            setForm({ name: '', email: '', message: '' }); 
            alert("✅ Message sent successfully! We will contact you soon.");
    } else {
        setStatus('Error: ' + result.message);
        alert("❌ Error sending: " + result.message);
        }
    } catch (err) {
        setStatus('Network Error.');
    }
  };

  return (
    <div className="max-w-4xl mx-auto px-4 py-12">
      <Helmet>
        <title>Contact Us | Global Parts-Technology</title>
        <meta name="description" content="Contact our sales team for AOG support and part inquiries. We are available 24/7 to keep you flying." />
        <link rel="canonical" href="https://globalpartstechnology.com/contact" />
      </Helmet>

      <h2 className="text-3xl font-bold text-gray-100 mb-8 drop-shadow-md">Contact Support</h2>
      <div className="grid md:grid-cols-2 gap-12">
        <div className="space-y-6 text-gray-300 bg-black/30 p-8 rounded-xl border border-slate-700/50 backdrop-blur-xl shadow-xl">
          <p className="flex items-center gap-4"><Phone className="text-cyan-500 w-5 h-5"/> +1 (754)240-7016 </p>
          <p className="flex items-center gap-4"><Mail className="text-cyan-500 w-5 h-5"/> global@globalpartstechnology.com</p>
          <p className="flex items-center gap-4"><MapPin className="text-cyan-500 w-5 h-5"/> 6735 CONROY ROAD Orlando, FL 32835, US</p>
          <div className="pt-6 border-t border-slate-700/50">
             <h4 className="text-sm font-bold text-slate-400 mb-3 uppercase tracking-wider">Business Hours</h4>
             <p className="text-sm">Mon-Fri: 24-hour</p>
             <p className="text-sm text-cyan-400 mt-1">AOG Support: 24/7</p>
          </div>
        </div>
        <form onSubmit={handleSubmit} className="space-y-4 bg-black/30 p-8 rounded-xl border border-slate-700/50 backdrop-blur-xl shadow-xl">
          <input className="w-full bg-black/20 border border-slate-700/50 p-3 rounded text-gray-200 placeholder-slate-400 focus:border-cyan-600 focus:outline-none backdrop-blur-sm" placeholder="NAME" value={form.name} onChange={e=>setForm({...form, name: e.target.value})} required/>
          <input className="w-full bg-black/20 border border-slate-700/50 p-3 rounded text-gray-200 placeholder-slate-400 focus:border-cyan-600 focus:outline-none backdrop-blur-sm" placeholder="EMAIL" value={form.email} onChange={e=>setForm({...form, email: e.target.value})} required/>
          <textarea className="w-full bg-black/20 border border-slate-700/50 p-3 rounded text-gray-200 placeholder-slate-400 focus:border-cyan-600 focus:outline-none backdrop-blur-sm" rows={4} placeholder="MESSAGE" value={form.message} onChange={e=>setForm({...form, message: e.target.value})} required/>
          <button disabled={status === 'Sending...'} className="w-full bg-cyan-700 text-white font-bold p-3 rounded cursor-pointer hover:bg-cyan-600 transition">
             {status || 'SEND MESSAGE'}
          </button>
        </form>
      </div>
    </div>
  );
};

// 6. ABOUT PAGE
const About = () => {
  useEffect(() => {
    window.prerenderReady = true;
  }, []);

  return (
    <div className="max-w-4xl mx-auto px-4 py-20 text-center">
      <Helmet>
        <title>About Us | Global Parts-Technology</title>
        <meta name="description" content="Learn more about Global Parts-Technology, a leading aviation components provider focused on hard-to-find solutions and quality certification." />
        <link rel="canonical" href="https://globalpartstechnology.com/about" />
      </Helmet>

      <h1 className="text-4xl font-bold text-gray-100 mb-8 drop-shadow-md">About Global Parts-Technology</h1>
      <div className="text-left bg-black/30 p-10 rounded-2xl border border-slate-700/50 space-y-6 backdrop-blur-xl shadow-2xl">
        <h2 className="text-2xl text-cyan-400 font-bold mb-4">Premier Solutions for Aviation and Aerospace</h2>
        
        <p className="text-slate-200 text-lg leading-relaxed">
          <strong className="text-white">Global Parts-Technology</strong> stands out as a leading provider of high-quality components for the commercial aviation, civil, aerospace, and hard-to-find electronic sectors. We are dedicated to meeting the high-tech industry's evolving needs through <strong className="text-cyan-400">unwavering reliability and precision</strong>.
        </p>

        {/* CORE PILLARS BLOCKS */}
        <div className="space-y-4 my-8">
          <div className="bg-slate-900/40 p-6 rounded-lg border-l-4 border-cyan-500 shadow-md">
              <h3 className="text-white font-bold text-lg flex items-center gap-2"><ShieldCheck className="w-5 h-5 text-cyan-500"/> Global Sourcing Power</h3>
              <p className="text-slate-300 text-sm mt-2 leading-relaxed">Leveraging an extensive network of trusted manufacturers, we specialize in sourcing specialized and obsolete components that others cannot find.</p>
          </div>
          <div className="bg-slate-900/40 p-6 rounded-lg border-l-4 border-cyan-500 shadow-md">
              <h3 className="text-white font-bold text-lg flex items-center gap-2"><CheckCircle className="w-5 h-5 text-cyan-500"/> Uncompromising Quality</h3>
              <p className="text-slate-300 text-sm mt-2 leading-relaxed">Safety is paramount. We comply with the strictest industry standards, ensuring every product is certified, original, and compliant with the highest safety standards.</p>
          </div>
          <div className="bg-slate-900/40 p-6 rounded-lg border-l-4 border-cyan-500 shadow-md">
              <h3 className="text-white font-bold text-lg flex items-center gap-2"><Zap className="w-5 h-5 text-cyan-500"/> Specialized Solutions</h3>
              <p className="text-slate-300 text-sm mt-2 leading-relaxed">Our dedicated team offers more than just parts; we provide customized solutions and ongoing support to maximize the value of your investment.</p>
          </div>
        </div>

        <p className="text-slate-200 text-lg leading-relaxed border-t border-slate-700/50 pt-6">
          Innovation and customer satisfaction drive us to remain at the technological forefront. <span className="text-white font-bold">Access over 12 Million aircraft parts and electronic components with a partner you can trust.</span>
        </p>
        
        {/* CERTIFICATION ICONS */}
        <div className="grid grid-cols-1 md:grid-cols-3 gap-6 pt-6 mt-2">
          <div className="text-center">
              <ShieldCheck className="w-8 h-8 text-cyan-500 mx-auto mb-2"/>
              <h3 className="font-bold text-white">Certified Quality</h3>
              <p className="text-xs text-slate-400"> </p>
          </div>
          <div className="text-center">
              <CheckCircle className="w-8 h-8 text-cyan-500 mx-auto mb-2"/>
              <h3 className="font-bold text-white"> Quality </h3>
              <p className="text-xs text-slate-400"> </p>
          </div>
          <div className="text-center">
              <FileText className="w-8 h-8 text-cyan-500 mx-auto mb-2"/>
              <h3 className="font-bold text-white">Traceability</h3>
              <p className="text-xs text-slate-400">100% Documentation</p>
          </div>
        </div>
      </div>
    </div>
  );
};

// --- MAIN APP COMPONENT ---
const App = () => {
  const [cart, setCart] = useState<CartItem[]>([]);
  const [isCartOpen, setIsCartOpen] = useState(false);
  const [isMobileMenuOpen, setIsMobileMenuOpen] = useState(false);
  
  // SMTP STATE
  const [isSending, setIsSending] = useState(false);
  const [customerInfo, setCustomerInfo] = useState({ name: '', email: '', phone: '' });
  
  const location = useLocation(); 

  const addToCart = (product: Product) => {
    setCart(prev => {
      const existing = prev.find(item => item.id === product.id);
      if (existing) return prev.map(item => item.id === product.id ? { ...item, quantity: item.quantity + 1 } : item);
      return [...prev, { ...product, quantity: 1 }];
    });
    setIsCartOpen(true);
  };
  const updateQuantity = (id: number, qty: number) => setCart(prev => prev.map(item => item.id === id ? { ...item, quantity: qty } : item));
  const removeFromCart = (id: number) => setCart(prev => prev.filter(item => item.id !== id));

  // ENVIO SMTP
  const sendQuote = async () => {
    if(!customerInfo.email || !customerInfo.name) { alert("Please fill Name/Email"); return; }
    setIsSending(true);
    try {
        const res = await fetch(`${API_BASE_URL}/send_email.php`, {
            method: 'POST',
            body: JSON.stringify({
                type: 'quote',
                name: customerInfo.name,
                email: customerInfo.email,
                phone: customerInfo.phone,
                items: cart
            })
        });
        const result = await res.json();
        if(result.success) {
            alert("RFQ Sent Successfully!");
            setCart([]);
            setIsCartOpen(false);
        } else {
            alert("Error: " + result.message);
        }
    } catch (error) {
        alert("Network error.");
    } finally {
        setIsSending(false);
    }
  };

  return (
    <HelmetProvider>
      <div className="fixed inset-0 -z-10 bg-black">
          <div className="absolute inset-0 bg-cover bg-center opacity-80" style={{ backgroundImage: `url(${HERO_IMAGE})` }}></div>
          <div className="absolute inset-0 bg-gradient-to-b from-black/40 via-black/50 to-black/80"></div> 
      </div>

      <div className="min-h-screen text-gray-300 font-sans selection:bg-cyan-600/40 selection:text-white relative bg-transparent flex flex-col">
        {/* HEADER */}
        <nav className="fixed w-full z-50 bg-black/40 backdrop-blur-xl border-b border-slate-700/50 shadow-lg">
          <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
            <div className="flex items-center justify-between h-20">
              <Link to="/" className="flex items-center cursor-pointer group">
                 <img src={LOGO_URL} alt="Global Parts" className="h-10 w-auto opacity-90 drop-shadow-md" />
                 <div className="flex items-center">
                  <div className="ml-3 flex flex-col justify-center">
                    <h1 className="text-xl font-bold tracking-tighter text-white leading-none drop-shadow-sm">
                      GLOBAL<span className="text-cyan-500">PARTS</span>
                    </h1>
                    <span className="text-[10px] tracking-[0.2em] text-slate-300 uppercase leading-none mt-1">Technology</span>
                  </div>
                </div>
              </Link>
              <div className="hidden md:block">
                <div className="ml-10 flex items-baseline space-x-8">
                  {['/', '/catalog', '/about', '/contact'].map(path => (
                      <Link key={path} to={path} className={`px-3 py-2 font-medium tracking-wide transition-colors drop-shadow-sm ${location.pathname === path || (path !== '/' && location.pathname.startsWith(path)) ? 'text-cyan-400' : 'text-slate-300 hover:text-cyan-400'}`}>{path === '/' ? 'HOME' : path.replace('/','').toUpperCase()}</Link>
                  ))}
                </div>
              </div>
              <div className="flex items-center gap-4">
                <div className="relative cursor-pointer group" onClick={() => setIsCartOpen(true)}>
                  <ShoppingCart className="h-6 w-6 text-slate-300 group-hover:text-cyan-400 transition-colors" />
                  {cart.length > 0 && <span className="absolute -top-2 -right-2 bg-cyan-600 text-white font-bold text-xs w-5 h-5 flex items-center justify-center rounded-full border border-black shadow-lg">{cart.length}</span>}
                </div>
                <button onClick={() => setIsMobileMenuOpen(!isMobileMenuOpen)} className="md:hidden text-slate-300" aria-label="Open menu"><Menu /></button>
              </div>
            </div>
          </div>
          {isMobileMenuOpen && (
            <div className="md:hidden bg-black/90 backdrop-blur-xl border-b border-slate-700/50 px-2 pt-2 pb-3 space-y-1">
               {['/', '/catalog', '/about', '/contact'].map(path => <Link key={path} to={path} className="block px-3 py-2 text-base font-medium text-slate-300 hover:text-cyan-400" onClick={() => setIsMobileMenuOpen(false)}>{path === '/' ? 'HOME' : path.replace('/','').toUpperCase()}</Link>)}
            </div>
          )}
        </nav>

        {/* ROTAS */}
        <main className="pt-20 relative z-10 flex-grow">
          <Routes>
            <Route path="/" element={<Home />} />
            <Route path="/catalog" element={<Catalog addToCart={addToCart} />} />
            <Route path="/part/:pn/:id" element={<ProductDetail addToCart={addToCart} />} />
            <Route path="/about" element={<About />} />
            <Route path="/contact" element={<Contact />} />
            <Route path="/admin" element={<AdminPanel />} />
            <Route path="/admin/sourcing" element={<GlobalSourcing />} />
          </Routes>
        </main>

        {/* FOOTER */}
        <footer className="bg-black/40 border-t border-slate-700/50 text-slate-400 py-12 relative z-10 backdrop-blur-md">
          <div className="max-w-7xl mx-auto px-4 grid grid-cols-1 md:grid-cols-4 gap-8 mb-8 text-sm">
             <div className="col-span-1 md:col-span-2">
                <h3 className="text-white font-bold mb-4">GLOBAL PARTS-TECHNOLOGY</h3>
                <p className="mb-4 max-w-sm">Premier aviation supply chain partner. Dedicated to keeping your fleet airborne with 24/7 AOG support and certified components.</p>
             </div>
             <div>
                <h4 className="text-white font-bold mb-4">QUICK LINKS</h4>
                <ul className="space-y-2">
                  <li><Link to="/catalog" className="hover:text-cyan-400 transition-colors">Inventory Search</Link></li>
                  <li><Link to="/about" className="hover:text-cyan-400 transition-colors">Quality Assurance</Link></li>
                  <li><Link to="/contact" className="hover:text-cyan-400 transition-colors">Contact Support</Link></li>
                  <li>
                    <a href="https://globalpartstechnology.com/directory.php" className="hover:text-cyan-400 transition-colors" title="A-Z Parts Directory">
                        Parts Directory
                    </a>
                  </li>
                </ul>
             </div>
             <div>
                <h4 className="text-white font-bold mb-4">LEGAL</h4>
                <ul className="space-y-2">
                  <li><a href="#" className="hover:text-cyan-400 transition-colors">Privacy Policy</a></li>
                  <li><a href="#" className="hover:text-cyan-400 transition-colors">Terms & Conditions</a></li>
                  <li><a href="#" className="hover:text-cyan-400 transition-colors">Shipping Policy</a></li>
                </ul>
             </div>
          </div>
          <div className="max-w-7xl mx-auto px-4 pt-8 border-t border-slate-700/50 flex flex-col md:flex-row justify-between items-center gap-4">
            <div className="text-center md:text-left">© {new Date().getFullYear()} Global Parts-Technology. All rights reserved.</div>
            <div className="flex items-center gap-4 text-xs opacity-50">
               <span></span>
               <span>•</span>
               <span> </span>
            </div>
          </div>
        </footer>

        {/* CART DRAWER (SMTP) */}
        {isCartOpen && (
          <div className="fixed inset-0 z-[60] flex justify-end">
            <div className="absolute inset-0 bg-black/60 backdrop-blur-sm" onClick={() => setIsCartOpen(false)}></div>
            <div className="relative bg-slate-950/90 w-full max-w-md h-full flex flex-col border-l border-slate-700/50 shadow-2xl backdrop-blur-xl">
              <div className="p-6 border-b border-slate-700/50 flex justify-between items-center bg-black/40">
                <h2 className="text-xl font-bold text-white flex items-center gap-2"><ShoppingCart className="text-cyan-500"/> Quote Cart</h2>
                <button onClick={() => setIsCartOpen(false)}><X className="text-slate-400 hover:text-white"/></button>
              </div>
              <div className="flex-1 overflow-y-auto p-6 space-y-4">
                  {cart.length === 0 ? <div className="text-center text-slate-500 mt-10">Your cart is empty.</div> : cart.map(item => (
                    <div key={item.id} className="bg-slate-900/40 p-4 rounded border border-slate-700/50 flex gap-4 backdrop-blur-sm items-center">
                      
                      {/* IMAGEM DINÂMICA DENTRO DO CARRINHO */}
                      <div className="w-16 h-16 flex-shrink-0 bg-black/50 border border-slate-700/50 rounded flex items-center justify-center overflow-hidden">
                        <img 
                          src={`${API_BASE_URL}/generate_image.php?pn=${encodeURIComponent(item.pn)}`} 
                          alt={item.pn} 
                          className="w-full h-full object-contain opacity-80"
                          onError={(e) => { e.currentTarget.src = '/peca.png'; }}
                        />
                      </div>

                      <div className="flex-1">
                        <div className="flex justify-between"><h4 className="text-slate-200 text-sm font-bold">{item.pn}</h4><button onClick={() => removeFromCart(item.id)}><Trash2 className="w-4 h-4 text-red-400 hover:text-red-300"/></button></div>
                        <div className="text-xs text-slate-400 mb-2">{item.name}</div>
                        <div className="flex items-center mt-2 gap-3"><label className="text-xs text-slate-500">Qty:</label><input type="number" min="1" value={item.quantity} onChange={(e) => updateQuantity(item.id, parseInt(e.target.value))} className="w-16 bg-black/50 border border-slate-700/50 rounded px-2 py-1 text-sm text-slate-300 focus:border-cyan-600 outline-none backdrop-blur-sm" /></div>
                      </div>
                    </div>
                  ))}
              </div>
              <div className="p-6 border-t border-slate-700/50 bg-black/40 space-y-3">
                 <p className="text-xs text-slate-400 mb-2">Enter your details to receive the quote:</p>
                 <input placeholder="Name *" className="w-full bg-slate-900 border border-slate-700 rounded p-2 text-white placeholder-slate-500 focus:border-cyan-500 outline-none" value={customerInfo.name} onChange={e => setCustomerInfo({...customerInfo, name: e.target.value})}/>
                 <input placeholder="Email *" className="w-full bg-slate-900 border border-slate-700 rounded p-2 text-white placeholder-slate-500 focus:border-cyan-500 outline-none" value={customerInfo.email} onChange={e => setCustomerInfo({...customerInfo, email: e.target.value})}/>
                 <input placeholder="Phone" className="w-full bg-slate-900 border border-slate-700 rounded p-2 text-white placeholder-slate-500 focus:border-cyan-500 outline-none" value={customerInfo.phone} onChange={e => setCustomerInfo({...customerInfo, phone: e.target.value})}/>
                <button onClick={sendQuote} disabled={cart.length === 0 || isSending} className="w-full bg-cyan-700 hover:bg-cyan-600 text-white font-bold py-3 rounded shadow-lg disabled:opacity-50 mt-4 cursor-pointer">{isSending ? 'SENDING...' : 'SEND RFQ NOW'}</button>
              </div>
            </div>
          </div>
        )}
      </div>
    </HelmetProvider>
  );
};

const AppWrapper = () => (<BrowserRouter><App /></BrowserRouter>);
export default AppWrapper;