import React,{useState,useEffect} from 'react';
import {createRoot} from 'react-dom/client';
import {HashRouter,Routes,Route,NavLink,useLocation,useNavigate,Navigate} from 'react-router-dom';
import {QueryClient,QueryClientProvider} from '@tanstack/react-query';
import {signIn,googleSignIn,resetPassword,signOut} from './auth';
import {useForm} from 'react-hook-form';
import {zodResolver} from '@hookform/resolvers/zod';
import {z} from 'zod';
import {Activity,ArrowUpRight,BarChart3,Bell,Bookmark,Check,CheckCheck,ChevronDown,ChevronLeft,ChevronRight,CircleHelp,ExternalLink,Globe,Inbox,LayoutDashboard,Link2,Menu,MessageCircle,MoreHorizontal,Plus,Search,Send,Settings,Shield,Star,Sun,Moon,Users,X,LogOut,RefreshCw,Mail,Clock,Filter,PanelLeftClose,Video,Command} from 'lucide-react';
import {ResponsiveContainer,AreaChart,Area,XAxis,YAxis,Tooltip,CartesianGrid,BarChart,Bar} from 'recharts';
import {AppProvider,useApp,useCollection} from './state';
import {supabase,configured,liveReady,call} from './supabase';
import {Accounts} from './Accounts';
import {AttachmentComposer,MessageMedia} from './media';
import {sortAudience} from './inbox';
import {CompanySettings} from './CompanySettings';
import {labels,platforms,type Platform,type Conversation,type Message,type Template} from './types';
import './styles.css';
const platformMarks:Record<Platform,string>={whatsapp:'◔',facebook:'f',instagram:'◎',tiktok:'♪',youtube:'▶'};
function PlatformIcon({platform,small=false}:{platform:Platform;small?:boolean}){return <span aria-label={labels[platform]} className={`platform ${platform} ${small?'small':''}`}>{platformMarks[platform]}</span>;}
function Avatar({name}:{name:string}){return <span className={'avatar tone'+name.length%5}>{name.split(' ').map(s=>s[0]).slice(0,2).join('')}</span>;}
function time(ts:number){return new Date(ts).toLocaleTimeString([],{hour:'2-digit',minute:'2-digit'});}
function relative(ts:number){const min=Math.max(0,Math.floor((Date.now()-ts)/60000));return min<1?'Just now':min<60?`${min}m`:min<1440?`${Math.floor(min/60)}h`:new Date(ts).toLocaleDateString();}
function Empty({title,body}:{title:string;body:string}){return <div className="empty"><Inbox size={34}/><h3>{title}</h3><p>{body}</p></div>;}
function App(){const a=useApp(),[recovery,setRecovery]=useState(new URLSearchParams(location.search).get('recovery')==='1');if(recovery&&a.user)return <PasswordRecovery onDone={()=>setRecovery(false)}/>;if(a.authLoading)return <div className="loading">Loading your workspace…</div>;if(!a.demo&&!a.user)return <SignIn/>;if(!a.demo&&!a.memberships.length)return <CreateWorkspace/>;return <Shell/>;}
function PasswordRecovery({onDone}:{onDone:()=>void}){const [password,setPassword]=useState(''),[error,setError]=useState(''),[busy,setBusy]=useState(false);return <div className="center-card"><Brand/><h1>Set a new password</h1><form onSubmit={async e=>{e.preventDefault();setBusy(true);try{const result=await supabase!.auth.updateUser({password});if(result.error)throw result.error;history.replaceState(null,'',location.pathname+location.hash);onDone();}catch(e){setError((e as Error).message);}finally{setBusy(false);}}}><label>New password<input type="password" autoComplete="new-password" minLength={8} required value={password} onChange={e=>setPassword(e.target.value)}/></label><button className="primary" disabled={busy}>Save password</button>{error&&<p className="error">{error}</p>}</form><Footer/></div>;}
const loginSchema=z.object({email:z.email(),password:z.string().min(6)});
function SignIn(){const a=useApp(),[register,setRegister]=useState(false),[error,setError]=useState(''),[busy,setBusy]=useState(false);const {register:field,handleSubmit,formState:{errors},getValues}=useForm<z.infer<typeof loginSchema>>({resolver:zodResolver(loginSchema)});
async function submit(data:z.infer<typeof loginSchema>){setBusy(true);try{const session=await signIn(data.email,data.password,register);if(register&&!session)setError('Check your email to confirm your account, then sign in.');}catch(e){setError((e as Error).message);}finally{setBusy(false);}}
return <div className="auth-page"><div className="auth-story"><Brand/><span className="eyebrow">EVERY CONVERSATION COUNTS</span><h1>A little less switching.<br/>A lot more connection.</h1><p>One thoughtful workspace for your messages, comments, and the people behind them.</p><div className="platform-row">{platforms.map(p=><PlatformIcon key={p} platform={p}/>)}</div><small>SMM – Barracks · Built for connected teams</small></div><main className="auth-form"><h2>{register?'Create your account':'Welcome back'}</h2><p>Your conversations are waiting for you.</p>{!liveReady&&<div className="notice">Live workspace setup is in progress. Explore the clearly labeled demo below.</div>}<form onSubmit={handleSubmit(submit)}><label>Email address<input autoComplete="email" {...field('email')} placeholder="you@company.com"/></label>{errors.email&&<small role="alert">Enter a valid email address.</small>}<label>Password<input type="password" autoComplete={register?'new-password':'current-password'} {...field('password')}/></label>{errors.password&&<small role="alert">Use at least 6 characters.</small>}<button className="primary wide" disabled={!liveReady||busy}>{busy?'Please wait…':register?'Create account':'Sign in'}</button></form><button className="wide" disabled={!liveReady} onClick={()=>googleSignIn().catch(e=>setError(e.message))}>Continue with Google</button><div className="inline"><button className="text-button" onClick={()=>setRegister(!register)}>{register?'Already have an account?':'Create an account'}</button><button className="text-button" disabled={!liveReady} onClick={()=>resetPassword(getValues('email')).then(()=>setError('Password reset email requested.')).catch(e=>setError(e.message))}>Reset password</button></div>{error&&<p role="alert" className="error">{error}</p>}<div className="divider">OR EXPLORE FIRST</div><button className="wide demo-button" onClick={()=>a.enterDemo(true)}>Open demo workspace <span>Synthetic data only</span></button><Footer/></main></div>;}
function Footer(){return <footer className="app-footer">© Copyright by CreativeX Technologies (Pvt) Ltd.</footer>;}
function Brand(){return <div className="brand" title="Social Media Management – Barracks Clothing"><span className="brand-icon"><Link2 size={23}/></span><span>SMM <b>– Barracks</b></span></div>;}
function CreateWorkspace(){const a=useApp(),[name,setName]=useState(''),[error,setError]=useState(''),[busy,setBusy]=useState(false);return <div className="center-card"><Brand/><h1>Make room for your team.</h1><p>Create a workspace, or ask your administrator to add your signed-in email.</p><form onSubmit={async e=>{e.preventDefault();setBusy(true);try{const r=await call<{id:string}>('createWorkspace',{name});a.setWorkspaceId(r.id);}catch(e){setError((e as Error).message);}finally{setBusy(false);}}}><label>Workspace name<input value={name} onChange={e=>setName(e.target.value)} minLength={2} maxLength={80} required/></label><button className="primary" disabled={busy}>Create workspace</button></form><p role="alert">{error}</p><button onClick={()=>signOut()}>Sign out</button><Footer/></div>;}
const nav=[['/','Overview',LayoutDashboard],['/inbox','Unified Inbox',Inbox],['/comments','Comments',MessageCircle],['/notifications','Notifications',Bell],['/replies','Saved Replies',Bookmark],['/analytics','Analytics',BarChart3],['/team','Team',Users],['/accounts','Connected Accounts',Link2],['/settings','Settings',Settings]] as const;
function Shell(){const a=useApp(),loc=useLocation(),navigate=useNavigate(),[mobile,setMobile]=useState(false),[search,setSearch]=useState('');useEffect(()=>{document.documentElement.dataset.theme='light';localStorage.removeItem('omni-theme');},[]);useEffect(()=>{setMobile(false);},[loc.pathname]);useEffect(()=>{const handler=(e:KeyboardEvent)=>{if((e.metaKey||e.ctrlKey)&&e.key==='k'){e.preventDefault();document.getElementById('global-search')?.focus();}};window.addEventListener('keydown',handler);return()=>window.removeEventListener('keydown',handler);},[]);const unread=a.notices.filter(n=>!n.read).length;return <div className="app-shell"><aside className={'sidebar '+(mobile?'mobile-open':'')}><Brand/><button className="workspace-switch" onClick={()=>navigate('/settings')}><span className="workspace-avatar">{'BC'}</span><span><strong>{a.demo?'Barracks Clothing':a.memberships.find(w=>w.id===a.workspaceId)?.name}</strong><small>{a.demo?'Demo workspace':'Company workspace'}</small></span><ChevronDown size={15}/></button><small className="nav-label">WORKSPACE</small><nav>{nav.slice(0,2).map(([path,label,Icon])=><NavLink end={path==='/'} to={path} key={path}><Icon size={18}/>{label}{path==='/inbox'&&<span className="nav-count">{a.conversations.filter(c=>c.unreadCount).length}</span>}</NavLink>)}<div className="channel-nav">{platforms.map(p=><NavLink key={p} to={'/inbox/'+p}><PlatformIcon platform={p} small/>{labels[p]}</NavLink>)}</div>{nav.slice(2,6).map(([path,label,Icon])=><NavLink to={path} key={path}><Icon size={18}/>{label}{path==='/notifications'&&!!unread&&<span className="nav-count">{unread}</span>}</NavLink>)}<small className="nav-label">MANAGE</small>{nav.slice(6).map(([path,label,Icon])=><NavLink to={path} key={path}><Icon size={18}/>{label}</NavLink>)}</nav><div className="sidebar-bottom"><div className="help-card"><span className="help-icon"><Globe size={18}/></span><strong>Bring it all together</strong><p>Connect your channels.<br/>Keep every conversation close.</p><button onClick={()=>navigate('/accounts')}>Manage connections</button></div><button className="profile" onClick={()=>navigate('/settings')}><Avatar name={a.demo?'Alex Morgan':a.user?.displayName||'Team Member'}/><span><strong>{a.demo?'Alex Morgan':a.user?.displayName||'Team member'}</strong><small>{a.role==='admin'?'Administrator':a.role}</small></span><MoreHorizontal size={18}/></button></div></aside><div className="workspace"><header className="topbar"><button className="icon-button mobile-toggle" aria-label="Toggle navigation" onClick={()=>setMobile(!mobile)}><Menu size={20}/></button><div className="breadcrumb">Workspace <ChevronRight size={14}/> <strong>{nav.find(n=>n[0]===loc.pathname)?.[1]||'Inbox'}</strong></div><form className="global-search" onSubmit={e=>{e.preventDefault();navigate('/inbox?q='+encodeURIComponent(search));}}><Search size={16}/><input id="global-search" aria-label="Search conversations" placeholder="Search conversations…" value={search} onChange={e=>setSearch(e.target.value)}/><kbd>⌘ K</kbd></form><div className="top-actions"><span className="health"><span/>{a.demo?'Demo preview':`${a.accounts.filter(x=>x.status==='connected').length} connected`}</span><button className="icon-button notification-bell" aria-label="Notifications" onClick={()=>navigate('/notifications')}><Bell size={19}/>{!!unread&&<i/>}</button></div></header>{a.demo&&<div className="demo-banner"><span><strong>Demo workspace</strong> · All conversations and metrics are synthetic. Nothing is sent to social platforms.</span><button onClick={()=>a.enterDemo(false)}>Exit demo</button></div>}{a.error&&<div className="error banner" role="alert">{a.error}</div>}<Routes><Route path="/" element={<Overview/>}/><Route path="/inbox/*" element={<InboxPage/>}/><Route path="/comments" element={<InboxPage comments/>}/><Route path="/notifications" element={<Notifications/>}/><Route path="/replies" element={<SavedReplies/>}/><Route path="/analytics" element={<Overview analytics/>}/><Route path="/team" element={<Team/>}/><Route path="/accounts" element={<Accounts/>}/><Route path="/settings" element={<SettingsPage/>}/><Route path="*" element={<Empty title="Page not found" body="Use the workspace navigation to continue."/>}/></Routes><Footer/></div>{a.toast&&<div className="toast" role="status">{a.toast}<button aria-label="Dismiss notification" onClick={()=>a.setToast('')}><X size={16}/></button></div>}</div>;}
function PageHeading({title,description,children}:{title:string;description:string;children?:React.ReactNode}){return <div className="page-heading"><div><h1>{title}</h1><p>{description}</p></div><div className="inline">{children}</div></div>;}
function Overview({analytics=false}:{analytics?:boolean}){const a=useApp(),navigate=useNavigate(),cs=a.conversations;const chart=Array.from({length:7},(_,i)=>{const date=new Date();date.setDate(date.getDate()-6+i);return {day:date.toLocaleDateString([],{weekday:'short'}),messages:cs.filter(c=>new Date(c.createdAt).toDateString()===date.toDateString()&&c.kind==='message').length,comments:cs.filter(c=>new Date(c.createdAt).toDateString()===date.toDateString()&&c.kind==='comment').length};});const response=cs.filter(c=>c.firstResponseAt).map(c=>(c.firstResponseAt!-c.createdAt)/60000);return <main className="page"><PageHeading title={analytics?'Engagement analytics':'A clearer view of your conversations.'} description={analytics?'Application-observed activity, across your connected channels.':`Welcome back${a.demo?', Alex':''}. Here’s what’s happening in your workspace.`}><span className="date-chip"><Clock size={15}/>{new Date().toLocaleDateString([],{month:'short',day:'numeric',year:'numeric'})}</span><button className="primary" onClick={()=>navigate('/inbox')}><Inbox size={16}/>Open inbox</button></PageHeading><div className="stats-grid">{[['Incoming conversations',cs.length,MessageCircle,'Across the loaded inbox'],['Needs a reply',cs.filter(c=>!c.answered&&c.status!=='resolved').length,Clock,'Ready for your attention'],['Resolved',cs.filter(c=>c.status==='resolved').length,CheckCheck,'Thoughtfully taken care of'],['First response',response.length?`${Math.round(response.reduce((x,y)=>x+y,0)/response.length)} min`:'—',Activity,response.length?'Observed average':'No measured responses yet']].map(([title,value,Icon,sub])=>{const I=Icon as typeof Activity;return <div className="stat-card" key={String(title)}><div><span>{String(title)}</span><I size={18}/></div><strong>{String(value)}</strong><small>{String(sub)}</small></div>;})}</div><div className="dashboard-grid"><section className="card activity-card"><div className="card-heading"><div><h2>Conversation activity</h2><p>A little perspective on your week</p></div><span className="pill">Last 7 days</span></div><div className="chart-legend"><span><i/>Messages</span><span><i/>Comments</span></div><div className="chart"><ResponsiveContainer width="100%" height="100%"><AreaChart data={chart}><defs><linearGradient id="activity-fill" x1="0" y1="0" x2="0" y2="1"><stop offset="0%" stopColor="var(--chart-primary)" stopOpacity={.2}/><stop offset="100%" stopColor="var(--chart-primary)" stopOpacity={0}/></linearGradient></defs><CartesianGrid strokeDasharray="3 5" vertical={false} stroke="var(--border)"/><XAxis dataKey="day" axisLine={false} tickLine={false} tick={{fill:'var(--chart-label)',fontSize:12}}/><YAxis allowDecimals={false} axisLine={false} tickLine={false} width={30} tick={{fill:'var(--chart-label)',fontSize:12}}/><Tooltip/><Area dataKey="messages" stroke="var(--chart-primary)" fill="url(#activity-fill)" strokeWidth={2.5} type="monotone"/><Area dataKey="comments" stroke="var(--chart-secondary)" fill="transparent" strokeWidth={2} type="monotone"/></AreaChart></ResponsiveContainer></div></section><section className="card"><div className="card-heading"><div><h2>Your channels</h2><p>Every connection, in one place</p></div><Link2 size={18}/></div><div className="channel-list">{platforms.map(p=>{const account=a.accounts.find(x=>x.platform===p),count=cs.filter(c=>c.platform===p).length;return <button key={p} onClick={()=>navigate('/inbox/'+p)}><PlatformIcon platform={p}/><span><strong>{labels[p]}</strong><small>{account?a.demo?'Demo account':account.status:'Not connected'}</small></span><strong>{count}</strong><ChevronRight size={15}/></button>;})}</div><button className="card-footer-button" onClick={()=>navigate('/accounts')}>Manage connected accounts <Plus size={15}/></button></section></div><section className="card recent"><div className="card-heading"><div><h2>Needs your attention</h2><p>Good conversations start with a timely reply.</p></div><button className="text-button" onClick={()=>navigate('/inbox')}>View inbox <ChevronRight size={15}/></button></div><div className="table-scroll"><table><thead><tr><th>Customer</th><th>Latest conversation</th><th>Channel</th><th>Status</th><th>Received</th><th/></tr></thead><tbody>{cs.filter(c=>!c.answered).slice(0,5).map(c=><tr key={c.id} onClick={()=>navigate('/inbox?selected='+c.id)} tabIndex={0} onKeyDown={e=>e.key==='Enter'&&navigate('/inbox?selected='+c.id)}><td><div className="person"><Avatar name={c.author}/><strong>{c.author}</strong></div></td><td className="preview-cell">{c.preview}</td><td><div className="inline"><PlatformIcon platform={c.platform} small/>{labels[c.platform]}</div></td><td><span className={'status '+c.status}>{c.status}</span></td><td>{relative(c.lastActivityAt)}</td><td><ChevronRight size={16}/></td></tr>)}</tbody></table>{!cs.length&&<Empty title="Your next conversation starts here" body="Connect an authorized account to begin synchronizing messages and comments."/>}</div></section><p className="data-footnote">{a.demo?'Synthetic preview data':'Observed data'} · Metrics cover the {cs.length} currently loaded conversations. Provider history may be incomplete.</p></main>;}
function InboxPage({comments=false}:{comments?:boolean}){const a=useApp(),loc=useLocation(),params=new URLSearchParams(loc.search),channel=loc.pathname.split('/')[2] as Platform|undefined;const [selected,setSelected]=useState(params.get('selected')||''),[search,setSearch]=useState(params.get('q')||''),[filter,setFilter]=useState('all'),[account,setAccount]=useState('all'),[date,setDate]=useState(''),[showFilters,setShowFilters]=useState(false),[audience,setAudience]=useState('recent'),[minAudience,setMinAudience]=useState('');useEffect(()=>setSearch(params.get('q')||''),[loc.search]);useEffect(()=>{const s=new URLSearchParams(loc.search).get('selected');if(s)setSelected(s);},[loc.search]);const list=sortAudience(a.conversations.filter(c=>(!channel||c.platform===channel)&&(!comments||c.kind==='comment')&&(account==='all'||c.accountId===account)&&(!date||c.lastActivityAt>=new Date(date).getTime())&&(`${c.author} ${c.preview}`.toLowerCase().includes(search.toLowerCase()))&&(filter==='all'||filter==='messages'&&c.kind==='message'||filter==='comments'&&c.kind==='comment'||filter==='unread'&&c.unreadCount>0||filter==='unanswered'&&!c.answered||filter==='mine'&&c.assignedTo===(a.demo?'demo':a.user?.uid)||filter==='priority'&&c.priority||c.status===filter)).filter(c=>minAudience===''||(c.audienceCount!=null&&c.audienceCount>=Number(minAudience))),audience);const current=a.conversations.find(c=>c.id===selected);return <main className={'inbox-page '+(current?'has-selection':'')+(showFilters?' show-filters':'')}><div className="inbox-heading"><div><h1>{comments?'All comments':channel?channel==='youtube'?'YouTube Comment Center':labels[channel]+' inbox':'Unified Inbox'}</h1><span className="pill">{list.length} conversations</span></div><button className="icon-button filter-toggle" aria-label="Toggle inbox filters" onClick={()=>setShowFilters(!showFilters)}><Filter size={18}/></button><button className="icon-button" title="Inbox help" onClick={()=>a.setToast('Search covers customer names and previews in the loaded page. Load more to search older conversations.')}><CircleHelp size={18}/></button></div><div className="inbox-layout"><aside className="inbox-filters"><span className="nav-label">VIEWS</span>{[['all','All conversations',Inbox],['messages','Messages',Mail],['comments','Comments',MessageCircle],['unread','Unread',Mail],['unanswered','Unanswered',Clock],['mine','Assigned to me',Users],['priority','Priority',Star],['pending','Pending',Clock],['resolved','Resolved',CheckCheck],['archived','Archived',Bookmark]].map(([id,label,Icon])=>{const I=Icon as typeof Inbox;return <button key={String(id)} className={'view-'+id+(filter===id?' active':'')} onClick={()=>setFilter(String(id))}><I size={16}/>{String(label)}</button>;})}<div className="filter-fields"><label>Account<select value={account} onChange={e=>setAccount(e.target.value)}><option value="all">All accounts</option>{a.accounts.map(x=><option key={x.id} value={x.id}>{x.name} · {labels[x.platform]}</option>)}</select></label><label>Minimum followers / subscribers<input type="number" min="0" value={minAudience} onChange={e=>setMinAudience(e.target.value)} placeholder="Any audience size"/></label><small>Unknown counts stay unknown. Filters apply to loaded conversations.</small><label>Activity since<input type="date" value={date} onChange={e=>setDate(e.target.value)}/></label></div><p className="filter-hint">One inbox.<br/>More meaningful connections.</p></aside><section className="conversation-list"><div className="list-search"><Search size={16}/><input aria-label="Search loaded conversations" placeholder="Search this inbox" value={search} onChange={e=>setSearch(e.target.value)}/><Filter size={15}/></div><div className="list-sort"><select aria-label="Sort conversations" value={audience} onChange={e=>setAudience(e.target.value)}><option value="recent">Latest activity</option><option value="audience">Followers / subscribers: highest</option></select><span>{list.length} results</span></div>{list.map(c=><button className={'conversation-item kind-'+c.kind+(c.unreadCount?' is-unread ':' ')+(selected===c.id?'selected':'')} key={c.id} onClick={()=>{setSelected(c.id);if(c.unreadCount&&a.role!=='analyst')a.updateConversation(c.id,{unreadCount:0}).catch(()=>{});}}><div className="conversation-avatar"><Avatar name={c.author}/><PlatformIcon platform={c.platform} small/></div><div className="conversation-summary"><div><strong>{c.author}</strong><time>{relative(c.lastActivityAt)}</time></div><p>{c.preview}</p><div><small>{c.kind==='comment'?'Comment':'Message'} · {c.accountName} · {c.audienceCount==null?'Audience unknown':c.audienceCount.toLocaleString()+' '+(c.platform==='youtube'?'subscribers':'followers')}</small>{c.priority&&<Star className="priority-star" size={13}/>} {!!c.unreadCount&&<i className="unread-dot"/>}</div></div></button>)}{!list.length&&<Empty title="All clear here" body="Try a different filter, or connect an account to receive conversations."/>}{!a.demo&&<button className="load-more" onClick={()=>a.setPageSize(x=>x+50)}>Load older conversations</button>}</section><section className="conversation-detail">{current?<ConversationDetail key={current.id} conversation={current} onBack={()=>setSelected('')}/>:<Empty title="A space for every conversation" body="Select a message or comment to see the details and keep the conversation going."/>}</section></div></main>;}
function ConversationDetail({conversation:c,onBack}:{conversation:Conversation;onBack:()=>void}){const a=useApp(),[text,setText]=useState(''),[busy,setBusy]=useState(false),[note,setNote]=useState(false),[confirm,setConfirm]=useState(false),[historyLimit,setHistoryLimit]=useState(200),[attachment,setAttachment]=useState<File|null>(null);const history=useCollection<Message>(a.base?`${a.base}/conversations/${c.id}/messages`:null,a.localMessages[c.id]||[],a.demo,'sentAt',historyLimit);const notes=useCollection<{id:string;content:string;author:string;createdAt:number}>(a.base?`${a.base}/conversations/${c.id}/notes`:null,[],a.demo,'createdAt');const account=a.accounts.find(x=>x.id===c.accountId),canEdit=a.role!=='analyst',canSend=canEdit&&(a.demo||!!account?.capabilities.reply&&account.status==='connected')&&!c.uncertainReply;
async function send(){setBusy(true);try{if(a.demo){if(note){a.setToast('Demo internal note saved for this preview.');notes.setItems(x=>[...x,{id:crypto.randomUUID(),content:text,author:'Alex Morgan',createdAt:Date.now()}]);}else{a.setLocalMessages(x=>({...x,[c.id]:[...(x[c.id]||[]),{id:crypto.randomUUID(),content:text,author:'Alex Morgan',direction:'outbound',sentAt:Date.now(),deliveryStatus:'demo only',...(attachment?{attachments:[{url:URL.createObjectURL(attachment),type:attachment.type,name:attachment.name}]}:{})}]}));await a.updateConversation(c.id,{answered:true,preview:text,lastActivityAt:Date.now()});a.setToast('Demo reply added locally. Nothing was sent.');}}else {let mediaPath:string|undefined;if(attachment&&!note){const {data}=await a.action('prepareUpload',{conversationId:c.id,name:attachment.name,size:attachment.size,type:attachment.type});const uploaded=await supabase!.storage.from('message-media').uploadToSignedUrl(data.path,data.token,attachment,{contentType:attachment.type});if(uploaded.error)throw uploaded.error;mediaPath=data.path;}await a.action(note?'addNote':'sendReply',{conversationId:c.id,text,mediaPath,...(!note?{operationId:crypto.randomUUID()}: {})});}setAttachment(null);setText('');setConfirm(false);}catch{}finally{setBusy(false);}}
return <><div className="detail-header"><button className="icon-button back-button" aria-label="Back to conversations" onClick={onBack}><ChevronLeft size={20}/></button><Avatar name={c.author}/><div><h2>{c.author}</h2><span><PlatformIcon platform={c.platform} small/>{labels[c.platform]} · {c.kind==='comment'?'Comment thread':'Direct message'}</span></div><button className={'icon-button '+(c.priority?'starred':'')} aria-label="Toggle priority" disabled={!canEdit} onClick={()=>a.updateConversation(c.id,{priority:!c.priority}).catch(()=>{})}><Star size={18}/></button><button className="resolve-button" disabled={!canEdit} onClick={()=>a.updateConversation(c.id,{status:c.status==='resolved'?'open':'resolved'}).catch(()=>{})}><Check size={16}/>{c.status==='resolved'?'Reopen':'Resolve'}</button></div><div className="detail-meta"><label><Users size={14}/>Assigned to<select aria-label="Assignee" disabled={!['admin','marketing'].includes(a.role)} value={c.assignedTo||''} onChange={e=>a.updateConversation(c.id,{assignedTo:e.target.value||null}).catch(()=>{})}><option value="">Unassigned</option>{a.members.map(m=><option key={m.id} value={m.id}>{m.name}</option>)}</select></label><select aria-label="Conversation status" disabled={!canEdit} value={c.status} onChange={e=>a.updateConversation(c.id,{status:e.target.value as Conversation['status']}).catch(()=>{})}>{['open','pending','resolved','archived'].map(x=><option key={x}>{x}</option>)}</select></div><div className="message-history">{c.kind==='comment'&&<div className="post-context"><div className="post-thumbnail">{c.context?.thumbnail&&c.context.thumbnail.startsWith("https://i.ytimg.com/")?<img src={c.context.thumbnail} alt="Video thumbnail" loading="lazy"/>:<Video size={28}/>}</div><div><small>ORIGINAL CONTENT</small><strong>{c.context?.title||'Source post'}</strong>{c.context?.publishedAt&&<small>Published {new Date(c.context.publishedAt).toLocaleDateString()}</small>}<p>{c.context?.history||'Only synchronized replies are shown.'}</p>{c.context?.likeCount!==undefined&&<small>{c.context.likeCount} likes</small>}</div></div>}<div className="history-actions">{!a.demo&&history.items.length>=historyLimit&&<button onClick={()=>setHistoryLimit(x=>x+200)}>Load older synchronized messages</button>}{c.platform==='youtube'&&!a.demo&&canEdit&&<button disabled={busy} onClick={async()=>{setBusy(true);try{const result=await a.action('loadYouTubeReplies',{conversationId:c.id,restart:!!c.repliesComplete});a.setToast(`${result.loaded} replies checked. ${result.hasMore?'More replies are available.':'All currently available replies loaded.'}`);}catch{}finally{setBusy(false);}}}>{busy?'Loading…':c.repliesComplete?'Refresh replies':'Load replies from YouTube'}</button>}</div><div className="day-divider">{new Date(c.createdAt).toLocaleDateString([],{month:'long',day:'numeric'})}</div>{history.error&&<p className="error">{history.error}</p>}{[...(a.demo?a.localMessages[c.id]||[]:history.items)].sort((x,y)=>x.sentAt-y.sentAt).map(m=><div key={m.id} className={'message '+m.direction}><small>{m.author}</small><div>{m.content}<MessageMedia attachments={m.attachments}/></div><time>{time(m.sentAt)} {m.direction==='outbound'&&<><CheckCheck size={13}/>{m.deliveryStatus}</>}</time></div>)}{notes.items.map(n=><div className="internal-note" key={n.id}><small>Internal note · {n.author}</small><p>{n.content}</p></div>)}{!history.items.length&&<p className="muted">No synchronized history is available.</p>}</div><div className="composer-area">{c.originalUrl&&/^https:\/\/(www\.)?(youtube\.com|facebook\.com|instagram\.com|tiktok\.com)\//.test(c.originalUrl)&&<a className="original-link" href={c.originalUrl} target="_blank" rel="noopener noreferrer">Open original {c.kind} <ExternalLink size={14}/></a>}{!canSend&&!note&&<p className="notice">{c.uncertainReply?'A prior reply needs reconciliation on the source platform. Sending is blocked to prevent duplicates.':'Direct reply is not available for this account or interaction.'}</p>}<div className={'composer '+(note?'note-mode':'')}><div className="composer-tabs"><button className={!note?'active':''} onClick={()=>setNote(false)}><MessageCircle size={14}/>Reply</button><button className={note?'active':''} onClick={()=>setNote(true)}>Internal note</button><span>{a.demo?'DEMO ONLY':labels[c.platform]}</span></div><textarea aria-label={note?'Internal note':'Reply text'} disabled={note?!canEdit:!canSend} placeholder={note?'Leave a note for your team…':`Write a thoughtful reply to ${c.author.split(' ')[0]}…`} value={text} maxLength={4000} onChange={e=>setText(e.target.value)}/><AttachmentComposer file={attachment} onFile={setAttachment} onEmoji={emoji=>setText(value=>value+emoji)} disabled={!canSend||note||busy} platform={c.platform} kind={c.kind}/><div className="composer-tools"><select aria-label="Insert saved reply" value="" onChange={e=>setText(a.templates.find(t=>t.id===e.target.value)?.content.replaceAll('{{customer}}',c.author.split(' ')[0])||text)}><option value="">＋ Saved reply</option>{a.templates.map(t=><option key={t.id} value={t.id}>{t.title}</option>)}</select><small>{text.length}/4000</small><button className="primary" disabled={(!text.trim()&&!attachment)||busy||(note?!canEdit:!canSend)} onClick={()=>note?send():setConfirm(true)}>{busy?'Sending…':note?'Save note':a.demo?'Demo reply':'Send reply'}<Send size={14}/></button></div></div><small className="composer-hint">{note?'Visible only to your workspace.':a.demo?'Preview only. No message leaves this workspace.':'Review your reply before sending. Platform restrictions apply.'}</small></div>{confirm&&<Modal title={a.demo?'Add demo reply?':'Send this reply?'} onClose={()=>setConfirm(false)}><p className="reply-preview">{text}{attachment&&<><br/>Attachment: {attachment.name}</>}</p><p>{a.demo?'This adds a synthetic reply to the preview only.':`This will send to ${c.author} on ${labels[c.platform]}.`}</p><button className="primary" disabled={busy} onClick={send}>{busy?'Sending…':'Confirm reply'}</button></Modal>}</>;}
function Modal({title,children,onClose}:{title:string;children:React.ReactNode;onClose:()=>void}){useEffect(()=>{const fn=(e:KeyboardEvent)=>{if(e.key==='Escape')onClose();};window.addEventListener('keydown',fn);return()=>window.removeEventListener('keydown',fn);},[onClose]);return <div className="modal-backdrop" onClick={onClose}><section className="modal" role="dialog" aria-modal="true" aria-label={title} onClick={e=>e.stopPropagation()}><div className="card-heading"><h2>{title}</h2><button className="icon-button" aria-label="Close dialog" onClick={onClose}><X size={20}/></button></div>{children}</section></div>;}
function Notifications(){const a=useApp(),navigate=useNavigate(),[unread,setUnread]=useState(false);return <main className="page"><PageHeading title="Notifications" description="The updates that keep your team in the loop."><button onClick={()=>setUnread(!unread)}>{unread?'Show all':'Unread only'}</button></PageHeading><section className="card notification-list">{a.notices.filter(n=>!unread||!n.read).map(n=><button key={n.id} className={!n.read?'unread':''} onClick={async()=>{if(a.demo)a.setNotices(x=>x.map(y=>y.id===n.id?{...y,read:true}:y));else try{await a.action('markNotification',{notificationId:n.id});}catch{return;}if(n.conversationId)navigate('/inbox?selected='+n.conversationId);}}><PlatformIcon platform={n.platform}/><span><strong>{n.title}</strong><small>{new Date(n.createdAt).toLocaleString()}</small></span>{!n.read&&<i className="unread-dot"/>}<ChevronRight size={16}/></button>)}{!a.notices.length&&<Empty title="You're up to date" body={a.role==='agent'?'Your assigned conversations are available in the inbox.':'New synchronized activity and connection alerts will appear here.'}/>}</section></main>;}
function SavedReplies(){const a=useApp(),[edit,setEdit]=useState<Template|null>(null),[search,setSearch]=useState(''),[busy,setBusy]=useState(false),canManage=['admin','marketing'].includes(a.role);async function save(remove=false){if(!edit)return;setBusy(true);try{if(a.demo)a.setTemplates(prev=>remove?prev.filter(t=>t.id!==edit.id):[...prev.filter(t=>t.id!==edit.id),{...edit,id:edit.id||crypto.randomUUID()}]);else await a.action('saveTemplate',{templateId:edit.id||undefined,title:edit.title,content:edit.content,category:edit.category,remove});setEdit(null);}catch{}finally{setBusy(false);}}return <main className="page"><PageHeading title="Saved replies" description="A helpful starting point. Always add your human touch."><button className="primary" disabled={!canManage} onClick={()=>setEdit({id:'',title:'',content:'',category:'General'})}><Plus size={16}/>New reply</button></PageHeading><div className="search-field"><Search size={17}/><input aria-label="Search saved replies" placeholder="Find a saved reply…" value={search} onChange={e=>setSearch(e.target.value)}/></div><div className="template-grid">{a.templates.filter(t=>(t.title+t.content+t.category).toLowerCase().includes(search.toLowerCase())).map(t=><article className="card template" key={t.id}><span className="pill">{t.category}</span><h2>{t.title}</h2><p>{t.content}</p><button disabled={!canManage} onClick={()=>setEdit(t)}>Edit reply</button></article>)}</div>{!a.templates.length&&<Empty title="Your best words, ready to reuse" body="Create a reply template to help your team respond consistently."/>}{edit&&<Modal title={edit.id?'Edit saved reply':'Create saved reply'} onClose={()=>setEdit(null)}><form onSubmit={e=>{e.preventDefault();save();}}><label>Title<input required maxLength={100} value={edit.title} onChange={e=>setEdit({...edit,title:e.target.value})}/></label><label>Category<input value={edit.category} maxLength={60} onChange={e=>setEdit({...edit,category:e.target.value})}/></label><label>Reply<textarea required maxLength={4000} rows={5} value={edit.content} onChange={e=>setEdit({...edit,content:e.target.value})}/></label><p className="muted">Use {'{{customer}}'} for the customer's first name. Review every reply before sending.</p><div className="inline"><button className="primary" disabled={busy}>Save reply</button>{edit.id&&<button type="button" className="danger" disabled={busy} onClick={()=>save(true)}>Delete reply</button>}</div></form></Modal>}</main>;}
function Team(){const a=useApp(),[open,setOpen]=useState(false),[email,setEmail]=useState(''),[role,setRole]=useState('agent'),[busy,setBusy]=useState(false);return <main className="page"><PageHeading title="Your team" description="Great customer experiences are a team effort."><button className="primary" disabled={a.role!=='admin'} onClick={()=>setOpen(true)}><Plus size={16}/>Add or update member</button></PageHeading><section className="card"><table><thead><tr><th>Team member</th><th>Role</th><th>Assigned conversations</th></tr></thead><tbody>{a.members.map(m=><tr key={m.id}><td><div className="person"><Avatar name={m.name}/><span><strong>{m.name}</strong><small>{m.email}</small></span></div></td><td><span className="pill">{m.role}</span></td><td>{a.conversations.filter(c=>c.assignedTo===m.id).length}</td></tr>)}</tbody></table></section><p className="data-footnote">Administrators manage membership. Agents can access only their assigned conversations. Analysts have read-only access.</p>{open&&<Modal title="Manage workspace membership" onClose={()=>setOpen(false)}><p>Ask your colleague to create an SMM – Barracks account first. This action does not send an invitation email.</p><form onSubmit={async e=>{e.preventDefault();if(a.demo){a.setToast('Team membership changes are unavailable in demo mode.');return;}setBusy(true);try{await a.action('manageMember',{email,role});setOpen(false);}catch{}finally{setBusy(false);}}}><label>Colleague's account email<input type="email" required value={email} onChange={e=>setEmail(e.target.value)}/></label><label>Role<select value={role} onChange={e=>setRole(e.target.value)}><option value="admin">Administrator</option><option value="marketing">Digital Marketing Officer</option><option value="agent">Support Agent</option><option value="analyst">Read-Only Analyst</option></select></label><button className="primary" disabled={busy}>Save membership</button><button type="button" className="danger" disabled={busy||a.demo||!email} onClick={async()=>{setBusy(true);try{await a.action('manageMember',{email,role,remove:true});setOpen(false);}catch{}finally{setBusy(false);}}}>Remove member</button></form></Modal>}</main>;}
function SettingsPage(){const a=useApp(),[tab,setTab]=useState('Workspace');const logs=useCollection<{id:string;action:string;target:string;uid:string;createdAt:number}>(a.base&&a.role==='admin'?a.base+'/auditLogs':null,[],a.demo,'createdAt');return <main className="page"><PageHeading title="Settings" description="Make your workspace work for you."/><div className="settings-tabs">{['Workspace','Profile','Security','Audit logs'].map(t=><button className={tab===t?'active':''} key={t} onClick={()=>setTab(t)}>{t}</button>)}</div><section className="card settings-card">{tab==='Workspace'?<><h2>Workspace preferences</h2><label>Active workspace<select value={a.workspaceId} disabled={a.demo} onChange={e=>a.setWorkspaceId(e.target.value)}>{a.demo?<option>Barracks Clothing · Demo</option>:a.memberships.map(w=><option key={w.id} value={w.id}>{w.name}</option>)}</select></label><p>Search and analytics cover the loaded conversation page. Full-text indexing, retention automation and workspace deletion are not implemented in this build.</p><CompanySettings/></>:tab==='Profile'?<><h2>Your profile</h2><p>{a.demo?'Alex Morgan':a.user?.displayName||'Team member'}</p><p>{a.demo?'alex@example.test':a.user?.email}</p><button onClick={()=>a.demo?a.enterDemo(false):signOut()}><LogOut size={16}/>Sign out</button></>:tab==='Security'?<><h2>Account security</h2><p>Application sessions use Supabase Authentication. Social credentials are available only to server functions. PostgreSQL row-level security isolates each workspace.</p><button disabled={a.demo||!a.user?.email} onClick={()=>a.user?.email&&resetPassword(a.user.email).then(()=>a.setToast('Password reset email requested.')).catch(e=>a.setToast(e.message))}>Send password reset email</button><p className="notice">Use a unique password and keep your social account permissions up to date.</p></>:<><h2>Audit logs</h2>{a.role!=='admin'?<p>Administrator access required.</p>:logs.items.length?logs.items.map(l=><div className="audit-row" key={l.id}><strong>{l.action}</strong><span>{l.target}</span><small>{new Date(l.createdAt).toLocaleString()}</small></div>):<Empty title="No audit events yet" body="Live backend actions create audit records here."/>}</>}</section></main>;}
const queryClient=new QueryClient();
createRoot(document.getElementById('root')!).render(<React.StrictMode><QueryClientProvider client={queryClient}><HashRouter><AppProvider><App/></AppProvider></HashRouter></QueryClientProvider></React.StrictMode>);

