// Aurelle Bride — Admin panel (hidden route /kr/pk/admin/moon)
// NOTE: This is a UI-only mock. Real auth + persistence requires a backend.

const { useState: aS, useEffect: aE, useMemo: aM } = React;
const Logo = window.Logo;
const I = window.I;
const Placeholder = window.Placeholder;
const useApp = window.useApp;
const ADMIN_KEY = 'aurelle_admin_session';
const ADMIN_DATA_KEY = 'aurelle_admin_data';

/* Default mock data, persisted to localStorage so admin actions feel real */
function emptyData(){
  return { products:[], inquiries:[], customs:[], specials:[], users:[], posts:[], settings:{} };
}
async function loadAdminDataFromApi(token){
  const h = { 'Authorization': `Bearer ${token}` };
  const [products,inquiries,customs,specials,posts,users,settings] = await Promise.all([
    fetch('/api/products.php').then(r=>r.json()),
    fetch('/api/inquiries.php',{headers:h}).then(r=>r.json()),
    fetch('/api/customs.php',{headers:h}).then(r=>r.json()),
    fetch('/api/specials.php',{headers:h}).then(r=>r.json()),
    fetch('/api/posts.php',{headers:h}).then(r=>r.json()),
    fetch('/api/users.php',{headers:h}).then(r=>r.json()),
    fetch('/api/settings.php').then(r=>r.json()),
  ]);
  return { products, inquiries, customs, specials, posts, users, settings };
}
function authToken(){ try { return JSON.parse(sessionStorage.getItem(ADMIN_KEY))?.token; } catch { return null; } } 

/* ==== LOGIN ==== */
function AdminLogin({ onAuth }){
  const [email, setEmail] = aS('info@aurellebride.com');
  const [pwd, setPwd] = aS('');
  const [err, setErr] = aS('');
  const [loading, setLoading] = aS(false);
const submit = async (e) => {
  e.preventDefault();
  setErr(''); setLoading(true);
  try {
    const r = await fetch('/api/auth.php?action=login', {
      method:'POST', headers:{'Content-Type':'application/json'},
      body: JSON.stringify({ email, password: pwd })
    });
    if (!r.ok) throw new Error('bad');
    const { token, user } = await r.json();
    const session = { ...user, token, ts: Date.now() };
    sessionStorage.setItem(ADMIN_KEY, JSON.stringify(session));
    onAuth(session);
  } catch {
    setErr('Invalid credentials.'); setLoading(false);
  }
};
  return (
    <div style={{minHeight:'100vh', display:'flex', alignItems:'center', justifyContent:'center', padding:24, background:'var(--bg)', position:'relative', overflow:'hidden'}}>
      <div aria-hidden style={{position:'absolute', inset:0, opacity:.5, pointerEvents:'none'}}>
        <div style={{position:'absolute', top:'15%', left:'10%', width:400, height:400, borderRadius:'50%', background:'radial-gradient(circle, var(--gold-soft), transparent 60%)', filter:'blur(60px)'}}/>
        <div style={{position:'absolute', bottom:'10%', right:'10%', width:500, height:500, borderRadius:'50%', background:'radial-gradient(circle, color-mix(in oklab, var(--gold) 15%, transparent), transparent 60%)', filter:'blur(80px)'}}/>
      </div>
      <div className="card" style={{width:'100%', maxWidth:440, padding:48, position:'relative', zIndex:1}}>
        <Logo size={28}/>
        <div className="eyebrow" style={{marginTop:32}}><span className="dot"/>SECURE LOGIN</div>
        <h1 style={{fontSize:36, marginTop:14, lineHeight:1.05}}>Atelier admin.</h1>
        <p style={{color:'var(--ink-2)', marginTop:10, fontSize:14}}>Authorized personnel only. All access is logged.</p>
        <form onSubmit={submit} style={{marginTop:32}}>
          <div className="field" style={{marginBottom:16}}>
            <label>Email or username</label>
            <input className="input" value={email} onChange={e=>setEmail(e.target.value)} required autoFocus/>
          </div>
          <div className="field" style={{marginBottom:8}}>
            <label>Password</label>
            <input className="input" type="password" value={pwd} onChange={e=>setPwd(e.target.value)} required/>
          </div>
          {err && <div style={{color:'#dc2626', fontSize:13, marginBottom:14}}>{err}</div>}
          <button className="btn btn-primary btn-lg" type="submit" disabled={loading} style={{width:'100%', justifyContent:'center', marginTop:14}}>
            {loading ? 'Signing in…' : 'Sign in'} {!loading && <I.arrow/>}
          </button>
        </form>
        <div style={{marginTop:28, paddingTop:20, borderTop:'1px solid var(--line)', fontFamily:'var(--mono)', fontSize:10, letterSpacing:'.18em', color:'var(--ink-3)', textAlign:'center'}}>
          DEMO · admin / admin · OR info@aurellebride.com / Aurelle@2026
        </div>
      </div>
    </div>
  );
}

/* ==== SHELL ==== */
function AdminShell({ session, sub, onLogout }){
  const { theme, toggleTheme, navigate } = useApp();
const [data, setData] = aS(emptyData());
const [showSidebar, setShowSidebar] = aS(true);
const [loadingData, setLoadingData] = aS(true);
aE(()=>{ (async ()=>{
  try { const fresh = await loadAdminDataFromApi(authToken()); setData(fresh); } catch(e){}
  setLoadingData(false);
})(); },[]);

const ENDPOINTS = { products:'products', inquiries:'inquiries', customs:'customs', specials:'specials', posts:'posts', users:'users', settings:'settings' };
const update = (patch) => {
  setData(d => ({ ...d, ...patch }));
  const tok = authToken();
  Object.entries(patch).forEach(([key, value]) => {
    if (!ENDPOINTS[key]) return;
    fetch(`/api/${ENDPOINTS[key]}.php`, {
      method:'PUT',
      headers:{ 'Content-Type':'application/json', 'Authorization': `Bearer ${tok}` },
      body: JSON.stringify(value)
    }).catch(()=>{});
  });
};
const nav = [
    { id:'',          label:'Dashboard',    icon:'grid' },
    { id:'products',  label:'Products',     icon:'box',   count:data.products.length },
    { id:'inquiries', label:'Inquiries',    icon:'mail',  count:data.inquiries.filter(x=>x.status==='new').length },
    { id:'customs',   label:'Custom briefs',icon:'sparkle', count:data.customs.filter(x=>x.status==='new').length },
    { id:'specials',  label:'Special requests', icon:'star', count:data.specials.filter(x=>x.status==='new').length },
    { id:'journal',   label:'Journal',      icon:'edit',  count:data.posts.length },
    { id:'users',     label:'Users',        icon:'user',  count:data.users.length },
    { id:'analytics', label:'Analytics',    icon:'chart' },
    { id:'settings',  label:'Settings',     icon:'cog' },
  ];
  const NavIcon = ({ k }) => {
      const nav = [
    { id:'',          label:'Dashboard',    icon:'grid' },
    { id:'products',  label:'Products',     icon:'box',   count:data.products.length },
    { id:'inquiries', label:'Inquiries',    icon:'mail',  count:data.inquiries.filter(x=>x.status==='new').length },
    { id:'customs',   label:'Custom briefs',icon:'sparkle', count:data.customs.filter(x=>x.status==='new').length },
    { id:'specials',  label:'Special requests', icon:'star', count:data.specials.filter(x=>x.status==='new').length },
    { id:'journal',   label:'Journal',      icon:'edit',  count:data.posts.length },
    { id:'users',     label:'Users',        icon:'user',  count:data.users.length },
    { id:'analytics', label:'Analytics',    icon:'chart' },
    { id:'settings',  label:'Settings',     icon:'cog' },
  ];
    const map = {
      grid: <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5"><rect x="3" y="3" width="7" height="7"/><rect x="14" y="3" width="7" height="7"/><rect x="3" y="14" width="7" height="7"/><rect x="14" y="14" width="7" height="7"/></svg>,
      box: <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5"><path d="M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16Z"/><path d="m3.3 7 8.7 5 8.7-5"/><path d="M12 22V12"/></svg>,
      mail: <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5"><rect x="2" y="4" width="20" height="16" rx="2"/><path d="m22 7-10 5L2 7"/></svg>,
      sparkle: <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5"><path d="M12 3v3M12 18v3M3 12h3M18 12h3M5.6 5.6 7.7 7.7M16.3 16.3l2.1 2.1M5.6 18.4 7.7 16.3M16.3 7.7l2.1-2.1"/><circle cx="12" cy="12" r="3"/></svg>,
      star: <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5"><polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"/></svg>,
      edit: <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5"><path d="M12 20h9"/><path d="M16.5 3.5a2.121 2.121 0 0 1 3 3L7 19l-4 1 1-4Z"/></svg>,
      user: <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5"><path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/></svg>,
      chart: <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5"><path d="M3 3v18h18"/><path d="M7 14l4-4 4 4 5-5"/></svg>,
      cog: <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5"><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 1 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 1 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 1 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 1 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"/></svg>,
    };
    return map[k];
  };

  const Page = () => {
    if (sub === '' || sub === '/') return <AdminDashboard data={data}/>;
    if (sub.startsWith('products')) return <AdminProducts data={data} update={update}/>;
    if (sub.startsWith('inquiries')) return <AdminInbox data={data} update={update} kind="inquiries"/>;
    if (sub.startsWith('customs')) return <AdminInbox data={data} update={update} kind="customs"/>;
    if (sub.startsWith('specials')) return <AdminInbox data={data} update={update} kind="specials"/>;
    if (sub.startsWith('journal')) return <AdminJournal data={data} update={update}/>;
    if (sub.startsWith('users')) return <AdminUsers data={data} update={update}/>;
    if (sub.startsWith('analytics')) return <AdminAnalytics data={data}/>;
    if (sub.startsWith('settings')) return <AdminSettings data={data} update={update}/>;
    return <AdminDashboard data={data}/>;
  };

  return (
    <div className="admin-shell">
      <aside className={`admin-side ${showSidebar?'':'collapsed'}`}>
        <div className="admin-brand">
          <Logo size={20} mark/>
          {showSidebar && <div><div style={{fontSize:13, fontWeight:500}}>Aurelle Bride</div><div style={{fontFamily:'var(--mono)', fontSize:9, letterSpacing:'.18em', color:'var(--ink-3)'}}>ADMIN</div></div>}
        </div>
        <nav style={{padding:'18px 12px', flex:1, overflowY:'auto'}}>
          {nav.map(n => (
            <a
  key={n.id}
  href={n.id ? `/kr/pk/admin/moon/${n.id}` : `/kr/pk/admin/moon`}
              className={`admin-nav-item ${(sub===n.id || (n.id && sub.startsWith(n.id)))?'active':''}`}>
              <NavIcon k={n.icon}/>
              {showSidebar && <>
                <span style={{flex:1}}>{n.label}</span>
                {n.count !== undefined && n.count > 0 && <span className="badge badge-ink" style={{fontSize:9}}>{n.count}</span>}
              </>}
            </a>
          ))}
        </nav>
        <div style={{padding:14, borderTop:'1px solid var(--line)'}}>
          <button className="admin-nav-item" onClick={onLogout} style={{width:'100%'}}>
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5"><path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"/><polyline points="16 17 21 12 16 7"/><line x1="21" y1="12" x2="9" y2="12"/></svg>
            {showSidebar && <span>Sign out</span>}
          </button>
        </div>
      </aside>
      <main className="admin-main">
        <div className="admin-topbar">
          <button className="icon-btn" onClick={()=>setShowSidebar(s=>!s)}>
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5"><line x1="3" y1="6" x2="21" y2="6"/><line x1="3" y1="12" x2="21" y2="12"/><line x1="3" y1="18" x2="21" y2="18"/></svg>
          </button>
          <div style={{flex:1}}>
            <div style={{fontFamily:'var(--mono)', fontSize:10, letterSpacing:'.22em', color:'var(--ink-3)'}}>· ADMIN · {sub.toUpperCase() || 'DASHBOARD'}</div>
          </div>
          <button className="icon-btn" onClick={toggleTheme} title="Toggle theme">
            {theme === 'dark' ? <I.sun/> : <I.moon/>}
          </button>
          <a className="btn btn-ghost" href="#/" style={{fontSize:12}}>View site →</a>
          <div className="admin-pill">
            <div className="dot-online"/>
            <span>{session.email}</span>
          </div>
        </div>
        <div className="admin-content">
          <Page/>
        </div>
      </main>
    </div>
  );
}

/* ==== DASHBOARD ==== */
function AdminDashboard({ data }){
  const newInq = data.inquiries.filter(x=>x.status==='new').length;
  const newCustom = data.customs.filter(x=>x.status==='new').length;
  const newSpecial = data.specials.filter(x=>x.status==='new').length;
  const stats = [
    { label:'Total products', val:data.products.length, delta:'+3 this month' },
    { label:'New inquiries',  val:newInq, delta:`${data.inquiries.length} total` },
    { label:'Custom briefs',  val:newCustom, delta:`${data.customs.length} total` },
    { label:'Special requests', val:newSpecial, delta:`${data.specials.length} total` },
  ];
  const recent = [...data.inquiries.map(x=>({...x,k:'Inquiry'})), ...data.customs.map(x=>({...x,k:'Custom'})), ...data.specials.map(x=>({...x,k:'Special'}))]
    .sort((a,b) => new Date(b.date) - new Date(a.date)).slice(0, 6);

  return (
    <div>
      <div style={{display:'flex', justifyContent:'space-between', alignItems:'flex-end', marginBottom:32, flexWrap:'wrap', gap:14}}>
        <div>
          <h1 style={{fontSize:42, lineHeight:1}}>Good morning, Aurelle.</h1>
          <p style={{color:'var(--ink-2)', marginTop:8}}>{new Date().toLocaleDateString('en-US', { weekday:'long', month:'long', day:'numeric', year:'numeric' })}</p>
        </div>
        <a className="btn btn-primary" href="/kr/pk/admin/moon/products"><I.plus/> Add new piece</a>
      </div>

      <div className="admin-stat-grid" style={{marginBottom:32}}>
        {stats.map(s => (
          <div key={s.label} className="admin-stat">
            <div style={{fontFamily:'var(--mono)', fontSize:10, letterSpacing:'.22em', color:'var(--ink-3)', textTransform:'uppercase'}}>{s.label}</div>
            <div style={{fontSize:42, fontFamily:'var(--serif)', marginTop:8, lineHeight:1}}>{s.val}</div>
            <div style={{fontSize:12, color:'var(--gold)', marginTop:8, fontFamily:'var(--mono)'}}>{s.delta}</div>
          </div>
        ))}
      </div>

      <div style={{display:'grid', gridTemplateColumns:'1.4fr 1fr', gap:24}}>
        <div className="card" style={{padding:28}}>
          <div style={{display:'flex', justifyContent:'space-between', marginBottom:18}}>
            <h3 style={{fontSize:22}}>Recent activity</h3>
            <a className="btn btn-link" href="/kr/pk/admin/moon/inquiries">View all →</a>
          </div>
          <div style={{display:'flex', flexDirection:'column', gap:12}}>
            {recent.map((r,i)=>(
              <div key={i} className="admin-row" style={{display:'flex', alignItems:'center', gap:14}}>
                <span className="badge" style={{flex:'none'}}>{r.k}</span>
                <div style={{flex:1, minWidth:0}}>
                  <div style={{fontSize:14, fontWeight:500, overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap'}}>{r.name} · {r.subject||r.summary||r.evt||r.detail?.slice(0,40)}</div>
                  <div style={{fontFamily:'var(--mono)', fontSize:10, letterSpacing:'.18em', color:'var(--ink-3)', marginTop:2}}>{r.email} · {r.date}</div>
                </div>
                <span className={`status-pill status-${r.status}`}>{r.status}</span>
              </div>
            ))}
          </div>
        </div>
        <div className="card" style={{padding:28}}>
          <h3 style={{fontSize:22, marginBottom:18}}>Quick actions</h3>
          <div style={{display:'flex', flexDirection:'column', gap:10}}>
            <a className="btn btn-ghost" href="/kr/pk/admin/moon/products" style={{justifyContent:'flex-start'}}><I.plus/> Add new product</a>
            <a className="btn btn-ghost" href="/kr/pk/admin/moon/journal" style={{justifyContent:'flex-start'}}><I.plus/> New journal post</a>
            <a className="btn btn-ghost" href="/kr/pk/admin/moon/users" style={{justifyContent:'flex-start'}}><I.plus/> Invite team member</a>
            <a className="btn btn-ghost" href="/kr/pk/admin/moon/settings" style={{justifyContent:'flex-start'}}><I.cog/> Site settings</a>
          </div>

          <div style={{marginTop:28, paddingTop:20, borderTop:'1px solid var(--line)'}}>
            <div style={{fontFamily:'var(--mono)', fontSize:10, letterSpacing:'.22em', color:'var(--ink-3)', marginBottom:14}}>· SYSTEM HEALTH</div>
            <div style={{display:'flex', flexDirection:'column', gap:8, fontSize:13}}>
              {[['Storefront','operational'],['Image CDN','operational'],['Email service','operational'],['Backup','last 4h ago']].map(([k,v])=>(
                <div key={k} style={{display:'flex', justifyContent:'space-between'}}><span style={{color:'var(--ink-2)'}}>{k}</span><span style={{color:'var(--gold)'}}>● {v}</span></div>
              ))}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

/* ==== PRODUCTS ==== */
function AdminProducts({ data, update }){
  const [editing, setEditing] = aS(null);
  const [search, setSearch] = aS('');
  const { showToast, formatPrice } = useApp();
  const list = data.products.filter(p => p.name.toLowerCase().includes(search.toLowerCase()));

  const blank = { id: Date.now(), name:'New piece', col:'Lehenga', priceValue:150000, status:'1 OF 1', desc:'', tone:'rich', date: new Date().toISOString().slice(0,10) };
  const save = (p) => {
    if (data.products.find(x => x.id === p.id)) {
      update({ products: data.products.map(x => x.id === p.id ? p : x) });
      showToast(`${p.name} updated`);
    } else {
      update({ products: [p, ...data.products] });
      showToast(`${p.name} added`);
    }
    setEditing(null);
  };
  const del = (id) => {
    if (confirm('Delete this product?')) {
      update({ products: data.products.filter(p => p.id !== id) });
      showToast('Product deleted');
    }
  };

  return (
    <div>
      <div style={{display:'flex', justifyContent:'space-between', alignItems:'center', flexWrap:'wrap', gap:14, marginBottom:24}}>
        <h1 style={{fontSize:36, lineHeight:1}}>Products</h1>
        <button className="btn btn-primary" onClick={()=>setEditing(blank)}><I.plus/> Add product</button>
      </div>
      <div className="card" style={{padding:0, overflow:'hidden'}}>
        <div style={{padding:'16px 20px', borderBottom:'1px solid var(--line)'}}>
          <input className="input" placeholder="Search products…" value={search} onChange={e=>setSearch(e.target.value)} style={{maxWidth:320}}/>
        </div>
        <div style={{overflowX:'auto'}}>
          <table className="admin-table">
            <thead><tr><th>Image</th><th>Name</th><th>Category</th><th>Price</th><th>Status</th><th></th></tr></thead>
            <tbody>
              {list.map(p => (
                <tr key={p.id}>
                    <td><div style={{width:60, height:80, borderRadius:4, overflow:'hidden', background:'var(--bg-2)'}}>
                      {p.image_url ? <img src={p.image_url} alt="" style={{width:'100%', height:'100%', objectFit:'cover'}}/> : <Placeholder label="" tone={p.tone}/>}
                    </div></td>
                  <td><div style={{fontWeight:500}}>{p.name}</div></td>
                  <td><span className="badge">{p.col}</span></td>
                  <td style={{fontFamily:'var(--serif)', fontStyle:'italic', color:'var(--gold)'}}>{formatPrice(p.priceValue)}</td>
                  <td><span className="status-pill status-published">{p.status}</span></td>
                  <td style={{textAlign:'right', whiteSpace:'nowrap'}}>
                    <button className="icon-btn" onClick={()=>setEditing({...p})} title="Edit"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5"><path d="M12 20h9"/><path d="M16.5 3.5a2.121 2.121 0 0 1 3 3L7 19l-4 1 1-4Z"/></svg></button>
                    <button className="icon-btn" onClick={()=>del(p.id)} title="Delete" style={{marginLeft:6, color:'#dc2626'}}><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5"><polyline points="3 6 5 6 21 6"/><path d="M19 6l-2 14a2 2 0 0 1-2 2H9a2 2 0 0 1-2-2L5 6"/></svg></button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>

      {editing && (
        <div className="modal-bg" onClick={()=>setEditing(null)}>
          <div className="modal-card" onClick={e=>e.stopPropagation()}>
            <div style={{display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom:24}}>
              <h2 style={{fontSize:28}}>{data.products.find(x=>x.id===editing.id) ? 'Edit piece' : 'New piece'}</h2>
              <button className="icon-btn" onClick={()=>setEditing(null)}><I.close/></button>
            </div>
            <div className="grid-2">
              <div className="field"><label htmlFor="p-name">Product name</label><input id="p-name" name="name" className="input" value={editing.name} onChange={e=>setEditing({...editing, name:e.target.value})}/></div>
              <div className="field"><label>Category</label><select className="select" value={editing.col} onChange={e=>setEditing({...editing, col:e.target.value})}>{['Lehenga','Sharara','Gharara','Bridal Mexi','Anarkali','Gown'].map(c=><option key={c}>{c}</option>)}</select></div>
              <div className="field"><label>Price (PKR)</label><input className="input" type="number" value={editing.priceValue} onChange={e=>setEditing({...editing, priceValue: parseInt(e.target.value||0)})}/></div>
              <div className="field"><label>Status</label><select className="select" value={editing.status} onChange={e=>setEditing({...editing, status:e.target.value})}>{['1 OF 1','MADE TO ORDER','SOLD','ARCHIVED'].map(s=><option key={s}>{s}</option>)}</select></div>
              <div className="field"><label>Image tone (placeholder)</label><select className="select" value={editing.tone} onChange={e=>setEditing({...editing, tone:e.target.value})}>{['rich','warm','gold','cool','sage','default'].map(t=><option key={t}>{t}</option>)}</select></div>
              <div className="field"><label>Date added</label><input className="input" type="date" value={editing.date} onChange={e=>setEditing({...editing, date:e.target.value})}/></div>
            </div>
            <div className="field" style={{marginTop:14}}>
  <label htmlFor="p-img-input">Product images</label>

  {/* Already-uploaded gallery */}
  {Array.isArray(editing.gallery) && editing.gallery.length > 0 && (
    <>
      <div style={{fontFamily:'var(--mono)', fontSize:10, letterSpacing:'.22em', color:'var(--ink-3)', marginBottom:10, marginTop:4}}>· UPLOADED</div>
      <div style={{display:'grid', gridTemplateColumns:'repeat(auto-fill, minmax(140px, 1fr))', gap:10, marginBottom:18}}>
        {editing.gallery.map((g) => {
          const isHero = editing.image_url === g.url;
          return (
            <div key={g.url} style={{borderRadius:6, overflow:'hidden', border: isHero ? '2px solid var(--gold)' : '1px solid var(--line)', background:'var(--bg-2)'}}>
              <div style={{position:'relative', aspectRatio:'3/4'}}>
                <img src={g.url} alt={g.label || ''} style={{width:'100%', height:'100%', objectFit:'cover'}}/>
                {isHero && <span style={{position:'absolute', top:6, left:6, background:'var(--gold)', color:'#0E0E10', fontFamily:'var(--mono)', fontSize:9, letterSpacing:'.14em', padding:'3px 6px', borderRadius:3}}>HERO</span>}
                <div style={{position:'absolute', bottom:6, right:6, display:'flex', gap:4}}>
                  {!isHero && (
                    <button type="button" className="icon-btn" title="Set as hero" style={{width:26, height:26, background:'rgba(0,0,0,.65)', color:'#fff', border:'none'}} onClick={()=>setEditing({...editing, image_url:g.url})}>
                      <svg width="12" height="12" viewBox="0 0 24 24" fill="currentColor"><path d="m12 2 3 6.9 7.1.6-5.4 4.7 1.7 7L12 17.3 5.6 21.2l1.7-7L1.9 9.5l7.1-.6L12 2z"/></svg>
                    </button>
                  )}
                  <button type="button" className="icon-btn" title="Delete image" style={{width:26, height:26, background:'rgba(220,38,38,.85)', color:'#fff', border:'none'}} onClick={async ()=>{
                    if (!confirm(`Delete "${g.label || 'this image'}"?`)) return;
                    try {
                      const r = await fetch('/api/product-image.php', {
                        method:'DELETE',
                        headers:{'Content-Type':'application/json', 'Authorization': `Bearer ${authToken()}`},
                        body: JSON.stringify({ product_id: editing.id, url: g.url })
                      });
                      const j = await r.json();
                      if (j.ok) {
                        setEditing({...editing, image_url: j.image_url, gallery: j.gallery});
                        showToast('Image deleted');
                      } else { showToast('Delete failed', 'error'); }
                    } catch { showToast('Delete failed', 'error'); }
                  }}><I.close/></button>
                </div>
              </div>
              <div style={{padding:8}}>
                <select className="select" style={{fontSize:12, padding:'6px 8px'}} value={g.label || ''} aria-label="Image label" onChange={async (e)=>{
                  const newLabel = e.target.value;
                  // Optimistic update
                  setEditing({...editing, gallery: editing.gallery.map(x => x.url===g.url ? {...x, label:newLabel} : x)});
                  try {
                    await fetch('/api/product-image-label.php', {
                      method:'PUT',
                      headers:{'Content-Type':'application/json', 'Authorization': `Bearer ${authToken()}`},
                      body: JSON.stringify({ product_id: editing.id, url: g.url, label: newLabel })
                    });
                  } catch {}
                }}>
                  <option value="">— Label —</option>
                  <option>Front</option>
                  <option>Back</option>
                  <option>Side</option>
                  <option>Neckline</option>
                  <option>Sleeves</option>
                  <option>Dupatta</option>
                  <option>Shirt / Upper</option>
                  <option>Lehenga / Lower</option>
                  <option>Sharara</option>
                  <option>Gharara</option>
                  <option>Embroidery detail</option>
                  <option>Drape</option>
                  <option>Fabric closeup</option>
                  <option>On model</option>
                  <option>Flat lay</option>
                </select>
              </div>
            </div>
          );
        })}
      </div>
    </>
  )}

  {/* Staging area: selected but not yet uploaded */}
  {Array.isArray(editing._staged) && editing._staged.length > 0 && (
    <>
      <div style={{fontFamily:'var(--mono)', fontSize:10, letterSpacing:'.22em', color:'var(--gold)', marginBottom:10}}>· READY TO UPLOAD ({editing._staged.length})</div>
      <div style={{display:'grid', gridTemplateColumns:'repeat(auto-fill, minmax(140px, 1fr))', gap:10, marginBottom:18}}>
        {editing._staged.map((s, idx) => (
          <div key={idx} style={{borderRadius:6, overflow:'hidden', border:'1px dashed var(--gold)', background:'var(--bg-2)'}}>
            <div style={{position:'relative', aspectRatio:'3/4'}}>
              <img src={s.preview} alt="" style={{width:'100%', height:'100%', objectFit:'cover', opacity:.85}}/>
                <button type="button" className="icon-btn" title="Remove from queue" style={{position:'absolute', top:6, right:6, width:26, height:26, background:'rgba(0,0,0,.7)', color:'#fff', border:'none'}} onClick={()=>{
                  setEditing({...editing, _staged: editing._staged.filter((_,j)=>j!==idx)});
                }}><I.close/></button>
            </div>
            <div style={{padding:8}}>
              <select className="select" style={{fontSize:12, padding:'6px 8px'}} value={s.label} aria-label="Image label" onChange={(e)=>{
                setEditing({...editing, _staged: editing._staged.map((x,j)=> j===idx ? {...x, label:e.target.value} : x)});
              }}>
                <option value="">— Label —</option>
                <option>Front</option>
                <option>Back</option>
                <option>Side</option>
                <option>Neckline</option>
                <option>Sleeves</option>
                <option>Dupatta</option>
                <option>Shirt / Upper</option>
                <option>Lehenga / Lower</option>
                <option>Sharara</option>
                <option>Gharara</option>
                <option>Embroidery detail</option>
                <option>Drape</option>
                <option>Fabric closeup</option>
                <option>On model</option>
                <option>Flat lay</option>
              </select>
              <div style={{fontSize:10, color:'var(--ink-3)', marginTop:4, fontFamily:'var(--mono)', overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap'}}>{s.file.name}</div>
            </div>
          </div>
        ))}
      </div>
      <div style={{display:'flex', gap:10, marginBottom:18}}>
        <button type="button" className="btn btn-primary" onClick={async ()=>{
          const staged = editing._staged || []; if (!staged.length) return;
          let p = editing;
          if (!data.products.find(x=>x.id===p.id)) update({ products: [p, ...data.products] });
          const fd = new FormData();
          staged.forEach(s => { fd.append('files[]', s.file); fd.append('labels[]', s.label || ''); });
          fd.append('parent_table','products');
          fd.append('parent_id', p.id);
          try {
            const r = await fetch('/api/upload.php', { method:'POST', body: fd });
            const j = await r.json();
            if (j.ok) {
              const fresh = await fetch('/api/products.php').then(r=>r.json());
              const updated = fresh.find(x => x.id === p.id);
              if (updated) setEditing(prev => ({...prev, image_url: updated.image_url, gallery: updated.gallery, _staged: []}));
              showToast(`${staged.length} image${staged.length>1?'s':''} uploaded`);
            } else { showToast('Upload failed', 'error'); }
          } catch { showToast('Upload failed', 'error'); }
        }}>Upload {editing._staged.length} image{editing._staged.length>1?'s':''}</button>
        <button type="button" className="btn btn-ghost" onClick={()=>{
          setEditing({...editing, _staged: []});
        }}>Clear queue</button>
      </div>
    </>
  )}

  {/* Picker */}
  <div className="card" style={{padding:24, textAlign:'center', borderStyle:'dashed', cursor:'pointer'}} onClick={()=>document.getElementById('p-img-input').click()}>
    <I.upload/>
    <p style={{fontSize:13, marginTop:8, color:'var(--ink-2)'}}>Click to select images</p>
    <p style={{fontSize:11, color:'var(--ink-3)', fontFamily:'var(--mono)', letterSpacing:'.18em', marginTop:4}}>JPG · PNG · MULTIPLE OK · LABEL EACH AFTER SELECTING</p>
<input id="p-img-input" name="product_images" type="file" multiple accept="image/*" style={{display:'none'}} onChange={(e)=>{
  const files = Array.from(e.target.files || []); if (!files.length) return;
  files.forEach(f => {
    const reader = new FileReader();
    reader.onload = (ev) => {
      setEditing(prev => ({...prev, _staged: [...(prev._staged || []), { file:f, preview: ev.target.result, label:'' }]}));
    };
    reader.readAsDataURL(f);
  });
  e.target.value = '';
}}/>
  </div>
</div>
            <div style={{display:'flex', gap:10, justifyContent:'flex-end', marginTop:28, paddingTop:20, borderTop:'1px solid var(--line)'}}>
              <button className="btn btn-ghost" onClick={()=>setEditing(null)}>Cancel</button>
              <button className="btn btn-primary" onClick={()=>save(editing)}>Save piece</button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

/* ==== INBOX (shared for inquiries / customs / specials) ==== */
function AdminInbox({ data, update, kind }) {
  const titles = {
    inquiries: 'Inquiries',
    customs: 'Custom briefs',
    specials: 'Special requests'
  };

  const items = data[kind] || [];
  const [selected, setSelected] = aS(items[0]?.id || null);
  const [filter, setFilter] = aS('all');
  const [replyText, setReplyText] = aS('');
  const [sending, setSending] = aS(false);
  const { showToast } = useApp();

  const filtered =
    filter === 'all'
      ? items
      : items.filter(i => i.status === filter);

  const item = items.find(i => i.id === selected);

  aE(() => {
    setReplyText('');
  }, [selected]);

  const authHeaders = () => ({
    'Content-Type': 'application/json',
    'Authorization': `Bearer ${authToken()}`
  });

  const setStatus = async (id, status) => {
    try {
      await fetch(`/api/${kind}.php`, {
        method: 'PUT',
        headers: authHeaders(),
        body: JSON.stringify({ id, status })
      });

      update({
        [kind]: items.map(i =>
          i.id === id ? { ...i, status } : i
        )
      });

      showToast(`Marked as ${status}`);
    } catch {
      showToast('Update failed', 'error');
    }
  };

  const sendReply = async () => {
    if (!item) return;

    if (!replyText.trim()) {
      showToast('Write a reply first', 'error');
      return;
    }

    try {
      setSending(true);

      const r = await fetch(`/api/${kind}.php`, {
        method: 'PUT',
        headers: authHeaders(),
        body: JSON.stringify({
          id: item.id,
          reply: replyText
        })
      });

      const j = await r.json();

      if (!j.ok) {
        showToast(j.error || 'Email send failed', 'error');
        return;
      }

      update({
        [kind]: items.map(i =>
          i.id === item.id
            ? { ...i, status: 'replied' }
            : i
        )
      });

      setReplyText('');
      showToast('Reply sent successfully');
    } catch {
      showToast('Email send failed', 'error');
    } finally {
      setSending(false);
    }
  };

  const del = async (id) => {
    if (!confirm('Delete this entry?')) return;

    try {
      await fetch(`/api/${kind}.php`, {
        method: 'DELETE',
        headers: authHeaders(),
        body: JSON.stringify({ id })
      });

      update({
        [kind]: items.filter(i => i.id !== id)
      });

      if (selected === id) {
        setSelected(null);
      }

      showToast('Deleted');
    } catch {
      showToast('Delete failed', 'error');
    }
  };

  return (
    <div>
      <div style={{
        display:'flex',
        justifyContent:'space-between',
        alignItems:'flex-end',
        marginBottom:24,
        flexWrap:'wrap',
        gap:14
      }}>
        <h1 style={{fontSize:36, lineHeight:1}}>
          {titles[kind]}
        </h1>

        <div className="tabs" style={{margin:0}}>
          {['all','new','in-review','replied'].map(f => (
            <button
              key={f}
              className={filter===f?'active':''}
              onClick={()=>setFilter(f)}
            >
              {f}
            </button>
          ))}
        </div>
      </div>

      <div style={{
        display:'grid',
        gridTemplateColumns:'380px 1fr',
        gap:20,
        height:'calc(100vh - 240px)'
      }}>
        <div className="card" style={{
          padding:0,
          overflow:'hidden',
          display:'flex',
          flexDirection:'column'
        }}>
          <div style={{overflowY:'auto', flex:1}}>
            {filtered.map(i => (
              <div
                key={i.id}
                onClick={()=>setSelected(i.id)}
                className={`admin-list-item ${selected===i.id?'active':''}`}
              >
                <div style={{
                  display:'flex',
                  justifyContent:'space-between'
                }}>
                  <div style={{fontWeight:500}}>
                    {i.name}
                  </div>

                  <span className={`status-pill status-${i.status}`}>
                    {i.status}
                  </span>
                </div>

                <div style={{
                  fontSize:12,
                  color:'var(--ink-2)',
                  marginTop:4
                }}>
                  {i.email}
                </div>
              </div>
            ))}
          </div>
        </div>

        <div className="card" style={{padding:32}}>
          {item ? (
            <>
              <h2>{item.name}</h2>
              <p>{item.email}</p>

              <div style={{marginTop:20}}>
                <p>{item.detail || item.summary}</p>
              </div>

              <div className="field" style={{marginTop:20}}>
                <label>Reply</label>

                <textarea
                  className="textarea"
                  rows="6"
                  value={replyText}
                  onChange={(e)=>setReplyText(e.target.value)}
                  placeholder={`Hi ${item.name},`}
                />
              </div>

              <div style={{
                display:'flex',
                gap:10,
                marginTop:20
              }}>
                <button
                  className="btn btn-primary"
                  onClick={sendReply}
                  disabled={sending}
                >
                  {sending ? 'Sending...' : 'Send reply'}
                </button>

                <button
                  className="btn btn-ghost"
                  onClick={()=>setStatus(item.id, 'in-review')}
                >
                  Mark in review
                </button>

                <button
                  className="btn btn-ghost"
                  onClick={()=>del(item.id)}
                  style={{color:'#dc2626'}}
                >
                  Delete
                </button>
              </div>
            </>
          ) : (
            <div>Select an entry</div>
          )}
        </div>
      </div>
    </div>
  );
}


/* ==== ADMIN JOURNAL ==== */
function AdminJournal({ data, update }){
  const { showToast } = useApp();
  const [editing, setEditing] = aS(null);
  const [search, setSearch] = aS('');

  const list = (data.posts || []).filter(p =>
    (p.title || '').toLowerCase().includes(search.toLowerCase())
  ).sort((a,b) => new Date(b.date) - new Date(a.date));

  const blank = {
    id: Date.now(),
    title: 'Untitled post',
    tag: 'Guides',
    body: '',
    cover_url: '',
    status: 'draft',
    date: new Date().toISOString().slice(0,10),
  };

  const save = (p) => {
    if ((data.posts || []).find(x => x.id === p.id)){
      update({ posts: data.posts.map(x => x.id === p.id ? p : x) });
      showToast(`${p.title} updated`);
    } else {
      update({ posts: [p, ...(data.posts || [])] });
      showToast(`${p.title} created`);
    }
    setEditing(null);
  };

  const del = (id) => {
    if (confirm('Delete this post?')){
      update({ posts: data.posts.filter(p => p.id !== id) });
      showToast('Post deleted');
    }
  };

  const tags = ['Guides','Atelier','Style','Trends','Care'];
  const statuses = ['draft','published','scheduled'];

  return (
    <div>
      <div style={{display:'flex', justifyContent:'space-between', alignItems:'center', flexWrap:'wrap', gap:14, marginBottom:24}}>
        <h1 style={{fontSize:36, lineHeight:1}}>Journal</h1>
        <button className="btn btn-primary" onClick={()=>setEditing(blank)}><I.plus/> New post</button>
      </div>

      <div className="card" style={{padding:0, overflow:'hidden'}}>
        <div style={{padding:'16px 20px', borderBottom:'1px solid var(--line)'}}>
          <input className="input" placeholder="Search posts…" value={search} onChange={e=>setSearch(e.target.value)} style={{maxWidth:320}}/>
        </div>
        <div style={{overflowX:'auto'}}>
          <table className="admin-table">
            <thead><tr><th>Cover</th><th>Title</th><th>Tag</th><th>Status</th><th>Date</th><th></th></tr></thead>
            <tbody>
              {list.length === 0 && <tr><td colSpan="6" style={{textAlign:'center', padding:40, color:'var(--ink-3)'}}>No posts yet. Create your first one.</td></tr>}
              {list.map(p => (
                <tr key={p.id}>
                  <td>
                    <div style={{width:60, height:60, borderRadius:4, overflow:'hidden', background:'var(--bg-2)'}}>
                      {p.cover_url
                        ? <img src={p.cover_url} alt="" style={{width:'100%', height:'100%', objectFit:'cover'}}/>
                        : <Placeholder label="" tone="gold"/>
                      }
                    </div>
                  </td>
                  <td><div style={{fontWeight:500, maxWidth:340, overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap'}}>{p.title}</div></td>
                  <td><span className="badge">{p.tag}</span></td>
                  <td><span className={`status-pill status-${p.status}`}>{p.status}</span></td>
                  <td style={{fontFamily:'var(--mono)', fontSize:11, color:'var(--ink-3)'}}>{p.date}</td>
                  <td style={{textAlign:'right', whiteSpace:'nowrap'}}>
                    <button className="icon-btn" onClick={()=>setEditing({...p})} title="Edit"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5"><path d="M12 20h9"/><path d="M16.5 3.5a2.121 2.121 0 0 1 3 3L7 19l-4 1 1-4Z"/></svg></button>
                    <button className="icon-btn" onClick={()=>del(p.id)} title="Delete" style={{marginLeft:6, color:'#dc2626'}}><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5"><polyline points="3 6 5 6 21 6"/><path d="M19 6l-2 14a2 2 0 0 1-2 2H9a2 2 0 0 1-2-2L5 6"/></svg></button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>

      {editing && (
        <div className="modal-bg" onClick={()=>setEditing(null)}>
          <div className="modal-card" onClick={e=>e.stopPropagation()} style={{maxWidth:760}}>
            <div style={{display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom:24}}>
              <h2 style={{fontSize:28}}>{(data.posts || []).find(x => x.id === editing.id) ? 'Edit post' : 'New post'}</h2>
              <button className="icon-btn" onClick={()=>setEditing(null)}><I.close/></button>
            </div>

            <div className="field" style={{marginBottom:14}}>
              <label htmlFor="post-title">Title</label>
              <input id="post-title" className="input" value={editing.title} onChange={e=>setEditing({...editing, title:e.target.value})}/>
            </div>

            <div className="field" style={{marginBottom:14}}>
              <label htmlFor="post-cover">Cover image URL (optional)</label>
              <input
                id="post-cover"
                className="input"
                value={editing.cover_url || ''}
                onChange={e=>setEditing({...editing, cover_url:e.target.value})}
                placeholder="/uploads/abc123_dress.jpg or full https URL"
              />
              <p style={{fontSize:11, color:'var(--ink-3)', fontFamily:'var(--mono)', letterSpacing:'.12em', marginTop:6}}>TIP · COPY ANY UPLOADED PRODUCT IMAGE URL FROM THE PRODUCTS PAGE</p>
              {editing.cover_url && (
                <div style={{marginTop:10, aspectRatio:'21/9', borderRadius:6, overflow:'hidden', border:'1px solid var(--line)', background:'var(--bg-2)'}}>
                  <img src={editing.cover_url} alt="Preview" onError={(e)=>{e.target.style.display='none';}} style={{width:'100%', height:'100%', objectFit:'cover', display:'block'}}/>
                </div>
              )}
            </div>

            <div className="grid-2" style={{marginBottom:14}}>
              <div className="field">
                <label>Tag</label>
                <select className="select" value={editing.tag} onChange={e=>setEditing({...editing, tag:e.target.value})}>
                  {tags.map(t => <option key={t}>{t}</option>)}
                </select>
              </div>
              <div className="field">
                <label>Status</label>
                <select className="select" value={editing.status} onChange={e=>setEditing({...editing, status:e.target.value})}>
                  {statuses.map(s => <option key={s}>{s}</option>)}
                </select>
              </div>
              <div className="field" style={{gridColumn:'1/-1'}}>
                <label>Date</label>
                <input className="input" type="date" value={editing.date} onChange={e=>setEditing({...editing, date:e.target.value})}/>
              </div>
            </div>

            <div className="field" style={{marginBottom:14}}>
              <label htmlFor="post-body">Body</label>
              <textarea
                id="post-body"
                className="textarea"
                rows="14"
                value={editing.body}
                onChange={e=>setEditing({...editing, body:e.target.value})}
                placeholder="Write your post here. Use **bold**, *italic*, and blank lines for paragraphs."
                style={{fontFamily:'var(--mono)', fontSize:13, lineHeight:1.7}}
              />
              <p style={{fontSize:11, color:'var(--ink-3)', fontFamily:'var(--mono)', letterSpacing:'.12em', marginTop:6}}>FORMATTING · **BOLD** · *ITALIC* · BLANK LINE FOR NEW PARAGRAPH</p>
            </div>

            <div style={{display:'flex', gap:10, justifyContent:'flex-end', marginTop:28, paddingTop:20, borderTop:'1px solid var(--line)'}}>
              <button className="btn btn-ghost" onClick={()=>setEditing(null)}>Cancel</button>
              <button className="btn btn-primary" onClick={()=>save(editing)}>Save post</button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}



function AdminUsers({ data, update }) {
  const { showToast } = useApp();

  const session = JSON.parse(sessionStorage.getItem(ADMIN_KEY) || '{}');
  const token = session.token;
  const currentUserId = session.user?.id || session.id;
  const isSuperAdmin = !!(session.user?.is_super_admin || session.is_super_admin);

  const PERMISSIONS = [
    { key:'products', label:'Products' },
    { key:'inquiries', label:'Inquiries' },
    { key:'customs', label:'Custom Briefs' },
    { key:'specials', label:'Special Requests' },
    { key:'journal', label:'Journal' },
    { key:'analytics', label:'Analytics' },
    { key:'settings', label:'Settings' },
    { key:'users', label:'Users Page' },
    { key:'manage_users', label:'Manage Users' },
    { key:'reset_passwords', label:'Reset Passwords' }
  ];

  const headers = {
    'Content-Type':'application/json',
    'Authorization': `Bearer ${token}`
  };

  const emptyUser = {
    id:null,
    name:'',
    email:'',
    role:'staff',
    password:'',
    permissions:[],
    is_super_admin:false
  };

  const [search, setSearch] = aS('');
  const [adding, setAdding] = aS(false);
  const [editing, setEditing] = aS(null);
  const [saving, setSaving] = aS(false);
  const [form, setForm] = aS(emptyUser);

  const filteredUsers = (data.users || []).filter(u => {
    const q = search.toLowerCase();
    return (
      (u.name || '').toLowerCase().includes(q) ||
      (u.email || '').toLowerCase().includes(q) ||
      (u.role || '').toLowerCase().includes(q)
    );
  });

  const togglePermission = (perm) => {
    const exists = form.permissions.includes(perm);

    setForm({
      ...form,
      permissions: exists
        ? form.permissions.filter(p => p !== perm)
        : [...form.permissions, perm]
    });
  };

  const openAdd = () => {
    setForm(emptyUser);
    setAdding(true);
  };

  const openEdit = (user) => {
    setForm({
      id:user.id,
      name:user.name || '',
      email:user.email || '',
      role:user.role || 'staff',
      password:'',
      permissions:user.permissions || [],
      is_super_admin:!!user.is_super_admin
    });

    setEditing(user);
  };

  const closeModal = () => {
    setAdding(false);
    setEditing(null);
    setForm(emptyUser);
  };

  const saveNewUser = async () => {
    if (!isSuperAdmin) {
      showToast('Only super admin can add users', 'error');
      return;
    }

    if (!form.name || !form.email || !form.password) {
      showToast('Complete all required fields', 'error');
      return;
    }

    try {
      setSaving(true);

      const res = await fetch('/api/users.php', {
        method:'POST',
        headers,
        body: JSON.stringify(form)
      });

      const json = await res.json();

      if (!res.ok) {
        showToast(json.error || 'Failed to create user', 'error');
        return;
      }

      showToast('User created');
      closeModal();
      update();
    } catch {
      showToast('Network error', 'error');
    } finally {
      setSaving(false);
    }
  };

  const saveEditUser = async () => {
    if (!isSuperAdmin) {
      showToast('Only super admin can edit users', 'error');
      return;
    }

    try {
      setSaving(true);

      const res = await fetch('/api/users.php', {
        method:'PUT',
        headers,
        body: JSON.stringify(form)
      });

      const json = await res.json();

      if (!res.ok) {
        showToast(json.error || 'Update failed', 'error');
        return;
      }

      showToast('User updated');
      closeModal();
      update();
    } catch {
      showToast('Network error', 'error');
    } finally {
      setSaving(false);
    }
  };

  const del = async (user) => {
    if (!isSuperAdmin) {
      showToast('Only super admin can delete users', 'error');
      return;
    }

    if (user.is_super_admin) {
      showToast('Super admin cannot be deleted', 'error');
      return;
    }

    if (user.id == currentUserId) {
      showToast('You cannot delete yourself', 'error');
      return;
    }

    if (!confirm(`Delete ${user.name || user.email}?`)) return;

    try {
      const res = await fetch('/api/users.php', {
        method:'DELETE',
        headers,
        body: JSON.stringify({ id:user.id })
      });

      const json = await res.json();

      if (!res.ok) {
        showToast(json.error || 'Delete failed', 'error');
        return;
      }

      showToast('User removed');
      update();
    } catch {
      showToast('Network error', 'error');
    }
  };

  const resetPassword = async (user) => {
    if (!isSuperAdmin) {
      showToast('Only super admin can reset passwords', 'error');
      return;
    }

    const pwd = prompt(`Set new password for ${user.email}`);

    if (!pwd) return;

    try {
      const res = await fetch('/api/users.php', {
        method:'PUT',
        headers,
        body: JSON.stringify({
          ...user,
          password: pwd
        })
      });

      const json = await res.json();

      if (!res.ok) {
        showToast(json.error || 'Password reset failed', 'error');
        return;
      }

      showToast('Password updated');
      update();
    } catch {
      showToast('Network error', 'error');
    }
  };

  return (
    <div>
      <div style={{
        display:'flex',
        justifyContent:'space-between',
        alignItems:'center',
        marginBottom:24,
        gap:16,
        flexWrap:'wrap'
      }}>
        <h1 style={{fontSize:36, lineHeight:1}}>Users</h1>

        <div style={{
          display:'flex',
          gap:10,
          alignItems:'center'
        }}>
          <input
            className="input"
            placeholder="Search users..."
            value={search}
            onChange={e => setSearch(e.target.value)}
            style={{minWidth:260}}
          />

          {isSuperAdmin && (
            <button
              className="btn btn-primary"
              onClick={openAdd}
            >
              <I.plus /> Add User
            </button>
          )}
        </div>
      </div>

      <div className="card" style={{padding:0, overflow:'hidden'}}>
        <table className="admin-table">
          <thead>
            <tr>
              <th>Name</th>
              <th>Email</th>
              <th>Role</th>
              <th>Permissions</th>
              <th>Last Login</th>
              <th></th>
            </tr>
          </thead>

          <tbody>
            {filteredUsers.length === 0 ? (
              <tr>
                <td
                  colSpan="6"
                  style={{
                    textAlign:'center',
                    padding:40,
                    color:'var(--ink-3)'
                  }}
                >
                  No users found
                </td>
              </tr>
            ) : (
              filteredUsers.map(user => (
                <tr key={user.id}>
                  <td>
                    {user.name || 'Unnamed'}
                    {user.is_super_admin && (
                      <span
                        className="badge"
                        style={{marginLeft:8}}
                      >
                        SUPER ADMIN
                      </span>
                    )}
                  </td>

                  <td>{user.email}</td>

                  <td>
                    <span className="badge">
                      {user.role || 'staff'}
                    </span>
                  </td>

                  <td>
                    <div style={{
                      display:'flex',
                      gap:6,
                      flexWrap:'wrap'
                    }}>
                      {(user.permissions || []).slice(0,3).map(p => (
                        <span key={p} className="badge">{p}</span>
                      ))}

                      {(user.permissions || []).length > 3 && (
                        <span className="badge">
                          +{user.permissions.length - 3}
                        </span>
                      )}
                    </div>
                  </td>

                  <td>{user.last || '-'}</td>

                  <td style={{textAlign:'right'}}>
                    <div style={{
                      display:'flex',
                      gap:8,
                      justifyContent:'flex-end',
                      flexWrap:'wrap'
                    }}>
                      {isSuperAdmin && (
                        <>
                          <button
                            className="btn btn-ghost"
                            onClick={() => openEdit(user)}
                          >
                            Edit
                          </button>

                          <button
                            className="btn btn-ghost"
                            onClick={() => resetPassword(user)}
                          >
                            Reset Password
                          </button>

                          {!user.is_super_admin && user.id != currentUserId && (
                            <button
                              className="btn btn-ghost"
                              onClick={() => del(user)}
                              style={{color:'#dc2626'}}
                            >
                              Delete
                            </button>
                          )}
                        </>
                      )}
                    </div>
                  </td>
                </tr>
              ))
            )}
          </tbody>
        </table>
      </div>

      {(adding || editing) && (
        <div className="modal-bg" onClick={closeModal}>
          <div
            className="modal-card"
            onClick={e => e.stopPropagation()}
            style={{maxWidth:850}}
          >
            <div style={{
              display:'flex',
              justifyContent:'space-between',
              alignItems:'center',
              marginBottom:24
            }}>
              <h2 style={{fontSize:28}}>
                {editing ? 'Edit User' : 'Add User'}
              </h2>

              <button
                className="icon-btn"
                onClick={closeModal}
              >
                <I.close />
              </button>
            </div>

            <div className="grid-2">
              <div className="field">
                <label>Name</label>
                <input
                  className="input"
                  value={form.name}
                  onChange={e => setForm({...form, name:e.target.value})}
                />
              </div>

              <div className="field">
                <label>Email</label>
                <input
                  className="input"
                  value={form.email}
                  onChange={e => setForm({...form, email:e.target.value})}
                />
              </div>

              <div className="field">
                <label>Role</label>
                <select
                  className="select"
                  value={form.role}
                  onChange={e => setForm({...form, role:e.target.value})}
                >
                  <option value="staff">Staff</option>
                  <option value="admin">Admin</option>
                  <option value="manager">Manager</option>
                </select>
              </div>

              {!editing && (
                <div className="field">
                  <label>Password</label>
                  <input
                    type="password"
                    className="input"
                    value={form.password}
                    onChange={e => setForm({...form, password:e.target.value})}
                  />
                </div>
              )}
            </div>

            <div className="field" style={{marginTop:24}}>
              <label>Permissions</label>

              <div style={{
                display:'grid',
                gridTemplateColumns:'repeat(2,1fr)',
                gap:10,
                marginTop:12
              }}>
                {PERMISSIONS.map(p => (
                  <label
                    key={p.key}
                    style={{
                      display:'flex',
                      alignItems:'center',
                      gap:10,
                      padding:'12px',
                      border:'1px solid var(--line)',
                      borderRadius:10,
                      cursor:'pointer'
                    }}
                  >
                    <input
                      type="checkbox"
                      checked={form.permissions.includes(p.key)}
                      onChange={() => togglePermission(p.key)}
                    />
                    <span>{p.label}</span>
                  </label>
                ))}
              </div>
            </div>

            <div style={{
              display:'flex',
              justifyContent:'flex-end',
              gap:10,
              marginTop:28
            }}>
              <button
                className="btn btn-ghost"
                onClick={closeModal}
              >
                Cancel
              </button>

              <button
                className="btn btn-primary"
                onClick={editing ? saveEditUser : saveNewUser}
                disabled={saving}
              >
                {saving
                  ? 'Saving...'
                  : editing
                    ? 'Update User'
                    : 'Create User'}
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}


/* ==== ANALYTICS ==== */
function AdminAnalytics({ data }){
  const visits = [320,280,410,500,470,620,580,710,690,820,790,880,940,1020,990,1100,1080,1170,1240,1320,1280,1410,1480,1540,1620,1580,1700,1820,1890,1950];
  const max = Math.max(...visits);
  const stats = [
    ['Page views (30d)', '32,418', '+18%'],
    ['Unique visitors',  '12,094', '+22%'],
    ['Avg session',      '4m 12s', '+8%'],
    ['Conversion',       '3.4%',  '+0.6%'],
  ];
  return (
    <div>
      <h1 style={{fontSize:36, lineHeight:1, marginBottom:24}}>Analytics</h1>
      <div className="admin-stat-grid" style={{marginBottom:24}}>
        {stats.map(([l,v,d]) => (
          <div key={l} className="admin-stat">
            <div style={{fontFamily:'var(--mono)', fontSize:10, letterSpacing:'.22em', color:'var(--ink-3)'}}>{l}</div>
            <div style={{fontSize:36, fontFamily:'var(--serif)', marginTop:8, lineHeight:1}}>{v}</div>
            <div style={{fontSize:12, color:'var(--gold)', marginTop:8, fontFamily:'var(--mono)'}}>{d}</div>
          </div>
        ))}
      </div>
      <div className="card" style={{padding:32}}>
        <div style={{display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom:24}}>
          <div>
            <h3 style={{fontSize:24}}>Traffic · 30 days</h3>
            <p style={{color:'var(--ink-3)', fontSize:13, marginTop:6, fontFamily:'var(--mono)', letterSpacing:'.14em'}}>UNIQUE VISITORS · DAILY</p>
          </div>
          <select className="select" style={{maxWidth:160}}><option>Last 30 days</option><option>Last 7 days</option><option>Last 90 days</option></select>
        </div>
        <div style={{display:'flex', alignItems:'flex-end', gap:6, height:240, paddingTop:20}}>
          {visits.map((v,i) => (
            <div key={i} style={{flex:1, height:`${(v/max)*100}%`, background:`linear-gradient(180deg, var(--gold), color-mix(in oklab, var(--gold) 30%, transparent))`, borderRadius:'4px 4px 0 0', minHeight:6, transition:'all .3s'}} title={v}/>
          ))}
        </div>
      </div>
      <div style={{display:'grid', gridTemplateColumns:'1fr 1fr', gap:20, marginTop:24}}>
        <div className="card" style={{padding:28}}>
          <h3 style={{fontSize:22, marginBottom:18}}>Top products</h3>
          {data.products.slice(0,5).map((p,i)=>(
            <div key={p.id} style={{display:'flex', justifyContent:'space-between', alignItems:'center', padding:'10px 0', borderTop: i?'1px solid var(--line)':0}}>
              <div><div style={{fontWeight:500, fontSize:14}}>{p.name}</div><div style={{fontSize:11, color:'var(--ink-3)', fontFamily:'var(--mono)'}}>{p.col.toUpperCase()}</div></div>
              <div style={{fontFamily:'var(--mono)', fontSize:13, color:'var(--gold)'}}>{Math.floor(2400/(i+1))} views</div>
            </div>
          ))}
        </div>
        <div className="card" style={{padding:28}}>
          <h3 style={{fontSize:22, marginBottom:18}}>Top sources</h3>
          {[['Direct',42],['Instagram',28],['Google',18],['Pinterest',8],['Referral',4]].map(([s,p],i)=>(
            <div key={s} style={{padding:'10px 0', borderTop: i?'1px solid var(--line)':0}}>
              <div style={{display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom:6}}><span style={{fontSize:14}}>{s}</span><span style={{fontFamily:'var(--mono)', fontSize:13, color:'var(--ink-2)'}}>{p}%</span></div>
              <div style={{height:4, background:'var(--bg-2)', borderRadius:2}}><div style={{width:`${p*2}%`, height:'100%', background:'var(--gold)', borderRadius:2}}/></div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

function AdminSettings({ data, update }) {
  const { showToast } = useApp();

  const defaultSettings = {
    brandName: 'Aurelle Bride',
    contactEmail: 'info@aurellebride.com',
    whatsapp: '+92',
    heroHeadline: 'Luxury Bridal Couture',
    heroSub: 'Timeless bridal craftsmanship for modern elegance.',
    adsenseId: '',
    adsensePlacements: {
      homepage: false,
      products: false,
      blog: false,
      checkout: false
    },
    shippingUplift: {
      pakistan: 0,
      gcc: 15,
      usa: 25,
      uk: 22,
      europe: 20
    }
  };

  const [s, setS] = aS({
    ...defaultSettings,
    ...(data?.settings || {}),
    adsensePlacements: {
      ...defaultSettings.adsensePlacements,
      ...(data?.settings?.adsensePlacements || {})
    },
    shippingUplift: {
      ...defaultSettings.shippingUplift,
      ...(data?.settings?.shippingUplift || {})
    }
  });

  const save = () => {
    update({ settings: s });
    showToast('Settings saved');
  };

  const setField = (k, v) =>
    setS(prev => ({
      ...prev,
      [k]: v
    }));

  return (
    <div>
      <div style={{
        display:'flex',
        justifyContent:'space-between',
        alignItems:'flex-end',
        marginBottom:24,
        flexWrap:'wrap',
        gap:14
      }}>
        <h1 style={{fontSize:36, lineHeight:1}}>Settings</h1>

        <button
          className="btn btn-primary"
          onClick={save}
        >
          Save changes
        </button>
      </div>

      <div style={{
        display:'grid',
        gridTemplateColumns:'1fr 1fr',
        gap:20
      }}>
        <div className="card" style={{padding:32}}>
          <h3 style={{fontSize:22, marginBottom:18}}>
            Brand & Contact
          </h3>

          <div className="field" style={{marginBottom:14}}>
            <label>Brand name</label>
            <input
              className="input"
              value={s.brandName}
              onChange={e => setField('brandName', e.target.value)}
            />
          </div>

          <div className="field" style={{marginBottom:14}}>
            <label>Contact email</label>
            <input
              className="input"
              value={s.contactEmail}
              onChange={e => setField('contactEmail', e.target.value)}
            />
          </div>

          <div className="field">
            <label>WhatsApp number</label>
            <input
              className="input"
              value={s.whatsapp}
              onChange={e => setField('whatsapp', e.target.value)}
            />
          </div>
        </div>

        <div className="card" style={{padding:32}}>
          <h3 style={{fontSize:22, marginBottom:18}}>
            Hero Copy
          </h3>

          <div className="field" style={{marginBottom:14}}>
            <label>Headline</label>
            <input
              className="input"
              value={s.heroHeadline}
              onChange={e => setField('heroHeadline', e.target.value)}
            />
          </div>

          <div className="field">
            <label>Subheadline</label>
            <textarea
              className="textarea"
              rows="3"
              value={s.heroSub}
              onChange={e => setField('heroSub', e.target.value)}
            />
          </div>
        </div>

        <div className="card" style={{padding:32}}>
          <h3 style={{fontSize:22, marginBottom:18}}>
            AdSense
          </h3>

          <div className="field" style={{marginBottom:14}}>
            <label>Publisher ID</label>
            <input
              className="input"
              value={s.adsenseId}
              onChange={e => setField('adsenseId', e.target.value)}
              placeholder="ca-pub-XXXXXXXXXXXXXXXX"
            />
          </div>

          <div style={{
            display:'flex',
            flexDirection:'column',
            gap:10,
            marginTop:14
          }}>
            {Object.entries(s.adsensePlacements || {}).map(([k, v]) => (
              <label key={k} className="checkbox">
                <input
                  type="checkbox"
                  checked={!!v}
                  onChange={e =>
                    setField('adsensePlacements', {
                      ...s.adsensePlacements,
                      [k]: e.target.checked
                    })
                  }
                />
                <span className="box" />
                <span style={{
                  marginLeft:8,
                  fontSize:14,
                  textTransform:'capitalize'
                }}>
                  {k} placement
                </span>
              </label>
            ))}
          </div>
        </div>

        <div className="card" style={{padding:32}}>
          <h3 style={{fontSize:22, marginBottom:6}}>
            International Shipping Uplift
          </h3>

          <p style={{
            fontSize:12,
            color:'var(--ink-3)',
            marginBottom:18
          }}>
            Percentage added to base PKR price for each region.
          </p>

          <div style={{
            display:'grid',
            gridTemplateColumns:'1fr 1fr',
            gap:10
          }}>
            {Object.entries(s.shippingUplift || {}).map(([k, v]) => (
              <div key={k} className="field">
                <label>{k}</label>

                <div style={{position:'relative'}}>
                  <input
                    className="input"
                    type="number"
                    value={v}
                    onChange={e =>
                      setField('shippingUplift', {
                        ...s.shippingUplift,
                        [k]: parseInt(e.target.value || 0)
                      })
                    }
                  />

                  <span style={{
                    position:'absolute',
                    right:14,
                    top:'50%',
                    transform:'translateY(-50%)',
                    color:'var(--ink-3)',
                    fontSize:13
                  }}>
                    %
                  </span>
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

/* ==== ROUTER ==== */
function AdminRouter({ subroute }){
  const [session, setSession] = aS(null);
  const [checking, setChecking] = aS(true);
  aE(()=>{
    (async () => {
      try {
        const raw = sessionStorage.getItem(ADMIN_KEY);
        if (!raw) { setChecking(false); return; }
        const stored = JSON.parse(raw);
        // Verify token is still valid against the server
        const r = await fetch('/api/inquiries.php', { headers: { 'Authorization': `Bearer ${stored.token}` } });
        if (r.ok) setSession(stored);
        else sessionStorage.removeItem(ADMIN_KEY);
      } catch(e){ sessionStorage.removeItem(ADMIN_KEY); }
      setChecking(false);
    })();
  },[]);
  if (checking) return <div style={{minHeight:'100vh', display:'flex', alignItems:'center', justifyContent:'center', background:'var(--bg)'}}><div style={{fontFamily:'var(--mono)', fontSize:11, letterSpacing:'.22em', color:'var(--ink-3)'}}>VERIFYING SESSION…</div></div>;
  const logout = () => {
    try { sessionStorage.removeItem(ADMIN_KEY); } catch(e){}
    setSession(null);
    window.location.href = '/kr/pk/admin/moon';
  };
  if (!session) return <AdminLogin onAuth={setSession}/>;
  return <AdminShell session={session} sub={subroute} onLogout={logout}/>;
}

window.AdminRouter = AdminRouter;
