const {useEffect,useState}=React;
const C=window.AUGURI_CONFIG,S=supabase.createClient(C.SUPABASE_URL,C.SUPABASE_ANON_KEY);
const money=n=>new Intl.NumberFormat('pt-BR',{style:'currency',currency:'BRL'}).format(n||0);
async function api(path,method='GET',body){const{data:{session}}=await S.auth.getSession();if(!session)throw new Error('Sessão encerrada.');const r=await fetch(C.API_URL+path,{method,headers:{Authorization:'Bearer '+session.access_token,'Content-Type':'application/json'},body:body&&JSON.stringify(body)});const data=await r.json();if(!r.ok)throw new Error(data.error||'Não foi possível concluir a operação.');return data}
function Login(){const[e,setE]=useState(''),[p,setP]=useState(''),[x,setX]=useState('');return <main className="login"><form onSubmit={async q=>{q.preventDefault();setX('');const{error}=await S.auth.signInWithPassword({email:e,password:p});if(error)setX('E-mail ou senha inválidos.')}}><div className="brand">AUGURI <b>•</b></div><p className="muted">Acesso privado</p><input placeholder="E-mail" type="email" onChange={q=>setE(q.target.value)}/><input placeholder="Senha" type="password" onChange={q=>setP(q.target.value)}/>{x&&<p>{x}</p>}<button>Entrar</button></form></main>}
function App(){const[session,setSession]=useState(null),[d,setD]=useState({}),[syncing,setSyncing]=useState(false),[notice,setNotice]=useState('');const load=()=>api('/dashboard').then(setD).catch(e=>setNotice(e.message));useEffect(()=>{S.auth.getSession().then(({data})=>setSession(data.session));return S.auth.onAuthStateChange((_,s)=>setSession(s)).data.subscription},[]);useEffect(()=>{if(session){load();const n=setInterval(load,900000);return()=>clearInterval(n)}},[session]);const sync=async()=>{setSyncing(true);setNotice('Consultando a Amazon…');try{const r=await api('/sync','POST');setNotice(`${r.processed} pedido(s) processado(s).`);await load()}catch(e){setNotice(e.message)}finally{setSyncing(false)}};if(!session)return <Login/>;return <div className="shell"><aside className="side"><div className="brand">AUGURI <b>•</b></div><button onClick={()=>S.auth.signOut()}>Sair</button></aside><main className="main"><div className="top"><div><h1>Visão geral</h1><p className="muted">Cancelados não entram nas vendas.</p></div><button className="sync" onClick={sync} disabled={syncing}>{syncing?'Sincronizando…':'Atualizar Amazon'}</button></div>{notice&&<p className="notice">{notice}</p>}<section className="cards"><div className="card"><small>Faturamento</small><strong>{money(d.revenue)}</strong></div><div className="card"><small>Pedidos válidos</small><strong>{d.orders||0}</strong></div><div className="card"><small>CMV estimado</small><strong>{money(d.cogs)}</strong></div><div className="card"><small>Lucro estimado</small><strong>{money(d.estimated_profit)}</strong></div></section><section className="panel"><h2>Resultado mensal</h2><table><tbody><tr><td>Unidades vendidas</td><td>{d.units||0}</td></tr><tr><td>Despesas fixas</td><td>{money(d.fixed_expenses)}</td></tr><tr><td>Despesas variáveis</td><td>{money(d.variable_expenses)}</td></tr><tr><td>Margem</td><td>{Number(d.margin||0).toFixed(1)}%</td></tr><tr><td>Última sincronização</td><td>{d.last_sync?new Date(d.last_sync).toLocaleString('pt-BR'):'Ainda não executada'}</td></tr></tbody></table></section></main></div>}
ReactDOM.createRoot(document.getElementById('root')).render(<App/>);
