// Sidebar + Topbar shell
const { useState, useEffect, useMemo, useRef } = React;

const NAV = [
  { id:'dashboard',  label:'Dashboard',          icon:'Home',  badge:null },
  { id:'cashflow',   label:'Daily Cash Flow',    icon:'Doc',   badge:'auto-cashflow' },
  { id:'decision',   label:'Make Decision',      icon:'Edit',  badge:null },
  { id:'general',    label:'General Information',icon:'Wallet',badge:null },
  { id:'selling',    label:'Selling Expenses',   icon:'Coin',  badge:'auto-expenses' },
  { id:'analytics',  label:'Analytics',          icon:'Bars',  badge:null },
  { id:'settings',   label:'Settings',           icon:'Cog',   badge:null },
];

// Resolve dynamic badges to actual numbers
const resolveBadge = (raw) => {
  if (raw === 'auto-cashflow'){
    // Total entries currently shown in the Daily Cash Flow box (= days of the current month dataset)
    return String((window.CASHFLOW || []).length || 0);
  }
  if (raw === 'auto-expenses'){
    return String((window.EXPENSE_CATS || []).length || 0);
  }
  return raw;
};

function Sidebar({ active, onNav, collapsed, onToggle }){
  const handleLogout = () => {
    window.confirmDialog({
      title:'Sign out of Smart FINX?',
      message:'Your session will end and any unsaved drafts will be kept locally.',
      tone:'danger', okLabel:'Sign out',
      onOk: () => window.toast('Signed out successfully', { tone:'success', title:'Goodbye 👋' })
    });
  };
  return (
    <aside className="sidebar">
      <div className="brand">
        <div className="brand-mark"><FinxLogo size={22}/></div>
        <div>
          <div className="brand-name">Smart FINX</div>
          <div className="brand-sub">Cash Flow OS</div>
        </div>
      </div>

      <div className="user">
        <div className="avatar"><div>ธ</div></div>
        <div className="meta">
          <div className="name thai">ธงชัย โฮ่หิ้น</div>
          <div className="role"><span className="dot"/> Finance · Online</div>
        </div>
      </div>

      <div className="nav-section-label">Workspace</div>
      {NAV.slice(0,6).map(n => {
        const Icon = I[n.icon];
        const badge = resolveBadge(n.id==='selling' ? (window.EXPENSE_CATS?.length || null) : n.badge);
        return (
          <div key={n.id}
               className={"navitem"+(active===n.id?' active':'')}
               onClick={()=>onNav(n.id)}>
            <span className="ico"><Icon size={18}/></span>
            <span>{n.label}</span>
            {badge && <span className="badge">{badge}</span>}
          </div>
        );
      })}

      <div className="nav-section-label">System</div>
      {NAV.slice(6).map(n => {
        const Icon = I[n.icon];
        return (
          <div key={n.id}
               className={"navitem"+(active===n.id?' active':'')}
               onClick={()=>onNav(n.id)}>
            <span className="ico"><Icon size={18}/></span>
            <span>{n.label}</span>
          </div>
        );
      })}

      <div className="nav-foot">
        <div className="navitem" onClick={handleLogout}>
          <span className="ico"><I.Logout size={18}/></span>
          <span>Sign out</span>
        </div>
      </div>
    </aside>
  );
}

function Topbar({ title, breadcrumb, onToggleSide, onNav }){
  const [q, setQ] = useState('');
  const [notifOpen, setNotifOpen] = useState(false);
  const [notifs, setNotifs] = useState([
    { id:1, t:'success', title:'CF-26050007 approved', msg:'ณัฐรดา approved your request', time:'2m ago', read:false },
    { id:2, t:'warn',    title:'Cash balance below threshold', msg:'Balance dropped under 50,000 THB on 11 May', time:'1h ago', read:false },
    { id:3, t:'info',    title:'Monthly report ready', msg:'May summary available for download', time:'3h ago', read:false },
    { id:4, t:'info',    title:'New user invited', msg:'Chanida W. has been invited as Viewer', time:'Yesterday', read:true },
  ]);
  const unread = notifs.filter(n=>!n.read).length;
  const ddRef = useRef();

  useEffect(()=>{
    const onDoc = (e) => { if (ddRef.current && !ddRef.current.contains(e.target)) setNotifOpen(false); };
    document.addEventListener('click', onDoc);
    return () => document.removeEventListener('click', onDoc);
  },[]);

  const showHelp = () => window.openModal({
    title:'Smart FINX · Quick Help',
    size:'md',
    message: (
      <div style={{display:'flex',flexDirection:'column',gap:14,fontSize:13.5,color:'var(--ink-2)',lineHeight:1.6}}>
        <div><b style={{color:'var(--ink)'}}>Keyboard shortcuts</b>
          <div style={{marginTop:6,display:'grid',gridTemplateColumns:'1fr 1fr',gap:8}}>
            {[
              ['⌘ K','Open search'],
              ['G then D','Go to Dashboard'],
              ['G then F','Daily Cash Flow'],
              ['G then M','Make Decision'],
              ['G then G','General Information'],
              ['G then A','Analytics'],
              ['G then S','Settings'],
              ['?','Show this help'],
            ].map(([k,l],i)=>(
              <div key={i} style={{display:'flex',justifyContent:'space-between',padding:'6px 10px',background:'#f7f8fc',borderRadius:8}}>
                <span>{l}</span><span style={{fontWeight:700,color:'var(--ink)'}}>{k}</span>
              </div>
            ))}
          </div>
        </div>
        <div><b style={{color:'var(--ink)'}}>Need more help?</b><br/>
          Contact <a href="#" style={{color:'var(--brand)'}}>support@finx.co</a> or open a ticket from Settings → Help.</div>
      </div>
    ),
    actions:[{ label:'Got it', kind:'primary' }]
  });

  const markAllRead = (e) => { e.stopPropagation(); setNotifs(ns => ns.map(n => ({...n, read:true}))); window.toast('All notifications marked as read', {tone:'success'}); };
  const clearAll    = (e) => { e.stopPropagation(); setNotifs([]); window.toast('Notifications cleared'); };

  const onSearchSubmit = (e) => {
    if (e.key === 'Enter' && q.trim()) {
      window.toast(`Searching for "${q}"…`, { title:'Search', tone:'info' });
    }
  };

  return (
    <div className="top">
      <button className="icon-btn" onClick={onToggleSide} title="Toggle sidebar"><I.Menu size={18}/></button>
      <div className="crumbs">
        <span>Smart FINX</span>
        <span className="sep">/</span>
        <b>{breadcrumb || title}</b>
      </div>
      <div className="search" role="search">
        <I.Search size={16} stroke="currentColor" style={{color:'#9aa3c2'}}/>
        <input placeholder="Search request, account, period…" value={q}
               onChange={e=>setQ(e.target.value)} onKeyDown={onSearchSubmit}/>
        <span className="kbd">⌘ K</span>
      </div>
      <div className="top-actions">
        <button className="icon-btn" title="Help" onClick={showHelp}><I.Globe size={18}/></button>
        <div style={{position:'relative'}} ref={ddRef}>
          <button className="icon-btn bell" title="Notifications"
                  onClick={(e)=>{ e.stopPropagation(); setNotifOpen(o=>!o); }}>
            <I.Bell size={18}/>
            {unread===0 && <style>{`.bell::after{display:none}`}</style>}
          </button>
          {notifOpen && (
            <div className="dropdown" onClick={e=>e.stopPropagation()}>
              <div className="dropdown-head">
                <div style={{fontWeight:700,fontSize:14}}>Notifications {unread>0 && <span className="chip" style={{marginLeft:6,fontSize:10}}>{unread} new</span>}</div>
                <div className="row" style={{gap:6}}>
                  <button className="btn sm" onClick={markAllRead}>Mark read</button>
                  <button className="btn sm" onClick={clearAll}>Clear</button>
                </div>
              </div>
              <div style={{maxHeight:360,overflow:'auto'}}>
                {notifs.length===0 && <div style={{padding:24,textAlign:'center',color:'var(--muted)',fontSize:13}}>No notifications</div>}
                {notifs.map(n => (
                  <div key={n.id} className="dropdown-item"
                       onClick={()=>{ setNotifs(ns => ns.map(x => x.id===n.id?{...x,read:true}:x)); window.toast(n.title); }}>
                    <div style={{
                      width:32,height:32,borderRadius:10,flex:'none',display:'grid',placeItems:'center',color:'#fff',
                      background: n.t==='success'?'linear-gradient(135deg,#10b981,#047857)'
                               : n.t==='warn'?'linear-gradient(135deg,#f59e0b,#b45309)'
                               : 'linear-gradient(135deg,#1f2a8e,#2e3bbf)'
                    }}>
                      {n.t==='success' ? <I.Check size={14}/> : n.t==='warn' ? <I.AlertCircle size={14}/> : <I.Bell size={14}/>}
                    </div>
                    <div style={{flex:1,minWidth:0}}>
                      <div style={{fontWeight:700,fontSize:13,display:'flex',alignItems:'center',gap:6}}>
                        {n.title}
                        {!n.read && <span style={{width:6,height:6,borderRadius:50,background:'#1f2a8e'}}/>}
                      </div>
                      <div style={{fontSize:12,color:'var(--muted)',marginTop:2}}>{n.msg}</div>
                      <div style={{fontSize:11.5,color:'var(--muted)',marginTop:2}}>{n.time}</div>
                    </div>
                  </div>
                ))}
              </div>
            </div>
          )}
        </div>
        <div style={{width:1,height:24,background:'var(--line)',margin:'0 4px'}}/>
        <div className="row" style={{gap:8,cursor:'pointer'}} onClick={()=>onNav && onNav('settings')}>
          <div className="avatar" style={{width:32,height:32}}><div style={{fontSize:12}}>ธ</div></div>
          <div style={{lineHeight:1.1}}>
            <div className="thai" style={{fontSize:12.5,fontWeight:700}}>ธงชัย โฮ่หิ้น</div>
            <div style={{fontSize:11,color:'var(--muted)'}}>Admin</div>
          </div>
        </div>
      </div>
    </div>
  );
}

window.Sidebar = Sidebar;
window.Topbar = Topbar;
window.NAV = NAV;
