// Marketing OS — Shell (Sidebar + Topbar + role switcher)
const { useState, useEffect, useMemo, useRef, useCallback } = React;

function Sidebar({ view, setView, currentUser }) {
  const canManage = window.hasPerm(currentUser.role, 'manage_users');
  const nav = [
    { id: 'dashboard', label: 'แดชบอร์ด',        icon: 'dashboard' },
    { id: 'entry',     label: 'กรอกข้อมูล',      icon: 'plus'      },
    { id: 'expenses',  label: 'ค่าใช้จ่าย',       icon: 'money'     },
    { id: 'records',   label: 'บันทึกทั้งหมด',   icon: 'entry'     },
    { id: 'team',      label: 'ทีม & สมาชิก',    icon: 'team'      },
  ];
  if (canManage) nav.push({ id: 'permissions', label: 'สิทธิ์การใช้งาน', icon: 'shield' });

  return (
    <aside className="sidebar">
      <div className="brand">
        <div className="brand-mark">M</div>
        <div>
          <div className="brand-name">Marketing OS</div>
          <div className="brand-sub">v1.0 · Internal</div>
        </div>
      </div>

      <div className="nav-section-label">เมนูหลัก</div>
      {nav.map(n => (
        <button key={n.id} className={`nav-item ${view === n.id ? 'active' : ''}`} onClick={() => setView(n.id)}>
          <span className="nav-icon"><Icon name={n.icon} size={15}/></span>
          {n.label}
        </button>
      ))}

      <div className="nav-section-label">การตั้งค่า</div>
      <button className={`nav-item ${view === 'settings' ? 'active' : ''}`} onClick={() => setView('settings')}>
        <span className="nav-icon"><Icon name="settings" size={15}/></span>
        ตั้งค่าระบบ
      </button>

      <div className="nav-spacer"/>

      <div className="user-card">
        <div className="user-row">
          <div className="avatar">{window.initials(currentUser.name)}</div>
          <div style={{minWidth:0, flex:1}}>
            <div className="user-name" style={{whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis'}}>{currentUser.name}</div>
            <div className="user-role">{window.ROLES[currentUser.role].label}</div>
          </div>
        </div>
        <div style={{display:'flex', gap:6}}>
          <button className="btn btn-secondary btn-sm" style={{flex:1, justifyContent:'center'}}>
            <Icon name="user" size={12}/> โปรไฟล์
          </button>
          <button className="btn btn-ghost btn-sm" style={{padding:'6px 10px'}} title="ออกจากระบบ">
            <Icon name="logout" size={13}/>
          </button>
        </div>
      </div>
    </aside>
  );
}

function Topbar({ view, currentUser, setCurrentUser, allUsers, onCreate }) {
  const titles = {
    dashboard:   { t: 'แดชบอร์ดภาพรวม',          s: 'สรุปผลการทำงานทีมการตลาด' },
    entry:       { t: 'กรอกข้อมูลประจำวัน',       s: 'บันทึกผลการขายและการตลาด' },
    expense_entry:{t: 'กรอกค่าใช้จ่าย',           s: 'บันทึกค่าใช้จ่ายที่ไม่ใช่ค่าแอด' },
    expenses:    { t: 'ค่าใช้จ่าย',               s: 'รายการค่าใช้จ่ายและ Import จาก Bot/Sheet' },
    records:     { t: 'บันทึกทั้งหมด',            s: 'รายการที่กรอกเข้าระบบ' },
    team:        { t: 'ทีม & สมาชิก',            s: 'จัดการโครงสร้างทีมและบุคลากร' },
    permissions: { t: 'สิทธิ์การใช้งาน',          s: 'จัดการสิทธิ์ตามตำแหน่ง' },
    settings:    { t: 'ตั้งค่าระบบ',              s: 'การตั้งค่าทั่วไป' },
  };
  const cur = titles[view] || titles.dashboard;

  // For demo: only show users who could plausibly log in (one per role tier + a couple per team)
  const switchableUsers = [
    allUsers.find(u => u.role === 'owner'),
    allUsers.find(u => u.role === 'super_admin'),
    ...allUsers.filter(u => u.role === 'team_lead'),
    ...allUsers.filter(u => u.role === 'sub_lead').slice(0,2),
    ...allUsers.filter(u => u.role === 'staff').slice(0,3),
  ].filter(Boolean);

  return (
    <div className="topbar">
      <div>
        <div className="topbar-title">{cur.t}</div>
        <div className="topbar-sub">{cur.s}</div>
      </div>
      <div className="topbar-spacer"/>

      <div className="row" style={{gap: 8}}>
        <button className="btn btn-secondary btn-sm" title="การแจ้งเตือน">
          <Icon name="bell" size={13}/>
          <span style={{display:'inline-flex', width:7, height:7, borderRadius:'50%', background:'var(--gold)', marginLeft:-3}}/>
        </button>

        {(view === 'entry' || view === 'expense_entry' || view === 'expenses') ? null : (
          <button className="btn btn-primary btn-sm" onClick={onCreate}>
            <Icon name="plus" size={13}/> เพิ่มรายการใหม่
          </button>
        )}
      </div>

      <div className="role-switch" title="สลับมุมมองตามตำแหน่ง (Demo)">
        <span className="role-switch-label">มุมมอง</span>
        <select value={currentUser.id} onChange={e => setCurrentUser(allUsers.find(u => u.id === e.target.value))}>
          {switchableUsers.map(u => (
            <option key={u.id} value={u.id}>
              {window.ROLES[u.role].short} — {u.name.replace(/^คุณ/, '')}
            </option>
          ))}
        </select>
      </div>
    </div>
  );
}

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