// ---------- Deposits ----------

function Deposits({ role }) {
  const [showAdd, setShowAdd] = React.useState(false);
  const isAccountant = role === 'accountant' || role === 'boss';

  const total = DEPOSITS.reduce((s,d) => s + d.amount, 0);
  const thisMonth = DEPOSITS.filter(d => d.deposit_date.startsWith('2026-04')).reduce((s,d) => s + d.amount, 0);
  const pending = DEPOSITS.filter(d => d.status === 'pending').length;

  return (
    <div style={{display:'flex',flexDirection:'column',gap:20}}>
      <div style={{display:'grid',gridTemplateColumns:'repeat(auto-fit,minmax(200px,1fr))',gap:14}}>
        <MiniKpi label="Total deposited" value={fmtNumber(total)+' FCFA'} delta="YTD" color="var(--green)"/>
        <MiniKpi label="April 2026" value={fmtNumber(thisMonth)+' FCFA'} delta="+8.2%" color="var(--accent)"/>
        <MiniKpi label="Pending" value={pending} delta="awaiting confirm" color="var(--gold)"/>
        <MiniKpi label="Avg deposit" value={fmtNumber(Math.round(total/DEPOSITS.length))+' FCFA'} delta="per entry" color="var(--blue)"/>
      </div>

      <div style={{display:'flex',justifyContent:'space-between',gap:12,flexWrap:'wrap'}}>
        <div style={{fontSize:12,color:'var(--text-dim)'}}>Cash and transfer deposits by retail outlets and production</div>
        {isAccountant && <button className="btn btn-primary btn-sm" onClick={()=>setShowAdd(true)}><Icon.Plus size={13}/> Record deposit</button>}
      </div>

      <TablePanel>
        <table style={{width:'100%',borderCollapse:'collapse'}}>
          <thead><tr>
            <Th>Date</Th><Th>Source</Th><Th>Method</Th><Th align="end">Amount</Th><Th>Recorded by</Th><Th>Status</Th><Th>Reference</Th>
          </tr></thead>
          <tbody>
            {DEPOSITS.map(d => (
              <tr key={d.id}>
                <Td><span className="mono" style={{fontSize:12}}>{fmtDate(d.deposit_date)}</span></Td>
                <Td><span style={{fontWeight:500}}>{d.source}</span></Td>
                <Td><span className="badge badge-muted" style={{textTransform:'capitalize'}}>{d.method}</span></Td>
                <Td align="end"><span className="mono" style={{fontWeight:600}}>{fmtNumber(d.amount)}</span> <span style={{color:'var(--text-dim)',fontSize:11}}>FCFA</span></Td>
                <Td><span style={{color:'var(--text-dim)'}}>{d.recorded_by}</span></Td>
                <Td><StatusBadge status={d.status}/></Td>
                <Td><span className="mono" style={{fontSize:11,color:'var(--text-dim)'}}>{d.reference}</span></Td>
              </tr>
            ))}
          </tbody>
        </table>
      </TablePanel>

      {showAdd && (
        <div className="modal-backdrop" onClick={()=>setShowAdd(false)}>
          <div className="modal" onClick={e=>e.stopPropagation()}>
            <h3 style={{fontSize:24,marginBottom:20}}>Record deposit</h3>
            <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:14}}>
              <div className="field"><label>Date</label><input type="date" defaultValue="2026-04-20"/></div>
              <div className="field"><label>Amount (FCFA)</label><input type="number" defaultValue="125000"/></div>
              <div className="field"><label>Source</label><select><option>Outlet · Avenue Charles de Gaulle</option><option>Outlet · Marché Central</option><option>Outlet · Klemat</option><option>Production HQ</option></select></div>
              <div className="field"><label>Method</label><select><option>cash</option><option>transfer</option><option>mobile_money</option></select></div>
              <div className="field" style={{gridColumn:'1 / -1'}}><label>Reference</label><input placeholder="DEP-2026-..."/></div>
              <div className="field" style={{gridColumn:'1 / -1'}}><label>Notes</label><textarea rows="2"/></div>
            </div>
            <div style={{display:'flex',gap:10,justifyContent:'flex-end',marginTop:24}}>
              <button className="btn btn-ghost btn-sm" onClick={()=>setShowAdd(false)}>Cancel</button>
              <button className="btn btn-primary btn-sm" onClick={()=>setShowAdd(false)}>Record</button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

// ---------- Users (admin access) ----------

function UserManagement({ role }) {
  const [showInvite, setShowInvite] = React.useState(false);
  const [accounts, setAccounts] = React.useState(() => [...(window.USER_ACCOUNTS || [])]);

  const approveUser = (id, selectedRole) => {
    setAccounts(prev => prev.map(u => u.id === id ? { ...u, status: 'active', role: selectedRole } : u));
  };
  const denyUser = (id) => {
    setAccounts(prev => prev.map(u => u.id === id ? { ...u, status: 'denied' } : u));
  };

  if (role !== 'boss') {
    return (
      <div style={{padding:40,textAlign:'center',color:'var(--text-dim)'}}>
        <Icon.Lock size={32} style={{margin:'0 auto 12px',display:'block',color:'var(--text-dim)'}}/>
        <div style={{fontSize:18,fontWeight:500,color:'var(--text)'}}>Access restricted</div>
        <div style={{fontSize:13,marginTop:6}}>Only the boss can manage user accounts and approvals.</div>
      </div>
    );
  }

  const pending = accounts.filter(u => u.status === 'pending_approval');
  const active = accounts.filter(u => u.status === 'active');

  return (
    <div style={{display:'flex',flexDirection:'column',gap:24}}>
      <div style={{display:'grid',gridTemplateColumns:'repeat(auto-fit,minmax(180px,1fr))',gap:14}}>
        <MiniKpi label="Total accounts" value={USER_ACCOUNTS.length} delta="all statuses" color="var(--accent)"/>
        <MiniKpi label="Pending approval" value={pending.length} delta="action needed" color="var(--gold)"/>
        <MiniKpi label="Active" value={active.length} delta="logged in 7d" color="var(--green)"/>
        <MiniKpi label="Suspended" value={USER_ACCOUNTS.filter(u=>u.status==='suspended').length} delta="—" color="var(--red)"/>
      </div>

      {pending.length > 0 && (
        <div style={{padding:20,background:'linear-gradient(180deg, var(--gold-dim), transparent)',border:'1px solid var(--gold-border)',borderRadius:16}}>
          <div style={{display:'flex',alignItems:'center',gap:10,marginBottom:14}}>
            <div style={{width:32,height:32,borderRadius:8,background:'var(--gold-dim)',display:'flex',alignItems:'center',justifyContent:'center',color:'var(--gold)'}}><Icon.Clock size={16}/></div>
            <div>
              <div style={{fontSize:15,fontWeight:600}}>{pending.length} account request{pending.length>1?'s':''} pending approval</div>
              <div style={{fontSize:12,color:'var(--text-dim)'}}>New sign-ups require your confirmation before they can access the system</div>
            </div>
          </div>
          <div style={{display:'flex',flexDirection:'column',gap:8}}>
            {pending.map(u => {
              const roleRef = React.useRef(u.requested_role || 'employee');
              return (
              <div key={u.id} style={{padding:14,background:'var(--card)',borderRadius:10,border:'1px solid var(--border)',display:'flex',alignItems:'center',gap:14,flexWrap:'wrap'}}>
                <div style={{width:38,height:38,borderRadius:'50%',background:'var(--gold-dim)',color:'var(--gold)',display:'flex',alignItems:'center',justifyContent:'center',fontSize:13,fontWeight:600}}>{u.full_name.split(' ').map(p=>p[0]).slice(0,2).join('')}</div>
                <div style={{flex:1,minWidth:180}}>
                  <div style={{fontWeight:500}}>{u.full_name}</div>
                  <div style={{fontSize:11,color:'var(--text-dim)',fontFamily:'JetBrains Mono'}}>{u.email} · requested {fmtDate(u.requested_at)}</div>
                </div>
                <select defaultValue={u.requested_role} onChange={e => { roleRef.current = e.target.value; }} style={{padding:'6px 10px',background:'var(--card2)',border:'1px solid var(--border)',borderRadius:6,fontSize:12}}>
                  <option value="employee">employee</option>
                  <option value="accountant">accountant</option>
                  <option value="production_manager">production_manager</option>
                </select>
                <div style={{display:'flex',gap:6}}>
                  <button type="button" className="btn btn-sm" onClick={() => approveUser(u.id, roleRef.current)} style={{background:'var(--green-dim)',color:'var(--green)',border:'1px solid var(--border)'}}><Icon.Check size={12}/> Approve</button>
                  <button type="button" className="btn btn-sm" onClick={() => denyUser(u.id)} style={{background:'var(--red-dim)',color:'var(--red)',border:'1px solid var(--border)'}}><Icon.X size={12}/> Deny</button>
                </div>
              </div>
              );
            })}
          </div>
        </div>
      )}

      <div style={{display:'flex',justifyContent:'space-between',alignItems:'center'}}>
        <h3 style={{fontSize:14,letterSpacing:'0.1em',textTransform:'uppercase',color:'var(--text-dim)'}}>All accounts</h3>
        <button className="btn btn-primary btn-sm" onClick={()=>setShowInvite(true)}><Icon.Plus size={13}/> Invite user</button>
      </div>

      <TablePanel>
        <table style={{width:'100%',borderCollapse:'collapse'}}>
          <thead><tr>
            <Th>Name</Th><Th>Email</Th><Th>Role</Th><Th>Status</Th><Th>Last login</Th><Th>Created</Th><Th align="end">Actions</Th>
          </tr></thead>
          <tbody>
            {USER_ACCOUNTS.map(u => (
              <tr key={u.id}>
                <Td><span style={{fontWeight:500}}>{u.full_name}</span></Td>
                <Td><span className="mono" style={{fontSize:12,color:'var(--text-dim)'}}>{u.email}</span></Td>
                <Td><span className="badge badge-muted" style={{textTransform:'capitalize'}}>{u.role.replace('_',' ')}</span></Td>
                <Td><StatusBadge status={u.status}/></Td>
                <Td><span className="mono" style={{fontSize:11,color:'var(--text-dim)'}}>{u.last_login || '—'}</span></Td>
                <Td><span className="mono" style={{fontSize:11,color:'var(--text-dim)'}}>{fmtDate(u.created_at)}</span></Td>
                <Td align="end"><button style={{color:'var(--text-dim)'}}><Icon.MoreH size={16}/></button></Td>
              </tr>
            ))}
          </tbody>
        </table>
      </TablePanel>

      {showInvite && (
        <div className="modal-backdrop" onClick={()=>setShowInvite(false)}>
          <div className="modal" onClick={e=>e.stopPropagation()}>
            <h3 style={{fontSize:24,marginBottom:20}}>Invite user</h3>
            <div style={{display:'flex',flexDirection:'column',gap:14}}>
              <div className="field"><label>Full name</label><input/></div>
              <div className="field"><label>Email</label><input type="email" placeholder="name@sagelateria.td"/></div>
              <div className="field"><label>Role</label><select><option>employee</option><option>accountant</option><option>production_manager</option></select></div>
            </div>
            <div style={{display:'flex',gap:10,justifyContent:'flex-end',marginTop:24}}>
              <button className="btn btn-ghost btn-sm" onClick={()=>setShowInvite(false)}>Cancel</button>
              <button className="btn btn-primary btn-sm" onClick={()=>setShowInvite(false)}>Send invite</button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

// ---------- Audit Log ----------

function AuditLog({ role }) {
  const [filter, setFilter] = React.useState('all');
  if (role !== 'boss') {
    return (
      <div style={{padding:40,textAlign:'center',color:'var(--text-dim)'}}>
        <Icon.Lock size={32} style={{margin:'0 auto 12px',display:'block'}}/>
        <div style={{fontSize:18,fontWeight:500,color:'var(--text)'}}>Access restricted</div>
        <div style={{fontSize:13,marginTop:6}}>Audit log is available to the boss only.</div>
      </div>
    );
  }
  const actions = ['all', ...new Set(AUDIT_LOG.map(a => a.action))];
  const filtered = filter==='all' ? AUDIT_LOG : AUDIT_LOG.filter(a => a.action === filter);

  return (
    <div style={{display:'flex',flexDirection:'column',gap:20}}>
      <div style={{fontSize:12,color:'var(--text-dim)'}}>Complete trail of sensitive actions across the system. Retained for 2 years.</div>
      <div style={{display:'flex',gap:8,flexWrap:'wrap'}}>
        {actions.map(a => (
          <button key={a} onClick={()=>setFilter(a)} style={{padding:'6px 12px',fontSize:11,borderRadius:999,border:'1px solid var(--border)',background: filter===a?'var(--accent)':'var(--card)',color: filter===a?'#fff':'var(--text-dim)',textTransform:'capitalize',fontFamily:'JetBrains Mono'}}>{a.replace(/_/g,' ')}</button>
        ))}
      </div>

      <TablePanel>
        <table style={{width:'100%',borderCollapse:'collapse'}}>
          <thead><tr>
            <Th>Time</Th><Th>Actor</Th><Th>Action</Th><Th>Target</Th><Th>Details</Th><Th>IP</Th>
          </tr></thead>
          <tbody>
            {filtered.map(a => (
              <tr key={a.id}>
                <Td><span className="mono" style={{fontSize:11,color:'var(--text-dim)'}}>{a.timestamp}</span></Td>
                <Td><span style={{fontWeight:500}}>{a.actor}</span></Td>
                <Td><span className="badge badge-muted" style={{fontFamily:'JetBrains Mono',fontSize:10}}>{a.action}</span></Td>
                <Td><span style={{color:'var(--text-dim)'}}>{a.target}</span></Td>
                <Td><span style={{color:'var(--text-dim)',fontSize:12}}>{a.details}</span></Td>
                <Td><span className="mono" style={{fontSize:11,color:'var(--text-dim)'}}>{a.ip}</span></Td>
              </tr>
            ))}
          </tbody>
        </table>
      </TablePanel>
    </div>
  );
}

// ---------- Settings ----------

function Settings({ role, theme, setTheme, accent, setAccent, fontSizeName, setFontSizeName, lang, setLang }) {
  return (
    <div style={{display:'flex',flexDirection:'column',gap:24,maxWidth:720}}>
      <SettingsSection title="Appearance" desc="Personalize how the dashboard looks on your device">
        <div style={{display:'flex',gap:10,flexWrap:'wrap'}}>
          {['dark','light','sand'].map(t => (
            <button key={t} onClick={()=>setTheme(t)} style={{padding:'10px 18px',borderRadius:10,border:'1px solid '+(theme===t?'var(--accent)':'var(--border)'),background: theme===t?'var(--accent-dim)':'var(--card)',color: theme===t?'var(--accent)':'var(--text)',textTransform:'capitalize',fontSize:13}}>{t}</button>
          ))}
        </div>
      </SettingsSection>

      <SettingsSection title="Accent color" desc="Used for primary actions and highlights">
        <div style={{display:'flex',gap:10,flexWrap:'wrap'}}>
          {[['terracotta','#C2553B'],['gold','#D4A24C'],['sahel','#A67C3D'],['teal','#3D7B7B'],['midnight','#2D4A6B']].map(([n,c]) => (
            <button key={n} onClick={()=>setAccent(n)} title={n} style={{width:40,height:40,borderRadius:10,background:c,border:'2px solid '+(accent===n?'#fff':'transparent'),outline:accent===n?'1px solid '+c:'none',outlineOffset:2}}/>
          ))}
        </div>
      </SettingsSection>

      <SettingsSection title="Text size" desc="Applies to the whole app (saved in this browser). Use +/− in the top bar anytime.">
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
          {[
            ['sm', 'S'], ['md', 'M'], ['lg', 'L'], ['xl', 'XL'], ['2xl', '2X'], ['3xl', '3X'], ['4xl', 'Max'],
          ].map(([v, label]) => (
            <button
              key={v}
              type="button"
              onClick={() => setFontSizeName && setFontSizeName(v)}
              style={{
                padding: '10px 14px', borderRadius: 10, fontSize: 13, fontWeight: 600, fontFamily: 'JetBrains Mono',
                border: '1px solid ' + (fontSizeName === v ? 'var(--accent)' : 'var(--border)'),
                background: fontSizeName === v ? 'var(--accent-dim)' : 'var(--card2)',
                color: fontSizeName === v ? 'var(--accent)' : 'var(--text)',
              }}
            >
              {label}
            </button>
          ))}
        </div>
      </SettingsSection>

      <SettingsSection title="Language" desc="Interface language">
        <div style={{display:'flex',gap:10}}>
          {[['fr','Français'],['en','English'],['ar','العربية']].map(([v,l]) => (
            <button key={v} onClick={()=>setLang(v)} style={{padding:'10px 18px',borderRadius:10,border:'1px solid '+(lang===v?'var(--accent)':'var(--border)'),background: lang===v?'var(--accent-dim)':'var(--card)',color: lang===v?'var(--accent)':'var(--text)',fontSize:13}}>{l}</button>
          ))}
        </div>
      </SettingsSection>

      <SettingsSection title="Notifications" desc="Get alerts about inventory, deposits and approvals">
        <div style={{display:'flex',flexDirection:'column',gap:10}}>
          {['Low inventory alerts','New leave requests','Account approvals','Daily revenue summary'].map((label,i) => (
            <label key={i} style={{display:'flex',alignItems:'center',gap:10,padding:'10px 14px',background:'var(--card2)',borderRadius:8,cursor:'pointer'}}>
              <input type="checkbox" defaultChecked={i!==3}/>
              <span style={{fontSize:13}}>{label}</span>
            </label>
          ))}
        </div>
      </SettingsSection>

      <SettingsSection title="Security" desc="Sessions and authentication">
        <div style={{display:'flex',flexDirection:'column',gap:10}}>
          <button className="btn btn-ghost btn-sm" style={{width:'fit-content'}}>Change password</button>
          <button className="btn btn-ghost btn-sm" style={{width:'fit-content'}}>Enable two-factor auth</button>
          <button className="btn btn-ghost btn-sm" style={{width:'fit-content',color:'var(--red)',borderColor:'var(--red-border)'}}>Sign out of all sessions</button>
        </div>
      </SettingsSection>
    </div>
  );
}

function SettingsSection({ title, desc, children }) {
  return (
    <div style={{padding:20,background:'var(--card)',border:'1px solid var(--border)',borderRadius:14}}>
      <div style={{marginBottom:14}}>
        <div style={{fontSize:15,fontWeight:600}}>{title}</div>
        <div style={{fontSize:12,color:'var(--text-dim)',marginTop:2}}>{desc}</div>
      </div>
      {children}
    </div>
  );
}

Object.assign(window, { Deposits, UserManagement, AuditLog, Settings });
