import { FormEvent } from 'react';
import { Search, Menu, Clock, ChefHat, Heart, Star, TrendingUp, Mail, Instagram, Bookmark, User, Share2, Globe } from 'lucide-react';

const DICT: Record<string, any> = {
  pt: {
    back: 'Voltar ao Início',
    search: 'Ex: Bolo de Chocolate',
    trending: 'BOMBANDO NA SEMANA',
    sidebarAd: 'Sponsor MREC',
    newsletterTitle: 'Assine e Receba!',
    newsletterDesc: 'As 10 melhores receitas semanais.',
    subscribeBtn: 'Quero Receber',
    latest: 'NOVIDADES E DICAS',
    popularWidget: 'TOP 5 HOJE',
    readTime: 'MIN',
    articles: [
      { id: '1', title: 'Bolo de Cenoura de Liquidificador Perfeito', excerpt: 'Aquela receita que nunca falha, com uma cobertura de chocolate que fica durinha e crocante. O favorito absoluto das tardes chuvosas no Brasil inteiro.', category: 'Bolos', time: '40', rating: '4.9', reviews: 1240 },
      { id: '2', title: 'Strogonoff de Frango Rápido e Cremoso', excerpt: 'O clássico almoço de domingo pronto em 20 minutos usando ingredientes da geladeira.', category: 'Prato Principal', time: '20', rating: '4.8', reviews: 856 },
      { id: '3', title: 'Pão de Queijo Mineiro Original', excerpt: 'Feito com polvilho azedo e muito queijo. Esqueça as massas prontas de saquinho hoje.', category: 'Salgados', time: '30', rating: '4.9', reviews: 2100 },
      { id: '4', title: 'Fricassê de Frango de Forno', excerpt: 'Uma travessa de puro conforto. Creme de milho sedoso com requeijão e muita batata.', category: 'Aves', time: '35', rating: '4.7', reviews: 432 },
      { id: '5', title: 'Pudim de Leite Condensado sem Furinhos', excerpt: 'O segredo da temperatura do forno e da calda de caramelo que não amarga.', category: 'Sobremesas', time: '60', rating: '5.0', reviews: 3405 },
      { id: '6', title: 'Torta de Frango de Liquidificador', excerpt: 'Massa super fofinha que derrete na boca com recheio bem molhadinho.', category: 'Tortas', time: '45', rating: '4.6', reviews: 670 },
      { id: '7', title: 'Escondidinho de Carne Seca com Mandioca', excerpt: 'Purê aveludado contrastando carne seca desfiada e queijo gratinado.', category: 'Carnes', time: '50', rating: '4.9', reviews: 920 },
      { id: '8', title: 'Mousse de Maracujá com 3 Ingredientes', excerpt: 'A sobremesa salvação dos preguiçosos. Feita usando suco concentrado.', category: 'Doces Fáceis', time: '10', rating: '4.5', reviews: 320 }
    ]
  }
};

export default function PopularTheme({ posts = [], activeView = 'home', currentArticle, children }: { posts?: any[], activeView?: 'home' | 'article', currentArticle?: any, children?: React.ReactNode }) {
  const lang = 'pt';
  const ui = DICT[lang] || DICT['pt'];

  // Mapeia posts reais do Supabase (gerados pela IA)
  const articlesToRender = posts && posts.length > 0 ? posts.map((p, i) => {
    return {
      id: p.slug || p.id,
      category: p.category_name || 'RECEITA',
      title: p.title,
      excerpt: p.excerpt,
      time: '15', 
      rating: '4.9',
      reviews: Math.floor(Math.random() * 2000) + 100,
      img: p.image || `https://images.unsplash.com/photo-1546069901-ba9599a7e63c?auto=format&fit=crop&q=80&w=800&random=${i}`,
      content: p.content,
      date: new Date(p.created_at || Date.now()).toLocaleDateString('pt-BR')
    };
  }) : ui.articles;

  const displayArticle = currentArticle ? {
    ...currentArticle,
    id: currentArticle.slug || currentArticle.id,
    category: currentArticle.category_name || 'RECEITA',
    time: '15',
    rating: '4.9',
    reviews: Math.floor(Math.random() * 2000) + 100,
    img: currentArticle.image || `https://images.unsplash.com/photo-1546069901-ba9599a7e63c?auto=format&fit=crop&q=80&w=800`
  } : articlesToRender[0];

  return (
    <div className="popular-portal bg-[#F3F4F6] text-[#1F2937] min-h-screen font-sans">
      
      {/* Top Banner (Thin Navbar) */}
      <div className="bg-[#FB923C] text-orange-50 px-4 py-2 flex justify-between items-center text-xs font-bold tracking-wide">
         <div className="flex items-center gap-6">
            <span className="hidden sm:flex items-center gap-2 cursor-pointer hover:text-white transition-colors"><Instagram className="w-4 h-4"/> Instagram</span>
            <span className="hidden sm:flex items-center gap-2 cursor-pointer hover:text-white transition-colors"><Share2 className="w-4 h-4"/> Redes Sociais</span>
         </div>
         <div className="flex gap-6">
            <a href="/login" className="hover:text-white transition-colors flex items-center gap-1"><User className="w-3 h-3"/> Mande Sua Receita</a>
            <a href="/faq" className="hover:text-white transition-colors">Ajuda</a>
         </div>
      </div>

      {/* Main Massive Header */}
      <header className="bg-white shadow-md sticky top-0 z-50">
        <div className="max-w-[1240px] mx-auto px-4 sm:px-6 lg:px-8 h-[90px] flex items-center justify-between gap-8">
           
           {/* Logo Space */}
           <a href="/" className="flex items-center gap-3 cursor-pointer group">
              <div className="w-14 h-14 bg-gradient-to-br from-[#F97316] to-[#EA580C] rounded-xl flex items-center justify-center shadow-inner group-hover:-translate-y-1 transition-transform">
                 <ChefHat className="w-8 h-8 text-white"/>
              </div>
              <div className="flex flex-col">
                 <span className="text-3xl font-black text-[#1F2937] tracking-tighter leading-none">Delícia<span className="text-[#EA580C]">Fácil</span></span>
                 <span className="text-[10px] font-bold text-gray-400 tracking-widest uppercase">Portal de Receitas</span>
              </div>
           </a>

           {/* Search Bar - Thick & Central */}
           <form className="hidden lg:flex flex-1 max-w-2xl relative" action="/search">
              <input name="q" type="text" placeholder={ui.search} className="w-full bg-[#F3F4F6] border-2 border-transparent px-6 py-4 rounded-full text-base font-medium outline-none focus:bg-white focus:border-[#FB923C] focus:ring-4 focus:ring-orange-100 transition-all placeholder:text-gray-400 shadow-inner" />
              <button type="submit" className="absolute right-2 top-1/2 -translate-y-1/2 bg-[#EA580C] text-white p-3 rounded-full hover:bg-[#C2410C] transition-colors shadow-md">
                 <Search className="w-5 h-5"/>
              </button>
           </form>

           {/* Profile & Saves */}
           <nav className="flex items-center gap-6 text-sm font-bold text-gray-600">
              <a href="/saved" className="hidden sm:flex flex-col items-center gap-1 hover:text-[#EA580C] transition-colors">
                <Bookmark className="w-6 h-6"/> <span className="text-[10px] uppercase">Salvos</span>
              </a>
              <button className="lg:hidden w-12 h-12 rounded-xl bg-gray-100 flex items-center justify-center text-gray-800 hover:bg-orange-100 hover:text-orange-600 transition-colors">
                <Menu className="w-6 h-6"/>
              </button>
           </nav>
        </div>
      </header>

      {activeView === 'home' ? (
        <main className="max-w-[1240px] mx-auto px-4 sm:px-6 lg:px-8 py-10">
          
          {/* Main Top Ad Unit (Leaderboard 970x90 or 970x250) */}
          <div className="w-full bg-white h-[120px] rounded-2xl mb-10 flex flex-col items-center justify-center border-2 border-dashed border-gray-200 cursor-pointer overflow-hidden relative shadow-sm">
             <span className="text-[10px] font-black uppercase text-gray-300 absolute top-2 right-4 tracking-widest">{ui.sidebarAd} // SUPER BANNER</span>
             <h3 className="text-xl font-black text-gray-400 text-center px-4">ESPAÇO PUBLICITÁRIO - GELADEIRAS COM 50% OFF</h3>
          </div>

          {/* Master 70/30 Grid */}
          <div className="grid lg:grid-cols-12 gap-8 lg:gap-12">
             
             {/* LEFT COLUMN: 70% (The Content Beast) */}
             <div className="lg:col-span-8 flex flex-col gap-10">
                
                {/* Hero Feature 1 & 2 */}
                <div className="flex items-center gap-3 border-b-4 border-gray-200 pb-2">
                   <TrendingUp className="w-8 h-8 text-[#EA580C]" />
                   <h2 className="text-3xl font-black text-gray-800 uppercase tracking-tighter">{ui.trending}</h2>
                </div>

                <div className="grid md:grid-cols-2 gap-6">
                   {articlesToRender.slice(0, 2).map((art: any, idx: number) => (
                      <a href={`/${art.id}`} key={art.id + idx} className="bg-white rounded-3xl overflow-hidden shadow-sm hover:shadow-xl border border-gray-100 cursor-pointer group flex flex-col transition-all duration-300">
                         {/* Rigid Aspect Ratio Box */}
                         <div className="w-full aspect-[4/3] relative overflow-hidden bg-gray-100">
                            <img src={art.img} className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-700" alt={art.title}/>
                            <div className="absolute top-4 left-4 bg-[#EA580C] text-white text-[10px] font-black uppercase px-3 py-1.5 rounded-full shadow-lg tracking-widest">
                               {art.category}
                            </div>
                         </div>
                         <div className="p-6 flex flex-col flex-1">
                            <h3 className="text-2xl font-black text-gray-800 leading-tight mb-3 group-hover:text-[#EA580C] transition-colors">{art.title}</h3>
                            <div className="flex items-center justify-between text-xs font-bold text-gray-500 mt-auto pt-4 border-t border-gray-100">
                               <div className="flex items-center gap-1.5 bg-orange-50 text-orange-700 px-3 py-1.5 rounded-lg"><Clock className="w-4 h-4"/> {art.time} {ui.readTime}</div>
                               <div className="flex items-center gap-1 text-yellow-500"><Star className="w-4 h-4 fill-current"/> {art.rating} ({art.reviews})</div>
                            </div>
                         </div>
                      </a>
                   ))}
                </div>

                {/* Latest Recipes Dense List */}
                <div className="flex items-center gap-3 border-b-4 border-gray-200 pb-2 mt-8">
                   <h2 className="text-3xl font-black text-gray-800 uppercase tracking-tighter">{ui.latest}</h2>
                </div>

                <div className="flex flex-col gap-6">
                   {articlesToRender.slice(2).map((art: any, i: number) => (
                      <a href={`/${art.id}`} key={art.id + i} className="flex flex-col sm:flex-row gap-6 bg-white p-4 sm:p-5 rounded-3xl shadow-sm hover:shadow-xl border border-gray-100 transition-all duration-300 cursor-pointer group">
                         {/* Thumbnail container strict sizing */}
                         <div className="w-full sm:w-[260px] aspect-video sm:aspect-square rounded-2xl overflow-hidden shrink-0 relative bg-gray-100">
                            <img src={art.img} className="w-full h-full object-cover group-hover:scale-110 transition-transform duration-700" alt={art.title} />
                         </div>
                         <div className="flex-1 flex flex-col justify-center py-2 sm:pr-4">
                            <span className="text-[#EA580C] text-[10px] font-black uppercase tracking-widest mb-3 bg-orange-50 w-fit px-3 py-1 rounded-full">{art.category}</span>
                            <h3 className="text-2xl font-black text-gray-800 leading-tight mb-4 group-hover:text-[#EA580C] transition-colors">{art.title}</h3>
                            <p className="text-gray-500 text-sm font-medium mb-6 line-clamp-2">{art.excerpt}</p>
                            <div className="flex flex-wrap items-center gap-4 text-xs font-bold text-gray-500 mt-auto">
                               <span className="flex items-center gap-1 bg-gray-50 px-3 py-1.5 rounded-lg border border-gray-100"><Clock className="w-4 h-4 text-gray-400"/> {art.time} {ui.readTime}</span>
                               <span className="flex items-center gap-1"><Star className="w-4 h-4 fill-yellow-400 text-yellow-400"/> {art.rating}</span>
                               <span className="flex items-center gap-1"><Heart className="w-4 h-4 text-gray-300 group-hover:text-red-500 transition-colors"/> Favoritar</span>
                            </div>
                         </div>
                      </a>
                   ))}
                </div>

                {/* Inline MREC Ad Mobile/Desktop */}
                <div className="w-full h-[250px] bg-white rounded-3xl flex items-center justify-center border-2 border-dashed border-gray-200 mt-8 relative cursor-pointer shadow-sm">
                   <span className="text-[10px] font-black uppercase text-gray-300 block absolute top-2 right-4 tracking-widest">{ui.sidebarAd} // MREC IN-FEED</span>
                   <h3 className="text-xl font-black text-gray-300">PUBLICIDADE</h3>
                </div>

                {/* Solid Pagination Block */}
                <div className="flex justify-center mt-6 mb-10">
                   <button className="bg-white border-2 border-[#EA580C] text-[#EA580C] font-black tracking-widest px-10 py-4 text-sm rounded-full shadow-lg hover:bg-[#EA580C] hover:text-white transition-all transform hover:-translate-y-1 uppercase">Mais Receitas</button>
                </div>
             </div>

             {/* RIGHT SIDEBAR: 30% (The Money Maker) */}
             <aside className="lg:col-span-4 flex flex-col gap-10">
                
                {/* 1. Newsletter Box Extreme Contrast */}
                <div className="bg-[#EA580C] p-8 sm:p-10 rounded-3xl text-center text-white relative overflow-hidden shadow-xl border-4 border-white">
                   <div className="absolute -top-10 -right-10 opacity-10 blur-sm"><ChefHat className="w-40 h-40"/></div>
                   <div className="w-16 h-16 bg-white/20 rounded-full flex items-center justify-center mx-auto mb-6 backdrop-blur relative z-10"><Mail className="w-8 h-8" /></div>
                   <h3 className="text-3xl font-black mb-3 relative z-10 tracking-tight">{ui.newsletterTitle}</h3>
                   <p className="text-sm text-orange-100 mb-8 relative z-10 font-bold">{ui.newsletterDesc}</p>
                   <form className="flex flex-col gap-4 relative z-10">
                      <input type="email" required placeholder="Seu melhor e-mail" className="w-full px-5 py-4 rounded-xl text-gray-800 text-sm outline-none font-bold text-center shadow-inner"/>
                      <button type="submit" className="w-full bg-[#1F2937] text-white font-black px-5 py-4 rounded-xl shadow-lg hover:bg-black transition-colors uppercase tracking-widest text-sm">{ui.subscribeBtn}</button>
                   </form>
                </div>

                {/* 2. Banner Lateral Direita (Skyscraper 300x600) */}
                <div className="w-full h-[600px] bg-white rounded-3xl flex flex-col items-center justify-center border-2 border-dashed border-gray-200 relative cursor-pointer shadow-sm group">
                   <span className="text-[9px] font-black uppercase text-gray-300 absolute top-2 right-4 tracking-widest">{ui.sidebarAd} // 300x600</span>
                   <h3 className="text-2xl font-black text-gray-400 text-center px-4 mb-6">PANELAS GOURMET<br/>OFERTA 300X600.</h3>
                   <button className="bg-blue-600 text-white font-bold px-8 py-3 text-xs rounded-full uppercase tracking-widest">VISITAR SITE</button>
                </div>

                {/* 3. Mais Acessadas Widget with Ranking Style */}
                <div className="bg-white p-8 rounded-3xl shadow-sm border border-gray-100 sticky top-28">
                   <div className="flex items-center gap-3 border-b-2 border-gray-100 pb-4 mb-6">
                      <Star className="w-6 h-6 text-[#EA580C]" />
                      <h3 className="font-black text-gray-800 uppercase tracking-tighter text-2xl">{ui.popularWidget}</h3>
                   </div>
                   <div className="flex flex-col gap-8">
                       {articlesToRender.slice(4, 9).map((art: any, i: number) => {
                          if (!art) return null;
                          return (
                          <a href={`/${art.id}`} key={art.id + i} className="flex items-center gap-5 group cursor-pointer">
                             <div className="w-12 h-12 rounded-2xl bg-orange-50 border border-orange-100 font-black text-2xl text-[#EA580C] flex items-center justify-center shrink-0 shadow-sm">{i+1}</div>
                             <div className="w-20 h-20 rounded-xl overflow-hidden shrink-0 border border-gray-100">
                                <img src={art.img} className="w-full h-full object-cover group-hover:scale-110 transition-transform duration-500" alt={art.title} />
                             </div>
                             <div className="flex flex-col justify-center">
                                <h4 className="font-bold text-gray-800 leading-tight group-hover:text-[#EA580C] transition-colors text-sm line-clamp-2 mb-2">{art.title}</h4>
                                <div className="flex items-center gap-1 text-[10px] font-black text-gray-400 uppercase tracking-widest">
                                   <Clock className="w-3 h-3"/> {art.time} {ui.readTime}
                                </div>
                             </div>
                          </a>
                       )})}
                    </div>
                </div>

             </aside>

          </div>
        </main>
      ) : (
        /* --- ARTICLE VIEW --- */
        <article className="max-w-[1000px] mx-auto px-4 sm:px-6 lg:px-8 py-10">
          
          <div className="bg-white rounded-[3rem] shadow-sm border border-gray-100 overflow-hidden mb-16">
             <div className="p-8 sm:p-12 text-center">
                <a href="/" className="flex items-center justify-center gap-2 text-xs font-black uppercase text-gray-400 hover:text-[#EA580C] mb-10 transition-colors mx-auto w-fit bg-gray-50 px-4 py-2 rounded-full border border-gray-200">
                  ← {ui.back}
                </a>

                <span className="bg-[#EA580C] text-white px-4 py-1.5 rounded-md text-[10px] font-black uppercase tracking-widest mb-6 inline-block shadow-md">
                  {displayArticle.category}
                </span>
                <h1 className="text-4xl sm:text-5xl lg:text-7xl font-black text-gray-800 leading-[1.05] mb-8 tracking-tighter">
                  {displayArticle.title}
                </h1>
                
                {/* Author Box Horizontal & Rating stats */}
                <div className="flex flex-wrap items-center justify-center gap-4 sm:gap-8 text-sm font-bold text-gray-600 bg-gray-50 p-4 rounded-2xl w-fit mx-auto border border-gray-100">
                  <div className="flex items-center gap-2 pr-4 border-r border-gray-300">
                    <img src="https://images.unsplash.com/photo-1573496359142-b8d87734a5a2?auto=format&fit=crop&w=100&h=100&q=80" className="w-10 h-10 rounded-full border-2 border-white shadow-sm" alt="Author"/>
                    <span>Por <span className="text-[#EA580C]">Luiza</span></span>
                  </div>
                  <div className="flex items-center gap-1 pr-4 border-r border-gray-300"><Clock className="w-5 h-5 text-gray-400"/> {displayArticle.time} {ui.readTime}</div>
                  <div className="flex items-center gap-1"><Star className="w-5 h-5 fill-yellow-400 text-yellow-400"/> {displayArticle.rating} ({displayArticle.reviews})</div>
                </div>
                
                <div className="flex justify-center gap-4 mt-8">
                   <button className="flex items-center gap-2 bg-[#1877F2] text-white font-bold text-xs uppercase tracking-widest px-6 py-3 rounded-xl shadow-md hover:bg-blue-700 transition">
                      <Share2 className="w-4 h-4"/> Compartilhar
                   </button>
                   <button className="flex items-center gap-2 bg-gray-100 text-gray-700 font-bold text-xs uppercase tracking-widest px-6 py-3 rounded-xl shadow-sm border border-gray-200 hover:bg-gray-200 transition">
                      <Bookmark className="w-4 h-4"/> Salvar / Imprimir
                   </button>
                </div>
             </div>

             <div className="w-full aspect-video sm:aspect-[21/9] bg-gray-100 relative">
                <img src={displayArticle.img} className="w-full h-full object-cover" alt={displayArticle.title} />
             </div>
          </div>

          <div className="grid lg:grid-cols-12 gap-12">
             
             {/* CONTENT LEFT (70%) */}
             <div className="lg:col-span-8">
                <div className="bg-white rounded-[2rem] p-8 sm:p-12 shadow-sm border border-gray-100 prose prose-lg prose-orange max-w-none text-gray-700 font-medium leading-relaxed prose-headings:font-black prose-headings:text-gray-800 prose-headings:tracking-tighter prose-a:text-[#EA580C] marker:text-[#EA580C] prose-img:rounded-3xl prose-img:shadow-md">
                   {children}
                </div>
             </div>

             {/* SIDEBAR RIGHT (30%) */}
             <div className="lg:col-span-4 flex flex-col gap-10">
                  {/* Half-Page Ad Sticky */}
                  <div className="w-full h-[600px] bg-white rounded-3xl flex flex-col items-center justify-center border-2 border-dashed border-gray-200 relative cursor-pointer sticky top-24 shadow-sm">
                    <span className="text-[10px] font-black uppercase text-gray-300 absolute top-4 right-4 tracking-widest">{ui.sidebarAd} // 300x600</span>
                    <ChefHat className="w-20 h-20 text-gray-200 mb-6"/>
                    <h3 className="text-2xl font-black text-gray-300 text-center px-4 tracking-tighter uppercase">OFERTA DE<br/>LIQUIDIFICADORES.</h3>
                  </div>
             </div>
          </div>
        </article>
      )}

      {/* Massive Chunky Corporate Footer */}
      <footer className="mt-20 border-t-[8px] border-[#EA580C] bg-white pt-20 pb-10">
         <div className="max-w-[1240px] mx-auto px-4 sm:px-6 lg:px-8 grid md:grid-cols-4 gap-12 text-center md:text-left mb-16 border-b border-gray-100 pb-16">
            <div className="md:col-span-2 flex flex-col items-center md:items-start">
               <div className="flex items-center gap-3 mb-6">
                 <div className="w-12 h-12 bg-gradient-to-br from-[#F97316] to-[#EA580C] rounded-xl flex items-center justify-center shadow-inner">
                    <ChefHat className="w-6 h-6 text-white"/>
                 </div>
                 <div className="flex flex-col">
                    <span className="text-2xl font-black text-[#1F2937] tracking-tighter leading-none">Delícia<span className="text-[#EA580C]">Fácil</span></span>
                 </div>
               </div>
               <p className="text-gray-500 font-medium text-sm max-w-md">O portal de engenharia JNews simulado reescrevendo o livro de regras de densidade comercial no Brasil. Maior controle de padding, cantos massivos e contraste laranja gritante.</p>
               <div className="flex gap-4 mt-8">
                  <a href="#" className="w-10 h-10 bg-gray-100 rounded-full flex items-center justify-center hover:bg-[#EA580C] hover:text-white transition-colors"><Instagram className="w-5 h-5"/></a>
                  <a href="#" className="w-10 h-10 bg-gray-100 rounded-full flex items-center justify-center hover:bg-[#EA580C] hover:text-white transition-colors"><Globe className="w-5 h-5"/></a>
                  <a href="#" className="w-10 h-10 bg-gray-100 rounded-full flex items-center justify-center hover:bg-[#EA580C] hover:text-white transition-colors"><Share2 className="w-5 h-5"/></a>
               </div>
            </div>
            <div>
               <h4 className="font-black text-gray-800 uppercase tracking-widest text-sm mb-6">Explore</h4>
               <ul className="space-y-4 text-sm font-bold text-gray-500">
                  <li><a href="/" className="hover:text-[#EA580C] transition-colors">Início</a></li>
                  <li><a href="/search" className="hover:text-[#EA580C] transition-colors">Receitas</a></li>
                  <li><a href="/login" className="hover:text-[#EA580C] transition-colors">Minha Conta</a></li>
               </ul>
            </div>
            <div>
               <h4 className="font-black text-gray-800 uppercase tracking-widest text-sm mb-6">Políticas</h4>
               <ul className="space-y-4 text-sm font-bold text-gray-500">
                  <li><a href="/privacy" className="hover:text-[#EA580C] transition-colors">Privacidade</a></li>
                  <li><a href="/terms" className="hover:text-[#EA580C] transition-colors">Termos de Uso</a></li>
                  <li><a href="/contact" className="hover:text-[#EA580C] transition-colors">Contato</a></li>
               </ul>
            </div>
         </div>
         <div className="text-center font-bold text-gray-400 text-xs tracking-widest uppercase">
            © {new Date().getFullYear()} Delícia Fácil LLC. Todos os direitos reservados.
         </div>
      </footer>
    </div>
  );
}
