import React, { useEffect, useMemo, useState } from 'react';
import { createRoot } from 'react-dom/client';
import { BarChart3, Home, LayoutDashboard, LogOut, Menu, Package, Plus, Search, Settings, ShoppingBag, Tag, Ticket, Trash2 } from 'lucide-react';
import { db } from './services/store';
import { Banner, Campaign, Category, Product } from './types';
import { money, slugify, today, uid } from './utils/helpers';
import './style.css';

type Route = { page: string; slug?: string; id?: string };
const routeFromHash = (): Route => { const raw = location.hash.replace('#', '') || '/'; const parts = raw.split('/').filter(Boolean); return { page: parts[0] || 'home', slug: parts[1], id: parts[2] }; };
const go = (path: string) => { location.hash = path; };

function useStore() { const [, setTick] = useState(0); useEffect(() => { const fn = () => setTick(x => x + 1); window.addEventListener('tooca:update', fn); window.addEventListener('hashchange', fn); db.init(); return () => { window.removeEventListener('tooca:update', fn); window.removeEventListener('hashchange', fn); }; }, []); return { products: db.products(), categories: db.categories(), banners: db.banners(), campaigns: db.campaigns(), clicks: db.clicks(), settings: db.settings(), route: routeFromHash(), auth: db.isAuth() }; }

function Header() { const { settings } = useStore(); return <header className="header"><a className="brand" onClick={() => go('/')}>🛒 {settings.storeName}</a><nav><a onClick={() => go('/produtos')}>Produtos</a><a onClick={() => go('/categorias')}>Categorias</a><a onClick={() => go('/ofertas')}>Ofertas</a><a onClick={() => go('/busca')}>Busca</a><a onClick={() => go('/admin/dashboard')}>Admin</a></nav></header>; }
function Footer() { const { settings } = useStore(); return <footer className="footer"><b>{settings.storeName}</b><span>Afiliados Mercado Livre • WhatsApp {settings.whatsapp} • Instagram {settings.instagram}</span></footer>; }
function Layout({ children }: { children: React.ReactNode }) { return <><Header /><main className="container">{children}</main><Footer /></>; }
function ProductCard({ product }: { product: Product }) { return <article className="card product"><img src={product.imageUrl}/><div className="pad"><small>{product.mercadoLivreId || 'Afiliado ML'}</small><h3>{product.title}</h3><p>{product.description}</p><div className="price">{money(product.price)} {product.oldPrice && <span>{money(product.oldPrice)}</span>}</div><div className="row"><button onClick={() => go(`/produto/${product.slug}`)}>Detalhes</button><button className="dark" onClick={() => go(`/redirect/${product.id}`)}>Ver no ML</button></div></div></article>; }
function ProductGrid({ products }: { products: Product[] }) { return <div className="grid products">{products.filter(p => p.active).map(p => <ProductCard key={p.id} product={p}/>)}</div>; }

function HomePage() { const { products, banners } = useStore(); const hero = banners.find(b => b.active && b.position === 'home_top'); return <Layout><section className="hero" style={{backgroundImage:`linear-gradient(90deg, rgba(0,0,0,.72), rgba(0,0,0,.15)), url(${hero?.imageUrl})`}}><h1>{hero?.title || 'Tooca Loja'}</h1><p>{hero?.subtitle || 'Achadinhos selecionados para você.'}</p><button onClick={() => go(hero?.linkUrl || '/produtos')}>Ver ofertas</button></section><h2>Produtos em destaque</h2><ProductGrid products={products.filter(p => p.featured)} /></Layout>; }
function ProductsPage() { const { products } = useStore(); return <Layout><Title icon={<Package/>} text="Todos os produtos"/><ProductGrid products={products}/></Layout>; }
function CategoriesPage() { const { categories } = useStore(); return <Layout><Title icon={<Tag/>} text="Categorias"/><div className="grid cats">{categories.filter(c=>c.active).map(c=><article className="card cat" onClick={()=>go(`/categoria/${c.slug}`)} key={c.id}><img src={c.imageUrl}/><div className="pad"><h3>{c.name}</h3><p>{c.description}</p></div></article>)}</div></Layout>; }
function CategoryPage({ slug }: { slug?: string }) { const { categories, products } = useStore(); const cat = categories.find(c => c.slug === slug); return <Layout><Title icon={<Tag/>} text={cat?.name || 'Categoria'}/><ProductGrid products={products.filter(p => cat && p.categoryIds.includes(cat.id))}/></Layout>; }
function OffersPage() { const { products } = useStore(); return <Layout><Title icon={<Ticket/>} text="Ofertas"/><ProductGrid products={products.filter(p => !!p.oldPrice)} /></Layout>; }
function SearchPage() { const { products } = useStore(); const [q,setQ] = useState(''); const filtered = products.filter(p => `${p.title} ${p.description}`.toLowerCase().includes(q.toLowerCase())); return <Layout><Title icon={<Search/>} text="Busca"/><input className="search" placeholder="Digite o nome do produto..." value={q} onChange={e=>setQ(e.target.value)}/><ProductGrid products={filtered}/></Layout>; }
function ProductPage({ slug }: { slug?: string }) { const { products, categories } = useStore(); const p = products.find(x => x.slug === slug); if (!p) return <Layout><h2>Produto não encontrado</h2></Layout>; return <Layout><section className="detail"><img src={p.imageUrl}/><div><small>{p.mercadoLivreId}</small><h1>{p.title}</h1><p>{p.description}</p><div className="price big">{money(p.price)} {p.oldPrice && <span>{money(p.oldPrice)}</span>}</div><p>{p.categoryIds.map(id=>categories.find(c=>c.id===id)?.name).filter(Boolean).join(' • ')}</p><button className="dark large" onClick={() => go(`/redirect/${p.id}`)}>Comprar no Mercado Livre</button></div></section></Layout>; }
function RedirectPage({ id }: { id?: string }) { const { products, campaigns } = useStore(); const p = products.find(x => x.id === id); useEffect(()=>{ if(p){ db.trackClick(p.id, campaigns.find(c=>c.active)?.id); setTimeout(()=>{ window.open(p.affiliateUrl || p.mercadoLivreUrl, '_blank'); go(`/produto/${p.slug}`); }, 800); } },[p?.id]); return <Layout><div className="center"><h1>Redirecionando...</h1><p>Registramos o clique e vamos abrir o Mercado Livre.</p></div></Layout>; }

function LoginPage() { const [email,setEmail]=useState('admin@tooca.com'); const [password,setPassword]=useState('123456'); const [err,setErr]=useState(''); return <main className="login"><div className="loginbox"><h1>Admin Tooca Loja</h1><input value={email} onChange={e=>setEmail(e.target.value)} placeholder="E-mail"/><input value={password} onChange={e=>setPassword(e.target.value)} placeholder="Senha" type="password"/><button className="dark" onClick={()=> db.login(email,password) ? go('/admin/dashboard') : setErr('Login inválido')}>Entrar</button>{err && <p className="error">{err}</p>}<small>admin@tooca.com / 123456</small></div></main>; }
function AdminLayout({children}:{children:React.ReactNode}) { const { auth }=useStore(); if(!auth) return <LoginPage/>; const item=(path:string,label:string,icon:React.ReactNode)=><a onClick={()=>go(path)}>{icon}{label}</a>; return <div className="admin"><aside><h2>Tooca Admin</h2>{item('/admin/dashboard','Dashboard',<LayoutDashboard/>)}{item('/admin/produtos','Produtos',<Package/>)}{item('/admin/categorias','Categorias',<Tag/>)}{item('/admin/banners','Banners',<Home/>)}{item('/admin/campanhas','Campanhas',<Ticket/>)}{item('/admin/afiliados','Afiliados',<ShoppingBag/>)}{item('/admin/cliques','Cliques',<BarChart3/>)}{item('/admin/config','Configurações',<Settings/>)}<a onClick={()=>{db.logout(); go('/admin/login')}}><LogOut/>Sair</a></aside><section className="adminContent">{children}</section></div>; }
function Title({icon,text}:{icon:React.ReactNode;text:string}){return <div className="title">{icon}<h1>{text}</h1></div>}
function Stat({label,value}:{label:string;value:string|number}){return <div className="stat"><strong>{value}</strong><span>{label}</span></div>}
function Dashboard(){ const {products,categories,clicks,banners}=useStore(); const top=[...products].sort((a,b)=>clicks.filter(c=>c.productId===b.id).length-clicks.filter(c=>c.productId===a.id).length).slice(0,5); return <AdminLayout><Title icon={<LayoutDashboard/>} text="Dashboard"/><div className="stats"><Stat label="Produtos" value={products.length}/><Stat label="Categorias" value={categories.length}/><Stat label="Banners" value={banners.length}/><Stat label="Cliques" value={clicks.length}/></div><h2>Produtos mais clicados</h2><Table rows={top.map(p=>[p.title, money(p.price), clicks.filter(c=>c.productId===p.id).length+' cliques'])}/></AdminLayout> }
function Table({rows}:{rows:(string|number)[][]}){return <table><tbody>{rows.map((r,i)=><tr key={i}>{r.map((c,j)=><td key={j}>{c}</td>)}</tr>)}</tbody></table>}

const emptyProduct: Product = { id:'', title:'', slug:'', description:'', price:0, oldPrice:0, imageUrl:'', mercadoLivreUrl:'https://www.mercadolivre.com.br', affiliateUrl:'https://www.mercadolivre.com.br?aff=tooca', mercadoLivreId:'', categoryIds:[], featured:false, active:true, createdAt: today() };
function ProductForm({edit}:{edit?:Product}){ const {categories}=useStore(); const [p,setP]=useState<Product>(edit || {...emptyProduct,id:uid('prod')}); const save=()=>{ db.saveProduct({...p, slug:p.slug||slugify(p.title)}); go('/admin/produtos');}; return <div className="form"><input placeholder="Título" value={p.title} onChange={e=>setP({...p,title:e.target.value,slug:slugify(e.target.value)})}/><textarea placeholder="Descrição" value={p.description} onChange={e=>setP({...p,description:e.target.value})}/><input placeholder="Preço" type="number" value={p.price} onChange={e=>setP({...p,price:+e.target.value})}/><input placeholder="Preço antigo" type="number" value={p.oldPrice||0} onChange={e=>setP({...p,oldPrice:+e.target.value})}/><input placeholder="Imagem URL" value={p.imageUrl} onChange={e=>setP({...p,imageUrl:e.target.value})}/><input placeholder="URL Mercado Livre" value={p.mercadoLivreUrl} onChange={e=>setP({...p,mercadoLivreUrl:e.target.value})}/><input placeholder="URL Afiliado" value={p.affiliateUrl} onChange={e=>setP({...p,affiliateUrl:e.target.value})}/><div className="checks">{categories.map(c=><label key={c.id}><input type="checkbox" checked={p.categoryIds.includes(c.id)} onChange={e=>setP({...p,categoryIds:e.target.checked?[...p.categoryIds,c.id]:p.categoryIds.filter(id=>id!==c.id)})}/>{c.name}</label>)}</div><label><input type="checkbox" checked={p.featured} onChange={e=>setP({...p,featured:e.target.checked})}/> Destaque</label><label><input type="checkbox" checked={p.active} onChange={e=>setP({...p,active:e.target.checked})}/> Ativo</label><button className="dark" onClick={save}>Salvar produto</button></div> }
function ProductsAdmin(){ const {products, route}=useStore(); if(route.slug==='novo') return <AdminLayout><Title icon={<Plus/>} text="Novo produto"/><ProductForm/></AdminLayout>; if(route.slug==='editar') return <AdminLayout><Title icon={<Package/>} text="Editar produto"/><ProductForm edit={products.find(p=>p.id===route.id)}/></AdminLayout>; return <AdminLayout><div className="between"><Title icon={<Package/>} text="Produtos"/><button onClick={()=>go('/admin/produtos/novo')}><Plus/> Novo</button></div><table><tbody>{products.map(p=><tr key={p.id}><td><img className="thumb" src={p.imageUrl}/></td><td>{p.title}</td><td>{money(p.price)}</td><td>{p.active?'Ativo':'Inativo'}</td><td><button onClick={()=>go(`/admin/produtos/editar/${p.id}`)}>Editar</button><button className="danger" onClick={()=>db.deleteProduct(p.id)}><Trash2/></button></td></tr>)}</tbody></table></AdminLayout> }
function SimpleAdmin({kind}:{kind:'categorias'|'banners'|'campanhas'}){ const s=useStore(); const title=kind==='categorias'?'Categorias':kind==='banners'?'Banners':'Campanhas'; const rows = kind==='categorias'?s.categories:kind==='banners'?s.banners:s.campaigns; const add=()=>{ if(kind==='categorias'){ const name=prompt('Nome da categoria')||''; if(name) db.saveCategory({id:uid('cat'),name,slug:slugify(name),description:'Nova categoria',imageUrl:'https://images.unsplash.com/photo-1607082349566-187342175e2f?q=80&w=1200',active:true}); } if(kind==='banners') db.saveBanner({id:uid('ban'),title:'Novo banner',subtitle:'Subtítulo',imageUrl:'https://images.unsplash.com/photo-1607082349566-187342175e2f?q=80&w=1200',linkUrl:'/produtos',position:'home_top',active:true}); if(kind==='campanhas') db.saveCampaign({id:uid('camp'),name:'Nova campanha',slug:'nova-campanha',description:'Descrição da campanha',startDate:today(),endDate:today(),active:true}); }; return <AdminLayout><div className="between"><Title icon={<Menu/>} text={title}/><button onClick={add}><Plus/> Adicionar</button></div><table><tbody>{rows.map((r:any)=><tr key={r.id}><td>{r.name||r.title}</td><td>{r.slug||r.position}</td><td>{r.active?'Ativo':'Inativo'}</td></tr>)}</tbody></table></AdminLayout> }
function Affiliates(){ const {products,settings}=useStore(); return <AdminLayout><Title icon={<ShoppingBag/>} text="Afiliados"/><p>Tag configurada: <b>{settings.affiliateTag}</b></p><table><tbody>{products.map(p=><tr key={p.id}><td>{p.title}</td><td><input readOnly value={p.affiliateUrl}/></td><td><button onClick={()=>navigator.clipboard.writeText(p.affiliateUrl)}>Copiar</button></td></tr>)}</tbody></table></AdminLayout> }
function ClicksAdmin(){ const {clicks,products,campaigns}=useStore(); return <AdminLayout><Title icon={<BarChart3/>} text="Cliques"/><table><tbody>{clicks.map(c=><tr key={c.id}><td>{new Date(c.createdAt).toLocaleString('pt-BR')}</td><td>{products.find(p=>p.id===c.productId)?.title}</td><td>{campaigns.find(x=>x.id===c.campaignId)?.name||'-'}</td><td>{c.source}</td></tr>)}</tbody></table></AdminLayout> }
function ConfigAdmin(){ const {settings}=useStore(); const [v,setV]=useState(settings); return <AdminLayout><Title icon={<Settings/>} text="Configurações"/><div className="form"><input value={v.storeName} onChange={e=>setV({...v,storeName:e.target.value})}/><input value={v.affiliateTag} onChange={e=>setV({...v,affiliateTag:e.target.value})}/><input value={v.whatsapp} onChange={e=>setV({...v,whatsapp:e.target.value})}/><input value={v.instagram} onChange={e=>setV({...v,instagram:e.target.value})}/><button className="dark" onClick={()=>db.saveSettings(v)}>Salvar</button><button className="danger" onClick={()=>db.reset()}>Resetar dados</button></div></AdminLayout> }

function App(){ const {route}=useStore(); if(route.page==='produtos') return <ProductsPage/>; if(route.page==='categorias') return <CategoriesPage/>; if(route.page==='categoria') return <CategoryPage slug={route.slug}/>; if(route.page==='ofertas') return <OffersPage/>; if(route.page==='busca') return <SearchPage/>; if(route.page==='produto') return <ProductPage slug={route.slug}/>; if(route.page==='redirect') return <RedirectPage id={route.slug}/>; if(route.page==='admin' && route.slug==='login') return <LoginPage/>; if(route.page==='admin' && route.slug==='dashboard') return <Dashboard/>; if(route.page==='admin' && route.slug==='produtos') return <ProductsAdmin/>; if(route.page==='admin' && route.slug==='categorias') return <SimpleAdmin kind="categorias"/>; if(route.page==='admin' && route.slug==='banners') return <SimpleAdmin kind="banners"/>; if(route.page==='admin' && route.slug==='campanhas') return <SimpleAdmin kind="campanhas"/>; if(route.page==='admin' && route.slug==='afiliados') return <Affiliates/>; if(route.page==='admin' && route.slug==='cliques') return <ClicksAdmin/>; if(route.page==='admin' && route.slug==='config') return <ConfigAdmin/>; return <HomePage/>; }

createRoot(document.getElementById('root')!).render(<App />);
