import React,{useEffect,useState,useMemo} from 'react';
import{createRoot}from'react-dom/client';
import{createClient}from'@supabase/supabase-js';
import{Plus,Minus,Search,Shirt,LogOut,Package,History,AlertTriangle,RefreshCw}from'lucide-react';

const url='https://dogrcntbcfqljcwekgfb.supabase.co',key='sb_publishable_33gVb6_v2zmR1Z7sMHzOLg_uGharO_L';
const db=url&&key?createClient(url,key):null;
function App(){
 const[session,setSession]=useState(null),[studio,setStudio]=useState(null),[items,setItems]=useState([]),[moves,setMoves]=useState([]),[tab,setTab]=useState('inventory'),[query,setQuery]=useState(''),[filter,setFilter]=useState('All'),[modal,setModal]=useState(false),[busy,setBusy]=useState(false),[error,setError]=useState(''),[email,setEmail]=useState(''),[password,setPassword]=useState(''),[signup,setSignup]=useState(false),[form,setForm]=useState({type:'T-Shirt',brand:'',color:'Black',size:'M',quantity:1,cost:3.59,threshold:3});
 useEffect(()=>{if(!db)return;db.auth.getSession().then(({data})=>setSession(data.session));const{data:{subscription}}=db.auth.onAuthStateChange((_e,s)=>setSession(s));return()=>subscription.unsubscribe()},[]);
 useEffect(()=>{if(!session||!db){setStudio(null);return}db.from('inventory_members').select('user_id').eq('user_id',session.user.id).maybeSingle().then(({data,error:e})=>{if(e)setError(e.message);setStudio(data?{id:'shared',name:'Beautifully Reckless Studio'}:null)})},[session]);
 async function refresh(){if(!studio)return;const[a,b]=await Promise.all([db.from('inventory').select('*').order('type').order('color').order('size'),db.from('stock_movements').select('*,inventory(type,color,size)').order('created_at',{ascending:false}).limit(100)]);if(a.error)setError(a.error.message);else setItems((a.data||[]).map(x=>({...x,threshold:x.low_stock_threshold})));if(!b.error)setMoves(b.data||[])}
 useEffect(()=>{if(!studio)return;refresh();const channel=db.channel('inventory-shared').on('postgres_changes',{event:'*',schema:'public',table:'inventory'},refresh).on('postgres_changes',{event:'*',schema:'public',table:'stock_movements'},refresh).subscribe();return()=>{db.removeChannel(channel)}},[studio]);
 async function login(e){e.preventDefault();setError('');setBusy(true);const{error:e2}=signup?await db.auth.signUp({email,password}):await db.auth.signInWithPassword({email,password});if(e2)setError(e2.message);else if(signup)setError('Account created. Check your email for a confirmation link, then sign in.');setBusy(false)}
 async function adjust(item,delta){if(busy)return;setBusy(true);setError('');const{error:e}=await db.rpc('adjust_stock',{item_id:item.id,change_amount:delta,reason:delta>0?'Restocked':'Used for order'});if(e)setError(e.message);await refresh();setBusy(false)}
 async function add(e){e.preventDefault();setBusy(true);setError('');const{error:e2}=await db.rpc('add_inventory_item',{t:form.type,b:form.brand,c:form.color,z:form.size,q:Number(form.quantity),unit_cost:Number(form.cost),low_threshold:Number(form.threshold)});if(e2)setError(e2.message);else{setModal(false);await refresh()}setBusy(false)}
 const shown=useMemo(()=>items.filter(x=>(filter==='All'||x.type===filter)&&`${x.type} ${x.brand} ${x.color} ${x.size}`.toLowerCase().includes(query.toLowerCase())),[items,filter,query]);
 const types=['All',...new Set(items.map(x=>x.type))],total=items.reduce((s,x)=>s+x.quantity,0),low=items.filter(x=>x.quantity<=x.threshold),value=items.reduce((s,x)=>s+x.quantity*Number(x.cost),0);
 if(!db)return <main className="center"><h1>Setup needed</h1><p>Add your Supabase URL and publishable key to the .env file to connect shared inventory.</p></main>;
 if(!session)return <main className="auth"><div className="authbox"><div className="logo">B<span>R</span>S</div><h1>Beautifully Reckless Studio</h1><p>Shared apparel inventory</p><form onSubmit={login}><label>Email<input type="email" required value={email} onChange={e=>setEmail(e.target.value)}/></label><label>Password<input type="password" minLength="6" required value={password} onChange={e=>setPassword(e.target.value)}/></label><button disabled={busy}>{signup?'Create account':'Sign in'}</button></form><button className="link" onClick={()=>{setSignup(!signup);setError('')}}>{signup?'Already have an account? Sign in':'Create an account'}</button>{error&&<p className="error">{error}</p>}</div></main>;
 if(!studio)return <main className="center"><h2>Welcome!</h2><p>Your account is signed in but hasn't been authorized yet. Ask the administrator to add your user ID to inventory_members in Supabase.</p><p>Account: {session.user.email}</p><button onClick={()=>db.auth.signOut()}>Sign out</button></main>;
 return <div className="app"><header><div><small>BEAUTIFULLY RECKLESS STUDIO</small><h1>Inventory</h1></div><button className="iconbutton" aria-label="Sign out" onClick={()=>db.auth.signOut()}><LogOut size={21}/></button></header><section className="stats"><article><span>Blanks in stock</span><strong>{total}</strong><Package size={19}/></article><article><span>Low stock styles</span><strong>{low.length}</strong><AlertTriangle size={19}/></article><article><span>Inventory value</span><strong>${value.toFixed(2)}</strong><Shirt size={19}/></article></section><nav><button className={tab==='inventory'?'active':''} onClick={()=>setTab('inventory')}><Shirt size={17}/> Inventory</button><button className={tab==='restock'?'active':''} onClick={()=>setTab('restock')}><AlertTriangle size={17}/> Restock</button><button className={tab==='history'?'active':''} onClick={()=>setTab('history')}><History size={17}/> History</button></nav>{error&&<div className="error">{error}<button onClick={()=>setError('')}>×</button></div>}{tab==='inventory'&&<><div className="search"><Search size={19}/><input placeholder="Search type, color, size..." value={query} onChange={e=>setQuery(e.target.value)}/></div><div className="filters">{types.map(t=><button key={t} className={filter===t?'selected':''} onClick={()=>setFilter(t)}>{t}</button>)}</div><div className="sectionhead"><h2>Your blanks <span>({shown.length})</span></h2><button className="smallbutton" onClick={refresh}><RefreshCw size={16}/> Refresh</button></div>{shown.map(item=><article className="item" key={item.id}><div className="shirticon"><Shirt/></div><div className="itemdetail"><b>{item.type}</b><span>{item.color} · {item.size}{item.brand?' · '+item.brand:''}</span>{item.quantity<=item.threshold&&<em>Low stock</em>}</div><div className="quantity"><button aria-label="Remove one" disabled={busy||item.quantity===0} onClick={()=>adjust(item,-1)}><Minus size={18}/></button><strong>{item.quantity}</strong><button aria-label="Add one" disabled={busy} onClick={()=>adjust(item,1)}><Plus size={18}/></button></div></article>)}{shown.length===0&&<p className="empty">No shirts found. Add your first blank to get started.</p>}</>}{tab==='restock'&&<><h2>Restock list</h2>{low.length===0?<p className="empty">Nothing needs restocking.</p>:low.map(x=><article className="item" key={x.id}><div className="shirticon"><Shirt/></div><div className="itemdetail"><b>{x.type} · {x.size}</b><span>{x.color} · {x.brand||'Unbranded'}</span></div><div className="restockqty">{x.quantity} left</div></article>)}</>}{tab==='history'&&<><h2>Recent stock changes</h2>{moves.length===0?<p className="empty">No changes yet.</p>:moves.map(m=><article className="movement" key={m.id}><div><b>{m.inventory?.type||'Item'} · {m.inventory?.color} · {m.inventory?.size}</b><span>{m.note} · {new Date(m.created_at).toLocaleString()}</span></div><strong className={m.delta>0?'positive':'negative'}>{m.delta>0?'+':''}{m.delta}</strong></article>)}</>}{tab==='inventory'&&<button className="addfloating" onClick={()=>setModal(true)}><Plus size={21}/> Add inventory</button>}{modal&&<div className="overlay" onClick={()=>setModal(false)}><div className="sheet" onClick={e=>e.stopPropagation()}><div className="sectionhead"><h2>Add apparel blanks</h2><button className="iconbutton" onClick={()=>setModal(false)}>✕</button></div><form onSubmit={add}><label>Type<select value={form.type} onChange={e=>setForm({...form,type:e.target.value})}>{['T-Shirt','Long Sleeve','Hoodie','Crewneck','Tank Top','Youth T-Shirt','Youth Hoodie','Other'].map(t=><option key={t}>{t}</option>)}</select></label><label>Brand<input value={form.brand} onChange={e=>setForm({...form,brand:e.target.value})} placeholder="Optional"/></label><div className="twocol"><label>Color<input required value={form.color} onChange={e=>setForm({...form,color:e.target.value})}/></label><label>Size<select value={form.size} onChange={e=>setForm({...form,size:e.target.value})}>{['2T','3T','4T','5T','YXS','YS','YM','YL','YXL','XS','S','M','L','XL','2XL','3XL','4XL','5XL','One Size'].map(s=><option key={s}>{s}</option>)}</select></label></div><div className="twocol"><label>Quantity<input type="number" min="0" required value={form.quantity} onChange={e=>setForm({...form,quantity:e.target.value})}/></label><label>Cost per blank ($)<input type="number" min="0" step=".01" required value={form.cost} onChange={e=>setForm({...form,cost:e.target.value})}/></label></div><label>Low stock alert at<input type="number" min="0" required value={form.threshold} onChange={e=>setForm({...form,threshold:e.target.value})}/></label><button disabled={busy}>Save to shared inventory</button></form></div></div>}</div>
}
createRoot(document.getElementById('root')).render(<App/>);
