// Settings — Permissions, roles, integrations, audit log

const ROLE_DEFS = [
  { id: 'admin', name: 'Admin', desc: 'Full access to every workspace, billing, and people management.', color: '#C2452C' },
  { id: 'manager', name: 'Manager', desc: 'Read/write within their department; HRM access for their direct reports.', color: '#3E73C7' },
  { id: 'employee', name: 'Employee', desc: 'Read access to most workspaces; write to assigned items.', color: '#5C6470' },
  { id: 'sales', name: 'Sales', desc: 'Full CRM, read-only on Projects + Affiliates.', color: '#2F8B5A' },
  { id: 'support', name: 'Support', desc: 'Full IT Services. Read access to CRM customers.', color: '#0E8A95' },
  { id: 'finance', name: 'Finance', desc: 'Affiliate payouts, project budgets, contract files.', color: '#A24FB8' },
];

// ACL workspaces are derived from the real sidebar nav so this list always
// matches the screens that actually exist in the app.
const SECTIONS_FOR_ACL = (window.NAV_SECTIONS || []).map(n => n.label);

// Default access level per role, by sidebar group.
const ACL_GROUP_DEFAULTS = {
  admin:    { main: 'admin', hr: 'admin', rev: 'admin',  fin: 'admin', ops: 'admin', sys: 'admin' },
  manager:  { main: 'read',  hr: 'admin', rev: 'read',   fin: 'read',  ops: 'write', sys: 'none'  },
  employee: { main: 'read',  hr: 'read',  rev: 'none',   fin: 'none',  ops: 'write', sys: 'none'  },
  sales:    { main: 'read',  hr: 'read',  rev: 'admin',  fin: 'none',  ops: 'read',  sys: 'none'  },
  support:  { main: 'read',  hr: 'read',  rev: 'read',   fin: 'none',  ops: 'admin', sys: 'none'  },
  finance:  { main: 'read',  hr: 'read',  rev: 'read',   fin: 'admin', ops: 'read',  sys: 'none'  },
};

const DEFAULT_PERMISSIONS = Object.fromEntries(ROLE_DEFS.map(r => [
  r.id,
  Object.fromEntries((window.NAV_SECTIONS || []).map(n => [n.label, (ACL_GROUP_DEFAULTS[r.id] || {})[n.group] || 'none'])),
]));

function Settings() {
  const D = window.HitcentsData;
  const [view, setView] = useState('roles');
  const [permissions, setPermissions] = useState(DEFAULT_PERMISSIONS);

  return (
    <div data-screen-label="Settings">
      <div className="page-head">
        <div>
          <h1>Settings</h1>
          <div className="sub">Workspace · Roles & permissions · Users · Audit</div>
        </div>
        <Button variant="primary" icon="check">Save changes</Button>
      </div>

      <div className="tabs" style={{ marginBottom: 18 }}>
        <button className={`tab ${view === 'roles' ? 'active' : ''}`} onClick={() => setView('roles')}>Roles & permissions</button>
        <button className={`tab ${view === 'users' ? 'active' : ''}`} onClick={() => setView('users')}>Users</button>
        <button className={`tab ${view === 'audit' ? 'active' : ''}`} onClick={() => setView('audit')}>Audit log</button>
      </div>

      {view === 'roles' && <RolesPermissions permissions={permissions} setPermissions={setPermissions} />}
      {view === 'users' && <Users />}
      {view === 'audit' && <AuditLog />}
    </div>
  );
}

function RolesPermissions({ permissions, setPermissions }) {
  const [selectedRole, setSelectedRole] = useState('manager');

  function setLevel(section, level) {
    setPermissions(p => ({ ...p, [selectedRole]: { ...p[selectedRole], [section]: level } }));
  }

  const levels = [
    { id: 'none', name: 'No access', icon: 'x', color: '#A89C92' },
    { id: 'read', name: 'Read only', icon: 'globe', color: '#3E73C7' },
    { id: 'write', name: 'Read & write', icon: 'pencil', color: '#D18A1F' },
    { id: 'admin', name: 'Admin', icon: 'shield', color: '#C2452C' },
  ];

  return (
    <div className="grid" style={{ gridTemplateColumns: '300px 1fr', gap: 16 }}>
      <div className="card" style={{ padding: 12 }}>
        <div className="dim" style={{ fontSize: 10.5, letterSpacing: 0.5, textTransform: 'uppercase', margin: '4px 8px 8px', fontWeight: 600 }}>Roles</div>
        {ROLE_DEFS.map(r => (
          <div key={r.id} onClick={() => setSelectedRole(r.id)}
               style={{ padding: 10, borderRadius: 8, cursor: 'pointer', marginBottom: 4,
                        background: selectedRole === r.id ? 'var(--brand-orange-tint)' : 'transparent' }}>
            <div className="row gap-2">
              <div style={{ width: 6, height: 6, borderRadius: 3, background: r.color }} />
              <strong style={{ fontSize: 13 }}>{r.name}</strong>
            </div>
            <div className="dim" style={{ fontSize: 11.5, marginTop: 4, lineHeight: 1.4 }}>{r.desc}</div>
          </div>
        ))}
        <div className="divider" />
        <Button variant="ghost" icon="plus" size="sm" style={{ width: '100%', justifyContent: 'center' }}>Create custom role</Button>
      </div>

      <div className="card">
        <div className="card-h">
          <div>
            <h3>Permissions for {ROLE_DEFS.find(r => r.id === selectedRole)?.name}</h3>
            <div className="sub">{Object.values(permissions[selectedRole]).filter(v => v !== 'none').length} of {SECTIONS_FOR_ACL.length} workspaces accessible</div>
          </div>
        </div>

        <div className="col" style={{ gap: 2 }}>
          {SECTIONS_FOR_ACL.map(section => {
            const current = permissions[selectedRole][section];
            return (
              <div key={section} className="row gap-3" style={{ padding: '10px 0', borderTop: '1px solid var(--border)' }}>
                <div style={{ width: 160, fontWeight: 500, fontSize: 13.5 }}>{section}</div>
                <div className="row gap-2" style={{ flex: 1 }}>
                  {levels.map(l => (
                    <button key={l.id} onClick={() => setLevel(section, l.id)}
                            className={`btn btn-sm ${current === l.id ? '' : 'btn-ghost'}`}
                            style={current === l.id ? {
                              background: l.color, color: '#fff', borderColor: l.color,
                            } : {}}>
                      <Icon name={l.icon} size={11} /> {l.name}
                    </button>
                  ))}
                </div>
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
}

function Users() {
  const D = window.HitcentsData;
  const [filter, setFilter] = useState('');

  // Users ARE the people in the business — every employee is a user.
  const byEmail = Object.fromEntries((D.USERS || []).map(u => [u.email, u]));
  const users = D.EMPLOYEES.map(e => {
    const u = byEmail[e.email] || {};
    return {
      emp: e,
      role: e.role || u.role || 'Employee',
      status: u.status || e.status || 'Active',
      lastActive: u.lastActive || '—',
      twofa: u.twofa != null ? u.twofa : (e.role === 'Admin' || e.role === 'Manager'),
    };
  });

  const filtered = users.filter(u =>
    !filter || `${u.emp.name} ${u.emp.email} ${u.emp.title} ${u.role}`.toLowerCase().includes(filter.toLowerCase())
  );
  const active = users.filter(u => u.status === 'Active').length;
  const no2fa = users.filter(u => !u.twofa).length;

  return (
    <div>
      <div className="toolbar">
        <div className="search-inline">
          <Icon name="search" size={14} />
          <input placeholder="Search users…" value={filter} onChange={e => setFilter(e.target.value)} />
        </div>
        <div style={{ marginLeft: 'auto' }} className="row gap-2">
          <span className="muted" style={{ fontSize: 12 }}>{users.length} users · {active} active · {no2fa} without 2FA</span>
          <Button variant="primary" icon="plus">Invite user</Button>
        </div>
      </div>

      <div className="card flush">
        <table className="table">
          <thead><tr><th>User</th><th>Title</th><th>Role</th><th>Status</th><th>Last active</th><th>2FA</th><th></th></tr></thead>
          <tbody>
            {filtered.map(u => (
              <tr key={u.emp.id}>
                <td>
                  <div className="row gap-2">
                    <Avatar person={u.emp} size={28} />
                    <div>
                      <div style={{ fontWeight: 500 }}>{u.emp.name}</div>
                      <div className="mono dim" style={{ fontSize: 11.5, whiteSpace: 'nowrap' }}>{u.emp.email}</div>
                    </div>
                  </div>
                </td>
                <td className="muted">{u.emp.title}</td>
                <td><Badge tone={u.role === 'Admin' ? 'red' : u.role === 'Manager' ? 'blue' : 'neutral'}>{u.role}</Badge></td>
                <td><Badge tone={u.status === 'Active' ? 'green' : u.status === 'Invited' ? 'amber' : 'neutral'}>{u.status}</Badge></td>
                <td className="dim" style={{ fontSize: 12 }}>{u.lastActive}</td>
                <td>{u.twofa ? <Badge tone="green"><Icon name="check" size={9} stroke={3} /> On</Badge> : <Badge tone="neutral">Off</Badge>}</td>
                <td><button className="icon-btn"><Icon name="more" size={14} /></button></td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}

function AuditLog() {
  const D = window.HitcentsData;
  const entries = [
    { time: '14:02', who: 'e1', action: 'updated.role', target: 'caleb@hitcents.com → Support', sev: 'info' },
    { time: '13:58', who: 'e6', action: 'invited.member', target: 'newhire@hitcents.com', sev: 'info' },
    { time: '13:44', who: 'e9', action: 'approved.payout', target: 'PO-204 ($7,820)', sev: 'info' },
    { time: '12:30', who: 'e2', action: 'permission.change', target: 'Engineering / CRM → read', sev: 'warn' },
    { time: '11:12', who: 'e25', action: 'export.csv', target: 'Tickets — last 30 days', sev: 'info' },
    { time: '10:47', who: 'e7', action: 'rotation.api_key', target: 'integration:zendesk', sev: 'warn' },
    { time: '09:30', who: 'e1', action: 'login.success', target: 'IP 73.42.x.x · Bowling Green', sev: 'info' },
    { time: '09:01', who: null,   action: 'login.failed', target: 'unknown@hitcents.com · 5x — blocked', sev: 'danger' },
  ];
  return (
    <div className="card flush">
      <table className="table">
        <thead><tr><th>Time</th><th>Member</th><th>Action</th><th>Target</th><th>Severity</th></tr></thead>
        <tbody>
          {entries.map((e, i) => {
            const w = e.who ? getEmployee(e.who) : null;
            return (
              <tr key={i}>
                <td className="mono dim" style={{ fontSize: 11.5 }}>Today {e.time}</td>
                <td>{w ? <div className="row gap-2"><Avatar person={w} size={20} /><span style={{ fontSize: 12.5 }}>{w.name}</span></div> : <span className="dim">System</span>}</td>
                <td className="mono" style={{ fontSize: 12 }}>{e.action}</td>
                <td>{e.target}</td>
                <td><Badge tone={e.sev === 'danger' ? 'red' : e.sev === 'warn' ? 'amber' : 'neutral'}>{e.sev}</Badge></td>
              </tr>
            );
          })}
        </tbody>
      </table>
    </div>
  );
}

window.Settings = Settings;
