(function() {
const h = React.createElement;
const { useState, useMemo } = React;

function GLDrawerOverlay({ filters, onClose, txns, showBackButton, onBack }) {
  const [search, setSearch] = useState('');

  const filtered = useMemo(() => {
    if (!txns || !filters) return [];
    return txns.filter(t => {
      const acct = (t.account_name||'').toLowerCase();
      const cat  = (t.canonical_category||'').toLowerCase();
      const pay  = (t.payee||t.contact_name||t.description||'').toLowerCase();
      const mon  = (t.posted_date||t.date||'').slice(0,7);
      if (filters.accountName && !acct.includes(filters.accountName.toLowerCase()) && !cat.includes(filters.accountName.toLowerCase())) return false;
      if (filters.category && !cat.includes(filters.category.toLowerCase())) return false;
      if (filters.month && mon !== filters.month) return false;
      if (filters.payee && !pay.includes(filters.payee.toLowerCase())) return false;
      if (search && !acct.includes(search) && !pay.includes(search) && !(t.description||'').toLowerCase().includes(search)) return false;
      return true;
    }).sort((a,b) => new Date(b.posted_date||b.date||0) - new Date(a.posted_date||a.date||0));
  }, [txns, filters, search]);

  const total = filtered.reduce((s,t) => s + Math.abs(parseFloat(t.amount||0)), 0);
  const fmt = v => v>=1000000?'$'+(v/1e6).toFixed(2)+'M':v>=1000?'$'+Math.round(v/1000)+'K':'$'+Math.round(v);
  const fmtD = d => { try { return new Date(d).toLocaleDateString('en-US',{month:'short',day:'numeric',year:'numeric'}); } catch(e){ return d||'—'; }};

  if (!filters) return null;

  return h('div', null,
    // Backdrop
    h('div', { onClick:onClose, style:{ position:'fixed',inset:0,background:'rgba(0,0,0,.35)',zIndex:999 } }),
    // Drawer
    h('div', { style:{ position:'fixed',top:0,right:0,bottom:0,width:'540px',maxWidth:'100vw',background:'white',boxShadow:'-4px 0 32px rgba(0,0,0,.18)',zIndex:1000,display:'flex',flexDirection:'column' } },
      // Header
      h('div', { style:{ background:'#0d2040',padding:'16px 20px',display:'flex',justifyContent:'space-between',alignItems:'flex-start',flexShrink:0 } },
        h('div', null,
          showBackButton ? h('button', { onClick: onBack || onClose, style:{ background:'rgba(255,255,255,.15)',border:'none',color:'white',padding:'5px 12px',borderRadius:'6px',cursor:'pointer',fontSize:'11px',fontWeight:'700',display:'flex',alignItems:'center',gap:'5px',marginBottom:'8px' } }, '← Back to Account Detail') : null,
          h('div', { style:{ color:'white',fontWeight:'800',fontSize:'14px' } }, 'GL Transactions'),
          h('div', { style:{ color:'rgba(255,255,255,.55)',fontSize:'11px',marginTop:'3px' } },
            `${filtered.length} transactions · ${fmt(total)}`
            + (filters.accountName ? ` · ${filters.accountName}` : '')
            + (filters.month ? ` · ${filters.month}` : '')
          )
        ),
        h('button', { onClick:onClose, style:{ background:'rgba(255,255,255,.15)',border:'none',color:'white',width:'30px',height:'30px',borderRadius:'50%',cursor:'pointer',fontSize:'18px',display:'flex',alignItems:'center',justifyContent:'center',lineHeight:1 } }, '×')
      ),
      // Search
      h('div', { style:{ padding:'10px 16px',borderBottom:'1px solid rgba(13,32,64,.08)',flexShrink:0 } },
        h('input', { type:'text',placeholder:'Search transactions...',value:search,
          onChange:e=>setSearch(e.target.value.toLowerCase()),
          style:{ width:'100%',padding:'7px 12px',border:'1px solid rgba(13,32,64,.15)',borderRadius:'7px',fontSize:'12px',outline:'none',boxSizing:'border-box' }
        })
      ),
      // Table
      h('div', { style:{ flex:1,overflowY:'auto' } },
        filtered.length === 0
          ? h('div', { style:{ padding:'40px',textAlign:'center',color:'#6475a0',fontSize:'12px' } }, 'No transactions match these filters.')
          : h('table', { style:{ width:'100%',borderCollapse:'collapse',fontSize:'11.5px' } },
              h('thead', null,
                h('tr', null,
                  ['Date','Account / Payee','Description','Amount'].map(col =>
                    h('th', { key:col, style:{ textAlign:col==='Amount'?'right':'left',padding:'8px 12px',background:'#0d2040',color:'white',fontWeight:'700',fontSize:'10px',textTransform:'uppercase',letterSpacing:'.05em',position:'sticky',top:0,zIndex:1 } }, col)
                  )
                )
              ),
              h('tbody', null,
                filtered.map((t,i) => {
                  const amt = Math.abs(parseFloat(t.amount||0));
                  const isIncome = parseFloat(t.amount||0) < 0;
                  return h('tr', { key:t.id||i, style:{ borderBottom:'1px solid rgba(13,32,64,.05)',background:i%2===0?'white':'rgba(248,249,252,1)' } },
                    h('td', { style:{ padding:'7px 12px',color:'#6475a0',whiteSpace:'nowrap',fontSize:'10.5px' } }, fmtD(t.posted_date||t.date)),
                    h('td', { style:{ padding:'7px 12px',color:'#0d2040',fontWeight:'500',maxWidth:'150px',overflow:'hidden',textOverflow:'ellipsis',whiteSpace:'nowrap' } },
                      t.account_name||t.payee||t.contact_name||'—'
                    ),
                    h('td', { style:{ padding:'7px 12px',color:'#4a5680',maxWidth:'160px',overflow:'hidden',textOverflow:'ellipsis',whiteSpace:'nowrap',fontSize:'10.5px' } },
                      t.description||t.memo||t.canonical_category||'—'
                    ),
                    h('td', { style:{ padding:'7px 12px',textAlign:'right',fontFamily:'JetBrains Mono,monospace',fontWeight:'700',color:isIncome?'#18a867':'#1a2540',whiteSpace:'nowrap' } },
                      (isIncome?'+':'')+fmt(amt)
                    )
                  );
                })
              )
            )
      ),
      // Footer
      h('div', { style:{ padding:'12px 16px',borderTop:'2px solid rgba(13,32,64,.10)',background:'rgba(13,32,64,.03)',display:'flex',justifyContent:'space-between',alignItems:'center',flexShrink:0 } },
        h('span', { style:{ fontSize:'11px',color:'#6475a0' } }, `${filtered.length} transactions`),
        h('span', { style:{ fontFamily:'JetBrains Mono,monospace',fontWeight:'800',color:'#0d2040',fontSize:'13px' } }, fmt(total))
      )
    )
  );
}

window.GLDrawerOverlay = GLDrawerOverlay;
})();
